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/unrevised_lemke_solver.cc | #include "drake/solvers/unrevised_lemke_solver.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <Eigen/LU>
#include "drake/common/autodiff.h"
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/fmt_eigen.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
#include "drake/common/unused.h"
using drake::log;
namespace drake {
namespace solvers {
namespace {
// A linear system solver that accommodates the inability of the LU
// factorization to be AutoDiff'd (true in Eigen 3, at least). For double types,
// the faster LU factorization and solve is used. For other types, QR
// factorization and solve is used.
template <class T>
class LinearSolver {
public:
explicit LinearSolver(const MatrixX<T>& m);
VectorX<T> Solve(const VectorX<T>& v) const;
private:
Eigen::ColPivHouseholderQR<MatrixX<T>> qr_;
Eigen::PartialPivLU<MatrixX<double>> lu_;
};
template <class T>
LinearSolver<T>::LinearSolver(const MatrixX<T>& M) {
if (M.rows() > 0) qr_ = Eigen::ColPivHouseholderQR<MatrixX<T>>(M);
}
template <>
LinearSolver<double>::LinearSolver(const MatrixX<double>& M) {
if (M.rows() > 0) lu_ = Eigen::PartialPivLU<MatrixX<double>>(M);
}
template <class T>
VectorX<T> LinearSolver<T>::Solve(const VectorX<T>& v) const {
if (v.rows() == 0) {
DRAKE_DEMAND(qr_.rows() == 0);
return VectorX<T>(0);
}
return qr_.solve(v);
}
template <>
VectorX<double> LinearSolver<double>::Solve(const VectorX<double>& v) const {
if (v.rows() == 0) {
DRAKE_DEMAND(lu_.rows() == 0);
return VectorX<double>(0);
}
return lu_.solve(v);
}
} // namespace
template <>
void UnrevisedLemkeSolver<AutoDiffXd>::DoSolve(
const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&,
MathematicalProgramResult*) const {
throw std::logic_error(
"UnrevisedLemkeSolver cannot yet be used in a "
"MathematicalProgram while templatized as an AutoDiff");
}
template <typename T>
void UnrevisedLemkeSolver<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(
"UnrevisedLemkeSolver doesn't support the feature of variable "
"scaling.");
}
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.
// Create a dummy variable for the number of pivots used.
int num_pivots = 0;
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 = SolveLcpLemke(constraint->M(), constraint->q(),
&constraint_solution, &num_pivots);
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);
}
// Utility function for copying an r-dimensional column vector v (designated by
// the indices in row_indices and col_index) from a matrix M to a target
// vector, `out`. Let M be the matrix `in` augmented with a single column of
// ones (i.e., the "covering vector"); put another way, M = | in 1 |, where "in"
// refers the n × m-dimensional matrix `in` and 1 is a column of ones (so M is
// n × (m+1)-dimensional). Let R be a r × n "row selection" matrix, constructed
// using `row_indices`. R is constructed using r = `row_indices.size()` as
// follows:
//
// Rᵢⱼ = { 1 if j = row_indices[i], ∀i ∈ 0..r-1, ∀j ∈ 0..n-1
// { 0 otherwise
//
// Consider the following example with `in` set to the 3 × 3 identity matrix,
// `row_indices = { 2, 0}` and `col_index = 1`. This would make:
// R = | 0 0 1 | and R⋅M = | 0 0 1 1 |
// | 1 0 0 | | 1 0 0 1 |
//
// The second column (`col_index = 1`) of R⋅M is v = | 0 |
// | 0 |
//
// `row_indices` need not be in sorted order, and `out` need not be properly
// sized on entry (it will be resized as necessary). However, this method aborts
// if any element of `row_indices` is out of range, `col_index` is out of range,
// *or* if there are any duplicated elements in `row_indices`.
template <class T>
void UnrevisedLemkeSolver<T>::SelectSubColumnWithCovering(
const MatrixX<T>& in, const std::vector<int>& row_indices, int col_index,
VectorX<T>* out) {
DRAKE_ASSERT(ValidateIndices(row_indices, in.rows()));
const int num_rows = row_indices.size();
out->resize(num_rows);
// Look for the covering vector first.
if (col_index == in.cols()) {
out->setOnes();
return;
}
DRAKE_DEMAND(0 <= col_index && col_index < in.cols());
const auto in_column = in.col(col_index);
for (int i = 0; i < num_rows; i++) {
DRAKE_ASSERT(row_indices[i] < in_column.size());
(*out)[i] = in_column[row_indices[i]];
}
}
// Utility function for copying an r-dimensional column vector v (designated by
// the indices in `row_indices`) from n-dimensional vector `in` to a target
// vector, `out`. Let R be a r × n "row selection" matrix, constructed using
// r = `row_indices.size()` as follows:
//
// Rᵢⱼ = { 1 if j = row_indices[i], ∀i ∈ 0..r-1, ∀j ∈ 0..n-1
// { 0 otherwise
//
// Consider the following example with `in` set to the vector [ 1 2 3 ]ᵀ,
// and `row_indices = { 2, 0}`. This would make:
// R = | 0 0 1 | and v = R⋅`in` = | 3 |
// | 1 0 0 | | 1 |
//
// `row_indices` need not be in sorted order, and `out` need not be properly
// sized on entry (it will be resized as necessary). However, this method aborts
// if any element of `row_indices` is out of range *or* if there are any
// duplicated elements in `row_indices`.
template <class T>
void UnrevisedLemkeSolver<T>::SelectSubVector(
const VectorX<T>& in, const std::vector<int>& row_indices,
VectorX<T>* out) {
DRAKE_ASSERT(ValidateIndices(row_indices, in.size()));
const int num_rows = row_indices.size();
out->resize(num_rows);
for (int i = 0; i < num_rows; i++) {
DRAKE_ASSERT(row_indices[i] < in.rows());
(*out)(i) = in(row_indices[i]);
}
}
// Utility function for copying an r-dimensional column vector v (designated by
// the indices in `row_indices`) into n-dimensional vector `out`. Let R be the
// r × n "row selection" matrix defined in the documentation of
// SelectSubVector(). Then, the result of the operation is:
// `out` = `out` + Rᵀ⋅(`v` - R⋅`out`)
//
// Consider the following example with `v` set to the vector [ 3 1 ]ᵀ,
// `row_indices = { 2, 0}`, and `out` set to the vector [ 4 5 6 ]. This would
// make:
// R = | 0 0 1 | and `out` + Rᵀ⋅(`v` - R⋅`out`) = | 1 |
// | 1 0 0 | | 5 |
// | 3 |
//
// `row_indices` need not be in sorted order. This method aborts if any element
// of `row_indices` is out of the range of `out`, if `row_indices` is not the
// same size as `v`, or if there are any duplicated elements in `row_indices`.
template <class T>
void UnrevisedLemkeSolver<T>::SetSubVector(const VectorX<T>& v,
const std::vector<int>& row_indices,
VectorX<T>* out) {
DRAKE_DEMAND(row_indices.size() == static_cast<size_t>(v.size()));
DRAKE_ASSERT(ValidateIndices(row_indices, out->size()));
for (size_t i = 0; i < row_indices.size(); ++i) (*out)[row_indices[i]] = v[i];
}
// Function for checking whether a set of indices that specify a view into
// a vector is valid. Returns `true` if row_indices are unique and each element
// lies in [0, vector_size-1] and `false` otherwise.
template <class T>
bool UnrevisedLemkeSolver<T>::ValidateIndices(
const std::vector<int>& row_indices, int vector_size) {
// Don't check anything for empty vectors.
if (row_indices.empty()) return true;
// Sort the vector first.
std::vector<int> sorted_row_indices = row_indices;
std::sort(sorted_row_indices.begin(), sorted_row_indices.end());
// Validate the maximum and minimum elements.
if (sorted_row_indices.back() >= vector_size) return false;
if (sorted_row_indices.front() < 0) return false;
// Make sure that the vector is unique.
return std::unique(sorted_row_indices.begin(), sorted_row_indices.end()) ==
sorted_row_indices.end();
}
// Function for checking whether a set of indices that specify a view into
// a matrix is valid. Returns `true` if each element of row_indices is unique
// lies in [0, num_rows-1] and if each element of col_indices is unique and
// lies in [0, num_cols-1]. Returns `false` otherwise.
template <class T>
bool UnrevisedLemkeSolver<T>::ValidateIndices(
const std::vector<int>& row_indices, const std::vector<int>& col_indices,
int num_rows, int num_cols) {
return ValidateIndices(row_indices, num_rows) &&
ValidateIndices(col_indices, num_cols);
}
// Utility function for copying an r × c dimensional submatrix S (designated by
// the indices in row_indices and col_indices) from a matrix M to a target
// matrix, `out`. Let M be the matrix `in` augmented with a single column of
// ones (i.e., the "covering vector"); put another way, M = | in 1 |, where "in"
// refers the n × m-dimensional matrix `in` and 1 is a column of ones (so M is
// n × (m+1)-dimensional). Let R be a r × n "row selection" matrix, constructed
// using `row_indices` and C be a (m+1) × c-dimensional "column selection"
// matrix constructed using `col_indices`. R and C are constructed using
// r = `row_indices.size()` and c = `col_indices.size()` as follows:
//
// Rᵢⱼ = { 1 if j = row_indices[i], ∀i ∈ 0..r-1, ∀j ∈ 0..n-1
// { 0 otherwise
// Cᵢⱼ = { 1 if col_indices[j] = i, ∀i ∈ 0..m, ∀j ∈ 0..c-1
// { 0 otherwise
//
// Consider the following example with `in` set to the 3 × 3 identity matrix,
// `row_indices = { 2, 1, 0}` and `col_indices = { 1, 2, 3 }`. This would make:
// R = | 0 0 1 | C = | 0 0 0 | and R⋅M⋅C = | 0 1 1 |
// | 0 1 0 | | 1 0 0 | | 1 0 1 |
// | 1 0 0 | | 0 1 0 | | 0 0 1 |
// | 0 0 1 |
// `row_indices` and `col_indices` need not be in sorted order, and `out` need
// not be properly sized on entry (it will be resized as necessary). However,
// this method aborts if any element of `row_indices` or `col_indices` is out
// of range *or* if there are any duplicated elements.
template <class T>
void UnrevisedLemkeSolver<T>::SelectSubMatrixWithCovering(
const MatrixX<T>& in, const std::vector<int>& row_indices,
const std::vector<int>& col_indices, MatrixX<T>* out) {
const int num_rows = row_indices.size();
const int num_cols = col_indices.size();
DRAKE_ASSERT(
ValidateIndices(row_indices, col_indices, in.rows(), in.cols() + 1));
out->resize(num_rows, num_cols);
for (int i = 0; i < num_rows; i++) {
const auto row_in = in.row(row_indices[i]);
// `row_out` is a "view" into `out`: any modifications to row_out are
// reflected in `out`.
auto row_out = out->row(i);
for (int j = 0; j < num_cols; j++) {
if (col_indices[j] < in.cols()) {
DRAKE_ASSERT(col_indices[j] >= 0);
row_out(j) = row_in(col_indices[j]);
} else {
DRAKE_ASSERT(col_indices[j] == in.cols());
row_out(j) = 1.0;
}
}
}
}
// Determines the various index sets defined in Section 1.1 of [Dai 2018].
template <class T>
void UnrevisedLemkeSolver<T>::DetermineIndexSets() const {
// Helper for determining index sets.
auto DetermineIndexSetsHelper = [this](
const std::vector<LCPVariable>& variables,
bool is_z, std::vector<int>* variable_set,
std::vector<int>* variable_set_prime) {
variable_and_array_indices_.clear();
for (int i = 0; i < static_cast<int>(variables.size()); ++i) {
if (variables[i].is_z() == is_z)
variable_and_array_indices_.emplace_back(variables[i].index(), i);
}
std::sort(variable_and_array_indices_.begin(),
variable_and_array_indices_.end());
// Construct the set and the primed set.
for (const auto& variable_and_array_index_pair :
variable_and_array_indices_) {
variable_set->push_back(variable_and_array_index_pair.first);
variable_set_prime->push_back(variable_and_array_index_pair.second);
}
};
// Clear all sets.
index_sets_.alpha.clear();
index_sets_.alpha_bar.clear();
index_sets_.alpha_prime.clear();
index_sets_.alpha_bar_prime.clear();
index_sets_.beta.clear();
index_sets_.beta_bar.clear();
index_sets_.beta_prime.clear();
index_sets_.beta_bar_prime.clear();
DetermineIndexSetsHelper(indep_variables_, false, &index_sets_.alpha,
&index_sets_.alpha_prime);
DetermineIndexSetsHelper(dep_variables_, false, &index_sets_.alpha_bar,
&index_sets_.alpha_bar_prime);
DetermineIndexSetsHelper(dep_variables_, true, &index_sets_.beta,
&index_sets_.beta_prime);
DetermineIndexSetsHelper(indep_variables_, true, &index_sets_.beta_bar,
&index_sets_.beta_bar_prime);
}
// Verifies that each element of the pivoting set is unique. This is an
// expensive operation and should only be executed in Debug mode.
template <class T>
bool UnrevisedLemkeSolver<T>::IsEachUnique(
const std::vector<LCPVariable>& vars) {
// Copy the set.
std::vector<LCPVariable> vars_copy = vars;
std::sort(vars_copy.begin(), vars_copy.end());
return (std::unique(vars_copy.begin(), vars_copy.end()) == vars_copy.end());
}
// Performs the pivoting operation, which is described in [Dai 2018].
// `M_prime_col` can be null, if the updated column of M' (pivoted version of M)
// is not needed and the driving_index corresponds to the artificial variable.
template <typename T>
bool UnrevisedLemkeSolver<T>::LemkePivot(const MatrixX<T>& M,
const VectorX<T>& q, int driving_index,
T zero_tol, VectorX<T>* M_prime_col,
VectorX<T>* q_prime) const {
DRAKE_DEMAND(q_prime != nullptr);
const int kArtificial = M.rows();
DRAKE_DEMAND(driving_index >= 0 && driving_index <= kArtificial);
// Verify that each member in the independent and dependent sets is unique.
DRAKE_ASSERT(IsEachUnique(indep_variables_));
DRAKE_ASSERT(IsEachUnique(dep_variables_));
// If the driving index does not correspond to the artificial variable,
// M_prime_col must be non-null.
if (!IsArtificial(indep_variables_[driving_index]))
DRAKE_DEMAND(M_prime_col != nullptr);
// Determine the sets.
DetermineIndexSets();
// Note: It is feasible to do a low-rank update to the factorization below,
// since alpha and beta should change by no more than a single index between
// consecutive pivots. Eigen only supports low-rank updates to Cholesky
// factorizations at the moment, however.
// Compute matrix and vector views.
SelectSubMatrixWithCovering(M, index_sets_.alpha, index_sets_.beta,
&M_alpha_beta_);
SelectSubMatrixWithCovering(M, index_sets_.alpha_bar, index_sets_.beta,
&M_alpha_bar_beta_);
SelectSubVector(q, index_sets_.alpha, &q_alpha_);
SelectSubVector(q, index_sets_.alpha_bar, &q_alpha_bar_);
// Equation (2) from [Dai 2018].
// Note: this equation, and those below, must be kept up-to-date with
// [Dai 2018].
LinearSolver<T> fMab(M_alpha_beta_); // Factorized M_alpha_beta_.
q_prime_beta_prime_ = -fMab.Solve(q_alpha_);
// Check whether the solution is sufficiently close. We need to do this
// because partial pivoting LU does not estimate rank (and, from prior
// experience in solving LCPs), loss of rank need not lead to errors in
// solving the LCP. We assume that if the factorization is good enough to
// solve this linear system, it's good enough to solve the subsequent
// linear system (below). NOTE: current unit tests do not exercise the
// affirmative evaluation of the conditional (meaning that the "return false"
// never gets called).
// @TODO(edrumwri) Institute a unit test that exercises the affirmative
// evaluation branch of the conditional when such a LCP has been
// identified.
if ((M_alpha_beta_ * q_prime_beta_prime_ + q_alpha_).norm() > zero_tol)
return false;
// Equation (3) from [Dai 2018].
q_prime_alpha_bar_prime_ =
M_alpha_bar_beta_ * q_prime_beta_prime_ + q_alpha_bar_;
// Set the components of q'.
SetSubVector(q_prime_beta_prime_, index_sets_.beta_prime, q_prime);
SetSubVector(q_prime_alpha_bar_prime_, index_sets_.alpha_bar_prime, q_prime);
DRAKE_LOGGER_DEBUG("q': {}", fmt_eigen(q_prime->transpose()));
// If it is not necessary to compute the column of M, quit now.
if (!M_prime_col) return true;
// Examine the driving variable.
if (!indep_variables_[driving_index].is_z()) {
DRAKE_LOGGER_DEBUG("Driving case #1: driving variable from w");
// Case from Section 2.2.1.
// Determine gamma by determining the position of the driving variable
// in INDEPENDENT W (as defined in [Dai 2018]).
const int n = static_cast<int>(indep_variables_.size());
int gamma = 0;
for (int i = 0; i < n; ++i) {
if (!indep_variables_[i].is_z()) {
if (indep_variables_[i].index() <
indep_variables_[driving_index].index()) {
++gamma;
}
}
}
// From Equation (4) in [Dai 2018].
DRAKE_ASSERT(index_sets_.alpha[gamma] ==
indep_variables_[driving_index].index());
// Set the unit vector.
e_.setZero(index_sets_.beta.size());
e_[gamma] = 1.0;
// Equation (5).
M_prime_driving_beta_prime_ = fMab.Solve(e_);
// Equation (6).
M_prime_driving_alpha_bar_prime_ =
M_alpha_bar_beta_ * M_prime_driving_beta_prime_;
} else {
DRAKE_LOGGER_DEBUG("Driving case #2: driving variable from z");
// Case from Section 2.2.2 of [Dai 2018].
// Determine zeta.
const int zeta = indep_variables_[driving_index].index();
// Compute g_alpha and g_alpha_bar.
SelectSubColumnWithCovering(M, index_sets_.alpha, zeta, &g_alpha_);
SelectSubColumnWithCovering(M, index_sets_.alpha_bar, zeta, &g_alpha_bar_);
// Equation (7).
M_prime_driving_beta_prime_ = -fMab.Solve(g_alpha_);
// Equation (8).
M_prime_driving_alpha_bar_prime_ =
g_alpha_bar_ + M_alpha_bar_beta_ * M_prime_driving_beta_prime_;
}
SetSubVector(M_prime_driving_beta_prime_, index_sets_.beta_prime,
M_prime_col);
SetSubVector(M_prime_driving_alpha_bar_prime_, index_sets_.alpha_bar_prime,
M_prime_col);
DRAKE_LOGGER_DEBUG("M' (driving): {}", fmt_eigen(M_prime_col->transpose()));
return true;
}
// Checks to see whether a given variable is the artificial variable.
template <class T>
bool UnrevisedLemkeSolver<T>::IsArtificial(const LCPVariable& v) const {
const int n = static_cast<int>(dep_variables_.size());
return v.is_z() && v.index() == n;
}
// Method for finding the index of the complement of an LCP variable in
// a tuple (strictly speaking, an unsorted vector) of independent variables.
// Aborts if the index is not found in the set or the variable is the artificial
// variable (it never should be).
template <class T>
int UnrevisedLemkeSolver<T>::FindComplementIndex(
const LCPVariable& query) const {
// Verify that the query is not the artificial variable.
DRAKE_DEMAND(!IsArtificial(query));
const auto iter = indep_variables_indices_.find(query.Complement());
DRAKE_DEMAND(iter != indep_variables_indices_.end());
return iter->second;
}
// Computes the solution using the current index sets. `z` must simply be
// non-null; it will be resized as necessary. Returns `true` if able to
// construct the solution and `false` if unable to find the solution to a
// necessary system of linear equations. Aborts (in LemkePivot()) if
// `artificial_index` does not correspond to the index of the artificial
// variable in the vector of independent_variables.
// @pre The artificial variable was the blocking variable, indicating that the
// solution to the LCP can be obtained after a final pivoting operation.
// @pre `artificial_index` corresponds to the index of the artificial variable
// in the vector of independent variables.
template <class T>
bool UnrevisedLemkeSolver<T>::ConstructLemkeSolution(const MatrixX<T>& M,
const VectorX<T>& q,
int artificial_index,
T zero_tol,
VectorX<T>* z) const {
DRAKE_DEMAND(z != nullptr);
const int n = q.rows();
// Compute the solution by pivoting the artificial variable, which was just
// identified as the blocking variable, from the set of dependent variables
// to the set of independent variables.
VectorX<T> q_prime(n);
if (!LemkePivot(M, q, artificial_index, zero_tol, nullptr, &q_prime))
return false;
z->setZero(n);
for (int i = 0; i < static_cast<int>(dep_variables_.size()); ++i) {
if (dep_variables_[i].is_z()) (*z)[dep_variables_[i].index()] = q_prime[i];
}
return true;
}
// Computes the blocking index using the minimum ratio test. Returns `true`
// if successful, `false` if not (due to, e.g., the driving variable being
// "unblocked" or a cycle being detected). If `false`, `blocking_index` will
// set to -1 on return.
template <typename T>
bool UnrevisedLemkeSolver<T>::FindBlockingIndex(const T& zero_tol,
const VectorX<T>& matrix_col,
const VectorX<T>& ratios,
int* blocking_index) const {
DRAKE_DEMAND(blocking_index != nullptr);
DRAKE_DEMAND(ratios.size() == matrix_col.size());
DRAKE_DEMAND(zero_tol > 0);
const int n = matrix_col.size();
T min_ratio = std::numeric_limits<double>::infinity();
*blocking_index = -1;
for (int i = 0; i < n; ++i) {
if (matrix_col[i] < -zero_tol) {
DRAKE_LOGGER_DEBUG("Ratio for index {}: {}", i, ratios[i]);
if (ratios[i] < min_ratio) {
min_ratio = ratios[i];
*blocking_index = i;
}
}
}
if (*blocking_index < 0) {
DRAKE_LOGGER_DEBUG("driving variable is unblocked- algorithm failed");
return false;
}
// Determine all variables within the zero tolerance of the minimum ratio,
// while simultaneously looking for the presence of the artificial variable
// among the (possible multiple) minima.
std::vector<int> blocking_indices;
for (int i = 0; i < n; ++i) {
if (matrix_col[i] < -zero_tol) {
DRAKE_LOGGER_DEBUG("Ratio for index {}: {}", i, ratios[i]);
if (ratios[i] < min_ratio + zero_tol) {
if (IsArtificial(dep_variables_[i])) {
// *Always* select the artificial variable, if multiple choices are
// possible ([Cottle 1992] p. 280).
*blocking_index = i;
return true;
}
blocking_indices.push_back(i);
}
}
}
// If there are multiple blocking variables, replace the blocking index with
// the cycling selection.
if (blocking_indices.size() > 1) {
auto& index = selections_[indep_variables_];
// Verify that we have not run out of indices to select, which means that
// cycling would be occurring, in spite of cycling prevention.
if (index >= static_cast<int>(blocking_indices.size())) {
DRAKE_LOGGER_DEBUG("Cycling detected- indicating failure.");
*blocking_index = -1;
return false;
}
*blocking_index = blocking_indices[index];
++index;
}
return true;
}
template <typename T>
bool UnrevisedLemkeSolver<T>::IsSolution(const MatrixX<T>& M,
const VectorX<T>& q,
const VectorX<T>& z, T zero_tol) {
using std::abs;
const T mod_zero_tol = (zero_tol > 0) ? zero_tol : ComputeZeroTolerance(M);
// Find the minima of z and w.
const T min_z = z.minCoeff();
const auto w = M * z + q;
const T min_w = w.minCoeff();
// Compute the dot product of z and w.
const T dot = w.dot(z);
const int n = q.size();
return (min_z > -mod_zero_tol && min_w > -mod_zero_tol &&
abs(dot) < 10 * n * mod_zero_tol);
}
// Note: maintainers should read Section 4.4 - 4.4.5 of [Cottle 1992] to
// understand Lemke's Algorithm (and this function).
template <typename T>
bool UnrevisedLemkeSolver<T>::SolveLcpLemke(const MatrixX<T>& M,
const VectorX<T>& q, VectorX<T>* z,
int* num_pivots,
const T& zero_tol) const {
using std::abs;
using std::max;
DRAKE_DEMAND(num_pivots != nullptr);
DRAKE_LOGGER_DEBUG(
"UnrevisedLemkeSolver::SolveLcpLemke() entered, M: {}, "
"q: {}, ",
fmt_eigen(M), fmt_eigen(q.transpose()));
const int n = q.size();
const int max_pivots = 50 * n; // O(n) pivots expected for solvable problems.
if (M.rows() != n || M.cols() != n)
throw std::logic_error("M's dimensions do not match that of q.");
// Update the pivots.
*num_pivots = 0;
// Look for immediate exit.
if (n == 0) {
DRAKE_LOGGER_DEBUG("-- LCP is zero dimensional");
z->resize(0);
return true;
}
// Denote the index of the artificial variable (i.e., the variable denoted
// z₀ in [Cottle 1992], p. 266). Because z₀ is prone to being confused with
// the first dimension of z in 0-indexed languages like C++, we refer to the
// artificial variable as zₙ in this implementation (it is denoted zₙ₊₁ in
// [Dai 2018], as that document uses the 1-indexing prevalent in algorithmic
// descriptions).
const int kArtificial = n;
// Compute 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);
// Checks to see whether the trivial solution z = 0 to the LCP w = Mz + q
// solves the LCP. This must be the case if q is non-negative, as w would then
// be non-negative, z would be non-negative (zero), and w'z = 0.
if (q.minCoeff() > -mod_zero_tol) {
z->setZero(q.size());
DRAKE_LOGGER_DEBUG(" -- trivial solution found");
DRAKE_LOGGER_DEBUG("UnrevisedLemkeSolver::SolveLcpLemke() exited");
return true;
}
// Clear the cycling selections.
selections_.clear();
// If 'n' is identical to the size of the last problem solved, try using the
// indices from the last problem solved.
if (static_cast<size_t>(n) == dep_variables_.size()) {
// Verify that the last call found a solution (indicated by the presence
// of the artificial variable (zn) in the independent set).
int zn_index = -1;
for (int i = 0;
i < static_cast<int>(indep_variables_.size()) && zn_index < 0; ++i) {
if (IsArtificial(indep_variables_[i])) zn_index = i;
}
if (zn_index >= 0) {
// Compute the candidate solution.
if (ConstructLemkeSolution(M, q, zn_index, mod_zero_tol, z)) {
if (IsSolution(M, q, *z, mod_zero_tol)) {
// If z truly is the solution, return now, indicating only one pivot
// (in the solution construction) was performed.
++(*num_pivots);
return true;
}
} else {
DRAKE_LOGGER_DEBUG(
"Failed to solve linear system implied by last solution");
}
}
}
// Set the LCP variables. Start with all z variables independent and all w
// variables dependent.
indep_variables_.resize(n + 1);
dep_variables_.resize(n);
for (int i = 0; i < n; ++i) {
dep_variables_[i] = LCPVariable(false, i);
indep_variables_[i] = LCPVariable(true, i);
}
// z needs one more variable (the artificial variable), whose index we
// denote as n to keep it from corresponding to any actual vector index.
indep_variables_[n] = LCPVariable(true, n);
// Compute zn*, the smallest value of the artificial variable zn for which
// w = q + zn >= 0. Let blocking denote a component of w that equals
// zero when zn = zn*.
int blocking_index = -1;
bool blocking_index_found =
FindBlockingIndex(mod_zero_tol, q, q, &blocking_index);
DRAKE_DEMAND(blocking_index_found);
// Pivot blocking, artificial. Note that we rely upon the dependent variables
// being ordered sequentially in both arrays.
LCPVariable blocking = dep_variables_[blocking_index];
int driving_index = blocking.index();
std::swap(dep_variables_[blocking_index], indep_variables_[kArtificial]);
DRAKE_LOGGER_DEBUG("First blocking variable {}{}",
((blocking.is_z()) ? "z" : "w"), blocking.index());
DRAKE_LOGGER_DEBUG("First driving variable (artificial)");
// Initialize the independent variable indices. We do this after the initial
// variable swap for simplicity.
for (int i = 0; i < static_cast<int>(indep_variables_.size()); ++i)
indep_variables_indices_[indep_variables_[i]] = i;
// Output the independent and dependent variable tuples.
auto to_string = [](const std::vector<LCPVariable>& vars) -> std::string {
std::ostringstream oss;
for (int i = 0; i < static_cast<int>(vars.size()); ++i)
oss << ((vars[i].is_z()) ? "z" : "w") << vars[i].index() << " ";
return oss.str();
};
unused(to_string); // ... when in release mode.
DRAKE_LOGGER_DEBUG("Independent set variables: {}",
to_string(indep_variables_));
DRAKE_LOGGER_DEBUG("Dependent set variables: {}", to_string(dep_variables_));
// Pivot up to the maximum number of times.
VectorX<T> q_prime(n), M_prime_col(n);
while (++(*num_pivots) < max_pivots) {
DRAKE_LOGGER_DEBUG("New driving variable {}{}",
((indep_variables_[driving_index].is_z()) ? "z" : "w"),
indep_variables_[driving_index].index());
// Compute the permuted q and driving column of the permuted M matrix.
if (!LemkePivot(M, q, driving_index, mod_zero_tol, &M_prime_col,
&q_prime)) {
DRAKE_LOGGER_DEBUG("Linear system solve failed.");
z->setZero(n);
return false;
}
// Find the blocking variable.
if (!FindBlockingIndex(mod_zero_tol, M_prime_col,
-(q_prime.array() / M_prime_col.array()).matrix(),
&blocking_index)) {
z->setZero(n);
return false;
}
blocking = dep_variables_[blocking_index];
DRAKE_LOGGER_DEBUG("Blocking variable {}{}",
((blocking.is_z()) ? "z" : "w"), blocking.index());
// See whether the artificial variable blocks the driving variable.
if (blocking.index() == kArtificial) {
DRAKE_DEMAND(blocking.is_z());
// Pivot zn with the driving variable.
std::swap(dep_variables_[blocking_index],
indep_variables_[driving_index]);
// Compute the permuted q, and convert it into a solution.
if (ConstructLemkeSolution(M, q, driving_index, mod_zero_tol, z)) {
if (IsSolution(M, q, *z)) return true;
DRAKE_LOGGER_DEBUG("Solution not computed to requested tolerance");
z->setZero(n);
return false;
}
// Otherwise, indicate failure.
DRAKE_LOGGER_DEBUG(
"Linear system solver failed to construct Lemke solution");
z->setZero(n);
return false;
}
// Pivot the blocking variable and the driving variable.
std::swap(dep_variables_[blocking_index], indep_variables_[driving_index]);
// Update the index map.
auto indep_variables_indices_iter =
indep_variables_indices_.find(dep_variables_[blocking_index]);
indep_variables_indices_.erase(indep_variables_indices_iter);
indep_variables_indices_[indep_variables_[driving_index]] = driving_index;
// Make the driving variable the complement of the blocking variable.
driving_index = FindComplementIndex(blocking);
DRAKE_LOGGER_DEBUG("Independent set variables: {}",
to_string(indep_variables_));
DRAKE_LOGGER_DEBUG("Dependent set variables: {}",
to_string(dep_variables_));
}
// If here, the maximum number of pivots has been exceeded.
z->setZero(n);
DRAKE_LOGGER_DEBUG("Maximum number of pivots exceeded");
return false;
}
template <typename T>
UnrevisedLemkeSolver<T>::UnrevisedLemkeSolver()
: SolverBase(id(), &is_available, &is_enabled,
&ProgramAttributesSatisfied) {}
template <typename T>
UnrevisedLemkeSolver<T>::~UnrevisedLemkeSolver() = default;
SolverId UnrevisedLemkeSolverId::id() {
static const never_destroyed<SolverId> singleton{"Unrevised Lemke"};
return singleton.access();
}
template <typename T>
SolverId UnrevisedLemkeSolver<T>::id() {
return UnrevisedLemkeSolverId::id();
}
template <typename T>
bool UnrevisedLemkeSolver<T>::is_available() {
return true;
}
template <typename T>
bool UnrevisedLemkeSolver<T>::is_enabled() {
return true;
}
template <typename T>
bool UnrevisedLemkeSolver<T>::ProgramAttributesSatisfied(
const MathematicalProgram& prog) {
// This solver 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;
}
} // namespace solvers
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS(
class ::drake::solvers::UnrevisedLemkeSolver)
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solve.h | #pragma once
#include <optional>
#include <string>
#include <vector>
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mathematical_program_result.h"
#include "drake/solvers/solver_base.h"
namespace drake {
namespace solvers {
/**
* Solves an optimization program, with optional initial guess and solver
* options. This function first chooses the best solver depending on the
* availability of the solver and the program formulation; it then constructs
* that solver and call the Solve function of that solver. The optimization
* result is stored in the return argument.
* @param prog Contains the formulation of the program, and possibly solver
* options.
* @param initial_guess The initial guess for the decision variables.
* @param solver_options The options in addition to those stored in @p prog.
* For each option entry (like print out), there are 4 ways to set that option,
* and the priority given to the solver options is as follows (from lowest /
* least, to highest / most):
* 1. common option set on the MathematicalProgram itself
* 2. common option passed as an argument to Solve
* 3. solver-specific option set on the MathematicalProgram itself
* 4. solver-specific option passed as an argument to Solve
* @return result The result of solving the program through the solver.
*/
MathematicalProgramResult Solve(
const MathematicalProgram& prog,
const std::optional<Eigen::VectorXd>& initial_guess,
const std::optional<SolverOptions>& solver_options);
/**
* Solves an optimization program with a given initial guess.
*/
MathematicalProgramResult Solve(
const MathematicalProgram& prog,
const Eigen::Ref<const Eigen::VectorXd>& initial_guess);
MathematicalProgramResult Solve(const MathematicalProgram& prog);
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_binary",
"drake_cc_googletest",
"drake_cc_library",
"drake_cc_package_library",
"drake_cc_test",
)
load(
"//tools/skylark:drake_py.bzl",
"drake_py_unittest",
)
load(
"//tools/skylark:test_tags.bzl",
"gurobi_test_tags",
"mosek_test_tags",
)
load(
":defs.bzl",
"drake_cc_optional_googletest",
"drake_cc_optional_library",
"drake_cc_variant_library",
)
package(default_visibility = ["//visibility:public"])
drake_cc_package_library(
name = "solvers",
visibility = ["//visibility:public"],
deps = [
":aggregate_costs_constraints",
":augmented_lagrangian",
":binding",
":branch_and_bound",
":choose_best_solver",
":clarabel_solver",
":clp_solver",
":constraint",
":cost",
":create_constraint",
":create_cost",
":csdp_solver",
":decision_variable",
":equality_constrained_qp_solver",
":evaluator_base",
":function",
":get_program_type",
":gurobi_solver",
":indeterminate",
":integer_inequality_solver",
":integer_optimization_util",
":ipopt_solver",
":linear_system_solver",
":mathematical_program",
":mathematical_program_result",
":minimum_value_constraint",
":mixed_integer_optimization_util",
":mixed_integer_rotation_constraint",
":moby_lcp_solver",
":mosek_solver",
":nlopt_solver",
":non_convex_optimization_util",
":osqp_solver",
":program_attribute",
":rotation_constraint",
":scs_clarabel_common",
":scs_solver",
":sdpa_free_format",
":semidefinite_relaxation",
":semidefinite_relaxation_internal",
":snopt_solver",
":solution_result",
":solve",
":solver_base",
":solver_id",
":solver_interface",
":solver_options",
":solver_type",
":solver_type_converter",
":sos_basis_generator",
":sparse_and_dense_matrix",
":unrevised_lemke_solver",
],
)
drake_cc_library(
name = "augmented_lagrangian",
srcs = ["augmented_lagrangian.cc"],
hdrs = ["augmented_lagrangian.h"],
interface_deps = [
":mathematical_program",
],
deps = [
":aggregate_costs_constraints",
],
)
drake_cc_library(
name = "integer_inequality_solver",
srcs = ["integer_inequality_solver.cc"],
hdrs = ["integer_inequality_solver.h"],
interface_deps = [
"@eigen",
],
deps = [
"//common:essential",
],
)
drake_cc_library(
name = "sos_basis_generator",
srcs = ["sos_basis_generator.cc"],
hdrs = ["sos_basis_generator.h"],
interface_deps = [
"//common/symbolic:expression",
"//common/symbolic:polynomial",
],
deps = [
":integer_inequality_solver",
],
)
drake_cc_library(
name = "binding",
srcs = [],
hdrs = ["binding.h"],
interface_deps = [
":decision_variable",
":evaluator_base",
],
deps = [],
)
drake_cc_library(
name = "choose_best_solver",
srcs = ["choose_best_solver.cc"],
hdrs = ["choose_best_solver.h"],
interface_deps = [
":mathematical_program",
":solver_id",
":solver_interface",
],
deps = [
":clarabel_solver",
":clp_solver",
":csdp_solver",
":equality_constrained_qp_solver",
":get_program_type",
":gurobi_solver",
":ipopt_solver",
":linear_system_solver",
":moby_lcp_solver",
":mosek_solver",
":nlopt_solver",
":osqp_solver",
":scs_solver",
":snopt_solver",
"@abseil_cpp_internal//absl/container:inlined_vector",
],
)
drake_cc_library(
name = "evaluator_base",
srcs = ["evaluator_base.cc"],
hdrs = ["evaluator_base.h"],
interface_deps = [
"//common:essential",
"//common:polynomial",
"//common/symbolic:expression",
"//math:autodiff",
":function",
],
deps = [
"//common:nice_type_name",
"//common/symbolic:latex",
],
)
drake_cc_library(
name = "constraint",
srcs = ["constraint.cc"],
hdrs = ["constraint.h"],
interface_deps = [
":decision_variable",
":evaluator_base",
":sparse_and_dense_matrix",
"//common:essential",
"//common:polynomial",
"//common/symbolic:expression",
],
deps = [
"//common/symbolic:latex",
"//common/symbolic:polynomial",
"//math:gradient",
"//math:matrix_util",
],
)
drake_cc_library(
name = "minimum_value_constraint",
srcs = ["minimum_value_constraint.cc"],
hdrs = ["minimum_value_constraint.h"],
interface_deps = [
":constraint",
],
deps = [
"//math:gradient",
"//math:soft_min_max",
],
)
drake_cc_library(
name = "cost",
srcs = ["cost.cc"],
hdrs = ["cost.h"],
interface_deps = [
":decision_variable",
":evaluator_base",
":sparse_and_dense_matrix",
],
deps = [
":constraint",
"//common/symbolic:latex",
"//math:gradient",
],
)
drake_cc_library(
name = "create_constraint",
srcs = ["create_constraint.cc"],
hdrs = ["create_constraint.h"],
interface_deps = [
"//common/symbolic:expression",
":binding",
":constraint",
],
deps = [
"//common/symbolic:polynomial",
"//math:quadratic_form",
],
)
drake_cc_library(
name = "create_cost",
srcs = ["create_cost.cc"],
hdrs = ["create_cost.h"],
interface_deps = [
":binding",
":cost",
"//common/symbolic:expression",
],
deps = [
"//common:polynomial",
"//common:unused",
"//common/symbolic:polynomial",
],
)
drake_cc_library(
name = "decision_variable",
srcs = ["decision_variable.cc"],
hdrs = ["decision_variable.h"],
interface_deps = [
"//common/symbolic:expression",
],
deps = [],
)
drake_cc_library(
name = "function",
srcs = [],
hdrs = ["function.h"],
interface_deps = [
"//common:essential",
],
deps = [],
)
drake_cc_library(
name = "get_program_type",
srcs = ["get_program_type.cc"],
hdrs = ["get_program_type.h"],
interface_deps = [
":mathematical_program",
],
deps = [],
)
drake_cc_library(
name = "solver_type",
hdrs = ["solver_type.h"],
)
drake_cc_library(
name = "solver_id",
srcs = ["solver_id.cc"],
hdrs = ["solver_id.h"],
deps = [
"//common:essential",
"//common:hash",
"//common:reset_after_move",
],
)
drake_cc_library(
name = "solver_options",
srcs = [
"common_solver_option.cc",
"solver_options.cc",
],
hdrs = [
"common_solver_option.h",
"solver_options.h",
],
interface_deps = [
":solver_id",
],
deps = [],
)
drake_cc_library(
name = "indeterminate",
srcs = ["indeterminate.cc"],
hdrs = ["indeterminate.h"],
interface_deps = [
"//common/symbolic:expression",
],
deps = [
"//solvers:decision_variable",
],
)
drake_cc_library(
name = "solver_type_converter",
srcs = ["solver_type_converter.cc"],
hdrs = ["solver_type_converter.h"],
interface_deps = [
":solver_id",
":solver_type",
"//common:essential",
],
deps = [
":clp_solver",
":csdp_solver",
":equality_constrained_qp_solver",
":gurobi_solver",
":ipopt_solver",
":linear_system_solver",
":moby_lcp_solver",
":mosek_solver",
":nlopt_solver",
":osqp_solver",
":scs_solver",
":snopt_solver",
":unrevised_lemke_solver",
],
)
drake_cc_library(
name = "mathematical_program",
srcs = ["mathematical_program.cc"],
hdrs = ["mathematical_program.h"],
interface_deps = [
":binding",
":create_constraint",
":create_cost",
":decision_variable",
":function",
":indeterminate",
":program_attribute",
":solver_options",
"//common:autodiff",
"//common:essential",
"//common:polynomial",
"//common/symbolic:expression",
"//common/symbolic:monomial_util",
"//common/symbolic:polynomial",
],
deps = [
":sos_basis_generator",
"//common/symbolic:latex",
"//math:matrix_util",
],
)
drake_cc_library(
name = "mathematical_program_result",
srcs = ["mathematical_program_result.cc"],
hdrs = ["mathematical_program_result.h"],
interface_deps = [
":binding",
":constraint",
":mathematical_program",
":solution_result",
":solver_id",
"//common:value",
"//common/symbolic:expression",
],
deps = [],
)
drake_cc_library(
name = "solver_interface",
srcs = ["solver_interface.cc"],
hdrs = ["solver_interface.h"],
interface_deps = [
":mathematical_program",
":mathematical_program_result",
":solution_result",
":solver_id",
":solver_options",
"//common:essential",
],
deps = [],
)
drake_cc_library(
name = "aggregate_costs_constraints",
srcs = ["aggregate_costs_constraints.cc"],
hdrs = ["aggregate_costs_constraints.h"],
interface_deps = [
":binding",
":mathematical_program",
],
deps = [
"//math:eigen_sparse_triplet",
],
)
drake_cc_library(
name = "branch_and_bound",
srcs = ["branch_and_bound.cc"],
hdrs = ["branch_and_bound.h"],
interface_deps = [
":mathematical_program",
":mathematical_program_result",
"//common:name_value",
],
deps = [
":choose_best_solver",
":gurobi_solver",
":scs_solver",
],
)
drake_cc_library(
name = "non_convex_optimization_util",
srcs = ["non_convex_optimization_util.cc"],
hdrs = ["non_convex_optimization_util.h"],
interface_deps = [
":mathematical_program",
],
deps = [
":solve",
"//math:quadratic_form",
],
)
drake_cc_library(
name = "integer_optimization_util",
srcs = ["integer_optimization_util.cc"],
hdrs = ["integer_optimization_util.h"],
interface_deps = [
":binding",
":constraint",
],
deps = [
":create_constraint",
],
)
drake_cc_library(
name = "rotation_constraint",
srcs = ["rotation_constraint.cc"],
hdrs = ["rotation_constraint.h"],
interface_deps = [
":mathematical_program",
],
deps = [],
)
drake_cc_library(
name = "mixed_integer_rotation_constraint",
srcs = [
"mixed_integer_rotation_constraint.cc",
"mixed_integer_rotation_constraint_internal.cc",
],
hdrs = [
"mixed_integer_rotation_constraint.h",
"mixed_integer_rotation_constraint_internal.h",
],
interface_deps = [
":mathematical_program",
":mixed_integer_optimization_util",
],
deps = [
":integer_optimization_util",
":solve",
"//common/symbolic:replace_bilinear_terms",
"//math:gray_code",
],
)
drake_cc_library(
name = "program_attribute",
srcs = ["program_attribute.cc"],
hdrs = ["program_attribute.h"],
interface_deps = [
"//common:hash",
],
deps = [],
)
drake_cc_library(
name = "sparse_and_dense_matrix",
srcs = ["sparse_and_dense_matrix.cc"],
hdrs = ["sparse_and_dense_matrix.h"],
interface_deps = [
"//common:essential",
],
deps = [],
)
drake_cc_library(
name = "rotation_constraint_visualization",
testonly = 1,
srcs = ["test/rotation_constraint_visualization.cc"],
hdrs = ["test/rotation_constraint_visualization.h"],
deps = [
":mixed_integer_rotation_constraint",
":rotation_constraint",
"//common/proto:call_python",
],
)
drake_cc_library(
name = "add_solver_util",
testonly = 1,
srcs = ["test/add_solver_util.cc"],
hdrs = ["test/add_solver_util.h"],
deps = [
":mathematical_program",
":solver_interface",
],
)
drake_cc_library(
name = "generic_trivial_cost",
testonly = 1,
srcs = [],
hdrs = ["test/generic_trivial_costs.h"],
deps = [
":constraint",
":cost",
],
)
drake_cc_library(
name = "generic_trivial_constraint",
testonly = 1,
srcs = [],
hdrs = ["test/generic_trivial_constraints.h"],
deps = [
":constraint",
],
)
drake_cc_googletest(
name = "indeterminate_test",
deps = [
":indeterminate",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_library(
name = "mathematical_program_test_util",
testonly = 1,
srcs = ["test/mathematical_program_test_util.cc"],
hdrs = ["test/mathematical_program_test_util.h"],
deps = [
":mathematical_program",
":solver_interface",
"@gtest//:without_main",
],
)
drake_cc_library(
name = "optimization_examples",
testonly = 1,
srcs = ["test/optimization_examples.cc"],
hdrs = ["test/optimization_examples.h"],
deps = [
":clarabel_solver",
":clp_solver",
":gurobi_solver",
":ipopt_solver",
":mathematical_program",
":mathematical_program_test_util",
":mosek_solver",
":nlopt_solver",
":osqp_solver",
":scs_solver",
":snopt_solver",
":solver_type_converter",
"//common/test_utilities:eigen_matrix_compare",
"@gtest//:without_main",
],
)
drake_cc_library(
name = "linear_program_examples",
testonly = 1,
srcs = ["test/linear_program_examples.cc"],
hdrs = ["test/linear_program_examples.h"],
deps = [
":ipopt_solver",
":mosek_solver",
":optimization_examples",
":solver_interface",
],
)
drake_cc_library(
name = "quadratic_program_examples",
testonly = 1,
srcs = ["test/quadratic_program_examples.cc"],
hdrs = ["test/quadratic_program_examples.h"],
deps = [
":gurobi_solver",
":mosek_solver",
":optimization_examples",
":scs_solver",
":snopt_solver",
],
)
drake_cc_library(
name = "quadratic_constrained_program_examples",
testonly = 1,
srcs = ["test/quadratic_constrained_program_examples.cc"],
hdrs = ["test/quadratic_constrained_program_examples.h"],
deps = [
":mathematical_program",
":mosek_solver",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"@gtest//:without_main",
],
)
drake_cc_library(
name = "second_order_cone_program_examples",
testonly = 1,
srcs = ["test/second_order_cone_program_examples.cc"],
hdrs = ["test/second_order_cone_program_examples.h"],
deps = [
":mathematical_program_test_util",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_library(
name = "l2norm_cost_examples",
testonly = 1,
srcs = ["test/l2norm_cost_examples.cc"],
hdrs = ["test/l2norm_cost_examples.h"],
deps = [
":mathematical_program_test_util",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_library(
name = "semidefinite_program_examples",
testonly = 1,
srcs = ["test/semidefinite_program_examples.cc"],
hdrs = ["test/semidefinite_program_examples.h"],
deps = [
":mathematical_program_test_util",
"//common/test_utilities:eigen_matrix_compare",
"//math:matrix_util",
],
)
drake_cc_library(
name = "sos_examples",
testonly = 1,
srcs = ["test/sos_examples.cc"],
hdrs = ["test/sos_examples.h"],
deps = [
":mathematical_program",
":mathematical_program_result",
"//common/test_utilities:symbolic_test_util",
"@gtest//:without_main",
],
)
drake_cc_library(
name = "exponential_cone_program_examples",
testonly = 1,
srcs = ["test/exponential_cone_program_examples.cc"],
hdrs = ["test/exponential_cone_program_examples.h"],
deps = [
":mathematical_program_test_util",
":solver_interface",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_library(
name = "solution_result",
srcs = ["solution_result.cc"],
hdrs = ["solution_result.h"],
deps = [
"//common:essential",
],
)
drake_cc_library(
name = "solver_base",
srcs = ["solver_base.cc"],
hdrs = ["solver_base.h"],
interface_deps = [
":mathematical_program",
":solver_interface",
],
deps = [],
)
drake_cc_library(
name = "solve",
srcs = ["solve.cc"],
hdrs = ["solve.h"],
interface_deps = [
":mathematical_program",
":mathematical_program_result",
":solver_base",
],
deps = [
":choose_best_solver",
"//common:nice_type_name",
],
)
# Internal Solvers.
drake_cc_library(
name = "equality_constrained_qp_solver",
srcs = ["equality_constrained_qp_solver.cc"],
hdrs = ["equality_constrained_qp_solver.h"],
interface_deps = [
":solver_base",
"//common:essential",
],
deps = [
":mathematical_program",
],
)
drake_cc_library(
name = "linear_system_solver",
srcs = ["linear_system_solver.cc"],
hdrs = ["linear_system_solver.h"],
interface_deps = [
":solver_base",
"//common:essential",
],
deps = [
":mathematical_program",
],
)
drake_cc_library(
name = "unrevised_lemke_solver",
srcs = ["unrevised_lemke_solver.cc"],
hdrs = ["unrevised_lemke_solver.h"],
interface_deps = [
":mathematical_program",
":solver_base",
"//common:essential",
],
deps = [
"//common:default_scalars",
],
)
drake_cc_library(
name = "moby_lcp_solver",
srcs = ["moby_lcp_solver.cc"],
hdrs = ["moby_lcp_solver.h"],
interface_deps = [
":mathematical_program",
":solver_base",
"//common:essential",
],
deps = [],
)
# External Solvers.
# If --config gurobi is used, this target builds object code that satisfies
# SolverInterface by calling Gurobi. Otherwise, this target builds dummy object
# code that fails at runtime.
drake_cc_variant_library(
name = "gurobi_solver",
opt_in_condition = "//tools:with_gurobi",
srcs_always = ["gurobi_solver_common.cc"],
srcs_enabled = ["gurobi_solver.cc"],
srcs_disabled = ["no_gurobi.cc"],
hdrs = ["gurobi_solver.h"],
interface_deps = [
":solver_base",
],
deps_always = [
":aggregate_costs_constraints",
":mathematical_program",
],
deps_enabled = [
":gurobi_solver_internal",
"//math:eigen_sparse_triplet",
"//common:find_resource",
"//common:scope_exit",
"//common:scoped_singleton",
"@gurobi//:gurobi_c",
"@fmt",
],
)
drake_cc_optional_library(
name = "gurobi_solver_internal",
opt_in_condition = "//tools:with_gurobi",
srcs = ["gurobi_solver_internal.cc"],
hdrs = ["gurobi_solver_internal.h"],
interface_deps = [":mathematical_program_result"],
deps = [
":aggregate_costs_constraints",
":mathematical_program",
"//math:quadratic_form",
"@gurobi//:gurobi_c",
],
)
# If --config mosek is used, this target builds object code that satisfies
# SolverInterface by calling MOSEK. Otherwise, this target builds dummy object
# code that fails at runtime.
drake_cc_variant_library(
name = "mosek_solver",
opt_in_condition = "//tools:with_mosek",
srcs_always = ["mosek_solver_common.cc"],
srcs_enabled = ["mosek_solver.cc"],
srcs_disabled = ["no_mosek.cc"],
hdrs = ["mosek_solver.h"],
interface_deps = [
":mathematical_program_result",
":solver_base",
],
deps_always = [
":aggregate_costs_constraints",
":mathematical_program",
],
deps_enabled = [
":mosek_solver_internal",
"//common:scoped_singleton",
"//common:scope_exit",
"@mosek",
],
)
drake_cc_optional_library(
name = "mosek_solver_internal",
opt_in_condition = "//tools:with_mosek",
srcs = ["mosek_solver_internal.cc"],
hdrs = ["mosek_solver_internal.h"],
interface_deps = [":mathematical_program_result"],
deps = [
":aggregate_costs_constraints",
":mathematical_program",
"//math:quadratic_form",
"@mosek",
],
)
# If --config snopt is used, this target builds object code that satisfies
# SolverInterface by calling SNOPT. Otherwise, this target builds dummy object
# code that fails at runtime.
drake_cc_variant_library(
name = "snopt_solver",
opt_in_condition = "//tools:with_snopt",
srcs_always = ["snopt_solver_common.cc"],
srcs_enabled = ["snopt_solver.cc"],
srcs_disabled = ["no_snopt.cc"],
hdrs = ["snopt_solver.h"],
interface_deps = [
":solver_base",
],
deps_always = [
":mathematical_program",
],
deps_enabled = [
"//common:scope_exit",
"//math:autodiff",
"@snopt//:snopt_cwrap",
],
)
drake_cc_variant_library(
name = "clp_solver",
opt_out_condition = "//tools:no_clp",
srcs_always = ["clp_solver_common.cc"],
srcs_enabled = ["clp_solver.cc"],
srcs_disabled = ["no_clp.cc"],
hdrs = ["clp_solver.h"],
interface_deps = [
":solver_base",
],
deps_always = [
":aggregate_costs_constraints",
":mathematical_program",
],
deps_enabled = [
"@clp_internal//:clp",
"//common:unused",
"//math:autodiff",
],
)
drake_cc_optional_library(
name = "ipopt_solver_internal",
opt_out_condition = "//tools:no_ipopt",
srcs = ["ipopt_solver_internal.cc"],
hdrs = ["ipopt_solver_internal.h"],
deps = [
":mathematical_program",
":mathematical_program_result",
"//common:drake_export",
"@ipopt",
],
)
drake_cc_variant_library(
name = "ipopt_solver",
opt_out_condition = "//tools:no_ipopt",
srcs_always = ["ipopt_solver_common.cc"],
srcs_enabled = [
"ipopt_solver.cc",
],
srcs_disabled = ["no_ipopt.cc"],
hdrs = [
"ipopt_solver.h",
],
interface_deps = [
":solver_base",
],
deps_always = [
":mathematical_program",
],
deps_enabled = [
":ipopt_solver_internal",
"@ipopt",
"//common:unused",
"//math:autodiff",
],
)
drake_cc_variant_library(
name = "nlopt_solver",
opt_out_condition = "//tools:no_nlopt",
srcs_always = ["nlopt_solver_common.cc"],
srcs_enabled = ["nlopt_solver.cc"],
srcs_disabled = ["no_nlopt.cc"],
hdrs = ["nlopt_solver.h"],
interface_deps = [
":solver_base",
],
deps_always = [
":mathematical_program",
],
deps_enabled = [
"//math:autodiff",
"@nlopt_internal//:nlopt",
],
)
drake_cc_variant_library(
name = "osqp_solver",
opt_out_condition = "//tools:no_osqp",
srcs_always = ["osqp_solver_common.cc"],
srcs_enabled = ["osqp_solver.cc"],
srcs_disabled = ["no_osqp.cc"],
hdrs = ["osqp_solver.h"],
interface_deps = [
":solver_base",
],
deps_always = [
":aggregate_costs_constraints",
":mathematical_program",
],
deps_enabled = [
"//math:eigen_sparse_triplet",
"@osqp_internal//:osqp",
],
)
drake_cc_variant_library(
name = "clarabel_solver",
opt_out_condition = "//tools:no_clarabel",
srcs_always = ["clarabel_solver_common.cc"],
srcs_enabled = ["clarabel_solver.cc"],
srcs_disabled = ["no_clarabel.cc"],
hdrs = ["clarabel_solver.h"],
interface_deps = [
":solver_base",
"//common:essential",
],
deps_always = [
":aggregate_costs_constraints",
":mathematical_program",
"//math:quadratic_form",
],
deps_enabled = [
":scs_clarabel_common",
"//math:eigen_sparse_triplet",
"//tools/workspace/clarabel_cpp_internal:serialize",
"@clarabel_cpp_internal//:clarabel_cpp",
],
)
drake_cc_library(
name = "scs_clarabel_common",
srcs = ["scs_clarabel_common.cc"],
hdrs = ["scs_clarabel_common.h"],
deps = [
":mathematical_program",
":mathematical_program_result",
],
)
drake_cc_variant_library(
name = "scs_solver",
opt_out_condition = "//tools:no_scs",
srcs_always = ["scs_solver_common.cc"],
srcs_enabled = ["scs_solver.cc"],
srcs_disabled = ["no_scs.cc"],
hdrs = ["scs_solver.h"],
interface_deps = [
":solver_base",
"//common:essential",
],
deps_always = [
":aggregate_costs_constraints",
":mathematical_program",
"//math:quadratic_form",
],
deps_enabled = [
":scs_clarabel_common",
"//common:scope_exit",
"//math:eigen_sparse_triplet",
"@scs_internal//:scsdir",
],
)
drake_cc_library(
name = "sdpa_free_format",
srcs = ["sdpa_free_format.cc"],
hdrs = ["sdpa_free_format.h"],
interface_deps = [
":mathematical_program",
"//common:type_safe_index",
],
deps = [],
)
drake_cc_library(
name = "semidefinite_relaxation",
srcs = ["semidefinite_relaxation.cc"],
hdrs = ["semidefinite_relaxation.h"],
interface_deps = [
":mathematical_program",
"//math:matrix_util",
],
)
drake_cc_library(
name = "semidefinite_relaxation_internal",
srcs = ["semidefinite_relaxation_internal.cc"],
hdrs = ["semidefinite_relaxation_internal.h"],
interface_deps = [
":mathematical_program",
"//math:matrix_util",
],
deps = [],
)
drake_cc_optional_library(
name = "csdp_solver_error_handling",
opt_out_condition = "//tools:no_csdp",
srcs = ["csdp_solver_error_handling.cc"],
hdrs = ["csdp_solver_error_handling.h"],
copts = ["-fvisibility=hidden"],
visibility = [
"@csdp//:__pkg__",
"@csdp_internal//:__pkg__",
],
)
drake_cc_optional_library(
name = "csdp_cpp_wrapper",
opt_out_condition = "//tools:no_csdp",
srcs = ["csdp_cpp_wrapper.cc"],
hdrs = ["csdp_cpp_wrapper.h"],
interface_deps = [
"@csdp_internal//:csdp",
],
deps = [
":csdp_solver_error_handling",
],
)
drake_cc_optional_library(
name = "csdp_solver_internal",
opt_out_condition = "//tools:no_csdp",
srcs = ["csdp_solver_internal.cc"],
hdrs = ["csdp_solver_internal.h"],
interface_deps = [
":csdp_cpp_wrapper",
":sdpa_free_format",
],
deps = [],
)
drake_cc_variant_library(
name = "csdp_solver",
opt_out_condition = "//tools:no_csdp",
srcs_always = ["csdp_solver_common.cc"],
srcs_enabled = ["csdp_solver.cc"],
srcs_disabled = ["no_csdp.cc"],
hdrs = ["csdp_solver.h"],
interface_deps = [
":solver_base",
":sdpa_free_format",
],
deps_always = [
":mathematical_program",
"//common:scope_exit",
],
deps_enabled = [
":csdp_solver_internal",
],
)
drake_cc_library(
name = "mixed_integer_optimization_util",
srcs = ["mixed_integer_optimization_util.cc"],
hdrs = ["mixed_integer_optimization_util.h"],
interface_deps = [
":mathematical_program",
],
deps = [
":integer_optimization_util",
"//math:gray_code",
],
)
# === test/ ===
drake_cc_googletest(
name = "binding_test",
deps = [
":binding",
":constraint",
":cost",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_googletest(
name = "branch_and_bound_test",
tags = gurobi_test_tags(),
deps = [
":branch_and_bound",
":gurobi_solver",
":mathematical_program_test_util",
":mixed_integer_optimization_util",
":scs_solver",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "evaluator_base_test",
deps = [
":evaluator_base",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:is_dynamic_castable",
"//math:gradient",
],
)
drake_cc_googletest(
name = "constraint_test",
deps = [
":constraint",
":generic_trivial_constraint",
"//common/symbolic:expression",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
"//common/test_utilities:symbolic_test_util",
"//math:gradient",
],
)
drake_cc_googletest(
name = "minimum_value_constraint_test",
deps = [
":minimum_value_constraint",
"//solvers/test_utilities",
],
)
# TODO(eric.cousineau): Remove dependence on create_cost
drake_cc_googletest(
name = "cost_test",
deps = [
":cost",
":create_cost",
":generic_trivial_cost",
"//common/symbolic:expression",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:is_dynamic_castable",
"//common/test_utilities:symbolic_test_util",
"//math:gradient",
],
)
drake_cc_googletest(
name = "complementary_problem_test",
tags = ["snopt"],
deps = [
":mathematical_program",
":snopt_solver",
":solve",
],
)
drake_cc_googletest(
name = "create_constraint_test",
deps = [
":create_constraint",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_library(
name = "csdp_test_examples",
testonly = 1,
srcs = ["test/csdp_test_examples.cc"],
hdrs = ["test/csdp_test_examples.h"],
deps = [
":mathematical_program",
"@gtest//:without_main",
],
)
drake_cc_googletest(
name = "sdpa_free_format_test",
deps = [
":csdp_solver_internal",
":csdp_test_examples",
":sdpa_free_format",
"//common:temp_directory",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "semidefinite_relaxation_test",
deps = [
":semidefinite_relaxation",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "semidefinite_relaxation_internal_test",
deps = [
":semidefinite_relaxation_internal",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
"//solvers:clarabel_solver",
"//solvers:csdp_solver",
"//solvers:mosek_solver",
"//solvers:scs_solver",
],
)
drake_cc_googletest(
name = "clp_solver_test",
deps = [
":clp_solver",
":linear_program_examples",
":quadratic_program_examples",
],
)
drake_cc_optional_googletest(
name = "csdp_solver_internal_test",
opt_out_condition = "//tools:no_csdp",
deps = [
":csdp_solver_internal",
":csdp_test_examples",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_optional_googletest(
name = "csdp_cpp_wrapper_test",
opt_out_condition = "//tools:no_csdp",
tags = [
# The longjmp handling definitely leaks memory, and we've decided to
# just live with that. If we see the longjmp handler triggering when
# called by CsdpSolver, we should fix MathematicalProgram or CsdpSolver
# to do more sanity checking before calling into CSDP. The longjmp
# handler should only serve as a last resort.
"no_lsan",
"no_memcheck",
],
deps = [
":csdp_cpp_wrapper",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "csdp_solver_test",
deps = [
":csdp_solver",
":csdp_test_examples",
":linear_program_examples",
":second_order_cone_program_examples",
":semidefinite_program_examples",
":sos_examples",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "decision_variable_test",
deps = [
":mathematical_program",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_googletest(
name = "equality_constrained_qp_solver_test",
deps = [
":equality_constrained_qp_solver",
":mathematical_program",
":mathematical_program_test_util",
":quadratic_program_examples",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "get_program_type_test",
deps = [
":get_program_type",
],
)
drake_cc_optional_googletest(
name = "gurobi_solver_internal_test",
opt_in_condition = "//tools:with_gurobi",
use_default_main = False,
deps = [
":gurobi_solver",
":gurobi_solver_internal",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:symbolic_test_util",
"//math:quadratic_form",
"@gurobi//:gurobi_c",
],
)
drake_cc_googletest(
name = "gurobi_solver_test",
tags = gurobi_test_tags(),
use_default_main = False,
deps = [
":gurobi_solver",
":l2norm_cost_examples",
":linear_program_examples",
":mathematical_program",
":mathematical_program_test_util",
":mixed_integer_optimization_util",
":quadratic_program_examples",
":second_order_cone_program_examples",
"//common:temp_directory",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "gurobi_solver_grb_license_file_test",
tags = gurobi_test_tags(),
deps = [
":gurobi_solver",
":mathematical_program",
"//common/test_utilities:expect_no_throw",
"//common/test_utilities:expect_throws_message",
],
)
drake_py_unittest(
name = "gurobi_solver_license_retention_test",
data = [
":gurobi_solver_license_retention_test_helper",
],
tags = gurobi_test_tags(),
)
drake_cc_binary(
name = "gurobi_solver_license_retention_test_helper",
testonly = True,
srcs = ["test/gurobi_solver_license_retention_test_helper.cc"],
visibility = ["//visibility:private"],
deps = [
":gurobi_solver",
],
)
drake_cc_googletest(
name = "integer_optimization_util_test",
deps = [
":integer_optimization_util",
":mathematical_program",
":osqp_solver",
":solve",
],
)
drake_cc_googletest(
name = "ipopt_solver_test",
copts = select({
"//conditions:default": [
"-DDRAKE_IPOPT_SOLVER_TEST_HAS_IPOPT=1",
],
"//tools:no_ipopt": [
],
}),
deps = [
":linear_program_examples",
":mathematical_program",
":mathematical_program_test_util",
":optimization_examples",
":quadratic_program_examples",
":second_order_cone_program_examples",
"//common:temp_directory",
"//common/test_utilities:eigen_matrix_compare",
] + select({
"//conditions:default": [
"@ipopt",
],
"//tools:no_ipopt": [
],
}),
)
drake_cc_googletest(
name = "linear_complementary_problem_test",
deps = [
":mathematical_program",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_no_throw",
],
)
drake_cc_googletest(
name = "linear_system_solver_test",
deps = [
":linear_system_solver",
":mathematical_program",
":mathematical_program_test_util",
":optimization_examples",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "mathematical_program_test",
deps = [
":generic_trivial_constraint",
":generic_trivial_cost",
":mathematical_program",
":mathematical_program_test_util",
":snopt_solver",
":solve",
"//common/symbolic:expression",
"//common/test_utilities",
"//math:matrix_util",
],
)
# TODO(hongkai-dai): Separate this test into a test that uses Gurobi, and a
# test that doesn't.
drake_cc_googletest(
name = "mixed_integer_optimization_test",
# This test uses Gurobi if present, but does not require it.
tags = gurobi_test_tags(),
deps = [
":add_solver_util",
":gurobi_solver",
":mathematical_program",
":mathematical_program_test_util",
":mosek_solver",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "moby_lcp_solver_test",
deps = [
":moby_lcp_solver",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "unrevised_lemke_solver_test",
deps = [
":mathematical_program",
":unrevised_lemke_solver",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_optional_googletest(
name = "mosek_solver_internal_test",
opt_in_condition = "//tools:with_mosek",
use_default_main = False,
deps = [
":mosek_solver",
":mosek_solver_internal",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:symbolic_test_util",
"//math:quadratic_form",
"@mosek",
],
)
drake_cc_googletest(
name = "mosek_solver_test",
tags = mosek_test_tags(),
use_default_main = False,
deps = [
":exponential_cone_program_examples",
":l2norm_cost_examples",
":linear_program_examples",
":mathematical_program",
":mathematical_program_test_util",
":mixed_integer_optimization_util",
":mosek_solver",
":quadratic_constrained_program_examples",
":quadratic_program_examples",
":second_order_cone_program_examples",
":semidefinite_program_examples",
":sos_examples",
"//common:temp_directory",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "mosek_solver_moseklm_license_file_test",
tags = mosek_test_tags(),
deps = [
":mathematical_program",
":mosek_solver",
"//common/test_utilities:expect_no_throw",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "nlopt_solver_test",
deps = [
":linear_program_examples",
":mathematical_program",
":mathematical_program_test_util",
":nlopt_solver",
":optimization_examples",
":quadratic_program_examples",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "non_convex_optimization_util_test",
# This test is quite long, so split it into 4 processes for better latency.
shard_count = 4,
tags = mosek_test_tags(),
deps = [
":decision_variable",
":non_convex_optimization_util",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_googletest(
name = "nonlinear_program_test",
deps = [
":mathematical_program",
":mathematical_program_test_util",
":optimization_examples",
"//common/test_utilities",
],
)
drake_cc_googletest(
name = "mixed_integer_rotation_constraint_test",
timeout = "long",
# This test is quite long, so split it into 4 processes for better latency.
shard_count = 4,
tags = gurobi_test_tags() + mosek_test_tags() + [
# Excluding asan and memcheck because it is unreasonably slow
# (> 30 minutes).
"no_asan",
"no_memcheck",
# Excluding tsan because an assertion fails in LLVM code. Issue #6179.
"no_tsan",
],
use_default_main = False,
deps = [
":gurobi_solver",
":integer_optimization_util",
":mathematical_program",
":mixed_integer_rotation_constraint",
":mosek_solver",
":rotation_constraint",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//math:geometric_transform",
"//math:gray_code",
],
)
drake_cc_googletest(
name = "mixed_integer_rotation_constraint_corner_test",
timeout = "long",
# This test is quite long, so split it into 4 processes for better latency.
shard_count = 4,
tags = gurobi_test_tags() + mosek_test_tags() + [
# Excluding asan because it is unreasonably slow (> 30 minutes).
"no_asan",
# Excluding tsan because an assertion fails in LLVM code. Issue #6179.
"no_tsan",
],
use_default_main = False,
deps = [
":integer_optimization_util",
":mathematical_program",
":mixed_integer_rotation_constraint",
":mosek_solver",
":rotation_constraint",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//math:gray_code",
],
)
drake_cc_googletest(
name = "rotation_constraint_test",
timeout = "long",
# This test is quite long, so split it into 4 processes for better latency.
shard_count = 4,
tags = gurobi_test_tags() + mosek_test_tags() + [
# Excluding asan because it is unreasonably slow (> 30 minutes).
"no_asan",
# Excluding tsan because an assertion fails in LLVM code. Issue #6179.
"no_tsan",
],
use_default_main = False,
deps = [
":gurobi_solver",
":mathematical_program",
":mosek_solver",
":rotation_constraint",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//math:geometric_transform",
],
)
drake_cc_googletest(
name = "osqp_solver_test",
deps = [
":mathematical_program",
":mathematical_program_test_util",
":osqp_solver",
":quadratic_program_examples",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_binary(
name = "plot_feasible_rotation_matrices",
testonly = 1,
srcs = ["test/plot_feasible_rotation_matrices.cc"],
deps = [
":mathematical_program",
":mixed_integer_rotation_constraint",
":rotation_constraint",
":solve",
"//common/proto:call_python",
],
)
drake_cc_googletest(
name = "program_attribute_test",
deps = [
":program_attribute",
],
)
drake_cc_googletest(
name = "mixed_integer_rotation_constraint_limit_test",
timeout = "long",
num_threads = 4,
tags = gurobi_test_tags() + [
# Times out with Valgrind
"no_memcheck",
# Excluding tsan because an assertion fails in LLVM code. Issue #6179.
"no_tsan",
],
deps = [
":gurobi_solver",
":mathematical_program",
":mixed_integer_rotation_constraint",
":rotation_constraint",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "clarabel_solver_test",
deps = [
":clarabel_solver",
":exponential_cone_program_examples",
":l2norm_cost_examples",
":linear_program_examples",
":mathematical_program",
":mathematical_program_test_util",
":quadratic_program_examples",
":second_order_cone_program_examples",
":semidefinite_program_examples",
":sos_examples",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "scs_solver_test",
deps = [
":exponential_cone_program_examples",
":l2norm_cost_examples",
":linear_program_examples",
":mathematical_program",
":mathematical_program_test_util",
":quadratic_program_examples",
":scs_solver",
":second_order_cone_program_examples",
":semidefinite_program_examples",
":sos_examples",
],
)
drake_cc_googletest(
name = "snopt_solver_test",
tags = [
# ThreadSanitizer: lock-order-inversion (potential deadlock) with
# snopt_fortran (#11657).
"no_tsan",
"snopt",
],
deps = [
":linear_program_examples",
":mathematical_program",
":mathematical_program_test_util",
":optimization_examples",
":quadratic_program_examples",
":second_order_cone_program_examples",
":snopt_solver",
"//common:find_resource",
"//common:temp_directory",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
"//math:geometric_transform",
],
)
drake_cc_googletest(
name = "solver_base_test",
deps = [
":mathematical_program",
":solver_base",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "solver_id_test",
deps = [
":solver_id",
"//common/test_utilities:limit_malloc",
],
)
drake_cc_googletest(
name = "solver_type_converter_test",
deps = [
":mathematical_program",
":solver_type_converter",
],
)
drake_cc_googletest(
name = "sos_constraint_test",
tags = mosek_test_tags(),
deps = [
":mathematical_program",
":solve",
":sos_basis_generator",
"//common/test_utilities",
],
)
drake_cc_googletest(
name = "sos_basis_generator_test",
deps = [
":mathematical_program",
":sos_basis_generator",
"//common/symbolic:monomial_util",
],
)
drake_cc_googletest(
name = "integer_inequality_solver_test",
deps = [
":integer_inequality_solver",
],
)
drake_cc_binary(
name = "plot_rotation_mccormick_envelope",
testonly = 1,
srcs = ["test/plot_rotation_mccormick_envelope.cc"],
deps = [
":rotation_constraint_visualization",
],
)
drake_cc_googletest(
name = "mixed_integer_optimization_util_test",
tags = gurobi_test_tags(gurobi_required = False),
deps = [
":gurobi_solver",
":mixed_integer_optimization_util",
"//common/test_utilities:eigen_matrix_compare",
"//math:gray_code",
],
)
drake_cc_googletest(
name = "mixed_integer_rotation_constraint_internal_test",
tags = mosek_test_tags() + gurobi_test_tags() + ["no_tsan"],
deps = [
":mathematical_program",
":mixed_integer_rotation_constraint",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//math:geometric_transform",
],
)
drake_cc_googletest(
name = "diagonally_dominant_matrix_test",
deps = [
":mathematical_program",
":snopt_solver",
":solve",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "diagonally_dominant_dual_cone_matrix_test",
deps = [
":mathematical_program",
":snopt_solver",
":solve",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "scaled_diagonally_dominant_matrix_test",
tags = gurobi_test_tags() + mosek_test_tags(),
deps = [
":mathematical_program",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_googletest(
name = "scaled_diagonally_dominant_dual_cone_matrix_test",
deps = [
":mathematical_program",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_googletest(
name = "mathematical_program_result_test",
deps = [
":cost",
":mathematical_program_result",
":osqp_solver",
":snopt_solver",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_googletest(
name = "choose_best_solver_test",
deps = [
":choose_best_solver",
":clarabel_solver",
":clp_solver",
":csdp_solver",
":equality_constrained_qp_solver",
":get_program_type",
":gurobi_solver",
":ipopt_solver",
":linear_system_solver",
":moby_lcp_solver",
":mosek_solver",
":nlopt_solver",
":osqp_solver",
":scs_solver",
":snopt_solver",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "solve_test",
deps = [
":choose_best_solver",
":gurobi_solver",
":linear_system_solver",
":scs_solver",
":snopt_solver",
":solve",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "aggregate_costs_constraints_test",
deps = [
":aggregate_costs_constraints",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:symbolic_test_util",
],
)
drake_cc_googletest(
name = "solver_options_test",
deps = [
":solver_options",
"//common/test_utilities:expect_no_throw",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "augmented_lagrangian_test",
deps = [
":aggregate_costs_constraints",
":augmented_lagrangian",
"//common/test_utilities:eigen_matrix_compare",
"//math:gradient",
],
)
drake_cc_googletest(
name = "sparse_and_dense_matrix_test",
tags = ["cpu:4"],
deps = [
":sparse_and_dense_matrix",
"//common/test_utilities:eigen_matrix_compare",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/csdp_solver.cc | #include "drake/solvers/csdp_solver.h"
#include <unistd.h>
#include <algorithm>
#include <csetjmp>
#include <cstdlib>
#include <filesystem>
#include <limits>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <Eigen/SparseQR>
#include "drake/common/scope_exit.h"
#include "drake/common/text_logging.h"
#include "drake/solvers/csdp_solver_internal.h"
#include "drake/solvers/sdpa_free_format.h"
// Note that in the below, the first argument to csdp::cpp_easy_sdp is a params
// filename, but that feature is a Drake-specific patch added to the CSDP
// headers and source; refer to drake/tools/workspace/csdp/repository.bzl
// for details.
namespace drake {
namespace solvers {
namespace internal {
namespace {
void SetCsdpSolverDetails(int csdp_ret, double pobj, double dobj, int y_size,
double* y, const csdp::blockmatrix& Z,
CsdpSolverDetails* solver_details) {
solver_details->return_code = csdp_ret;
solver_details->primal_objective = pobj;
solver_details->dual_objective = dobj;
solver_details->y_val.resize(y_size);
for (int i = 0; i < y_size; ++i) {
// CSDP uses Fortran 1-index array so the array y points to will be of size
// y_size + 1 with the zero entry ignored.
solver_details->y_val(i) = y[i + 1];
}
ConvertCsdpBlockMatrixtoEigen(Z, &(solver_details->Z_val));
}
SolutionResult ConvertCsdpReturnToSolutionResult(int csdp_ret) {
switch (csdp_ret) {
case 0:
case 3:
return SolutionResult::kSolutionFound;
case 1:
return SolutionResult::kInfeasibleConstraints;
case 2:
return SolutionResult::kDualInfeasible;
case 4:
return SolutionResult::kIterationLimit;
default:
return SolutionResult::kSolverSpecificError;
}
}
void SetProgramSolution(const SdpaFreeFormat& sdpa_free_format,
const csdp::blockmatrix& X,
const Eigen::VectorXd& s_val,
Eigen::VectorXd* prog_sol) {
for (int i = 0;
i < static_cast<int>(sdpa_free_format.prog_var_in_sdpa().size()); ++i) {
if (std::holds_alternative<DecisionVariableInSdpaX>(
sdpa_free_format.prog_var_in_sdpa()[i])) {
const auto& decision_var_in_X = std::get<DecisionVariableInSdpaX>(
sdpa_free_format.prog_var_in_sdpa()[i]);
double X_entry_val{};
switch (X.blocks[decision_var_in_X.entry_in_X.block_index + 1]
.blockcategory) {
case csdp::MATRIX: {
X_entry_val =
X.blocks[decision_var_in_X.entry_in_X.block_index + 1]
.data.mat[CsdpMatrixIndex(
decision_var_in_X.entry_in_X.row_index_in_block,
decision_var_in_X.entry_in_X.column_index_in_block,
X.blocks[decision_var_in_X.entry_in_X.block_index + 1]
.blocksize)];
break;
}
case csdp::DIAG: {
X_entry_val =
X.blocks[decision_var_in_X.entry_in_X.block_index + 1]
.data
.vec[decision_var_in_X.entry_in_X.row_index_in_block + 1];
break;
}
default: {
throw std::runtime_error(
"SetProgramSolution(): unknown X block type.");
}
}
(*prog_sol)(i) =
decision_var_in_X.offset +
(decision_var_in_X.coeff_sign == internal::Sign::kPositive
? X_entry_val
: -X_entry_val);
} else if (std::holds_alternative<double>(
sdpa_free_format.prog_var_in_sdpa()[i])) {
(*prog_sol)(i) = std::get<double>(sdpa_free_format.prog_var_in_sdpa()[i]);
} else if (std::holds_alternative<SdpaFreeFormat::FreeVariableIndex>(
sdpa_free_format.prog_var_in_sdpa()[i])) {
(*prog_sol)(i) = s_val(int{std::get<SdpaFreeFormat::FreeVariableIndex>(
sdpa_free_format.prog_var_in_sdpa()[i])});
}
}
}
void SolveProgramWithNoFreeVariables(const MathematicalProgram& prog,
const SdpaFreeFormat& sdpa_free_format,
const std::string& csdp_params_pathname,
MathematicalProgramResult* result) {
DRAKE_ASSERT(sdpa_free_format.num_free_variables() == 0);
csdp::blockmatrix C;
double* rhs;
csdp::constraintmatrix* constraints{nullptr};
GenerateCsdpProblemDataWithoutFreeVariables(sdpa_free_format, &C, &rhs,
&constraints);
struct csdp::blockmatrix X, Z;
double* y;
csdp::cpp_initsoln(sdpa_free_format.num_X_rows(), sdpa_free_format.g().rows(),
C, rhs, constraints, &X, &y, &Z);
double pobj, dobj;
const int ret = csdp::cpp_easy_sdp(
csdp_params_pathname.c_str(), sdpa_free_format.num_X_rows(),
sdpa_free_format.g().rows(), C, rhs, constraints,
-sdpa_free_format.constant_min_cost_term(), &X, &y, &Z, &pobj, &dobj);
// Set solver details.
CsdpSolverDetails& solver_details =
result->SetSolverDetailsType<CsdpSolverDetails>();
SetCsdpSolverDetails(ret, pobj, dobj, sdpa_free_format.g().rows(), y, Z,
&solver_details);
// Retrieve the information back to result.
// Since CSDP solves a maximization problem max -cost, where "cost" is the
// minimization cost in MathematicalProgram, we need to negate the cost.
result->set_optimal_cost(
ret == 1 /* primal infeasible */ ? MathematicalProgram::
kGlobalInfeasibleCost
: -pobj);
result->set_solution_result(ConvertCsdpReturnToSolutionResult(ret));
Eigen::VectorXd prog_sol(prog.num_vars());
SetProgramSolution(sdpa_free_format, X, Eigen::VectorXd::Zero(0), &prog_sol);
result->set_x_val(prog_sol);
csdp::cpp_free_prob(sdpa_free_format.num_X_rows(),
sdpa_free_format.g().rows(), C, rhs, constraints, X, y,
Z);
}
void SolveProgramThroughNullspaceApproach(
const MathematicalProgram& prog, const SdpaFreeFormat& sdpa_free_format,
const std::string& csdp_params_pathname,
MathematicalProgramResult* result) {
static const logging::Warn log_once(
"The problem has free variables, and CSDP removes the free "
"variables by computing the null space of linear constraint in the "
"dual space. This step can be time consuming. Consider providing a lower "
"and/or upper bound for each decision variable.");
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;
sdpa_free_format.RemoveFreeVariableByNullspaceApproach(
&C_hat, &A_hat, &rhs_hat, &y_hat, &QR_B);
// Now try to call CSDP to solve this problem.
csdp::blockmatrix C_csdp;
double* rhs_csdp{nullptr};
csdp::constraintmatrix* constraints_csdp{nullptr};
ConvertSparseMatrixFormatToCsdpProblemData(sdpa_free_format.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(sdpa_free_format.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(
csdp_params_pathname.c_str(), sdpa_free_format.num_X_rows(),
rhs_hat.rows(), C_csdp, rhs_csdp, constraints_csdp,
-sdpa_free_format.constant_min_cost_term() +
sdpa_free_format.g().dot(y_hat),
&X_csdp, &y, &Z, &pobj, &dobj);
Eigen::SparseMatrix<double> X_hat(sdpa_free_format.num_X_rows(),
sdpa_free_format.num_X_rows());
ConvertCsdpBlockMatrixtoEigen(X_csdp, &X_hat);
// Now compute the free variable values.
// AX(i) is trace(Ai, X_hat)
Eigen::VectorXd AX(sdpa_free_format.A().size());
for (int i = 0; i < AX.rows(); ++i) {
AX(i) = (sdpa_free_format.A()[i].cwiseProduct(X_hat)).sum();
}
Eigen::VectorXd s_val;
s_val = QR_B.solve(sdpa_free_format.g() - AX);
// Set solver details.
CsdpSolverDetails& solver_details =
result->SetSolverDetailsType<CsdpSolverDetails>();
SetCsdpSolverDetails(ret, pobj, dobj, rhs_hat.rows(), y, Z, &solver_details);
// Retrieve the information back to result
// Since CSDP solves a maximization problem max -cost, where "cost" is the
// minimization cost in MathematicalProgram, we need to negate the cost.
result->set_solution_result(ConvertCsdpReturnToSolutionResult(ret));
result->set_optimal_cost(
ret == 1 /* primal infeasible */ ? MathematicalProgram::
kGlobalInfeasibleCost
: -pobj);
Eigen::VectorXd prog_sol(prog.num_vars());
SetProgramSolution(sdpa_free_format, X_csdp, s_val, &prog_sol);
result->set_x_val(prog_sol);
csdp::cpp_free_prob(sdpa_free_format.num_X_rows(), rhs_hat.rows(), C_csdp,
rhs_csdp, constraints_csdp, X_csdp, y, Z);
}
/**
* 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ᵢ))
*/
void SolveProgramThroughTwoSlackVariablesApproach(
const MathematicalProgram& prog, const SdpaFreeFormat& sdpa_free_format,
const std::string& csdp_params_pathname,
MathematicalProgramResult* result) {
static const logging::Warn log_once(
"The problem has free variables, and CSDP removes the free "
"variables by introducing the slack variable y_plus >=0 , y_minus >= "
"0, and constraint y_plus - y_minus = free_variable. This can "
"introduce numerical problems to the solver. Consider providing a lower "
"and/or upper bound for each decision variable.");
std::vector<internal::BlockInX> X_hat_blocks;
std::vector<Eigen::SparseMatrix<double>> A_hat;
Eigen::SparseMatrix<double> C_hat;
sdpa_free_format.RemoveFreeVariableByTwoSlackVariablesApproach(
&X_hat_blocks, &A_hat, &C_hat);
const int num_X_hat_rows =
sdpa_free_format.num_X_rows() + 2 * sdpa_free_format.num_free_variables();
// Now try to call CSDP to solve this problem.
csdp::blockmatrix C_csdp;
double* rhs_csdp{nullptr};
csdp::constraintmatrix* constraints_csdp{nullptr};
ConvertSparseMatrixFormatToCsdpProblemData(X_hat_blocks, C_hat, A_hat,
sdpa_free_format.g(), &C_csdp,
&rhs_csdp, &constraints_csdp);
struct csdp::blockmatrix X_csdp, Z;
double* y{nullptr};
csdp::cpp_initsoln(num_X_hat_rows, sdpa_free_format.g().rows(), C_csdp,
rhs_csdp, constraints_csdp, &X_csdp, &y, &Z);
double pobj{0};
double dobj{0};
const int ret = csdp::cpp_easy_sdp(
csdp_params_pathname.c_str(), num_X_hat_rows, sdpa_free_format.g().rows(),
C_csdp, rhs_csdp, constraints_csdp,
-sdpa_free_format.constant_min_cost_term(), &X_csdp, &y, &Z, &pobj,
&dobj);
Eigen::SparseMatrix<double> X_hat(num_X_hat_rows, num_X_hat_rows);
ConvertCsdpBlockMatrixtoEigen(X_csdp, &X_hat);
// Now retrieve the value for the free variable s as y⁺ - y⁻.
Eigen::VectorXd s_val(sdpa_free_format.num_free_variables());
for (int i = 0; i < sdpa_free_format.num_free_variables(); ++i) {
double y_plus_val{0};
for (Eigen::SparseMatrix<double>::InnerIterator it(
X_hat, sdpa_free_format.num_X_rows() + i);
it; ++it) {
y_plus_val = it.value();
}
double y_minus_val{0};
for (Eigen::SparseMatrix<double>::InnerIterator it(
X_hat, sdpa_free_format.num_X_rows() +
sdpa_free_format.num_free_variables() + i);
it; ++it) {
y_minus_val = it.value();
}
s_val(i) = y_plus_val - y_minus_val;
}
CsdpSolverDetails& solver_details =
result->SetSolverDetailsType<CsdpSolverDetails>();
SetCsdpSolverDetails(ret, pobj, dobj, sdpa_free_format.g().rows(), y, Z,
&solver_details);
// Retrieve the information back to result
// Since CSDP solves a maximization problem max -cost, where "cost" is the
// minimization cost in MathematicalProgram, we need to negate the cost.
result->set_solution_result(ConvertCsdpReturnToSolutionResult(ret));
result->set_optimal_cost(
ret == 1 /* primal infeasible */ ? MathematicalProgram::
kGlobalInfeasibleCost
: -pobj);
Eigen::VectorXd prog_sol(prog.num_vars());
SetProgramSolution(sdpa_free_format, X_csdp, s_val, &prog_sol);
result->set_x_val(prog_sol);
csdp::cpp_free_prob(num_X_hat_rows, sdpa_free_format.g().rows(), C_csdp,
rhs_csdp, constraints_csdp, X_csdp, y, Z);
}
/*
* 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.
* max tr(Ĉ * X̂)
* s.t tr(Âᵢ*X̂) = aᵢ
* X̂ ≽ 0
* Refer to RemoveFreeVariableByLorentzConeSlackApproach in sdpa_free_format.h
* for more details.
*/
void SolveProgramThroughLorentzConeSlackApproach(
const MathematicalProgram& prog, const SdpaFreeFormat& sdpa_free_format,
const std::string& csdp_params_pathname,
MathematicalProgramResult* result) {
static const logging::Warn log_once(
"The problem has free variables, and CSDP removes the free "
"variables by introducing a slack variable t with the Lorentz cone "
"constraint t>= sqrt(s'*s) This can introduce numerical problems to the "
"solver. Consider providing a lower "
"and/or upper bound for each decision variable.");
std::vector<internal::BlockInX> X_hat_blocks;
std::vector<Eigen::SparseMatrix<double>> A_hat;
Eigen::VectorXd rhs_hat;
Eigen::SparseMatrix<double> C_hat;
sdpa_free_format.RemoveFreeVariableByLorentzConeSlackApproach(
&X_hat_blocks, &A_hat, &rhs_hat, &C_hat);
const int num_X_hat_rows =
sdpa_free_format.num_X_rows() + sdpa_free_format.num_free_variables() + 1;
// Now try to call CSDP to solve this problem.
csdp::blockmatrix C_csdp;
double* rhs_csdp{nullptr};
csdp::constraintmatrix* constraints_csdp{nullptr};
ConvertSparseMatrixFormatToCsdpProblemData(X_hat_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(num_X_hat_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(
csdp_params_pathname.c_str(), num_X_hat_rows, rhs_hat.rows(), C_csdp,
rhs_csdp, constraints_csdp, -sdpa_free_format.constant_min_cost_term(),
&X_csdp, &y, &Z, &pobj, &dobj);
Eigen::SparseMatrix<double> X_hat(num_X_hat_rows, num_X_hat_rows);
ConvertCsdpBlockMatrixtoEigen(X_csdp, &X_hat);
// Now retrieve the value for the free variable s from Y.
Eigen::VectorXd s_val =
Eigen::VectorXd::Zero(sdpa_free_format.num_free_variables());
for (int i = 0; i < sdpa_free_format.num_free_variables(); ++i) {
for (Eigen::SparseMatrix<double>::InnerIterator it(
X_hat, sdpa_free_format.num_X_rows() + i + 1);
it; ++it) {
s_val(i) = it.value();
// There are two non-zero entries in this column, Y(0, i+1) = s(i) and
// Y(i+1, i+1) = t(i). We only care about the first non-zero entry Y(0,
// i+1), so break here.
break;
}
}
CsdpSolverDetails& solver_details =
result->SetSolverDetailsType<CsdpSolverDetails>();
SetCsdpSolverDetails(ret, pobj, dobj, rhs_hat.rows(), y, Z, &solver_details);
// Retrieve the information back to result.
// Since CSDP solves a maximization problem max -cost, where "cost" is the
// minimization cost in MathematicalProgram, we need to negate the cost.
result->set_solution_result(ConvertCsdpReturnToSolutionResult(ret));
result->set_optimal_cost(
ret == 1 /* primal infeasible */ ? MathematicalProgram::
kGlobalInfeasibleCost
: -pobj);
Eigen::VectorXd prog_sol(prog.num_vars());
SetProgramSolution(sdpa_free_format, X_csdp, s_val, &prog_sol);
result->set_x_val(prog_sol);
csdp::cpp_free_prob(num_X_hat_rows, rhs_hat.rows(), C_csdp, rhs_csdp,
constraints_csdp, X_csdp, y, Z);
}
std::string MaybeWriteCsdpParams(const SolverOptions& options) {
// We'll consolidate options into this config string to pass to CSDP.
std::string all_csdp_params;
// Map the common options into CSDP's conventions.
if (options.get_print_to_console()) {
all_csdp_params += "printlevel=1\n";
}
// Add the specific options next (so they trump the common options).
for (const auto& [key, value] : options.GetOptionsInt(CsdpSolver::id())) {
all_csdp_params += fmt::format("{}={}\n", key, value);
}
for (const auto& [key, value] : options.GetOptionsDouble(CsdpSolver::id())) {
all_csdp_params += fmt::format("{}={}\n", key, value);
}
// TODO(jwnimmer-tri) Throw an error if there were any string options set.
if (all_csdp_params.empty()) {
// No need to write a temporary file.
return {};
}
// Choose a temporary filename.
const char* dir = std::getenv("TEST_TMPDIR");
if (!dir) {
dir = std::getenv("TMPDIR");
}
if (!dir) {
dir = "/tmp";
}
std::filesystem::path path_template(dir);
path_template.append("robotlocomotion_drake_XXXXXX");
std::string result = path_template;
int fd = ::mkstemp(result.data());
DRAKE_THROW_UNLESS(fd != -1);
const size_t total = all_csdp_params.size();
ssize_t written = ::write(fd, all_csdp_params.data(), total);
DRAKE_THROW_UNLESS(written != -1);
DRAKE_THROW_UNLESS(written == static_cast<ssize_t>(total));
::close(fd);
return result;
}
} // namespace
} // namespace internal
void CsdpSolver::DoSolve(const MathematicalProgram& prog,
const Eigen::VectorXd&,
const SolverOptions& merged_options,
MathematicalProgramResult* result) const {
if (!prog.GetVariableScaling().empty()) {
static const logging::Warn log_once(
"CsdpSolver doesn't support the feature of variable scaling.");
}
// If necessary, write the custom CSDP parameters to a temporary file, which
// we should remove when this function returns.
const std::string csdp_params_pathname =
internal::MaybeWriteCsdpParams(merged_options);
ScopeExit guard([&csdp_params_pathname]() {
if (!csdp_params_pathname.empty()) {
::unlink(csdp_params_pathname.c_str());
}
});
result->set_solver_id(CsdpSolver::id());
const internal::SdpaFreeFormat sdpa_free_format(prog);
if (sdpa_free_format.num_free_variables() == 0) {
internal::SolveProgramWithNoFreeVariables(prog, sdpa_free_format,
csdp_params_pathname, result);
} else {
const auto int_options = merged_options.GetOptionsInt(CsdpSolver::id());
const auto it_method = int_options.find("drake::RemoveFreeVariableMethod");
RemoveFreeVariableMethod method = RemoveFreeVariableMethod::kNullspace;
if (it_method != int_options.end()) {
if (it_method->second >= 1 && it_method->second <= 3) {
method = static_cast<RemoveFreeVariableMethod>(it_method->second);
} else {
throw std::runtime_error(
"CsdpSolver::sol(), unknown value for "
"drake::RemoveFreeVariableMethod");
}
}
switch (method) {
case RemoveFreeVariableMethod::kNullspace: {
internal::SolveProgramThroughNullspaceApproach(
prog, sdpa_free_format, csdp_params_pathname, result);
break;
}
case RemoveFreeVariableMethod::kTwoSlackVariables: {
internal::SolveProgramThroughTwoSlackVariablesApproach(
prog, sdpa_free_format, csdp_params_pathname, result);
break;
}
case RemoveFreeVariableMethod::kLorentzConeSlack: {
internal::SolveProgramThroughLorentzConeSlackApproach(
prog, sdpa_free_format, csdp_params_pathname, result);
break;
}
}
}
}
bool CsdpSolver::is_available() {
return true;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/common_solver_option.h | #pragma once
#include <ostream>
#include "drake/common/fmt_ostream.h"
namespace drake {
namespace solvers {
/**
* Some options can be applied to not one solver, but many solvers (for example,
* many solvers support printing out the progress in each iteration).
* CommonSolverOption contain the names of these supported options.
* The user can use these options as "key" in SolverOption::SetOption().
*/
enum class CommonSolverOption {
/** Many solvers support printing the progress of each iteration to a file.
* The user can call SolverOptions::SetOption(kPrintFileName, file_name) where
* file_name is a string. If the user doesn't want to print to a file, then
* use SolverOptions::SetOption(kPrintFileName, ""), where the empty string ""
* indicates no print.
*/
kPrintFileName,
/** Many solvers support printing the progress of each iteration to the
* console, the user can call SolverOptions::SetOption(kPrintToConsole, 1) to
* turn on printing to the console, or
* SolverOptions::SetOption(kPrintToConsole, 0) to turn off printing to the
* console.
*/
kPrintToConsole,
};
std::ostream& operator<<(std::ostream& os,
CommonSolverOption common_solver_option);
} // namespace solvers
} // namespace drake
// TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<.
namespace fmt {
template <>
struct formatter<drake::solvers::CommonSolverOption>
: drake::ostream_formatter {};
} // namespace fmt
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/choose_best_solver.cc | #include "drake/solvers/choose_best_solver.h"
#include <array>
#include <string>
#include <unordered_map>
#include "absl/container/inlined_vector.h"
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
#include "drake/solvers/clarabel_solver.h"
#include "drake/solvers/clp_solver.h"
#include "drake/solvers/csdp_solver.h"
#include "drake/solvers/equality_constrained_qp_solver.h"
#include "drake/solvers/get_program_type.h"
#include "drake/solvers/gurobi_solver.h"
#include "drake/solvers/ipopt_solver.h"
#include "drake/solvers/linear_system_solver.h"
#include "drake/solvers/moby_lcp_solver.h"
#include "drake/solvers/mosek_solver.h"
#include "drake/solvers/nlopt_solver.h"
#include "drake/solvers/osqp_solver.h"
#include "drake/solvers/scs_solver.h"
#include "drake/solvers/snopt_solver.h"
namespace drake {
namespace solvers {
namespace {
// A collection of function pointers to the static member functions that are
// twins to the SolverInterface virtual member functions. These pointers are
// useful when we want to interrogate solvers without constructing them.
class StaticSolverInterface {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(StaticSolverInterface)
template <typename SomeSolver>
static constexpr StaticSolverInterface Make() {
StaticSolverInterface result;
result.id_ = &SomeSolver::id;
result.is_available_ = &SomeSolver::is_available;
result.is_enabled_ = &SomeSolver::is_enabled;
result.are_program_attributes_satisfied_ =
&SomeSolver::ProgramAttributesSatisfied;
result.make_ = &MakeAndUpcast<SomeSolver>;
return result;
}
SolverId id() const { return (*id_)(); }
bool is_available() const { return (*is_available_)(); }
bool is_enabled() const { return (*is_enabled_)(); }
bool AreProgramAttributesSatisfied(const MathematicalProgram& prog) const {
return (*are_program_attributes_satisfied_)(prog);
}
std::unique_ptr<SolverInterface> Make() const { return (*make_)(); }
private:
StaticSolverInterface() = default;
// A helper function that combines make_unique with an upcast.
template <typename SomeSolver>
static std::unique_ptr<SolverInterface> MakeAndUpcast() {
return std::make_unique<SomeSolver>();
}
SolverId (*id_)() = nullptr;
bool (*is_available_)() = nullptr;
bool (*is_enabled_)() = nullptr;
bool (*are_program_attributes_satisfied_)(const MathematicalProgram& prog) =
nullptr;
std::unique_ptr<SolverInterface> (*make_)() = nullptr;
};
// The list of all solvers compiled in Drake.
constexpr std::array<StaticSolverInterface, 13> kKnownSolvers{
StaticSolverInterface::Make<ClarabelSolver>(),
StaticSolverInterface::Make<ClpSolver>(),
StaticSolverInterface::Make<CsdpSolver>(),
StaticSolverInterface::Make<EqualityConstrainedQPSolver>(),
StaticSolverInterface::Make<GurobiSolver>(),
StaticSolverInterface::Make<IpoptSolver>(),
StaticSolverInterface::Make<LinearSystemSolver>(),
StaticSolverInterface::Make<MobyLCPSolver<double>>(),
StaticSolverInterface::Make<MosekSolver>(),
StaticSolverInterface::Make<NloptSolver>(),
StaticSolverInterface::Make<OsqpSolver>(),
StaticSolverInterface::Make<ScsSolver>(),
StaticSolverInterface::Make<SnoptSolver>()};
constexpr int kNumberOfSolvers = kKnownSolvers.size();
// The list of all solvers compiled in Drake, indexed by SolverId.
using KnownSolversMap =
std::unordered_map<SolverId, const StaticSolverInterface*>;
const KnownSolversMap& GetKnownSolversMap() {
static const never_destroyed<KnownSolversMap> result{[]() {
KnownSolversMap prototype;
for (const auto& solver : kKnownSolvers) {
prototype.emplace(solver.id(), &solver);
}
return prototype;
}()};
return result.access();
}
SolverId ChooseFirstMatchingSolver(
const MathematicalProgram& prog,
const absl::InlinedVector<SolverId, kNumberOfSolvers>& solver_ids,
std::string_view additional_error_message = "") {
const auto& map = GetKnownSolversMap();
for (const auto& solver_id : solver_ids) {
if (map.at(solver_id)->AreProgramAttributesSatisfied(prog)) {
return solver_id;
}
}
throw std::invalid_argument(
fmt::format("There is no available solver for the optimization program{}",
additional_error_message));
}
template <typename SomeSolver>
void AddSolverIfAvailable(
absl::InlinedVector<SolverId, kNumberOfSolvers>* solver_ids) {
if (SomeSolver::is_available() && SomeSolver::is_enabled()) {
solver_ids->push_back(SomeSolver::id());
}
}
template <typename SomeSolver, typename... SomeSolvers>
void AddSolversIfAvailable(
absl::InlinedVector<SolverId, kNumberOfSolvers>* solver_ids) {
AddSolverIfAvailable<SomeSolver>(solver_ids);
if constexpr (sizeof...(SomeSolvers) > 0) {
AddSolversIfAvailable<SomeSolvers...>(solver_ids);
}
}
// Outputs the list of solvers which can solve the given program type.
// If conservative is true, outputs the list that can _always_ solve
// any program of that the type; if false, outputs the list that can
// solve _at least one_ instance of the type, but maybe not all.
// @param[out] result The available solvers which can solve the given program
// type. We use InlinedVector here to avoid heap memory allocation as
// ChooseBestSolver is performance sensitive (it may run inside a loop to solve
// optimization problems online).
void GetAvailableSolversHelper(
ProgramType prog_type, bool conservative,
absl::InlinedVector<SolverId, kNumberOfSolvers>* result) {
result->clear();
switch (prog_type) {
case ProgramType::kLP: {
if (!conservative) {
// LinearSystemSolver solves a specific type of problem A*x=b, we
// put the more specific solver ahead of other general solvers.
AddSolversIfAvailable<LinearSystemSolver>(result);
}
AddSolversIfAvailable<
// Preferred solvers.
// The order between Mosek and Gurobi can be changed. According to the
// benchmark http://plato.asu.edu/bench.html, Gurobi is slightly
// faster than Mosek (as of 07-26-2021), but the difference is not
// significant.
// Clp is slower than Gurobi and Mosek (with the barrier method).
// Clarabel is also a very good open-source solver. I found that
// Clarabel is slightly less accurate than Clp.
GurobiSolver, MosekSolver, ClpSolver, ClarabelSolver,
// Dispreferred (generic nonlinear solvers).
// I generally find SNOPT faster than IPOPT. Nlopt is less reliable.
SnoptSolver, IpoptSolver, NloptSolver,
// Dispreferred (cannot handle free variables).
CsdpSolver,
// Dispreferred (ADMM, low accuracy).
ScsSolver>(result);
return;
}
case ProgramType::kQP: {
if (!conservative) {
// EqualityConstrainedQPSolver solves a specific QP with only linear
// equality constraints. We put the more specific solver ahead of
// the general solvers.
AddSolversIfAvailable<EqualityConstrainedQPSolver>(result);
}
AddSolversIfAvailable<
// Preferred solvers.
// According to http://plato.asu.edu/ftp/cconvex.html, Mosek is
// slightly faster than Gurobi. In practice, I find their performance
// comparable, so the order between these two can be switched.
MosekSolver, GurobiSolver,
// Clarabel is an open-source QP solver with relatively good accuracy.
// (But might not be as fast as OSQP).
ClarabelSolver,
// Dispreferred (ADMM, low accuracy).
// Although both OSQP and SCS use ADMM, I find OSQP to be more
// accurate than SCS. Oftentime I find OSQP generates solution with
// reasonable accuracy, so I put it before SNOPT/IPOPT/NLOPT (which
// are often slower than OSQP).
OsqpSolver,
// TODO(hongkai.dai): add CLP to this list when we resolve the
// memory issue in CLP. Dispreferred (generic nonlinear solvers). I
// find SNOPT often faster than IPOPT. NLOPT is less reliable.
SnoptSolver, IpoptSolver, NloptSolver,
// Dispreferred (ADMM, low accuracy).
ScsSolver>(result);
return;
}
case ProgramType::kSOCP: {
AddSolversIfAvailable<
// Preferred solvers.
// According to http://plato.asu.edu/ftp/socp.html, Mosek is slightly
// faster than Gurobi for SOCP, but the difference is small.
MosekSolver, GurobiSolver,
// ClarabelSolver is a good open-source convex solver.
ClarabelSolver,
// Dispreferred (cannot handle free variables).
CsdpSolver,
// Dispreferred (ADMM, low accuracy).
ScsSolver,
// Dispreferred (generic nonlinear solvers).
// I strongly suggest NOT to use these solvers for SOCP. These
// gradient-based solvers ignore the convexity of the problem, and
// also these solvers require smooth gradient, while the second-order
// cone constraint is not differentiable at the tip of the cone.
SnoptSolver, IpoptSolver, NloptSolver>(result);
return;
}
case ProgramType::kSDP: {
AddSolversIfAvailable<
// Preferred solvers.
MosekSolver,
// Clarabel is a good open-source convex solver. Preferred.
ClarabelSolver,
// Dispreferred (cannot handle free variables).
CsdpSolver,
// Dispreferred (ADMM, low accuracy).
ScsSolver>(result);
// Dispreferred (generic nonlinear solvers). I strongly
// suggest NOT to use these solvers for SDP. These gradient-based
// solvers ignore the convexity of the problem, and also these solvers
// require smooth gradient, while the semidefinite cone constraint is
// not differentiable everywhere (when the minimal eigen value is not
// unique).
if (!conservative) {
AddSolversIfAvailable<SnoptSolver, IpoptSolver, NloptSolver>(result);
}
return;
}
case ProgramType::kGP:
case ProgramType::kCGP: {
// TODO(hongkai.dai): These types of programs should not be called GP or
// CGP. GP are programs with posynomial constraints. Find the right name
// of these programs with exponential cones, and add to the documentation
// in https://drake.mit.edu/doxygen_cxx/group__solvers.html
AddSolversIfAvailable<
// Preferred solver.
MosekSolver,
// Open-source preferred solver.
ClarabelSolver,
// Dispreferred solver, low accuracy (with ADMM method).
ScsSolver>(result);
return;
}
case ProgramType::kMILP:
case ProgramType::kMIQP:
case ProgramType::kMISOCP: {
// According to http://plato.asu.edu/ftp/misocp.html, Gurobi is a lot
// faster than Mosek for MISOCP. The benchmark doesn't compare Mosek
// against Gurobi for MILP and MIQP.
AddSolversIfAvailable<GurobiSolver, MosekSolver>(result);
return;
}
case ProgramType::kMISDP: {
return;
}
case ProgramType::kQuadraticCostConicConstraint: {
AddSolversIfAvailable<
// Preferred solvers.
// I don't know if Mosek is better than Gurobi for this type of
// programs.
MosekSolver, GurobiSolver,
// Open-source preferred solver.
ClarabelSolver,
// Dispreferred solver (ADMM, low accuracy).
ScsSolver>(result);
return;
}
case ProgramType::kNLP: {
// I find SNOPT often faster than IPOPT. NLOPT is less reliable.
AddSolversIfAvailable<SnoptSolver, IpoptSolver, NloptSolver>(result);
return;
}
case ProgramType::kLCP: {
AddSolversIfAvailable<
// Preferred solver.
MobyLCPSolver<double>,
// Dispreferred solver (generic nonlinear solver).
SnoptSolver>(result);
if (!conservative) {
// TODO(hongkai.dai): enable IPOPT and NLOPT for linear complementarity
// constraints.
AddSolversIfAvailable<IpoptSolver, NloptSolver>(result);
}
return;
}
case ProgramType::kUnknown: {
if (!conservative) {
// The order of solvers listed here is an approximation of a total
// order, drawn from all of the partial orders given throughout the
// other case statements shown above.
AddSolversIfAvailable<LinearSystemSolver, EqualityConstrainedQPSolver,
MosekSolver, GurobiSolver, ClarabelSolver,
OsqpSolver, ClpSolver, MobyLCPSolver<double>,
SnoptSolver, IpoptSolver, NloptSolver, CsdpSolver,
ScsSolver>(result);
}
return;
}
}
DRAKE_UNREACHABLE();
}
} // namespace
// This function is performance sensitive, so we want to use InlinedVector and
// constexpr code to avoid heap memory allocation.
SolverId ChooseBestSolver(const MathematicalProgram& prog) {
const ProgramType program_type = GetProgramType(prog);
absl::InlinedVector<SolverId, kNumberOfSolvers> solver_ids;
GetAvailableSolversHelper(program_type, false /* conservative=false*/,
&solver_ids);
switch (program_type) {
case ProgramType::kLP:
case ProgramType::kQP:
case ProgramType::kSOCP:
case ProgramType::kSDP:
case ProgramType::kGP:
case ProgramType::kCGP:
case ProgramType::kQuadraticCostConicConstraint:
case ProgramType::kNLP:
case ProgramType::kLCP:
case ProgramType::kUnknown: {
return ChooseFirstMatchingSolver(prog, solver_ids);
}
case ProgramType::kMILP:
case ProgramType::kMIQP:
case ProgramType::kMISOCP: {
return ChooseFirstMatchingSolver(
prog, solver_ids,
", please manually instantiate MixedIntegerBranchAndBound and solve "
"the problem if the problem size is small, typically with less than "
"a dozen of binary variables.");
}
case ProgramType::kMISDP: {
throw std::runtime_error(
"ChooseBestSolver():MISDP problems are not well-supported yet. You "
"can try Drake's implementation MixedIntegerBranchAndBound for small "
"sized MISDPs.");
}
}
DRAKE_UNREACHABLE();
}
const std::set<SolverId>& GetKnownSolvers() {
static const never_destroyed<std::set<SolverId>> result{[]() {
std::set<SolverId> prototype;
for (const auto& solver : kKnownSolvers) {
prototype.insert(solver.id());
}
return prototype;
}()};
return result.access();
}
std::unique_ptr<SolverInterface> MakeSolver(const SolverId& id) {
const auto& map = GetKnownSolversMap();
auto iter = map.find(id);
if (iter != map.end()) {
const StaticSolverInterface& solver = *(iter->second);
return solver.Make();
}
throw std::invalid_argument("MakeSolver: no matching solver " + id.name());
}
std::unique_ptr<SolverInterface> MakeFirstAvailableSolver(
const std::vector<SolverId>& solver_ids) {
const auto& map = GetKnownSolversMap();
for (const auto& solver_id : solver_ids) {
auto iter = map.find(solver_id);
if (iter != map.end()) {
const StaticSolverInterface& solver = *(iter->second);
if (solver.is_available() && solver.is_enabled()) {
return solver.Make();
}
}
}
std::string solver_names = "";
for (const auto& solver_id : solver_ids) {
solver_names.append(solver_id.name() + " ");
}
throw std::runtime_error("MakeFirstAvailableSolver(): none of the solvers " +
solver_names + "is available and enabled.");
}
std::vector<SolverId> GetAvailableSolvers(ProgramType prog_type) {
absl::InlinedVector<SolverId, kNumberOfSolvers> solver_ids;
GetAvailableSolversHelper(prog_type, true /* conservative=true */,
&solver_ids);
return std::vector<SolverId>(solver_ids.begin(), solver_ids.end());
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/minimum_value_constraint.cc | #include "drake/solvers/minimum_value_constraint.h"
#include <limits>
#include "drake/math/autodiff_gradient.h"
#include "drake/math/soft_min_max.h"
namespace drake {
namespace solvers {
namespace {
constexpr double kInf = std::numeric_limits<double>::infinity();
using ValueFunctionDoubleType =
std::function<VectorX<double>(const VectorX<double>&, double)>;
using ValueFunctionAutodiffType =
std::function<AutoDiffVecXd(const AutoDiffVecXd&, double)>;
/** Computes a smooth over approximation of max(x). */
template <typename T>
T SmoothOverMax(const std::vector<T>& x) {
// We compute the smooth max of x as smoothmax(x) = log(∑ᵢ exp(αxᵢ)) / α.
// This smooth max approaches max(x) as α increases. We choose α = 100, as
// that gives a qualitatively good fit for xᵢ ∈ [0, 1], which is the range of
// potential penalty values when the MinimumValueConstraint is feasible.
return math::SoftOverMax(x, 100 /* alpha */);
}
/** Computes a smooth under approximation of max(x). */
template <typename T>
T SmoothUnderMax(const std::vector<T>& x) {
// This SoftUnderMax approaches max(x) as α increases. We choose α = 100, as
// that gives a qualitatively good fit for xᵢ around 1.
return math::SoftUnderMax(x, 100 /* alpha */);
}
template <typename T>
T ScaleValue(T value, double minimum_value, double influence_value) {
return (value - influence_value) / (influence_value - minimum_value);
}
void InitializeY(const Eigen::Ref<const Eigen::VectorXd>&, Eigen::VectorXd* y,
int y_index, double y_value) {
(*y)(y_index) = y_value;
}
void InitializeY(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y,
int y_index, double y_value) {
(*y)(y_index).value() = y_value;
(*y)(y_index).derivatives() =
Eigen::RowVectorXd::Zero(x(0).derivatives().size());
}
void Penalty(const double& value, double minimum_value, double influence_value,
const MinimumValuePenaltyFunction& penalty_function, double* y) {
double penalty;
const double x = ScaleValue(value, minimum_value, influence_value);
penalty_function(x, &penalty, nullptr);
*y = penalty;
}
void Penalty(const AutoDiffXd& value, double minimum_value,
double influence_value,
const MinimumValuePenaltyFunction& penalty_function,
AutoDiffXd* y) {
const AutoDiffXd scaled_value_autodiff =
ScaleValue(value, minimum_value, influence_value);
double penalty, dpenalty_dscaled_value;
penalty_function(scaled_value_autodiff.value(), &penalty,
&dpenalty_dscaled_value);
const Vector1<AutoDiffXd> penalty_autodiff = math::InitializeAutoDiff(
Vector1d(penalty),
dpenalty_dscaled_value *
math::ExtractGradient(Vector1<AutoDiffXd>{scaled_value_autodiff}));
*y = penalty_autodiff(0);
}
void set_penalty_function_impl(MinimumValuePenaltyFunction new_penalty_function,
MinimumValuePenaltyFunction* penalty_function,
double* penalty_output_scaling) {
*penalty_function = std::move(new_penalty_function);
double unscaled_penalty_at_minimum_value{};
(*penalty_function)(-1, &unscaled_penalty_at_minimum_value, nullptr);
*penalty_output_scaling = 1 / unscaled_penalty_at_minimum_value;
}
VectorX<double> Values(const Eigen::Ref<const VectorX<double>>& x,
double influence_value,
const ValueFunctionDoubleType& value_function_double,
const ValueFunctionAutodiffType& value_function_ad) {
return value_function_double ? value_function_double(x, influence_value)
: math::ExtractValue(value_function_ad(
x.cast<AutoDiffXd>(), influence_value));
}
AutoDiffVecXd Values(const Eigen::Ref<const AutoDiffVecXd>& x,
double influence_value,
const ValueFunctionDoubleType& value_function_double,
const ValueFunctionAutodiffType& value_function_ad) {
unused(value_function_double);
return value_function_ad(x, influence_value);
}
// Given v, evaluate
// smooth_fun( φ((vᵢ - v_influence)/(v_influence - bound_value)) / φ(-1) )
template <typename T>
void EvalPenalty(double bound_value, const VectorX<T>& values,
int max_num_values, double influence_value,
MinimumValuePenaltyFunction penalty_function,
double penalty_output_scaling,
const std::function<T(const std::vector<T>&)>& smooth_func,
T* y) {
const int num_values = values.size();
std::vector<T> penalties;
penalties.reserve(max_num_values);
for (int i = 0; i < num_values; ++i) {
const T& value = values(i);
if (value < influence_value) {
penalties.emplace_back();
Penalty(value, bound_value, influence_value, penalty_function,
&(penalties.back()));
penalties.back() *= penalty_output_scaling;
}
}
if (!penalties.empty()) {
// Pad penalties up to max_num_values_ so that the constraint
// function is actually smooth.
penalties.resize(max_num_values, T{0.0});
(*y) = smooth_func(penalties);
}
}
template <typename T>
void EvalGeneric(
double bound, int max_num_values, double y_for_empty_value,
double influence_value,
const ValueFunctionDoubleType& value_function_double,
const ValueFunctionAutodiffType& value_function_ad,
const std::function<double(const std::vector<double>&)>& smooth_func_double,
const std::function<T(const std::vector<T>&)>& smooth_func,
const MinimumValuePenaltyFunction& penalty_function,
double penalty_output_scaling, const Eigen::Ref<const VectorX<T>>& x,
VectorX<T>* y) {
y->resize(1);
// If we know that Values() will return at most zero values, then this
// is a non-constraint. Return zero for the lower bound constraint
if (max_num_values == 0) {
InitializeY(x, y, 0, y_for_empty_value);
return;
}
// Initialize y to SmoothOverMax([0,..., 0])
// We choose 0 because that is φ((v - v_influence)/(v_influence -
// bound_value)) / φ(-1) when v = v_influence.
InitializeY(x, y, 0,
smooth_func_double(std::vector<double>(max_num_values, 0.0)));
VectorX<T> values =
Values(x, influence_value, value_function_double, value_function_ad);
const int num_values = static_cast<int>(values.size());
DRAKE_ASSERT(num_values <= max_num_values);
EvalPenalty<T>(bound, values, max_num_values, influence_value,
penalty_function, penalty_output_scaling, smooth_func,
y->data());
}
} // namespace
void ExponentiallySmoothedHingeLoss(double x, double* penalty,
double* dpenalty_dx) {
if (x >= 0) {
*penalty = 0;
if (dpenalty_dx) {
*dpenalty_dx = 0;
}
} else {
const double exp_one_over_x = std::exp(1.0 / x);
*penalty = -x * exp_one_over_x;
if (dpenalty_dx) {
*dpenalty_dx = -exp_one_over_x + exp_one_over_x / x;
}
}
}
void QuadraticallySmoothedHingeLoss(double x, double* penalty,
double* dpenalty_dx) {
if (x >= 0) {
*penalty = 0;
if (dpenalty_dx) {
*dpenalty_dx = 0;
}
} else {
if (x > -1) {
*penalty = x * x / 2;
if (dpenalty_dx) {
*dpenalty_dx = x;
}
} else {
*penalty = -0.5 - x;
if (dpenalty_dx) {
*dpenalty_dx = -1;
}
}
}
}
MinimumValueLowerBoundConstraint::MinimumValueLowerBoundConstraint(
int num_vars, double minimum_value_lower, double influence_value_offset,
int max_num_values,
std::function<AutoDiffVecXd(const Eigen::Ref<const AutoDiffVecXd>&, double)>
value_function,
std::function<VectorX<double>(const Eigen::Ref<const VectorX<double>>&,
double)>
value_function_double)
: Constraint(1, num_vars, Vector1d(-kInf), Vector1d(1)),
value_function_{std::move(value_function)},
value_function_double_{std::move(value_function_double)},
minimum_value_lower_{minimum_value_lower},
influence_value_{influence_value_offset + minimum_value_lower},
max_num_values_{max_num_values} {
DRAKE_DEMAND(std::isfinite(minimum_value_lower_));
DRAKE_DEMAND(std::isfinite(influence_value_offset));
DRAKE_DEMAND(influence_value_offset > 0);
this->set_penalty_function(QuadraticallySmoothedHingeLoss);
}
void MinimumValueLowerBoundConstraint::set_penalty_function(
MinimumValuePenaltyFunction new_penalty_function) {
set_penalty_function_impl(new_penalty_function, &penalty_function_,
&penalty_output_scaling_);
}
template <typename T>
void MinimumValueLowerBoundConstraint::DoEvalGeneric(
const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const {
// If we know that Values() will return at most zero values, then this
// is a non-constraint. Set y=0 which trivially satisfies the constraint y
// <= 1.
const double y_for_empty_value = 0;
EvalGeneric<T>(minimum_value_lower_, max_num_values_, y_for_empty_value,
influence_value_, value_function_double_, value_function_,
SmoothOverMax<double>, SmoothOverMax<T>, penalty_function_,
penalty_output_scaling_, x, y);
}
void MinimumValueLowerBoundConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric<double>(x, y);
}
void MinimumValueLowerBoundConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DoEvalGeneric<AutoDiffXd>(x, y);
}
MinimumValueUpperBoundConstraint::MinimumValueUpperBoundConstraint(
int num_vars, double minimum_value_upper, double influence_value_offset,
int max_num_values,
std::function<AutoDiffVecXd(const Eigen::Ref<const AutoDiffVecXd>&, double)>
value_function,
std::function<VectorX<double>(const Eigen::Ref<const VectorX<double>>&,
double)>
value_function_double)
: Constraint(1, num_vars, Vector1d(1), Vector1d(kInf)),
value_function_{std::move(value_function)},
value_function_double_{std::move(value_function_double)},
minimum_value_upper_{minimum_value_upper},
influence_value_{influence_value_offset + minimum_value_upper},
max_num_values_{max_num_values} {
DRAKE_DEMAND(std::isfinite(minimum_value_upper_));
DRAKE_DEMAND(std::isfinite(influence_value_offset));
DRAKE_DEMAND(influence_value_offset > 0);
this->set_penalty_function(QuadraticallySmoothedHingeLoss);
}
void MinimumValueUpperBoundConstraint::set_penalty_function(
MinimumValuePenaltyFunction new_penalty_function) {
set_penalty_function_impl(new_penalty_function, &penalty_function_,
&penalty_output_scaling_);
}
template <typename T>
void MinimumValueUpperBoundConstraint::DoEvalGeneric(
const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const {
// If we know that Values() will return at most zero values, then this
// is a non-constraint. Set y=2 which always satisfies the constraint is y
// >= 1.
const double y_for_empty_value = 2;
EvalGeneric<T>(minimum_value_upper_, max_num_values_, y_for_empty_value,
influence_value_, value_function_double_, value_function_,
SmoothUnderMax<double>, SmoothUnderMax<T>, penalty_function_,
penalty_output_scaling_, x, y);
}
void MinimumValueUpperBoundConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric<double>(x, y);
}
void MinimumValueUpperBoundConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DoEvalGeneric<AutoDiffXd>(x, y);
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/evaluator_base.h | #pragma once
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include <Eigen/Core>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/fmt_ostream.h"
#include "drake/common/polynomial.h"
#include "drake/common/symbolic/expression.h"
#include "drake/math/autodiff.h"
#include "drake/solvers/function.h"
namespace drake {
namespace solvers {
/**
* Provides an abstract interface to represent an expression, mapping a fixed
* or dynamic number of inputs to a fixed number of outputs, that may be
* evaluated on a scalar type of double or AutoDiffXd.
*
* These objects, and its derivatives, are meant to be bound to a given set
* of variables using the Binding<> class.
*/
class EvaluatorBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(EvaluatorBase)
virtual ~EvaluatorBase() {}
// TODO(bradking): consider using a Ref for `y`. This will require the client
// to do allocation, but also allows it to choose stack allocation instead.
/**
* Evaluates the expression.
* @param[in] x A `num_vars` x 1 input vector.
* @param[out] y A `num_outputs` x 1 output vector.
*/
void Eval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DRAKE_ASSERT(x.rows() == num_vars_ || num_vars_ == Eigen::Dynamic);
DoEval(x, y);
DRAKE_ASSERT(y->rows() == num_outputs_);
}
// TODO(eric.cousineau): Move this to DifferentiableConstraint derived class
// if/when we need to support non-differentiable functions (at least, if
// DifferentiableConstraint is ever implemented).
/**
* Evaluates the expression.
* @param[in] x A `num_vars` x 1 input vector.
* @param[out] y A `num_outputs` x 1 output vector.
*/
void Eval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DRAKE_ASSERT(x.rows() == num_vars_ || num_vars_ == Eigen::Dynamic);
DoEval(x, y);
DRAKE_ASSERT(y->rows() == num_outputs_);
}
/**
* Evaluates the expression.
* @param[in] x A `num_vars` x 1 input vector.
* @param[out] y A `num_outputs` x 1 output vector.
*/
void Eval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DRAKE_ASSERT(x.rows() == num_vars_ || num_vars_ == Eigen::Dynamic);
DoEval(x, y);
DRAKE_ASSERT(y->rows() == num_outputs_);
}
/**
* Set a human-friendly description for the evaluator.
*/
void set_description(const std::string& description) {
description_ = description;
}
/**
* Getter for a human-friendly description for the evaluator.
*/
const std::string& get_description() const { return description_; }
/**
* Formats this evaluator into the given stream using `vars` for the bound
* decision variable names.
*
* The size of `vars` must match the `num_vars()` declared by this evaluator.
* (If `num_vars()` is `Eigen::Dynamic`, then `vars` may be any size.)
*/
std::ostream& Display(std::ostream& os,
const VectorX<symbolic::Variable>& vars) const;
/**
* Formats this evaluator into the given stream, without displaying the
* decision variables it is bound to.
*/
std::ostream& Display(std::ostream& os) const;
/** Returns a LaTeX string describing this evaluator. Does not include any
* characters to enter/exit math mode; you might want, e.g. "$$" +
* evaluator.ToLatex() + "$$". */
std::string ToLatex(const VectorX<symbolic::Variable>& vars,
int precision = 3) const;
/**
* Getter for the number of variables, namely the number of rows in x, as
* used in Eval(x, y).
*/
int num_vars() const { return num_vars_; }
/**
* Getter for the number of outputs, namely the number of rows in y, as used
* in Eval(x, y).
*/
int num_outputs() const { return num_outputs_; }
/**
* Set the sparsity pattern of the gradient matrix ∂y/∂x (the gradient of
* y value in Eval, w.r.t x in Eval) . gradient_sparsity_pattern contains
* *all* the pairs of (row_index, col_index) for which the corresponding
* entries could have non-zero value in the gradient matrix ∂y/∂x.
*/
void SetGradientSparsityPattern(
const std::vector<std::pair<int, int>>& gradient_sparsity_pattern);
/**
* Returns the vector of (row_index, col_index) that contains all the entries
* in the gradient of Eval function (∂y/∂x) whose value could be non-zero,
* namely if ∂yᵢ/∂xⱼ could be non-zero, then the pair (i, j) is in
* gradient_sparsity_pattern.
* @retval gradient_sparsity_pattern If nullopt, then we regard all entries of
* the gradient as potentially non-zero.
*/
const std::optional<std::vector<std::pair<int, int>>>&
gradient_sparsity_pattern() const {
return gradient_sparsity_pattern_;
}
protected:
/**
* Constructs a evaluator.
* @param num_outputs. The number of rows in the output.
* @param num_vars. The number of rows in the input.
* If the input dimension is not known, then set `num_vars` to Eigen::Dynamic.
* @param description A human-friendly description.
* @see Eval(...)
*/
EvaluatorBase(int num_outputs, int num_vars,
const std::string& description = "")
: num_vars_(num_vars),
num_outputs_(num_outputs),
description_(description) {}
/**
* Implements expression evaluation for scalar type double.
* @param x Input vector.
* @param y Output vector.
* @pre x must be of size `num_vars` x 1.
* @post y will be of size `num_outputs` x 1.
*/
virtual void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const = 0;
/**
* Implements expression evaluation for scalar type AutoDiffXd.
* @param x Input vector.
* @param y Output vector.
* @pre x must be of size `num_vars` x 1.
* @post y will be of size `num_outputs` x 1.
*/
virtual void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const = 0;
/**
* Implements expression evaluation for scalar type symbolic::Expression.
* @param[in] x Input vector.
* @param[out] y Output vector.
* @pre x must be of size `num_vars` x 1.
* @post y will be of size `num_outputs` x 1.
*/
virtual void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const = 0;
/**
* NVI implementation of Display. The default implementation will report
* the NiceTypeName, get_description, and list the bound variables.
* Subclasses may override to customize the message.
* @pre vars size is consistent with num_vars".
*/
virtual std::ostream& DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const;
virtual std::string DoToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const;
// Setter for the number of outputs.
// This method is only meant to be called, if the sub-class structure permits
// to change the number of outputs. One example is LinearConstraint in
// solvers/Constraint.h, which can change the number of outputs, if the
// matrix in the linear constraint is resized.
void set_num_outputs(int num_outputs) { num_outputs_ = num_outputs; }
private:
int num_vars_{};
int num_outputs_{};
std::string description_;
// gradient_sparsity_pattern_ records the pair (row_index, col_index) that
// contains the non-zero entries in the gradient of the Eval
// function. Note that if the entry (row_index, col_index) *can* be non-zero
// for certain value of x, then it should be included in
// gradient_sparsity_patten_. When gradient_sparsity_pattern_.has_value() =
// false, the gradient matrix is regarded as non-sparse, i.e., every entry of
// the gradient matrix can be non-zero.
std::optional<std::vector<std::pair<int, int>>> gradient_sparsity_pattern_;
};
/**
* Print out the evaluator.
*/
std::ostream& operator<<(std::ostream& os, const EvaluatorBase& e);
/**
* Implements an evaluator of the form P(x, y...) where P is a multivariate
* polynomial in x, y, ...
*
* The Polynomial class uses a different variable naming scheme; thus the
* caller must provide a list of Polynomial::VarType variables that correspond
* to the members of the Binding<> (the individual scalar elements of the
* given VariableList).
*/
class PolynomialEvaluator : public EvaluatorBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PolynomialEvaluator)
/**
* Constructs a polynomial evaluator given a set of polynomials and the
* corresponding variables.
* @param polynomials Polynomial vector, a `num_outputs` x 1 vector.
* @param poly_vars Polynomial variables, a `num_vars` x 1 vector.
*/
PolynomialEvaluator(const VectorXPoly& polynomials,
const std::vector<Polynomiald::VarType>& poly_vars)
: EvaluatorBase(polynomials.rows(), poly_vars.size()),
polynomials_(polynomials),
poly_vars_(poly_vars) {}
const VectorXPoly& polynomials() const { return polynomials_; }
const std::vector<Polynomiald::VarType>& poly_vars() const {
return poly_vars_;
}
private:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const override {
throw std::logic_error(
"PolynomialEvaluator does not support symbolic evaluation.");
}
const VectorXPoly polynomials_;
const std::vector<Polynomiald::VarType> poly_vars_;
// To avoid repeated allocation, reuse a map for the evaluation point.
// Do not assume that these values will persist across invocations!
// TODO(eric.cousineau): Consider removing this for thread safety?
mutable std::map<Polynomiald::VarType, double> double_evaluation_point_temp_;
mutable std::map<Polynomiald::VarType, AutoDiffXd>
taylor_evaluation_point_temp_;
};
/**
* An evaluator that may be specified using a callable object. Consider
* constructing these instances using MakeFunctionEvaluator(...).
* @tparam F The function / functor's type.
*/
template <typename F>
class FunctionEvaluator : public EvaluatorBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FunctionEvaluator)
/**
* Constructs an instance by copying from an lvalue or rvalue of `F`.
* @tparam FF Perfect-forwarding type of `F` (e.g., `const F&`, `F&&`).
* @param f The callable object. If rvalue, this value will be std::move'd.
* Otherwise, it will be copied.
* @param args Arguments to be forwarded to EvaluatorBase constructor.
*/
template <typename FF, typename... Args>
FunctionEvaluator(FF&& f, Args&&... args)
: EvaluatorBase(internal::FunctionTraits<F>::numOutputs(f),
internal::FunctionTraits<F>::numInputs(f),
std::forward<Args>(args)...),
f_(std::forward<FF>(f)) {}
private:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override {
y->resize(internal::FunctionTraits<F>::numOutputs(f_));
DRAKE_ASSERT(static_cast<size_t>(x.rows()) ==
internal::FunctionTraits<F>::numInputs(f_));
DRAKE_ASSERT(static_cast<size_t>(y->rows()) ==
internal::FunctionTraits<F>::numOutputs(f_));
internal::FunctionTraits<F>::eval(f_, x, y);
}
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override {
y->resize(internal::FunctionTraits<F>::numOutputs(f_));
DRAKE_ASSERT(static_cast<size_t>(x.rows()) ==
internal::FunctionTraits<F>::numInputs(f_));
DRAKE_ASSERT(static_cast<size_t>(y->rows()) ==
internal::FunctionTraits<F>::numOutputs(f_));
internal::FunctionTraits<F>::eval(f_, x, y);
}
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const override {
throw std::logic_error(
"FunctionEvaluator does not support symbolic evaluation.");
}
const F f_;
};
/**
* Creates a FunctionEvaluator instance bound to a given callable object.
* @tparam FF Perfect-forwarding type of `F` (e.g., `const F&`, `F&&`).
* @param f Callable function object.
* @return An implementation of EvaluatorBase using the callable object.
* @relates FunctionEvaluator
*/
template <typename FF>
std::shared_ptr<EvaluatorBase> MakeFunctionEvaluator(FF&& f) {
using F = std::decay_t<FF>;
return std::make_shared<FunctionEvaluator<F>>(std::forward<FF>(f));
}
/**
* Defines a simple evaluator with no outputs that takes a callback function
* pointer. This is intended for debugging / visualization of intermediate
* results during an optimization (for solvers that support it).
*/
class VisualizationCallback : public EvaluatorBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(VisualizationCallback)
typedef std::function<void(const Eigen::Ref<const Eigen::VectorXd>&)>
CallbackFunction;
VisualizationCallback(int num_inputs, const CallbackFunction& callback,
const std::string& description = "")
: EvaluatorBase(0, num_inputs, description), callback_(callback) {}
void EvalCallback(const Eigen::Ref<const Eigen::VectorXd>& x) const {
DRAKE_ASSERT(x.size() == num_vars());
callback_(x);
}
private:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override {
DRAKE_ASSERT(x.size() == num_vars());
y->resize(0);
callback_(x);
}
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override {
DRAKE_ASSERT(x.size() == num_vars());
y->resize(0);
callback_(math::ExtractValue(x));
}
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const override {
throw std::logic_error(
"VisualizationCallback does not support symbolic evaluation.");
}
const CallbackFunction callback_;
};
} // namespace solvers
} // namespace drake
// TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<.
namespace fmt {
template <typename T>
struct formatter<
T,
std::enable_if_t<std::is_base_of_v<drake::solvers::EvaluatorBase, T>, char>>
: drake::ostream_formatter {};
} // namespace fmt
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/gurobi_solver_internal.h | #pragma once
// For external users, please do not include this header file. It only exists so
// that we can expose the internals to gurobi_solver_internal_test.
#include <limits>
#include <vector>
// NOLINTNEXTLINE(build/include) False positive due to weird include style.
#include "gurobi_c.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
namespace internal {
// Adds a constraint of one of the following forms :
// lb ≤ A*x ≤ ub
// or
// A*x == lb
//
// @param is_equality True if the imposed constraint is
// A*x == lb, false otherwise.
// @param[in, out] num_gurobi_linear_constraints The number of linear
// constraints stored in the gurobi model.
// @return error as an integer. The full set of error values are
// described here :
// https://www.gurobi.com/documentation/10.0/refman/error_codes.html
// This function assumes `vars` doesn't contain duplicate variables.
int AddLinearConstraintNoDuplication(
const MathematicalProgram& prog, GRBmodel* model,
const Eigen::SparseMatrix<double>& A, const Eigen::VectorXd& lb,
const Eigen::VectorXd& ub, const VectorXDecisionVariable& vars,
bool is_equality, int* num_gurobi_linear_constraints);
// Add the linear constraint lb <= A * vars <= ub to Gurobi model.
int AddLinearConstraint(const MathematicalProgram& prog, GRBmodel* model,
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& lb, const Eigen::VectorXd& ub,
const VectorXDecisionVariable& vars, bool is_equality,
int* num_gurobi_linear_constraints);
/*
* Add (rotated) Lorentz cone constraints, that z = A*x+b is in the (rotated)
* Lorentz cone.
* A vector z is in the Lorentz cone, if
* z(0) >= sqrt(z(1)^2 + ... + z(N-1)^2)
* A vector z is in the rotated Lorentz cone, if
* z(0)*z(1) >= z(2)^2 + ... + z(N-1)^2
* z(0) >= 0, z(1) >= 0
* @tparam C A constraint type, either LorentzConeConstraint or
* RotatedLorentzConeConstraint.
* @param second_order_cone_constraints A vector of Binding objects, containing
* either Lorentz cone constraints, or rotated Lorentz cone constraints.
* @param second_order_cone_new_variable_indices. The indices of variable z in
* the Gurobi model.
* @param model The Gurobi model.
* @param[in, out] num_gurobi_linear_constraints The number of linear
* constraints stored in the gurobi model.
*/
template <typename C>
int AddSecondOrderConeConstraints(
const MathematicalProgram& prog,
const std::vector<Binding<C>>& second_order_cone_constraints,
const std::vector<std::vector<int>>& second_order_cone_new_variable_indices,
GRBmodel* model, int* num_gurobi_linear_constraints);
// For Lorentz and rotated Lorentz cone constraints
// Ax + b in (rotated) Lorentz cone, we will introduce new variables z as
// z = Ax+b
// z in (rotated) Lorentz cone.
// So add the new variable z before constructing the Gurobi model, as
// recommended by the Gurobi manual, to add all decision variables at once
// when constructing the problem.
// @param second_order_cone_variable_indices
// second_order_cone_variable_indices[i]
// contains the indices of the newly added variable z for the i'th second order
// cone in @p second_order_cones[i].
// @p tparam C Either LorentzConeConstraint or RotatedLorentzConeConstraint.
// TODO(hongkai.dai): rewrite this function not templated on Binding, when
// Binding class is moved out from MathematicalProgram as a public class.
// @param second_order_cones A vector of bindings, containing either Lorentz
// cone constraint, or rotated Lorentz cone constraint.
// @param is_new_variable is_new_variable[i] is true if the i'th variable in
// Gurobi model is not included in MathematicalProgram.
// @param num_gurobi_vars Number of variables in Gurobi model.
// @param second_order_cone_variable_indices
// second_order_cone_variable_indices[i]
// contains the indices of variable z stored in Gurobi model, in \p
// second_order_cones[i].
// @param gurobi_var_type. The type of the Gurobi variables.
// @param xlow The lower bound of the Gurobi variables.
// @param xupp The upper bound of the Gurobi variables.
template <typename C>
void AddSecondOrderConeVariables(
const std::vector<Binding<C>>& second_order_cones,
std::vector<bool>* is_new_variable, int* num_gurobi_vars,
std::vector<std::vector<int>>* second_order_cone_variable_indices,
std::vector<char>* gurobi_var_type, std::vector<double>* xlow,
std::vector<double>* xupp);
// For an L2 norm cost min |Cx+d|₂, we consider introducing a Lorentz cone
// constraint as
// z in Lorentz cone.
// z[1:] = C*x + d
// min z[0]
// So we will need to add the slack variable z.
// @param[in/out] is_new_variable is_new_variable[i] is true if the i'th
// variable in Gurobi model is not included in MathematicalProgram.
// @param[in/out] num_gurobi_vars Number of variables in Gurobi model.
// @param[out] lorentz_cone_variable_indices lorentz_cone_variable_indices[i] is
// the indices of the variable z for l2_norm_costs[i] in the Gurobi model.
// @param[in/out] gurobi_var_type gurobi_var_type[i] is the type of the i'th
// variable in the Gurobi model.
// @param[in/out] xlow The lower bound of the Gurobi variables.
// @param[in/out] xupp The upper bound of the Gurobi variables.
void AddL2NormCostVariables(
const std::vector<Binding<L2NormCost>>& l2_norm_costs,
std::vector<bool>* is_new_variable, int* num_gurobi_vars,
std::vector<std::vector<int>>* lorentz_cone_variable_indices,
std::vector<char>* gurobi_var_type, std::vector<double>* xlow,
std::vector<double>* xupp);
// Adds L2 norm cost |Cx+d|₂ to Gurobi.
// We introduce a Lorentz cone constraint as
// z in Lorentz cone.
// z[1:] = C*x + d
// min z[0]
// @param[in] prog All prog.l2norm_costs() will be added to Gurobi model.
// @param[in] l2norm_costs_lorentz_cone_variable_indices
// l2norm_costs_lorentz_cone_variable_indices[i] are the indices of the slack
// variable z for prog.l2norm_costs()[i] in Gurobi model.
// @param[in/out] model The Gurobi model.
// @param[in/out] num_gurobi_linear_constraints The number of linear constraints
// in Gurobi before/after calling this function.
int AddL2NormCosts(const MathematicalProgram& prog,
const std::vector<std::vector<int>>&
l2norm_costs_lorentz_cone_variable_indices,
GRBmodel* model, int* num_gurobi_linear_constraints);
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/csdp_solver_internal.h | #pragma once
// For external users, please do not include this header file. It only exists so
// that we can expose the internals to csdp_solver_internal_test.cc
#include <vector>
#include <Eigen/Core>
#include <Eigen/Sparse>
#include "drake/solvers/csdp_cpp_wrapper.h"
#include "drake/solvers/sdpa_free_format.h"
namespace drake {
namespace solvers {
namespace internal {
/**
* For a problem
* max tr(C * X)
* s.t tr(Ai * X) = rhs_i
* X ≽ 0
* We are given C, Ai, rhs in the Eigen sparse matrix format, convert these data
* to CSDP format.
* This function allocates memory for the CSDP solver, by allocating memory to
* @p C_csdp, @p rhs_csdp and @p constraints. The memory should be cleared by
* calling FreeCsdpProblemData().
*/
void ConvertSparseMatrixFormatToCsdpProblemData(
const std::vector<BlockInX>& X_blocks, const Eigen::SparseMatrix<double>& C,
const std::vector<Eigen::SparseMatrix<double>> A,
const Eigen::VectorXd& rhs, csdp::blockmatrix* C_csdp, double** rhs_csdp,
csdp::constraintmatrix** constraints);
/**
* Converts to a CSDP problem data if `sdpa_free_format` has no free variables.
* @throws std::exception if sdpa_free_format has free variables.
*/
void GenerateCsdpProblemDataWithoutFreeVariables(
const SdpaFreeFormat& sdpa_free_format, csdp::blockmatrix* C, double** b,
csdp::constraintmatrix** constraints);
void ConvertCsdpBlockMatrixtoEigen(const csdp::blockmatrix& X_csdp,
Eigen::SparseMatrix<double>* X);
void FreeCsdpProblemData(int num_constraints, csdp::blockmatrix C_csdp,
double* rhs_csdp, csdp::constraintmatrix* constraints);
/**
* Csdp internally stores each block of the matrix as an array. This function
* takes the row and column index inside this block (the row/column indices are
* 0-indexed), and return the index of the entry in the array.
*/
int CsdpMatrixIndex(int row, int col, int num_rows);
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/scs_clarabel_common.h | // The solvers Clarabel and Scs share a lot of similar APIs. This file contains
// some common functions for ClarabelSolver and ScsSolver
#pragma once
#include <utility>
#include <vector>
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mathematical_program_result.h"
namespace drake {
namespace solvers {
namespace internal {
// @param dual The pointer to the start of the dual solution.
// @param dual_length The length of the dual solution (as a continuous chunk of
// memory).
// @param linear_constraint_dual_indices
// linear_constraint_dual_indices[i][j][0]/linear_constraint_dual_indices[i][j][1]
// is the index of the dual variable for the lower/upper bound of the j'th row
// in the linear constraint prog.linear_constraint()[i]. We use an index of -1
// to indicate that the lower or upper bound is infinity and therefore there is
// no associated dual variable.
// @param linear_eq_y_start_indices 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.
// @param lorentz_cone_y_start_indices lorentz_cone_y_start_indices[i] is the
// starting index of the dual variable for the constraint
// prog.lorentz_cone_constraints()[i]. 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].
// @param rotated_lorentz_cone_y_start_indices
// rotated_lorentz_cone_y_start_indices[i] is the starting index of the dual
// variable for the constraint prog.rotated_lorentz_cone_constraints()[i].
// y[rotated_lorentz_cone_y_start_indices[i]:
// rotated_lorentz_cone_y_start_indices[i] + second_order_cone_length[i]]
// are the dual variables for prog.rotated_lorentz_cone_constraints()[i].
void SetDualSolution(
const MathematicalProgram& prog,
const Eigen::Ref<const Eigen::VectorXd>& dual,
const std::vector<std::vector<std::pair<int, int>>>&
linear_constraint_dual_indices,
const std::vector<int>& linear_eq_y_start_indices,
const std::vector<int>& lorentz_cone_y_start_indices,
const std::vector<int>& rotated_lorentz_cone_y_start_indices,
MathematicalProgramResult* result);
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solver_type.h | #pragma once
namespace drake {
namespace solvers {
/** This type only exists for backwards compatibility, and should not be used in
new code. */
enum class SolverType {
kClp,
kCsdp,
kEqualityConstrainedQP,
kGurobi,
kIpopt,
kLinearSystem,
kMobyLCP,
kMosek,
kNlopt,
kOsqp,
kSnopt,
kScs,
kUnrevisedLemke
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/cost.h | #pragma once
#include <cstddef>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include <Eigen/SparseCore>
#include "drake/common/drake_deprecated.h"
#include "drake/solvers/decision_variable.h"
#include "drake/solvers/evaluator_base.h"
#include "drake/solvers/sparse_and_dense_matrix.h"
namespace drake {
namespace solvers {
/**
* Provides an abstract base for all costs.
*
* @ingroup solver_evaluators
*/
class Cost : public EvaluatorBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Cost)
protected:
/**
* Constructs a cost evaluator.
* @param num_vars Number of input variables.
* @param description Human-friendly description.
*/
explicit Cost(int num_vars, const std::string& description = "")
: EvaluatorBase(1, num_vars, description) {}
};
/**
* Implements a cost of the form @f[ a'x + b @f].
*
* @ingroup solver_evaluators
*/
class LinearCost : public Cost {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearCost)
/**
* Construct a linear cost of the form @f[ a'x + b @f].
* @param a Linear term.
* @param b (optional) Constant term.
*/
// NOLINTNEXTLINE(runtime/explicit) This conversion is desirable.
LinearCost(const Eigen::Ref<const Eigen::VectorXd>& a, double b = 0.)
: Cost(a.rows()), a_(a), b_(b) {}
~LinearCost() override {}
Eigen::SparseMatrix<double> GetSparseMatrix() const {
// TODO(eric.cousineau): Consider storing or caching sparse matrix, such
// that we can return a const lvalue reference.
return a_.sparseView();
}
const Eigen::VectorXd& a() const { return a_; }
double b() const { return b_; }
/**
* Updates the coefficients of the cost.
* Note that the number of variables (size of a) cannot change.
* @param new_a New linear term.
* @param new_b (optional) New constant term.
*/
void UpdateCoefficients(const Eigen::Ref<const Eigen::VectorXd>& new_a,
double new_b = 0.) {
if (new_a.rows() != a_.rows()) {
throw std::runtime_error("Can't change the number of decision variables");
}
a_ = new_a;
b_ = new_b;
}
protected:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override;
std::ostream& DoDisplay(std::ostream&,
const VectorX<symbolic::Variable>&) const override;
std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override;
private:
template <typename DerivedX, typename U>
void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<U>* y) const;
Eigen::VectorXd a_;
double b_{};
};
/**
* Implements a cost of the form @f[ .5 x'Qx + b'x + c @f].
*
* @ingroup solver_evaluators
*/
class QuadraticCost : public Cost {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QuadraticCost)
/**
* Constructs a cost of the form @f[ .5 x'Qx + b'x + c @f].
* @param Q Quadratic term.
* @param b Linear term.
* @param c (optional) Constant term.
* @param is_hessian_psd (optional) Indicates if the Hessian matrix Q is
* positive semidefinite (psd) or not. If set to true, then the user
* guarantees that Q is psd; if set to false, then the user guarantees that Q
* is not psd. If set to std::nullopt, then the constructor will check if Q is
* psd or not. The default is std::nullopt. To speed up the constructor, set
* is_hessian_psd to either true or false.
*/
template <typename DerivedQ, typename Derivedb>
QuadraticCost(const Eigen::MatrixBase<DerivedQ>& Q,
const Eigen::MatrixBase<Derivedb>& b, double c = 0.,
std::optional<bool> is_hessian_psd = std::nullopt)
: Cost(Q.rows()), Q_((Q + Q.transpose()) / 2), b_(b), c_(c) {
DRAKE_ASSERT(Q_.rows() == Q_.cols());
DRAKE_ASSERT(Q_.cols() == b_.rows());
if (is_hessian_psd.has_value()) {
is_convex_ = is_hessian_psd.value();
} else {
is_convex_ = CheckHessianPsd();
}
}
~QuadraticCost() override {}
/// Returns the symmetric matrix Q, as the Hessian of the cost.
const Eigen::MatrixXd& Q() const { return Q_; }
const Eigen::VectorXd& b() const { return b_; }
double c() const { return c_; }
/**
* Returns true if this cost is convex. A quadratic cost if convex if and only
* if its Hessian matrix Q is positive semidefinite.
*/
bool is_convex() const { return is_convex_; }
/**
* Updates the quadratic and linear term of the constraint. The new
* matrices need to have the same dimension as before.
* @param new_Q New quadratic term.
* @param new_b New linear term.
* @param new_c (optional) New constant term.
* @param is_hessian_psd (optional) Indicates if the Hessian matrix Q is
* positive semidefinite (psd) or not. If set to true, then the user
* guarantees that Q is psd; if set to false, then the user guarantees that Q
* is not psd. If set to std::nullopt, then this function will check if Q is
* psd or not. The default is std::nullopt. To speed up the computation, set
* is_hessian_psd to either true or false.
*/
template <typename DerivedQ, typename DerivedB>
void UpdateCoefficients(const Eigen::MatrixBase<DerivedQ>& new_Q,
const Eigen::MatrixBase<DerivedB>& new_b,
double new_c = 0.,
std::optional<bool> is_hessian_psd = std::nullopt) {
if (new_Q.rows() != new_Q.cols() || new_Q.rows() != new_b.rows() ||
new_b.cols() != 1) {
throw std::runtime_error("New constraints have invalid dimensions");
}
if (new_b.rows() != b_.rows()) {
throw std::runtime_error("Can't change the number of decision variables");
}
Q_ = (new_Q + new_Q.transpose()) / 2;
b_ = new_b;
c_ = new_c;
if (is_hessian_psd.has_value()) {
is_convex_ = is_hessian_psd.value();
} else {
is_convex_ = CheckHessianPsd();
}
}
private:
template <typename DerivedX, typename U>
void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<U>* y) const;
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override;
std::ostream& DoDisplay(std::ostream&,
const VectorX<symbolic::Variable>&) const override;
std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override;
bool CheckHessianPsd();
Eigen::MatrixXd Q_;
Eigen::VectorXd b_;
double c_{};
bool is_convex_{};
};
/**
* Creates a cost term of the form (x-x_desired)'*Q*(x-x_desired).
*
* @ingroup solver_evaluators
*/
std::shared_ptr<QuadraticCost> MakeQuadraticErrorCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& x_desired);
/**
* Creates a quadratic cost of the form |Ax-b|²=(Ax-b)ᵀ(Ax-b)
*
* @ingroup solver_evaluators
*/
std::shared_ptr<QuadraticCost> Make2NormSquaredCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b);
/**
* Implements a cost of the form ‖Ax + b‖₁. Note that this cost is
* non-differentiable when any element of Ax + b equals zero.
*
* @ingroup solver_evaluators
*/
class L1NormCost : public Cost {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(L1NormCost)
/**
* Construct a cost of the form ‖Ax + b‖₁.
* @param A Linear term.
* @param b Constant term.
*/
L1NormCost(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b);
~L1NormCost() override {}
const Eigen::MatrixXd& A() const { return A_; }
const Eigen::VectorXd& b() const { return b_; }
/**
* Updates the coefficients of the cost.
* Note that the number of variables (columns of A) cannot change.
* @param new_A New linear term.
* @param new_b New constant term.
*/
void UpdateCoefficients(const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b);
protected:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override;
std::ostream& DoDisplay(std::ostream&,
const VectorX<symbolic::Variable>&) const override;
std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override;
private:
Eigen::MatrixXd A_;
Eigen::VectorXd b_;
};
/**
* Implements a cost of the form ‖Ax + b‖₂.
*
* @ingroup solver_evaluators
*/
class L2NormCost : public Cost {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(L2NormCost)
// TODO(russt): Add an option to select an implementation that smooths the
// gradient discontinuity at the origin.
/**
* Construct a cost of the form ‖Ax + b‖₂.
* @param A Linear term.
* @param b Constant term.
* @pydrake_mkdoc_identifier{dense_A}
*/
L2NormCost(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b);
/**
* Overloads constructor with a sparse A matrix.
* @pydrake_mkdoc_identifier{sparse_A}
*/
L2NormCost(const Eigen::SparseMatrix<double>& A,
const Eigen::Ref<const Eigen::VectorXd>& b);
~L2NormCost() override {}
DRAKE_DEPRECATED("2024-08-01", "Use A_dense function instead.")
const Eigen::MatrixXd& A() const { return GetDenseA(); }
const Eigen::SparseMatrix<double>& get_sparse_A() const {
return A_.get_as_sparse();
}
const Eigen::MatrixXd& GetDenseA() const { return A_.GetAsDense(); }
const Eigen::VectorXd& b() const { return b_; }
/**
* Updates the coefficients of the cost.
* Note that the number of variables (columns of A) cannot change.
* @param new_A New linear term.
* @param new_b New constant term.
* @pydrake_mkdoc_identifier{dense_A}
*/
void UpdateCoefficients(const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b);
/**
* Overloads UpdateCoefficients but with a sparse A matrix.
* @pydrake_mkdoc_identifier{sparse_A}
*/
void UpdateCoefficients(const Eigen::SparseMatrix<double>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b);
protected:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override;
std::ostream& DoDisplay(std::ostream&,
const VectorX<symbolic::Variable>&) const override;
std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override;
private:
internal::SparseAndDenseMatrix A_;
Eigen::VectorXd b_;
};
/**
* Implements a cost of the form ‖Ax + b‖∞. Note that this cost is
* non-differentiable when any two or more elements of Ax + b are equal.
*
* @ingroup solver_evaluators
*/
class LInfNormCost : public Cost {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LInfNormCost)
/**
* Construct a cost of the form ‖Ax + b‖∞.
* @param A Linear term.
* @param b Constant term.
*/
LInfNormCost(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b);
~LInfNormCost() override {}
const Eigen::MatrixXd& A() const { return A_; }
const Eigen::VectorXd& b() const { return b_; }
/**
* Updates the coefficients of the cost.
* Note that the number of variables (columns of A) cannot change.
* @param new_A New linear term.
* @param new_b New constant term.
*/
void UpdateCoefficients(const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b);
protected:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override;
std::ostream& DoDisplay(std::ostream&,
const VectorX<symbolic::Variable>&) const override;
std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override;
private:
Eigen::MatrixXd A_;
Eigen::VectorXd b_;
};
/**
* If \f$ z = Ax + b,\f$ implements a cost of the form:
* @f[
* (z_1^2 + z_2^2 + ... + z_{n-1}^2) / z_0.
* @f]
* Note that this cost is convex when we additionally constrain z_0 > 0. It is
* treated as a generic nonlinear objective by most solvers.
*
* Costs of this form are sometimes referred to as "quadratic over linear".
*
* @ingroup solver_evaluators
*/
class PerspectiveQuadraticCost : public Cost {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PerspectiveQuadraticCost)
/**
* Construct a cost of the form (z_1^2 + z_2^2 + ... + z_{n-1}^2) / z_0 where
* z = Ax + b.
* @param A Linear term.
* @param b Constant term.
*/
PerspectiveQuadraticCost(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b);
~PerspectiveQuadraticCost() override {}
const Eigen::MatrixXd& A() const { return A_; }
const Eigen::VectorXd& b() const { return b_; }
/**
* Updates the coefficients of the cost.
* Note that the number of variables (columns of A) cannot change.
* @param new_A New linear term.
* @param new_b New constant term.
*/
void UpdateCoefficients(const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b);
protected:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override;
std::ostream& DoDisplay(std::ostream&,
const VectorX<symbolic::Variable>&) const override;
std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override;
private:
template <typename DerivedX, typename U>
void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<U>* y) const;
Eigen::MatrixXd A_;
Eigen::VectorXd b_;
};
/**
* A cost that may be specified using another (potentially nonlinear)
* evaluator.
* @tparam EvaluatorType The nested evaluator.
*
* @ingroup solver_evaluators
*/
// TODO(hongkai.dai):
// MathematicalProgram::AddCost(EvaluatorCost<LinearConstraint>(...)) should
// recognize that the compounded cost is linear.
template <typename EvaluatorType = EvaluatorBase>
class EvaluatorCost : public Cost {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(EvaluatorCost)
explicit EvaluatorCost(const std::shared_ptr<EvaluatorType>& evaluator)
: Cost(evaluator->num_vars()),
evaluator_{evaluator},
a_{std::nullopt},
b_{0} {
DRAKE_DEMAND(evaluator->num_outputs() == 1);
}
/**
* This cost computes a.dot(evaluator(x)) + b
* @pre a.rows() == evaluator->num_outputs()
*/
EvaluatorCost(const std::shared_ptr<EvaluatorType>& evaluator,
const Eigen::Ref<const Eigen::VectorXd>& a, double b = 0)
: Cost(evaluator->num_vars()), evaluator_(evaluator), a_{a}, b_{b} {
DRAKE_DEMAND(evaluator->num_outputs() == a_->rows());
}
protected:
const EvaluatorType& evaluator() const { return *evaluator_; }
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override {
this->DoEvalGeneric<double, double>(x, y);
}
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override {
this->DoEvalGeneric<AutoDiffXd, AutoDiffXd>(x, y);
}
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override {
this->DoEvalGeneric<symbolic::Variable, symbolic::Expression>(x, y);
}
private:
template <typename T, typename S>
void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x,
VectorX<S>* y) const {
if (a_.has_value()) {
VectorX<S> y_inner;
evaluator_->Eval(x, &y_inner);
y->resize(1);
(*y)(0) = a_->dot(y_inner) + b_;
} else {
evaluator_->Eval(x, y);
}
}
std::shared_ptr<EvaluatorType> evaluator_;
std::optional<Eigen::VectorXd> a_;
double b_{};
};
/**
* Implements a cost of the form P(x, y...) where P is a multivariate
* polynomial in x, y, ...
*
* The Polynomial class uses a different variable naming scheme; thus the
* caller must provide a list of Polynomial::VarType variables that correspond
* to the members of the Binding<> (the individual scalar elements of the
* given VariableList).
*
* @ingroup solver_evaluators
*/
class PolynomialCost : public EvaluatorCost<PolynomialEvaluator> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PolynomialCost)
/**
* Constructs a polynomial cost
* @param polynomials Polynomial vector, a 1 x 1 vector.
* @param poly_vars Polynomial variables, a `num_vars` x 1 vector.
*/
PolynomialCost(const VectorXPoly& polynomials,
const std::vector<Polynomiald::VarType>& poly_vars)
: EvaluatorCost(
std::make_shared<PolynomialEvaluator>(polynomials, poly_vars)) {}
const VectorXPoly& polynomials() const { return evaluator().polynomials(); }
const std::vector<Polynomiald::VarType>& poly_vars() const {
return evaluator().poly_vars();
}
};
/**
* Impose a generic (potentially nonlinear) cost represented as a symbolic
* Expression. Expression::Evaluate is called on every constraint evaluation.
*
* Uses symbolic::Jacobian to provide the gradients to the AutoDiff method.
*
* @ingroup solver_evaluators
*/
class ExpressionCost : public Cost {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ExpressionCost)
explicit ExpressionCost(const symbolic::Expression& e);
/**
* @return the list of the variables involved in the vector of expressions,
* in the order that they are expected to be received during DoEval.
* Any Binding that connects this constraint to decision variables should
* pass this list of variables to the Binding.
*/
const VectorXDecisionVariable& vars() const;
/** @return the symbolic expression. */
const symbolic::Expression& expression() const;
protected:
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override;
std::ostream& DoDisplay(std::ostream&,
const VectorX<symbolic::Variable>&) const override;
std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override;
private:
std::unique_ptr<EvaluatorBase> evaluator_;
};
/**
* Converts an input of type @p F to a nonlinear cost.
* @tparam FF The forwarded function type (e.g., `const F&, `F&&`, ...).
* The class `F` should have functions numInputs(), numOutputs(), and
* eval(x, y).
*
* @ingroup solver_evaluators
*/
template <typename FF>
std::shared_ptr<Cost> MakeFunctionCost(FF&& f) {
return std::make_shared<EvaluatorCost<>>(
MakeFunctionEvaluator(std::forward<FF>(f)));
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/no_csdp.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/csdp_solver.h"
/* clang-format on */
#include <stdexcept>
namespace drake {
namespace solvers {
bool CsdpSolver::is_available() {
return false;
}
void CsdpSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&,
const SolverOptions&,
MathematicalProgramResult*) const {
throw std::runtime_error(
"The CSDP bindings were not compiled. You'll need to use a different "
"solver.");
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/semidefinite_relaxation_internal.cc | #include "drake/solvers/semidefinite_relaxation_internal.h"
#include <algorithm>
#include <limits>
#include <vector>
#include "drake/common/fmt_eigen.h"
#include "drake/common/symbolic/decompose.h"
#include "drake/math/matrix_util.h"
namespace drake {
namespace solvers {
namespace internal {
using Eigen::SparseMatrix;
using Eigen::Triplet;
using symbolic::Expression;
using symbolic::Variable;
using symbolic::Variables;
namespace {
const double kInf = std::numeric_limits<double>::infinity();
} // namespace
Eigen::SparseMatrix<double> SparseKroneckerProduct(
const Eigen::SparseMatrix<double>& A,
const Eigen::SparseMatrix<double>& B) {
Eigen::SparseMatrix<double> C(A.rows() * B.rows(), A.cols() * B.cols());
std::vector<Eigen::Triplet<double>> C_triplets;
C_triplets.reserve(A.nonZeros() * B.nonZeros());
C.reserve(A.nonZeros() * B.nonZeros());
for (int iA = 0; iA < A.outerSize(); ++iA) {
for (SparseMatrix<double>::InnerIterator itA(A, iA); itA; ++itA) {
for (int iB = 0; iB < B.outerSize(); ++iB) {
for (SparseMatrix<double>::InnerIterator itB(B, iB); itB; ++itB) {
C_triplets.emplace_back(itA.row() * B.rows() + itB.row(),
itA.col() * B.cols() + itB.col(),
itA.value() * itB.value());
}
}
}
}
C.setFromTriplets(C_triplets.begin(), C_triplets.end());
return C;
}
SparseMatrix<double> GetWAdjForTril(const int r) {
DRAKE_DEMAND(r > 0);
// Y is a symmetric matrix of size (r-1) hence we have (r choose 2) lower
// triangular entries.
const int Y_tril_size = (r * (r - 1)) / 2;
std::vector<Triplet<double>> W_adj_triplets;
// The map operates on the diagonal twice, and then on one of the columns
// without the first element once.
W_adj_triplets.reserve(2 * (r - 1) + (r - 2));
int idx = 0;
for (int i = 0; idx < Y_tril_size; ++i) {
W_adj_triplets.emplace_back(0, idx, 1);
W_adj_triplets.emplace_back(1, idx, idx > 0 ? -1 : 1);
idx += (r - 1) - i;
}
for (int i = 2; i < r; ++i) {
W_adj_triplets.emplace_back(i, i - 1, 2);
}
SparseMatrix<double> W_adj(r, Y_tril_size);
W_adj.setFromTriplets(W_adj_triplets.begin(), W_adj_triplets.end());
return W_adj;
}
namespace {
template <typename T,
typename = std::enable_if_t<std::is_same_v<T, Expression> ||
std::is_same_v<T, Variable>>>
void DoAddMatrixIsLorentzByPositiveOrthantSeparableConstraint(
const Eigen::Ref<const MatrixX<T>>& X, MathematicalProgram* prog) {
for (int i = 0; i < X.cols(); ++i) {
// TODO(Alexandre.Amice) AddLorentzConeConstraint only has a MatrixBase
// version of the method not an Eigen::Ref version and so we need to make
// this temporary copy rather than being able to call
// prog->AddLorentzConeConstraint(X.col(i));
const VectorX<T> x = X.col(i);
prog->AddLorentzConeConstraint(x);
}
}
} // namespace
void AddMatrixIsLorentzByPositiveOrthantSeparableConstraint(
const Eigen::Ref<const MatrixX<Variable>>& X, MathematicalProgram* prog) {
DoAddMatrixIsLorentzByPositiveOrthantSeparableConstraint<Variable>(X, prog);
}
void AddMatrixIsLorentzByPositiveOrthantSeparableConstraint(
const Eigen::Ref<const MatrixX<Expression>>& X, MathematicalProgram* prog) {
DoAddMatrixIsLorentzByPositiveOrthantSeparableConstraint<Expression>(X, prog);
}
void AddMatrixIsPositiveOrthantByLorentzSeparableConstraint(
const Eigen::Ref<const MatrixX<Variable>>& X, MathematicalProgram* prog) {
DoAddMatrixIsLorentzByPositiveOrthantSeparableConstraint<Variable>(
X.transpose(), prog);
}
void AddMatrixIsPositiveOrthantByLorentzSeparableConstraint(
const Eigen::Ref<const MatrixX<Expression>>& X, MathematicalProgram* prog) {
DoAddMatrixIsLorentzByPositiveOrthantSeparableConstraint<Expression>(
X.transpose(), prog);
}
namespace {
// Special case when min(X.rows(), X.cols()) ≤ 2. In this case, the Lorentz cone
// is just a linear transformation of the positive orthant (i.e. the Lorentz
// cone is simplicial). Therefore, being Lorentz-Lorentz separable is
// equivalent to being Lorentz by positive orthant separable and should be
// encoded as such.
template <typename T,
typename = std::enable_if_t<std::is_same_v<T, Expression> ||
std::is_same_v<T, Variable>>>
void DoAddMatrixIsLorentzByLorentzSeparableConstraintSimplicialCase(
const Eigen::Ref<const Eigen::MatrixX<T>>& X, MathematicalProgram* prog) {
DRAKE_DEMAND(X.rows() <= 2 || X.cols() <= 2);
// In 2d, the Lorentz cone is x₀ ≥ 0 and x₀ ≥ √x₁² and so is equivalent to the
// constraint linear constraints x₀ ≥ 0, x₀ ≥ x₁, x₀ ≥ -x₁. This can be
// expressed as R(π/4) x ∈ ⊗ R₊ⁿ, where R(π/4) is rotation matrix by π/4
// counterclockwise. In 1d, the Lorentz cone is just x₀ ≥ 0 so there is
// nothing special that needs to be done.
Eigen::MatrixX<Expression> X_expr = X.template cast<Expression>();
const Eigen::Matrix2d R{{1 / std::sqrt(2), -1 / std::sqrt(2)},
{1 / std::sqrt(2), 1 / std::sqrt(2)}};
if (X.rows() == 2) {
X_expr = R * X_expr;
}
if (X.cols() == 2) {
X_expr = X_expr * R.transpose();
}
if (X.rows() <= 2 && X.cols() <= 2) {
// In this case, we have that X_expr must be
// positive-orthant-positive-orthant separable, i.e. pointwise positive.
prog->AddLinearConstraint(
X_expr, Eigen::MatrixXd::Zero(X_expr.rows(), X_expr.cols()),
kInf * Eigen::MatrixXd::Ones(X_expr.rows(), X_expr.cols()));
} else if (X.rows() > 2) {
AddMatrixIsLorentzByPositiveOrthantSeparableConstraint(X_expr, prog);
} else if (X.cols() > 2) {
AddMatrixIsPositiveOrthantByLorentzSeparableConstraint(X_expr, prog);
} else {
// Unreachable since X.rows() <= 2 || X.cols() <= 2.
DRAKE_UNREACHABLE();
}
}
// Constrain that the affine expression A * x + b, is Lorentz by Lorentz
// separable. Concretely, this means that the matrix
// Z = (A * x + b).reshaped(m,n) can be written as Z = ∑ᵢ λᵢuᵢwᵢᵀ where λᵢ ≥ 0,
// uᵢ is in the Lorentz cone of size m and w is in the Lorentz cone of size n.
void DoAddMatrixIsLorentzByLorentzSeparableConstraint(
const SparseMatrix<double>& A, const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorX<Variable>>& x, const int m, const int n,
MathematicalProgram* prog) {
DRAKE_DEMAND(A.rows() == n * m);
DRAKE_DEMAND(A.cols() == x.rows());
DRAKE_DEMAND(n > 2 || m > 2);
// The lower triangular part of Y ∈ S⁽ⁿ⁻¹⁾ ⊗ S⁽ᵐ⁻¹⁾
auto y = prog->NewContinuousVariables((n * (n - 1) * m * (m - 1)) / 4, "y");
MatrixX<Variable> Y = ToSymmetricMatrixFromTensorVector(y, n - 1, m - 1);
prog->AddPositiveSemidefiniteConstraint(Y);
const SparseMatrix<double> W_adj_n = GetWAdjForTril(n);
const SparseMatrix<double> W_adj_m = GetWAdjForTril(m);
// [W_adj_n ⊗ W_adj_m; -A]
SparseMatrix<double> CoefficientMat(
W_adj_m.rows() * W_adj_n.rows(),
W_adj_m.cols() * W_adj_n.cols() + A.cols());
std::vector<Triplet<double>> CoefficientMat_triplets;
CoefficientMat_triplets.reserve(W_adj_n.nonZeros() * W_adj_m.nonZeros() +
A.nonZeros());
// Set the left columns of CoefficientMat to W_adj_n ⊗ W_adj_m.
for (int idx_n = 0; idx_n < W_adj_n.outerSize(); ++idx_n) {
for (SparseMatrix<double>::InnerIterator it_n(W_adj_n, idx_n); it_n;
++it_n) {
for (int idx_m = 0; idx_m < W_adj_m.outerSize(); ++idx_m) {
for (SparseMatrix<double>::InnerIterator it_m(W_adj_m, idx_m); it_m;
++it_m) {
CoefficientMat_triplets.emplace_back(
it_n.row() * W_adj_m.rows() + it_m.row(),
it_n.col() * W_adj_m.cols() + it_m.col(),
it_n.value() * it_m.value());
}
}
}
}
int col = W_adj_m.cols() * W_adj_n.cols();
// Set the right columns of CoefficientMat to -A.
for (int i = 0; i < A.outerSize(); ++i) {
for (SparseMatrix<double>::InnerIterator it(A, i); it; ++it) {
CoefficientMat_triplets.emplace_back(it.row(), it.col() + col,
-it.value());
}
}
CoefficientMat.setFromTriplets(CoefficientMat_triplets.begin(),
CoefficientMat_triplets.end());
VectorX<Variable> yx(y.size() + x.size());
yx << y, x;
prog->AddLinearEqualityConstraint(CoefficientMat, b, yx);
}
} // namespace
void AddMatrixIsLorentzByLorentzSeparableConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X,
MathematicalProgram* prog) {
if (std::min(X.rows(), X.cols()) <= 2) {
DoAddMatrixIsLorentzByLorentzSeparableConstraintSimplicialCase(X, prog);
} else {
const int m = X.rows();
const int n = X.cols();
SparseMatrix<double> I(n * m, n * m);
I.setIdentity();
const Eigen::VectorX<Variable> x =
Eigen::Map<const Eigen::VectorX<Variable>>(X.data(), X.size());
DoAddMatrixIsLorentzByLorentzSeparableConstraint(
I, Eigen::VectorXd::Zero(I.rows()),
Eigen::Map<const Eigen::VectorX<Variable>>(X.data(), X.size()), m, n,
prog);
}
}
void AddMatrixIsLorentzByLorentzSeparableConstraint(
const Eigen::Ref<const MatrixX<Expression>>& X, MathematicalProgram* prog) {
if (std::min(X.rows(), X.cols()) <= 2) {
DoAddMatrixIsLorentzByLorentzSeparableConstraintSimplicialCase(X, prog);
} else {
const int m = X.rows();
const int n = X.cols();
Eigen::MatrixXd A;
Eigen::VectorXd b;
VectorX<Variable> x;
symbolic::DecomposeAffineExpressions(
Eigen::Map<const VectorX<Expression>>(X.data(), X.size()), &A, &b, &x);
DoAddMatrixIsLorentzByLorentzSeparableConstraint(A.sparseView(), b, x, m, n,
prog);
}
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/defs.bzl | load("//tools/lint:cpplint.bzl", "cpplint_extra")
load("//tools/skylark:drake_cc.bzl", "drake_cc_googletest", "drake_cc_library")
# This file contains macros that help abbreviate patterns that frequently
# appear in the solvers folder.
def _sync_conditions(condition1, condition2):
"""Asserts that one and only one condition is given. Sets the other
condition to "//conditions:default" and returns them in the same order
as they were given.
"""
if int(bool(condition1)) + int(bool(condition2)) != 1:
fail("Specify exactly one of opt-in or opt-out")
return (
condition1 or "//conditions:default",
condition2 or "//conditions:default",
)
def drake_cc_variant_library(
name,
*,
opt_in_condition = None,
opt_out_condition = None,
srcs_always,
srcs_enabled,
srcs_disabled,
hdrs,
interface_deps,
deps_always,
deps_enabled,
internal = False,
visibility = None):
"""Declares a library with a uniform set of header files (typically just
one header file) but with two different cc file implementations, depending
on a configuration setting. This is how we turn on/off specific solver
back-end implementations, e.g., `snopt_solver.cc` vs `no_snopt.cc`.
The same hdrs are used unconditionally. The interface_deps should list the
dependencies for the header file(s), and thus are also unconditional.
Exactly one of opt_in_condition or opt_out_condition must be provided, to
specify the configuration setting that chooses which cc files to use.
Open-source solvers are usually ON by default (so, will use opt_out_...).
Commercial solvers are usually OFF by default (so, will use opt_in_...).
The sources listed in srcs_always contain definitions that are appropriate
whether or not a back-end is enabled. This usually contains things such as
the solver name, ID, and attribute support. The deps_always lists the
dependencies of these files.
The sources listed in srcs_enabled contain the code of the fully-featured
implementation. The deps_enabled lists the dependencies of these srcs.
The sources listed in srcs_disabled contain the alternative (stub)
definitions that report failure (e.g., returning false or throwing).
This rule enables linting of all of the mentioned source files, even if
the compiler will not build them in the current configuration. We want all
files to be lint-free, even when the commercial solvers are disabled.
"""
opt_in_condition, opt_out_condition = _sync_conditions(
opt_in_condition,
opt_out_condition,
)
drake_cc_library(
name = name,
srcs = select({
opt_in_condition: srcs_always + srcs_enabled,
opt_out_condition: srcs_always + srcs_disabled,
}),
hdrs = hdrs,
interface_deps = interface_deps,
deps = select({
opt_in_condition: deps_always + deps_enabled,
opt_out_condition: deps_always,
}),
internal = internal,
visibility = visibility,
)
cpplint_extra(
name = name + "_cpplint",
srcs = hdrs + srcs_always + srcs_enabled + srcs_disabled,
)
def drake_cc_optional_library(
name,
*,
opt_in_condition = None,
opt_out_condition = None,
srcs,
hdrs,
copts = None,
visibility = ["//visibility:private"],
interface_deps = None,
deps = None):
"""Declares a private library (package-local, not installed) guarded by a
configuration setting. When the configuration is disabled, the library is
totally empty (but still a valid library label). This is used for helper
or utility code that's called by a fully-feataured back-end implementation.
Exactly one of opt_in_condition or opt_out_condition must be provided, to
specify the configuration setting that chooses which cc files to use.
Open-source solvers are usually ON by default (so, will use opt_out_...).
Commercial solvers are usually OFF by default (so, will use opt_in_...).
This rule enables linting of all of the mentioned source files, even if
the compiler will not build them in the current configuration. We want all
files to be lint-free, even when the commercial solvers are disabled.
"""
opt_in_condition, opt_out_condition = _sync_conditions(
opt_in_condition,
opt_out_condition,
)
drake_cc_library(
name = name,
srcs = select({
opt_in_condition: srcs,
opt_out_condition: [],
}),
hdrs = select({
opt_in_condition: hdrs,
opt_out_condition: [],
}),
install_hdrs_exclude = select({
opt_in_condition: hdrs,
opt_out_condition: [],
}),
copts = select({
opt_in_condition: copts or [],
opt_out_condition: [],
}),
tags = ["exclude_from_package"],
visibility = visibility,
interface_deps = None if interface_deps == None else select({
opt_in_condition: interface_deps,
opt_out_condition: [],
}),
deps = select({
opt_in_condition: deps or [],
opt_out_condition: [],
}),
)
cpplint_extra(
name = name + "_cpplint",
srcs = hdrs + srcs,
)
def drake_cc_optional_googletest(
name,
*,
opt_in_condition = None,
opt_out_condition = None,
tags = None,
deps,
use_default_main = True):
"""Declares a test that is not even compiled under certain configurations.
This is intended only for testing of drake_cc_optional_library targets,
where the header file(s) are not even present under certain configurations.
For testing a drake_cc_variant_library, the header(s) should always be
available, so there is no reason we avoid compiling the unit test.
Exactly one of opt_in_condition or opt_out_condition must be provided, to
specify the configuration setting that chooses which cc files to use.
Open-source solvers are usually ON by default (so, will use opt_out_...).
Commercial solvers are usually OFF by default (so, will use opt_in_...).
This rule enables linting of all of the mentioned source files, even if
the compiler will not build them in the current configuration. We want all
files to be lint-free, even when the commercial solvers are disabled.
"""
opt_in_condition, opt_out_condition = _sync_conditions(
opt_in_condition,
opt_out_condition,
)
srcs = ["test/{}.cc".format(name)]
if use_default_main:
opt_out_deps = []
else:
# The `srcs` provide a main() function, but in the opt_out case we
# won't be linking them; to cope, we'll fall back to the default main.
opt_out_deps = ["//common/test_utilities:drake_cc_googletest_main"]
drake_cc_googletest(
name = name,
srcs = select({
opt_in_condition: srcs,
opt_out_condition: [],
}),
tags = tags,
deps = select({
opt_in_condition: deps,
opt_out_condition: opt_out_deps,
}),
use_default_main = use_default_main,
)
cpplint_extra(
name = name + "_cpplint",
srcs = srcs,
)
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/no_mosek.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/mosek_solver.h"
/* clang-format on */
#include <stdexcept>
using std::runtime_error;
using std::shared_ptr;
namespace drake {
namespace solvers {
shared_ptr<MosekSolver::License> MosekSolver::AcquireLicense() {
return shared_ptr<MosekSolver::License>();
}
bool MosekSolver::is_available() {
return false;
}
void MosekSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&,
const SolverOptions&,
MathematicalProgramResult*) const {
throw runtime_error(
"Mosek is not installed in your build. You'll need to use a different "
"solver.");
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/clarabel_solver.cc | #include "drake/solvers/clarabel_solver.h"
#include <unordered_map>
#include <utility>
#include <vector>
#include <Clarabel>
#include <Eigen/Eigen>
#include "drake/common/name_value.h"
#include "drake/common/ssize.h"
#include "drake/common/text_logging.h"
#include "drake/solvers/aggregate_costs_constraints.h"
#include "drake/solvers/scs_clarabel_common.h"
#include "drake/tools/workspace/clarabel_cpp_internal/serialize.h"
namespace drake {
namespace solvers {
namespace {
// Parse all the bounding box constraints in `prog` to Clarabel form A*x+s=b, s
// in zero cone or positive cone.
// @param[in/out] A_triplets Append non-zero (row, col, val) triplet in matrix
// A.
// @param[in/out] b append entries to b.
// @param[in/out] A_row_count The number of rows in A before/after calling this
// function.
// @param[in/out] cones The type of cones on s before/after calling this
// function.
// @param[out] bbcon_dual_indices bbcon_dual_indices[i][j] are the indices of
// the dual variable for the j'th row of prog.bounding_box_constraints()[i]. We
// use -1 to indicate that it is impossible for this constraint to be active
// (for example, another BoundingBoxConstraint imposes a tighter bound on the
// same variable).
//
// Unlike SCS, Clarabel allows specifying the cone type of each individual s
// variable (in SCS, the s variables for the same type of cone have to be
// grouped together as a continuous fragment). Hence in Clarabel we can check
// the type of each individual bounding box constraint, and differentiate them
// based on whether it is an equality (s in zero-cone) or an inequality (s in
// positive orthant cone) constraint.
void ParseBoundingBoxConstraints(
const MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<clarabel::SupportedConeT<double>>* cones,
std::vector<std::vector<std::pair<int, int>>>* bbcon_dual_indices) {
const std::unordered_map<symbolic::Variable, Bound> variable_bounds =
AggregateBoundingBoxConstraints(prog.bounding_box_constraints());
// For each variable with lb <= x <= ub, we check the following
// 1. If lb == ub (and both are finite), then we add the constraint x + s = ub
// with s in the zero cone.
// 2. Otherwise, if ub is finite, then we add the constraint x + s = ub with s
// in the positive orthant cone. If lb is finite, then we add the constraint
// -x + s = -lb with s in the positive orthant cone.
// Set the dual variable indices.
bbcon_dual_indices->reserve(ssize(prog.bounding_box_constraints()));
for (int i = 0; i < ssize(prog.bounding_box_constraints()); ++i) {
bbcon_dual_indices->emplace_back(
prog.bounding_box_constraints()[i].variables().rows(),
std::pair<int, int>(-1, -1));
for (int j = 0; j < prog.bounding_box_constraints()[i].variables().rows();
++j) {
const int var_index = prog.FindDecisionVariableIndex(
prog.bounding_box_constraints()[i].variables()(j));
const Bound& var_bound =
variable_bounds.at(prog.bounding_box_constraints()[i].variables()(j));
// We use the lower bound of this constraint in the optimization
// program.
const bool use_lb =
var_bound.lower ==
prog.bounding_box_constraints()[i].evaluator()->lower_bound()(
j) &&
std::isfinite(var_bound.lower);
const bool use_ub =
var_bound.upper ==
prog.bounding_box_constraints()[i].evaluator()->upper_bound()(
j) &&
std::isfinite(var_bound.upper);
if (use_lb && use_ub && var_bound.lower == var_bound.upper) {
// This is an equality constraint x = ub.
// Add the constraint x + s = ub and s in the zero cone.
A_triplets->emplace_back(*A_row_count, var_index, 1);
b->push_back(var_bound.upper);
(*bbcon_dual_indices)[i][j].first = *A_row_count;
(*bbcon_dual_indices)[i][j].second = *A_row_count;
cones->push_back(clarabel::ZeroConeT<double>(1));
++(*A_row_count);
} else {
if (use_ub) {
// Add the constraint x + s = ub and s in the nonnegative orthant
// cone.
A_triplets->emplace_back(*A_row_count, var_index, 1);
b->push_back(var_bound.upper);
(*bbcon_dual_indices)[i][j].second = *A_row_count;
cones->push_back(clarabel::NonnegativeConeT<double>(1));
++(*A_row_count);
}
if (use_lb) {
// Add the constraint -x + s = -lb and s in the nonnegative orthant
// cone.
A_triplets->emplace_back(*A_row_count, var_index, -1);
b->push_back(-var_bound.lower);
(*bbcon_dual_indices)[i][j].first = *A_row_count;
cones->push_back(clarabel::NonnegativeConeT<double>(1));
++(*A_row_count);
}
}
}
}
}
// The solver status is defined in
// https://oxfordcontrol.github.io/ClarabelDocs/stable/api_jl/#Clarabel.SolverStatus
std::string SolverStatusToString(const clarabel::SolverStatus status) {
switch (status) {
case clarabel::SolverStatus::Unsolved:
return "Unsolved";
case clarabel::SolverStatus::Solved:
return "Solved";
case clarabel::SolverStatus::PrimalInfeasible:
return "PrimalInfeasible";
case clarabel::SolverStatus::DualInfeasible:
return "DualInfeasible";
case clarabel::SolverStatus::AlmostSolved:
return "AlmostSolved";
case clarabel::SolverStatus::AlmostPrimalInfeasible:
return "AlmostPrimalInfeasible";
case clarabel::SolverStatus::AlmostDualInfeasible:
return "AlmostDualInfeasible";
case clarabel::SolverStatus::MaxIterations:
return "MaxIterations";
case clarabel::SolverStatus::MaxTime:
return "MaxTime";
case clarabel::SolverStatus::NumericalError:
return "NumericalError";
case clarabel::SolverStatus::InsufficientProgress:
return "InsufficientProgress";
}
DRAKE_UNREACHABLE();
}
void SetSolverDetails(
const clarabel::DefaultSolution<double>& clarabel_solution,
ClarabelSolverDetails* solver_details) {
solver_details->iterations = clarabel_solution.iterations;
solver_details->solve_time = clarabel_solution.solve_time;
solver_details->status = SolverStatusToString(clarabel_solution.status);
}
class SettingsConverter {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SettingsConverter);
explicit SettingsConverter(const SolverOptions& solver_options) {
// Propagate Drake's common options into `settings_`.
settings_.verbose = solver_options.get_print_to_console();
// TODO(jwnimmer-tri) Handle get_print_file_name().
// Copy the Clarabel-specific `solver_options` to pending maps.
pending_options_double_ =
solver_options.GetOptionsDouble(ClarabelSolver::id());
pending_options_int_ = solver_options.GetOptionsInt(ClarabelSolver::id());
pending_options_str_ = solver_options.GetOptionsStr(ClarabelSolver::id());
// Move options from `pending_..._` to `settings_`.
Serialize(this, settings_);
// Identify any unsupported names (i.e., any leftovers in `pending_..._`).
std::vector<std::string> unknown_names;
for (const auto& [name, _] : pending_options_double_) {
unknown_names.push_back(name);
}
for (const auto& [name, _] : pending_options_int_) {
unknown_names.push_back(name);
}
for (const auto& [name, _] : pending_options_str_) {
unknown_names.push_back(name);
}
if (unknown_names.size() > 0) {
throw std::logic_error(fmt::format(
"ClarabelSolver: unrecognized solver options {}. Please check "
"https://oxfordcontrol.github.io/ClarabelDocs/stable/api_settings/ "
"for the supported solver options.",
fmt::join(unknown_names, ", ")));
}
}
const clarabel::DefaultSettings<double>& settings() const {
return settings_;
}
void Visit(const NameValue<double>& x) {
this->SetFromDoubleMap(x.name(), x.value());
}
void Visit(const NameValue<bool>& x) {
auto it = pending_options_int_.find(x.name());
if (it != pending_options_int_.end()) {
const int option_value = it->second;
DRAKE_THROW_UNLESS(option_value == 0 || option_value == 1);
}
this->SetFromIntMap(x.name(), x.value());
}
void Visit(const NameValue<uint32_t>& x) {
auto it = pending_options_int_.find(x.name());
if (it != pending_options_int_.end()) {
const int option_value = it->second;
DRAKE_THROW_UNLESS(option_value >= 0);
}
this->SetFromIntMap(x.name(), x.value());
}
void Visit(const NameValue<clarabel::ClarabelDirectSolveMethods>& x) {
DRAKE_THROW_UNLESS(x.name() == std::string{"direct_solve_method"});
// TODO(jwnimmer-tri) Add support for this option.
// For now it is unsupported and will throw (as an unknown name, below).
}
private:
void SetFromDoubleMap(const char* name, double* clarabel_value) {
auto it = pending_options_double_.find(name);
if (it != pending_options_double_.end()) {
*clarabel_value = it->second;
pending_options_double_.erase(it);
}
}
template <typename T>
void SetFromIntMap(const char* name, T* clarabel_value) {
auto it = pending_options_int_.find(name);
if (it != pending_options_int_.end()) {
*clarabel_value = it->second;
pending_options_int_.erase(it);
}
}
std::unordered_map<std::string, double> pending_options_double_;
std::unordered_map<std::string, int> pending_options_int_;
std::unordered_map<std::string, std::string> pending_options_str_;
clarabel::DefaultSettings<double> settings_ =
clarabel::DefaultSettingsBuilder<double>::default_settings().build();
};
// See ParseBoundingBoxConstraints for the meaning of bbcon_dual_indices.
void SetBoundingBoxDualSolution(
const MathematicalProgram& prog,
const Eigen::Ref<const Eigen::VectorXd>& dual,
const std::vector<std::vector<std::pair<int, int>>>& bbcon_dual_indices,
MathematicalProgramResult* result) {
for (int i = 0; i < ssize(prog.bounding_box_constraints()); ++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 (prog.bounding_box_constraints()[i].evaluator()->lower_bound()(j) ==
prog.bounding_box_constraints()[i].evaluator()->upper_bound()(j)) {
// This is an equality constraint.
// Notice that we have a negative sign in front of dual.
// This is because in Clarabel, for a problem with the linear equality
// constraint
// min cᵀx
// s.t A*x=b
// Clarabel formulates the dual problem as
// max -bᵀy
// s.t Aᵀy = -c
// Note that there is a negation sign before b and c in the Clarabel
// dual problem, which is different from the standard formulation (no
// negation sign). Hence the dual variable for the linear equality
// constraint is the negation of the shadow price.
bbcon_dual[j] = -dual(bbcon_dual_indices[i][j].second);
} else {
if (bbcon_dual_indices[i][j].first != -1) {
// lower bound is not infinity.
// The shadow price for the lower bound is positive. The Clarabel dual
// for the positive cone is also positive, so we add the Clarabel
// dual.
bbcon_dual[j] += dual(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. The Clarabel dual
// for the positive cone is positive, so we subtract the Clarabel
// dual.
bbcon_dual[j] -= dual(bbcon_dual_indices[i][j].second);
}
}
}
result->set_dual_solution(prog.bounding_box_constraints()[i], bbcon_dual);
}
}
} // namespace
bool ClarabelSolver::is_available() {
return true;
}
void ClarabelSolver::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(
"ClarabelSolver doesn't support the feature of variable scaling.");
}
// Clarabel doesn't have an API to provide the initial guess yet.
unused(initial_guess);
// Clarabel solves the problem in this form
// min 0.5xᵀPx + qᵀx
// s.t A x + s = b
// s in K
// where K is a Cartesian product of some primitive cones.
// The cones include
// 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ᵀ }
// Exponential cone {x,y,z): y>0, y*exp(x/y) <= z}
// Power cone {(x, y, z): pow(x, α)*pow(y, 1-α) >= |z|, x>=0, y>=0} with α in
// (0, 1)
// Clarabel doesn't impose an ordering of specifying these cone constraints
// (which is different from SCS). Notice that due to the special problem form
// supported by Clarabel, we need to convert our generic constraints to
// Clarabel 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 A*x+s=b. 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 Clarabel form.
int num_x = prog.num_vars();
// Clarabel takes an Eigen::Sparse matrix as A. We will build this sparse
// matrix from the triplets recording its non-zero entries.
std::vector<Eigen::Triplet<double>> A_triplets;
// 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. Clarabel only takes the upper triangular entries of
// the symmetric Hessian.
std::vector<Eigen::Triplet<double>> P_upper_triplets;
// A_row_count will increment, when we add each constraint.
int A_row_count = 0;
std::vector<double> b;
std::vector<clarabel::SupportedConeT<double>> cones;
// `q` is the coefficient in the linear cost qᵀx
std::vector<double> q(num_x, 0.0);
// Our costs (LinearCost, QuadraticCost, etc) also allows a constant term, we
// add these constant terms to `cost_constant`.
double cost_constant{0};
internal::ParseLinearCosts(prog, &q, &cost_constant);
internal::ParseQuadraticCosts(prog, &P_upper_triplets, &q, &cost_constant);
std::vector<int> l2norm_costs_second_order_cone_length;
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,
&l2norm_costs_second_order_cone_length,
&l2norm_costs_lorentz_cone_y_start_indices, &q,
&l2norm_costs_t_slack_indices);
for (const int soc_length : l2norm_costs_second_order_cone_length) {
cones.push_back(clarabel::SecondOrderConeT<double>(soc_length));
}
// 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);
cones.push_back(
clarabel::ZeroConeT<double>(num_linear_equality_constraints_rows));
// Parse bounding box constraints.
// bbcon_dual_indices[i][j][0] (resp. bbcon_dual_indices[i][j][1]) is the dual
// variable for the lower (resp. upper) bound of the j'th row in the bounding
// box constraint prog.bounding_box_constraint()[i]
// Since the dual variables are constrained to be positive, we use -1 to
// indicate that this bound can never be active (for example, another
// BoundingBoxConstraint imposes a tighter bound on the same variable).
std::vector<std::vector<std::pair<int, int>>> bbcon_dual_indices;
ParseBoundingBoxConstraints(prog, &A_triplets, &b, &A_row_count, &cones,
&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);
cones.push_back(
clarabel::NonnegativeConeT<double>(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;
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);
for (const int soc_length : second_order_cone_length) {
cones.push_back(clarabel::SecondOrderConeT<double>(soc_length));
}
std::vector<int> psd_cone_length;
internal::ParsePositiveSemidefiniteConstraints(
prog, /* upper triangular = */ true, &A_triplets, &b, &A_row_count,
&psd_cone_length);
for (const int length : psd_cone_length) {
cones.push_back(clarabel::PSDTriangleConeT<double>(length));
}
internal::ParseExponentialConeConstraints(prog, &A_triplets, &b,
&A_row_count);
for (int i = 0; i < ssize(prog.exponential_cone_constraints()); ++i) {
cones.push_back(clarabel::ExponentialConeT<double>());
}
Eigen::SparseMatrix<double> P(num_x, num_x);
P.setFromTriplets(P_upper_triplets.begin(), P_upper_triplets.end());
Eigen::Map<Eigen::VectorXd> q_vec{q.data(), ssize(q)};
Eigen::SparseMatrix<double> A(A_row_count, num_x);
A.setFromTriplets(A_triplets.begin(), A_triplets.end());
const Eigen::Map<Eigen::VectorXd> b_vec{b.data(), ssize(b)};
const SettingsConverter settings_converter(merged_options);
clarabel::DefaultSettings<double> settings = settings_converter.settings();
clarabel::DefaultSolver<double> solver(P, q_vec, A, b_vec, cones, settings);
solver.solve();
clarabel::DefaultSolution<double> solution = solver.solution();
// Now set the solution.
ClarabelSolverDetails& solver_details =
result->SetSolverDetailsType<ClarabelSolverDetails>();
SetSolverDetails(solution, &solver_details);
SolutionResult solution_result{SolutionResult::kSolutionResultNotSet};
result->set_x_val(
Eigen::Map<Eigen::VectorXd>(solution.x.data(), prog.num_vars()));
SetBoundingBoxDualSolution(prog, solution.z, bbcon_dual_indices, result);
internal::SetDualSolution(prog, solution.z, linear_constraint_dual_indices,
linear_eq_y_start_indices,
lorentz_cone_y_start_indices,
rotated_lorentz_cone_y_start_indices, result);
if (solution.status == clarabel::SolverStatus::Solved ||
solution.status == clarabel::SolverStatus::AlmostSolved) {
solution_result = SolutionResult::kSolutionFound;
result->set_optimal_cost(solution.obj_val + cost_constant);
} else if (solution.status == clarabel::SolverStatus::PrimalInfeasible ||
solution.status ==
clarabel::SolverStatus::AlmostPrimalInfeasible) {
solution_result = SolutionResult::kInfeasibleConstraints;
result->set_optimal_cost(MathematicalProgram::kGlobalInfeasibleCost);
} else if (solution.status == clarabel::SolverStatus::DualInfeasible ||
solution.status == clarabel::SolverStatus::AlmostDualInfeasible) {
solution_result = SolutionResult::kDualInfeasible;
result->set_optimal_cost(MathematicalProgram::kUnboundedCost);
} else if (solution.status == clarabel::SolverStatus::MaxIterations) {
solution_result = SolutionResult::kIterationLimit;
result->set_optimal_cost(solution.obj_val + cost_constant);
} else {
drake::log()->info("Clarabel returns {}",
SolverStatusToString(solution.status));
solution_result = SolutionResult::kSolverSpecificError;
}
result->set_solution_result(solution_result);
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/ipopt_solver_internal.h | #pragma once
// For external users, please do not include this header file. It only exists so
// that we can expose the internals to ipopt_solver_internal_test.
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
#include <IpIpoptApplication.hpp>
#include <IpTNLP.hpp>
#include "drake/common/drake_export.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mathematical_program_result.h"
namespace drake {
namespace solvers {
namespace internal {
// IPOPT uses separate callbacks to get the result and the gradients. When
// this code was initially written, the gradient values were populated in the
// cache during the result calculation for constraints (this is still true for
// costs). However, it was later discovered that because IPOPT does not
// always ask for the gradients to be calculated, it's actually faster to
// calculate the constraint values only and then recalculate later with
// gradients only if necessary. This likely makes the cache ineffective for
// constraints.
//
// See #13841 and #13891 for more discussion.
struct ResultCache {
ResultCache(size_t x_size, size_t result_size, size_t grad_size);
/// @param n The size of the array located at @p x_in.
bool is_x_equal(Ipopt::Index n, const Ipopt::Number* x_in);
// Sugar to copy an IPOPT bare array into `x`.
void SetX(const Ipopt::Index n, const Ipopt::Number* x_arg);
// Sugar to copy one of our member fields into an IPOPT bare array.
static void Extract(const std::vector<Ipopt::Number>& cache_data,
const Ipopt::Index dest_size, Ipopt::Number* dest);
std::vector<Ipopt::Number> x;
std::vector<Ipopt::Number> result;
std::vector<Ipopt::Number> grad;
bool grad_valid{false};
};
// The C++ interface for IPOPT is described here:
// https://coin-or.github.io/Ipopt/INTERFACES.html#INTERFACE_CPP
//
// IPOPT provides a pure(-ish) virtual base class which you have to
// implement a concrete version of as the solver interface.
// IpoptSolver creates an instance of IpoptSolver_NLP which lives for
// the duration of the Solve() call.
// Use DRAKE_NO_EXPORT to hide the visibility of this class to the linker.
class DRAKE_NO_EXPORT IpoptSolver_NLP : public Ipopt::TNLP {
public:
IpoptSolver_NLP(const MathematicalProgram& problem,
const Eigen::VectorXd& x_init,
MathematicalProgramResult* result);
virtual ~IpoptSolver_NLP() {}
virtual bool get_nlp_info(
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
Ipopt::Index& n, Ipopt::Index& m, Ipopt::Index& nnz_jac_g,
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
Ipopt::Index& nnz_h_lag, IndexStyleEnum& index_style);
virtual bool get_bounds_info(Ipopt::Index n, Ipopt::Number* x_l,
Ipopt::Number* x_u, Ipopt::Index m,
Ipopt::Number* g_l, Ipopt::Number* g_u);
virtual bool get_starting_point(Ipopt::Index n, bool init_x, Ipopt::Number* x,
bool init_z, Ipopt::Number* z_L,
Ipopt::Number* z_U, Ipopt::Index m,
bool init_lambda, Ipopt::Number* lambda);
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
virtual bool eval_f(
Ipopt::Index n, const Ipopt::Number* x, bool new_x,
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
Ipopt::Number& obj_value);
virtual bool eval_grad_f(Ipopt::Index n, const Ipopt::Number* x, bool new_x,
Ipopt::Number* grad_f);
virtual bool eval_g(Ipopt::Index n, const Ipopt::Number* x, bool new_x,
Ipopt::Index m, Ipopt::Number* g);
virtual bool eval_jac_g(Ipopt::Index n, const Ipopt::Number* x, bool new_x,
Ipopt::Index m, Ipopt::Index nele_jac,
Ipopt::Index* iRow, Ipopt::Index* jCol,
Ipopt::Number* values);
virtual void finalize_solution(
Ipopt::SolverReturn status, Ipopt::Index n, const Ipopt::Number* x,
const Ipopt::Number* z_L, const Ipopt::Number* z_U, Ipopt::Index m,
const Ipopt::Number* g, const Ipopt::Number* lambda,
Ipopt::Number obj_value, const Ipopt::IpoptData* ip_data,
Ipopt::IpoptCalculatedQuantities* ip_cq);
const Ipopt::SolverReturn& status() const { return status_; }
const Eigen::VectorXd& z_L() const { return z_L_; }
const Eigen::VectorXd& z_U() const { return z_U_; }
const Eigen::VectorXd& g() const { return g_; }
const Eigen::VectorXd& lambda() const { return lambda_; }
private:
void EvaluateCosts(Ipopt::Index n, const Ipopt::Number* x);
void EvaluateConstraints(Ipopt::Index n, const Ipopt::Number* x,
bool eval_gradient);
const MathematicalProgram* const problem_;
std::unique_ptr<ResultCache> cost_cache_;
std::unique_ptr<ResultCache> constraint_cache_;
Eigen::VectorXd x_init_;
MathematicalProgramResult* const result_;
// status, z_L, z_U, g, lambda will be stored in IpoptSolverDetails, which is
// declared in ipopt_solver.h. But ipopt_solver_internal doesn't depend on
// ipopt_solver.h (in fact, ipopt_solver depends on ipopt_solver_internal). So
// we store z_L, z_U, g, lambda here, and set IpoptSolverDetails in
// ipopt_solver.cc
Ipopt::SolverReturn status_;
Eigen::VectorXd z_L_;
Eigen::VectorXd z_U_;
Eigen::VectorXd g_;
Eigen::VectorXd lambda_;
// bb_con_dual_variable_indices_[constraint] maps the bounding box constraint
// to the indices of its dual variables (one for lower bound and one for upper
// bound). If this constraint doesn't have a dual variable (because the bound
// is looser than some other bounding box constraint, hence this constraint
// can never be active), then the index is set to -1.
std::unordered_map<Binding<BoundingBoxConstraint>,
std::pair<std::vector<int>, std::vector<int>>>
bb_con_dual_variable_indices_;
// constraint_dual_start_index_[constraint] stores the starting index of the
// corresponding dual variables.
std::unordered_map<Binding<Constraint>, int> constraint_dual_start_index_;
};
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/rotation_constraint.h | #pragma once
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "drake/common/eigen_types.h"
#include "drake/solvers/decision_variable.h"
#include "drake/solvers/mathematical_program.h"
/// @file
/// Functions for reasoning about 3D rotations in a @MathematicalProgram.
///
/// There are a number of choices for representing 3D rotations in a
/// mathematical program -- many of these choices involve using more than
/// the minimal three parameters and therefore require additional constraints
/// For example:
///
/// - the 4 parameters of a quaternion should form a vector with unit length.
/// - the 9 parameters of a rotation matrix should form a matrix which is
/// orthonormal (R.transpose() = R.inverse()) and det(R)=1.
///
/// Unfortunately, in the context of mathematical programming, most of these
/// constraints are non-convex. The methods below include convex relaxations
/// of these non-convex constraints.
// TODO(all): Other concepts to potentially implement:
// - PSDlift from section 1.2 of https://arxiv.org/pdf/1403.4914.pdf . This
// is waiting on the symbolic expression tools.
// - Principle minor SOCP relaxations of the SDP conditions
// - MILP constraints that push outside the cube contained by the L2 ball,
// with vertices at (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), (-sqrt(3)/3,
// sqrt(3)/3, sqrt(3)/3), ... this would have 6 faces/binary variables per
// column of R instead of the 8 in the L1 norm constraint.
// - Axis angle and/or gaze cone constraints, as mentioned here:
// https://reviewable.io/reviews/robotlocomotion/drake/4653#-K_YGsAOBY5ooX3OBqo7
namespace drake {
namespace solvers {
/// Allocates a 3x3 matrix of decision variables with the trivial bounding
/// box constraint ensuring all elements are [-1,1], and the linear constraint
/// imposing -1 <= trace(R) <= 3.
MatrixDecisionVariable<3, 3> NewRotationMatrixVars(
MathematicalProgram* prog, const std::string& name = "R");
enum RollPitchYawLimitOptions {
kNoLimits = 0,
kRPYError = 1 << 0, ///< Do not use, to avoid & vs. && typos.
kRoll_NegPI_2_to_PI_2 = 1 << 1,
kRoll_0_to_PI = 1 << 2,
kPitch_NegPI_2_to_PI_2 = 1 << 3,
kPitch_0_to_PI = 1 << 4,
kYaw_NegPI_2_to_PI_2 = 1 << 5,
kYaw_0_to_PI = 1 << 6,
kRoll_0_to_PI_2 = (1 << 1) | (1 << 2),
kPitch_0_to_PI_2 = (1 << 3) | (1 << 4),
kYaw_0_to_PI_2 = (1 << 5) | (1 << 6)
};
typedef uint32_t RollPitchYawLimits;
/// Applies *very conservative* limits on the entries of R for the cases when
/// rotations can be limited (for instance, if you want to search over
/// rotations, but there is an obvious symmetry in the problem so that e.g.
/// 0 < pitch < PI need not be considered). A matrix so constrained may still
/// contain rotations outside of this envelope.
/// Note: For simple rotational symmetry over PI, prefer
/// kPitch_NegPI_2_to_PI_2 (over 0_to_PI)
/// because it adds one more constraint (when combined with constraints on roll
/// and yaw).
/// Note: The Roll-Pitch-Yaw angles follow the convention in RollPitchYaw,
/// namely extrinsic rotations about Space-fixed x-y-z axes, respectively.
void AddBoundingBoxConstraintsImpliedByRollPitchYawLimits(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
RollPitchYawLimits limits = kNoLimits);
/// Adds constraint (10) from https://arxiv.org/pdf/1403.4914.pdf ,
/// which exactly represents the convex hull of all rotation matrices in 3D.
void AddRotationMatrixSpectrahedralSdpConstraint(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R);
/// Adds a set of convex constraints which approximate the set of orthogonal
/// matrices, O(3). Adds the bilinear constraints that the each column Ri has
/// length <= 1 and that Ri'Rj approx 0 via
/// -2 + |Ri|^2 + |Rj|^2 <= 2Ri'Rj <= 2 - |Ri|^2 - |Rj|^2 (for all i!=j),
/// using a second-order-cone relaxation. Additionally, the same constraints
/// are applied to all of the rows.
void AddRotationMatrixOrthonormalSocpConstraint(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R);
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mixed_integer_rotation_constraint.h | #pragma once
#include <array>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "drake/common/fmt_ostream.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mixed_integer_optimization_util.h"
namespace drake {
namespace solvers {
/**
* We relax the non-convex SO(3) constraint on rotation matrix R to
* mixed-integer linear constraints. The formulation of these constraints are
* described in
* Global Inverse Kinematics via Mixed-integer Convex Optimization
* by Hongkai Dai, Gregory Izatt and Russ Tedrake, ISRR, 2017
*
* The SO(3) constraint on a rotation matrix R = [r₁, r₂, r₃], rᵢ∈ℝ³ is
* ```
* rᵢᵀrᵢ = 1 (1)
* rᵢᵀrⱼ = 0 (2)
* r₁ x r₂ = r₃ (3)
* ```
* To relax SO(3) constraint on rotation matrix R, we divide the range [-1, 1]
* (the range of each entry in R) into smaller intervals [φ(i), φ(i+1)], and
* then relax the SO(3) constraint within each interval. We provide 3 approaches
* for relaxation
* 1. By replacing each bilinear product in constraint (1), (2) and (3) with a
* new variable, in the McCormick envelope of the bilinear product w = x * y.
* 2. By considering the intersection region between axis-aligned boxes, and the
* surface of a unit sphere in 3D.
* 3. By combining the two approaches above. This will result in a tighter
* relaxation.
*
* These three approaches give different relaxation of SO(3) constraint (the
* feasible sets for each relaxation are different), and different computation
* speed. The users can switch between the approaches to find the best fit for
* their problem.
*
* @note If you have several rotation matrices that all need to be relaxed
* through mixed-integer constraint, then you can create a single
* MixedIntegerRotationConstraintGenerator object, and add the mixed-integer
* constraint to each rotation matrix, by calling AddToProgram() function
* repeatedly.
*/
class MixedIntegerRotationConstraintGenerator {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(
MixedIntegerRotationConstraintGenerator)
enum class Approach {
kBoxSphereIntersection, ///< Relax SO(3) constraint by considering the
///< intersection between boxes and the unit sphere
///< surface.
kBilinearMcCormick, ///< Relax SO(3) constraint by considering the
///< McCormick envelope on the bilinear product.
kBoth, ///< Relax SO(3) constraint by considering both the
///< intersection between boxes and the unit sphere
///< surface, and the McCormick envelope on the
///< bilinear product.
};
struct ReturnType {
/**
* B_ contains the new binary variables added to the program.
* B_[i][j] represents in which interval R(i, j) lies. If we use linear
* binning, then B_[i][j] is of length 2 * num_intervals_per_half_axis_.
* B_[i][j](k) = 1 => φ(k) ≤ R(i, j) ≤ φ(k + 1)
* B_[i][j](k) = 0 => R(i, j) ≥ φ(k + 1) or R(i, j) ≤ φ(k)
* If we use logarithmic binning, then B_[i][j] is of length
* 1 + log₂(num_intervals_per_half_axis_). If B_[i][j] represents integer
* k in reflected Gray code, then R(i, j) is in the interval [φ(k), φ(k+1)].
*/
std::array<std::array<VectorXDecisionVariable, 3>, 3> B_;
/**
* λ contains part of the new continuous variables added to the program.
* λ_[i][j] is of length 2 * num_intervals_per_half_axis_ + 1, such that
* R(i, j) = φᵀ * λ_[i][j]. Notice that λ_[i][j] satisfies the special
* ordered set of type 2 (SOS2) constraint. Namely at most two entries in
* λ_[i][j] can be strictly positive, and these two entries have to
* be consecutive. Mathematically
* ```
* ∑ₖ λ_[i][j](k) = 1
* λ_[i][j](k) ≥ 0 ∀ k
* ∃ m s.t λ_[i][j](n) = 0 if n ≠ m and n ≠ m+1
* ```
*/
std::array<std::array<VectorXDecisionVariable, 3>, 3> lambda_;
};
/**
* Constructor
* @param approach Refer to MixedIntegerRotationConstraintGenerator::Approach
* for the details.
* @param num_intervals_per_half_axis We will cut the range [-1, 1] evenly
* to 2 * `num_intervals_per_half_axis` small intervals. The number of binary
* variables will depend on the number of intervals.
* @param interval_binning The binning scheme we use to add SOS2 constraint
* with binary variables. If interval_binning = kLinear, then we will add
* 9 * 2 * `num_intervals_per_half_axis binary` variables;
* if interval_binning = kLogarithmic, then we will add
* 9 * (1 + log₂(num_intervals_per_half_axis)) binary variables. Refer to
* AddLogarithmicSos2Constraint and AddSos2Constraint for more details.
*/
MixedIntegerRotationConstraintGenerator(Approach approach,
int num_intervals_per_half_axis,
IntervalBinning interval_binning);
/**
* Add the mixed-integer linear constraints to the optimization program, as
* a relaxation of SO(3) constraint on the rotation matrix `R`.
* @param R The rotation matrix on which the SO(3) constraint is imposed.
* @param prog The optimization program to which the mixed-integer constraints
* (and additional variables) are added.
*/
ReturnType AddToProgram(
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
MathematicalProgram* prog) const;
/** Getter for φ. */
const Eigen::VectorXd& phi() const { return phi_; }
/** Getter for φ₊, the non-negative part of φ. */
const Eigen::VectorXd phi_nonnegative() const { return phi_nonnegative_; }
Approach approach() const { return approach_; }
int num_intervals_per_half_axis() const {
return num_intervals_per_half_axis_;
}
IntervalBinning interval_binning() const { return interval_binning_; }
private:
Approach approach_;
int num_intervals_per_half_axis_;
IntervalBinning interval_binning_;
// φ(i) = -1 + 1 / num_intervals_per_half_axis_ * i
Eigen::VectorXd phi_;
// φ₊(i) = 1 / num_intervals_per_half_axis_ * i
Eigen::VectorXd phi_nonnegative_;
// When considering the intersection between the box and the sphere surface,
// we will compute the vertices of the intersection region, and find one tight
// halfspace nᵀx ≥ d, such that all points on the intersection surface satisfy
// this halfspace constraint. For intersection region between the box
// [φ₊(xi), φ₊(xi+1)] x [φ₊(yi), φ₊(yi+1)] x [φ₊(zi), φ₊(zi+1)] and the sphere
// surface, the vertices of the intersection region is in
// box_sphere_intersection_vertices_[xi][yi][zi], and the halfspace is
// (box_sphere_intersection_halfspace_[xi][yi][zi].first)ᵀ x ≥
// box_sphere_intersection_halfspace[xi][yi][zi].second
std::vector<std::vector<std::vector<std::vector<Eigen::Vector3d>>>>
box_sphere_intersection_vertices_;
std::vector<std::vector<std::vector<std::pair<Eigen::Vector3d, double>>>>
box_sphere_intersection_halfspace_;
};
std::string to_string(MixedIntegerRotationConstraintGenerator::Approach type);
std::ostream& operator<<(
std::ostream& os,
const MixedIntegerRotationConstraintGenerator::Approach& type);
/**
* Some of the newly added variables in function
* AddRotationMatrixBoxSphereIntersectionMilpConstraints.
* CRpos, CRneg, BRpos and BRneg can only take value 0 or 1. `CRpos` and `CRneg`
* are declared as continuous variables, while `BRpos` and `BRneg` are declared
* as binary variables. The definition for these variables are
* <pre>
* CRpos[k](i, j) = 1 => k / N <= R(i, j) <= (k+1) / N
* CRneg[k](i, j) = 1 => -(k+1) / N <= R(i, j) <= -k / N
* BRpos[k](i, j) = 1 => R(i, j) >= k / N
* BRneg[k](i, j) = 1 => R(i, j) <= -k / N
* </pre>
* where `N` is `num_intervals_per_half_axis`, one of the input argument of
* AddRotationMatrixBoxSphereIntersectionMilpConstraints.
*/
struct AddRotationMatrixBoxSphereIntersectionReturn {
std::vector<Matrix3<symbolic::Expression>> CRpos;
std::vector<Matrix3<symbolic::Expression>> CRneg;
std::vector<Matrix3<symbolic::Variable>> BRpos;
std::vector<Matrix3<symbolic::Variable>> BRneg;
};
/**
* Adds binary variables that constrain the value of the column *and* row
* vectors of R, in order to add the following (in some cases non-convex)
* constraints as an MILP. Specifically, for column vectors Ri, we constrain:
*
* - forall i, |Ri| = 1 ± envelope,
* - forall i,j. i ≠ j, Ri.dot(Rj) = 0 ± envelope,
* - R2 = R0.cross(R1) ± envelope,
* and again for R0=R1.cross(R2), and R1=R2.cross(R0).
*
* Then all of the same constraints are also added to R^T. The size of the
* envelope decreases quickly as num_binary_variables_per_half_axis is
* is increased.
*
* @note Creates `9*2*num_binary_variables_per_half_axis binary` variables named
* "BRpos*(*,*)" and "BRneg*(*,*)", and the same number of continuous variables
* named "CRpos*(*,*)" and "CRneg*(*,*)".
*
* @note The particular representation/algorithm here was developed in an
* attempt:
* - to enable efficient reuse of the variables between the constraints
* between multiple rows/columns (e.g. the constraints on Rᵀ use the same
* variables as the constraints on R), and
* - to facilitate branch-and-bound solution techniques -- binary regions are
* layered so that constraining one region establishes constraints
* on large portions of SO(3), and confers hopefully "useful" constraints
* the on other binary variables.
* @param R The rotation matrix
* @param num_intervals_per_half_axis number of intervals for a half axis.
* @param prog The mathematical program to which the constraints are added.
* @note This method uses the same approach as
* MixedIntegerRotationConstraintGenerator with kBoxSphereIntersection, namely
* the feasible sets to both relaxation are the same. But they use different
* sets of binary variables, and thus the computation speed can be different
* inside optimization solvers.
*/
AddRotationMatrixBoxSphereIntersectionReturn
AddRotationMatrixBoxSphereIntersectionMilpConstraints(
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
int num_intervals_per_half_axis, MathematicalProgram* prog);
} // namespace solvers
} // namespace drake
// TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<.
namespace fmt {
template <>
struct formatter<
drake::solvers::MixedIntegerRotationConstraintGenerator::Approach>
: drake::ostream_formatter {};
} // namespace fmt
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/no_gurobi.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/gurobi_solver.h"
/* clang-format on */
#include <stdexcept>
namespace drake {
namespace solvers {
std::shared_ptr<GurobiSolver::License> GurobiSolver::AcquireLicense() {
return {};
}
bool GurobiSolver::is_available() {
return false;
}
void GurobiSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&,
const SolverOptions&,
MathematicalProgramResult*) const {
throw std::runtime_error(
"The Gurobi bindings were not compiled. You'll need to use a different "
"solver.");
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/program_attribute.h | #pragma once
#include <ostream>
#include <string>
#include <unordered_set>
#include "drake/common/fmt_ostream.h"
#include "drake/common/hash.h"
namespace drake {
namespace solvers {
enum class ProgramAttribute {
kGenericCost, ///< A generic cost, doesn't belong to any specific cost type
/// below.
kGenericConstraint, ///< A generic constraint, doesn't belong to any specific
/// constraint type below.
kQuadraticCost, ///< A quadratic function as the cost.
kQuadraticConstraint, ///< A constraint on a quadratic function.
kLinearCost, ///< A linear function as the cost.
kLinearConstraint, ///< A constraint on a linear function.
kLinearEqualityConstraint, ///< An equality constraint on a linear function.
kLinearComplementarityConstraint, ///< A linear complementarity constraint in
/// the form 0 ≤ z ⊥ Mz+q ≥ 0.
kLorentzConeConstraint, ///< A Lorentz cone constraint.
kRotatedLorentzConeConstraint, ///< A rotated Lorentz cone constraint.
kPositiveSemidefiniteConstraint, ///< A positive semidefinite constraint.
kExponentialConeConstraint, ///< An exponential cone constraint.
kL2NormCost, ///< An L2 norm |Ax+b|
kBinaryVariable, ///< Variable taking binary value {0, 1}.
kCallback, ///< Supports callback during solving the problem.
};
using ProgramAttributes = std::unordered_set<ProgramAttribute, DefaultHash>;
/** Returns true iff @p required is a subset of @p supported.
@param[out] unsupported_message (Optional) When provided, if this function
returns false, the message will be set to a phrase describing the unsupported
attributes; or if this function returns true, the message will be set to the
empty string.
*/
bool AreRequiredAttributesSupported(const ProgramAttributes& required,
const ProgramAttributes& supported,
std::string* unsupported_message = nullptr);
std::string to_string(const ProgramAttribute&);
std::ostream& operator<<(std::ostream&, const ProgramAttribute&);
std::string to_string(const ProgramAttributes&);
std::ostream& operator<<(std::ostream&, const ProgramAttributes&);
/**
* A coarse categorization of the optimization problem based on the type of
* constraints/costs/variables.
* Notice that Drake chooses the solver based on a finer category; for example
* we have a specific solver for equality-constrained convex QP.
*/
enum class ProgramType {
kLP, ///< Linear Programming, with a linear cost and linear constraints.
kQP, ///< Quadratic Programming, with a convex quadratic cost and linear
///< constraints.
kSOCP, ///< Second-order Cone Programming, with a linear cost and
///< second-order cone constraints.
kSDP, ///< Semidefinite Programming, with a linear cost and positive
///< semidefinite matrix constraints.
kGP, ///< Geometric Programming, with a linear cost and exponential cone
///< constraints.
kCGP, ///< Conic Geometric Programming, this is a superset that unifies
///< GP and SDP. Refer to
///< http://people.lids.mit.edu/pari/cgp_preprint.pdf for more
///< details.
kMILP, ///< Mixed-integer Linear Programming. LP with some variables
///< taking binary values.
kMIQP, ///< Mixed-integer Quadratic Programming. QP with some variables
///< taking binary values.
kMISOCP, ///< Mixed-integer Second-order Cone Programming. SOCP with some
///< variables taking binary values.
kMISDP, ///< Mixed-integer Semidefinite Programming. SDP with some
///< variables taking binary values.
kQuadraticCostConicConstraint, ///< convex quadratic cost with nonlinear
///< conic constraints.
kNLP, ///< nonlinear programming. Programs with generic costs or
///< constraints.
kLCP, ///< Linear Complementarity Programs. Programs with linear
///< complementary constraints and no cost.
kUnknown, ///< Does not fall into any of the types above.
};
std::string to_string(const ProgramType&);
std::ostream& operator<<(std::ostream&, const ProgramType&);
} // namespace solvers
} // namespace drake
// TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<.
namespace fmt {
template <>
struct formatter<drake::solvers::ProgramAttribute> : drake::ostream_formatter {
};
template <>
struct formatter<drake::solvers::ProgramAttributes> : drake::ostream_formatter {
};
template <>
struct formatter<drake::solvers::ProgramType> : drake::ostream_formatter {};
} // namespace fmt
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/aggregate_costs_constraints.cc | #include "drake/solvers/aggregate_costs_constraints.h"
#include <algorithm>
#include <limits>
#include <map>
#include <fmt/format.h>
#include "drake/common/ssize.h"
#include "drake/math/eigen_sparse_triplet.h"
namespace drake {
namespace solvers {
namespace {
const double kInf = std::numeric_limits<double>::infinity();
// A helper class to add variable to an ordered vector while aggregating
// costs/constraints.
class VariableVector {
public:
VariableVector() {}
// Get the index of a variable if it is in the vector already, otherwise add
// it to the vector. Returns the index of this variable in the vector.
int GetOrAdd(const symbolic::Variable& var) {
const auto it = var_to_index_map_.find(var.get_id());
int var_index = -1;
if (it == var_to_index_map_.end()) {
var_index = vars_.size();
vars_.push_back(var);
var_to_index_map_.emplace_hint(it, var.get_id(), var_index);
} else {
var_index = it->second;
}
return var_index;
}
// Returns the variable as an Eigen vector.
VectorX<symbolic::Variable> CopyToEigen() const {
VectorX<symbolic::Variable> result(vars_.size());
for (int i = 0; i < static_cast<int>(vars_.size()); ++i) {
result(i) = vars_[i];
}
return result;
}
int size() const { return vars_.size(); }
private:
std::vector<symbolic::Variable> vars_;
std::map<symbolic::Variable::Id, int> var_to_index_map_;
};
// @param Q_lower[out] the lower triangular matrix of Q.
// @param quadratic_var_vec[out] A vector containing all the variables shown
// up in the quadratic cost.
// @param linear_coeff_triplets[in/out] The coefficients of the linear cost.
// @param linear_var_vec[in/out] The variables in the linear costs.
// @param constant_cost[in/out] The total constant term in the quadratic cost.
void AggregateQuadraticCostsHelper(
const std::vector<Binding<QuadraticCost>>& quadratic_costs,
Eigen::SparseMatrix<double>* Q_lower, VariableVector* quadratic_var_vec,
std::vector<Eigen::Triplet<double>>* linear_coeff_triplets,
VariableVector* linear_var_vec, double* constant_cost) {
std::vector<Eigen::Triplet<double>> Q_lower_triplets;
for (const auto& quadratic_cost : quadratic_costs) {
const int num_cost_var = quadratic_cost.variables().rows();
// cost_quadratic_var_indices[i] stores the index of
// quadratic_cost.variables()(i) in `quadratic_vars`.
std::vector<int> cost_quadratic_var_indices(num_cost_var);
for (int i = 0; i < num_cost_var; ++i) {
const symbolic::Variable& var = quadratic_cost.variables()(i);
cost_quadratic_var_indices[i] = quadratic_var_vec->GetOrAdd(var);
}
for (int i = 0; i < num_cost_var; ++i) {
if (quadratic_cost.evaluator()->b()(i) != 0) {
const symbolic::Variable& var_i = quadratic_cost.variables()(i);
const int linear_var_index = linear_var_vec->GetOrAdd(var_i);
linear_coeff_triplets->emplace_back(linear_var_index, 0,
quadratic_cost.evaluator()->b()(i));
}
for (int j = 0; j < num_cost_var; ++j) {
if (quadratic_cost.evaluator()->Q()(i, j) != 0) {
if (cost_quadratic_var_indices[i] >= cost_quadratic_var_indices[j]) {
Q_lower_triplets.emplace_back(
cost_quadratic_var_indices[i], cost_quadratic_var_indices[j],
quadratic_cost.evaluator()->Q()(i, j));
}
}
}
}
*constant_cost += quadratic_cost.evaluator()->c();
}
*Q_lower = Eigen::SparseMatrix<double>(quadratic_var_vec->size(),
quadratic_var_vec->size());
Q_lower->setFromTriplets(Q_lower_triplets.begin(), Q_lower_triplets.end());
}
// @param linear_coeff_triplets[in/out] The coefficient of linear costs.
// @param var_vec[in/out] The linear variables.
// @param constant_cost[in/out] The constant term in the cost.
void AggregateLinearCostsHelper(
const std::vector<Binding<LinearCost>>& linear_costs,
std::vector<Eigen::Triplet<double>>* linear_coeff_triplets,
VariableVector* var_vec, double* constant_cost) {
for (const auto& cost : linear_costs) {
const Eigen::SparseVector<double> cost_coeff =
cost.evaluator()->a().sparseView();
for (Eigen::SparseVector<double>::InnerIterator it(cost_coeff); it; ++it) {
const symbolic::Variable var = cost.variables()(it.index());
const int var_index = var_vec->GetOrAdd(var);
linear_coeff_triplets->emplace_back(var_index, 0, it.value());
}
*constant_cost += cost.evaluator()->b();
}
}
} // namespace
void AggregateLinearCosts(const std::vector<Binding<LinearCost>>& linear_costs,
Eigen::SparseVector<double>* linear_coeff,
VectorX<symbolic::Variable>* vars,
double* constant_cost) {
std::vector<Eigen::Triplet<double>> linear_coeff_triplets;
// We first store all the variables in var_vec, and convert it to VectorX
// object in the end.
VariableVector var_vec{};
*constant_cost = 0;
AggregateLinearCostsHelper(linear_costs, &linear_coeff_triplets, &var_vec,
constant_cost);
*linear_coeff = Eigen::SparseVector<double>(var_vec.size());
for (const auto& triplet : linear_coeff_triplets) {
linear_coeff->coeffRef(triplet.row()) += triplet.value();
}
*vars = var_vec.CopyToEigen();
}
void AggregateQuadraticAndLinearCosts(
const std::vector<Binding<QuadraticCost>>& quadratic_costs,
const std::vector<Binding<LinearCost>>& linear_costs,
Eigen::SparseMatrix<double>* Q_lower,
VectorX<symbolic::Variable>* quadratic_vars,
Eigen::SparseVector<double>* linear_coeff,
VectorX<symbolic::Variable>* linear_vars, double* constant_cost) {
VariableVector quadratic_var_vec{};
std::vector<Eigen::Triplet<double>> linear_coeff_triplets;
VariableVector linear_var_vec{};
*constant_cost = 0;
AggregateQuadraticCostsHelper(quadratic_costs, Q_lower, &quadratic_var_vec,
&linear_coeff_triplets, &linear_var_vec,
constant_cost);
AggregateLinearCostsHelper(linear_costs, &linear_coeff_triplets,
&linear_var_vec, constant_cost);
*linear_coeff = Eigen::SparseVector<double>(linear_var_vec.size());
for (const auto& triplet : linear_coeff_triplets) {
linear_coeff->coeffRef(triplet.row()) += triplet.value();
}
*linear_vars = linear_var_vec.CopyToEigen();
*quadratic_vars = quadratic_var_vec.CopyToEigen();
}
std::unordered_map<symbolic::Variable, Bound> AggregateBoundingBoxConstraints(
const std::vector<Binding<BoundingBoxConstraint>>&
bounding_box_constraints) {
std::unordered_map<symbolic::Variable, Bound> bounds;
for (const auto& constraint : bounding_box_constraints) {
for (int i = 0; i < constraint.variables().rows(); ++i) {
const symbolic::Variable& var = constraint.variables()(i);
const double var_lower = constraint.evaluator()->lower_bound()(i);
const double var_upper = constraint.evaluator()->upper_bound()(i);
auto it = bounds.find(var);
if (it == bounds.end()) {
bounds.emplace_hint(it, var,
Bound{.lower = var_lower, .upper = var_upper});
} else {
if (var_lower > it->second.lower) {
it->second.lower = var_lower;
}
if (var_upper < it->second.upper) {
it->second.upper = var_upper;
}
}
}
}
return bounds;
}
namespace {
template <typename C>
void AggregateBoundingBoxConstraintsImpl(const MathematicalProgram& prog,
C* lower, C* upper) {
for (const auto& constraint : prog.bounding_box_constraints()) {
for (int i = 0; i < constraint.variables().rows(); ++i) {
const int var_index =
prog.FindDecisionVariableIndex(constraint.variables()(i));
if (constraint.evaluator()->lower_bound()(i) > (*lower)[var_index]) {
(*lower)[var_index] = constraint.evaluator()->lower_bound()(i);
}
if (constraint.evaluator()->upper_bound()(i) < (*upper)[var_index]) {
(*upper)[var_index] = constraint.evaluator()->upper_bound()(i);
}
}
}
}
} // namespace
void AggregateBoundingBoxConstraints(const MathematicalProgram& prog,
Eigen::VectorXd* lower,
Eigen::VectorXd* upper) {
*lower = Eigen::VectorXd::Constant(prog.num_vars(), -kInf);
*upper = Eigen::VectorXd::Constant(prog.num_vars(), kInf);
AggregateBoundingBoxConstraintsImpl(prog, lower, upper);
}
void AggregateBoundingBoxConstraints(const MathematicalProgram& prog,
std::vector<double>* lower,
std::vector<double>* upper) {
*lower = std::vector<double>(prog.num_vars(), -kInf);
*upper = std::vector<double>(prog.num_vars(), kInf);
AggregateBoundingBoxConstraintsImpl(prog, lower, upper);
}
void AggregateDuplicateVariables(const Eigen::SparseMatrix<double>& A,
const VectorX<symbolic::Variable>& vars,
Eigen::SparseMatrix<double>* A_new,
VectorX<symbolic::Variable>* vars_new) {
// First select the unique variables from decision_vars.
vars_new->resize(vars.rows());
// vars_to_vars_new records the mapping from vars to vars_new. Namely
// vars[i] = (*vars_new)[vars_to_vars_new[vars[i].get_id()]]
std::unordered_map<symbolic::Variable::Id, int> vars_to_vars_new;
int unique_var_count = 0;
for (int i = 0; i < vars.rows(); ++i) {
const bool seen_already = vars_to_vars_new.contains(vars(i).get_id());
if (!seen_already) {
(*vars_new)(unique_var_count) = vars(i);
vars_to_vars_new.emplace(vars(i).get_id(), unique_var_count);
unique_var_count++;
}
}
// A * vars = A_new * vars_new.
// A_new_triplets are the non-zero triplets in A_new.
std::vector<Eigen::Triplet<double>> A_new_triplets;
A_new_triplets.reserve(A.nonZeros());
for (int i = 0; i < A.cols(); ++i) {
const int A_new_col = vars_to_vars_new.at(vars(i).get_id());
for (Eigen::SparseMatrix<double>::InnerIterator it(A, i); it; ++it) {
A_new_triplets.emplace_back(it.row(), A_new_col, it.value());
}
}
*A_new = Eigen::SparseMatrix<double>(A.rows(), unique_var_count);
A_new->setFromTriplets(A_new_triplets.begin(), A_new_triplets.end());
vars_new->conservativeResize(unique_var_count);
}
const Binding<QuadraticCost>* FindNonconvexQuadraticCost(
const std::vector<Binding<QuadraticCost>>& quadratic_costs) {
return internal::FindNonconvexQuadraticCost(quadratic_costs);
}
namespace internal {
const Binding<QuadraticCost>* FindNonconvexQuadraticCost(
const std::vector<Binding<QuadraticCost>>& quadratic_costs) {
for (const auto& cost : quadratic_costs) {
if (!cost.evaluator()->is_convex()) {
return &cost;
}
}
return nullptr;
}
const Binding<QuadraticConstraint>* FindNonconvexQuadraticConstraint(
const std::vector<Binding<QuadraticConstraint>>& quadratic_constraints) {
for (const auto& constraint : quadratic_constraints) {
if (!constraint.evaluator()->is_convex()) {
return &constraint;
}
}
return nullptr;
}
bool CheckConvexSolverAttributes(const MathematicalProgram& prog,
const ProgramAttributes& solver_capabilities,
std::string_view solver_name,
std::string* explanation) {
const ProgramAttributes& required_capabilities = prog.required_capabilities();
const bool capabilities_match = AreRequiredAttributesSupported(
required_capabilities, solver_capabilities, explanation);
if (!capabilities_match) {
if (explanation) {
*explanation = fmt::format("{} is unable to solve because {}.",
solver_name, *explanation);
}
return false;
}
const Binding<QuadraticCost>* nonconvex_quadratic_cost =
internal::FindNonconvexQuadraticCost(prog.quadratic_costs());
if (nonconvex_quadratic_cost != nullptr) {
if (explanation) {
*explanation = fmt::format(
"{} is unable to solve because (at least) the quadratic cost {} is "
"non-convex. Either change this cost to a convex one, or switch "
"to a different solver like SNOPT/IPOPT/NLOPT.",
solver_name, nonconvex_quadratic_cost->to_string());
}
return false;
}
if (explanation) {
explanation->clear();
}
const Binding<QuadraticConstraint>* nonconvex_quadratic_constraint =
internal::FindNonconvexQuadraticConstraint(prog.quadratic_constraints());
if (nonconvex_quadratic_constraint != nullptr) {
if (explanation) {
*explanation = fmt::format(
"{} is unable to solve because (at least) the quadratic constraint "
"{} is non-convex. Either change this constraint to a convex one, or "
"switch to a different solver like SNOPT/IPOPT/NLOPT.",
solver_name, nonconvex_quadratic_constraint->to_string());
}
return false;
}
return true;
}
void ParseLinearCosts(const MathematicalProgram& prog, std::vector<double>* c,
double* constant) {
DRAKE_DEMAND(static_cast<int>(c->size()) >= prog.num_vars());
for (const auto& linear_cost : prog.linear_costs()) {
// Each linear cost is in the form of aᵀx + b
const auto& a = linear_cost.evaluator()->a();
const VectorXDecisionVariable& x = linear_cost.variables();
for (int i = 0; i < a.rows(); ++i) {
(*c)[prog.FindDecisionVariableIndex(x(i))] += a(i);
}
(*constant) += linear_cost.evaluator()->b();
}
}
void ParseLinearEqualityConstraints(
const MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<int>* linear_eq_y_start_indices,
int* num_linear_equality_constraints_rows) {
DRAKE_ASSERT(linear_eq_y_start_indices->empty());
DRAKE_ASSERT(static_cast<int>(b->size()) == *A_row_count);
*num_linear_equality_constraints_rows = 0;
linear_eq_y_start_indices->reserve(prog.linear_equality_constraints().size());
// The linear equality constraint A x = b is converted to
// A x + s = b. s in zero cone.
for (const auto& linear_equality_constraint :
prog.linear_equality_constraints()) {
const Eigen::SparseMatrix<double>& Ai =
linear_equality_constraint.evaluator()->get_sparse_A();
const std::vector<Eigen::Triplet<double>> Ai_triplets =
math::SparseMatrixToTriplets(Ai);
A_triplets->reserve(A_triplets->size() + Ai_triplets.size());
const solvers::VectorXDecisionVariable& x =
linear_equality_constraint.variables();
// x_indices[i] is the index of x(i)
const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);
for (const auto& Ai_triplet : Ai_triplets) {
A_triplets->emplace_back(Ai_triplet.row() + *A_row_count,
x_indices[Ai_triplet.col()], Ai_triplet.value());
}
const int num_Ai_rows =
linear_equality_constraint.evaluator()->num_constraints();
b->reserve(b->size() + num_Ai_rows);
for (int i = 0; i < num_Ai_rows; ++i) {
b->push_back(linear_equality_constraint.evaluator()->lower_bound()(i));
}
linear_eq_y_start_indices->push_back(*A_row_count);
*A_row_count += num_Ai_rows;
*num_linear_equality_constraints_rows += num_Ai_rows;
}
}
void ParseLinearConstraints(const solvers::MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets,
std::vector<double>* b, int* A_row_count,
std::vector<std::vector<std::pair<int, int>>>*
linear_constraint_dual_indices,
int* num_linear_constraint_rows) {
// The linear constraint lb ≤ aᵀx ≤ ub is converted to
// -aᵀx + s1 = lb,
// aᵀx + s2 = ub
// s1, s2 in the positive cone.
// The special cases are when ub = ∞ or lb = -∞.
// When ub = ∞, then we only add the constraint
// -aᵀx + s = lb, s in the positive cone.
// When lb = -∞, then we only add the constraint
// aᵀx + s = ub, s in the positive cone.
*num_linear_constraint_rows = 0;
linear_constraint_dual_indices->reserve(prog.linear_constraints().size());
for (const auto& linear_constraint : prog.linear_constraints()) {
linear_constraint_dual_indices->emplace_back(
linear_constraint.evaluator()->num_constraints());
const Eigen::VectorXd& ub = linear_constraint.evaluator()->upper_bound();
const Eigen::VectorXd& lb = linear_constraint.evaluator()->lower_bound();
const VectorXDecisionVariable& x = linear_constraint.variables();
const Eigen::SparseMatrix<double>& Ai =
linear_constraint.evaluator()->get_sparse_A();
// We store the starting row index in A_triplets for each row of
// linear_constraint. Namely the constraint lb(i) <= A.row(i)*x <= ub(i) is
// stored in A_triplets with starting_row_indices[i] (or
// starting_row_indices[i]+1 if both lb(i) and ub(i) are finite).
std::vector<int> starting_row_indices(
linear_constraint.evaluator()->num_constraints());
for (int i = 0; i < linear_constraint.evaluator()->num_constraints(); ++i) {
const bool needs_ub{!std::isinf(ub(i))};
const bool needs_lb{!std::isinf(lb(i))};
auto& dual_index = linear_constraint_dual_indices->back()[i];
// Use -1 to indicate the constraint bound is infinity.
dual_index.first = -1;
dual_index.second = -1;
if (!needs_ub && !needs_lb) {
// We use -1 to indicate that we won't add linear constraint when both
// bounds are infinity.
starting_row_indices[i] = -1;
} else {
starting_row_indices[i] = *A_row_count + *num_linear_constraint_rows;
// We first add the constraint for lower bound, and then add the
// constraint for upper bound. This is consistent with the loop below
// when we modify A_triplets.
if (needs_lb) {
b->push_back(-lb(i));
dual_index.first = *A_row_count + *num_linear_constraint_rows;
(*num_linear_constraint_rows)++;
}
if (needs_ub) {
b->push_back(ub(i));
dual_index.second = *A_row_count + *num_linear_constraint_rows;
(*num_linear_constraint_rows)++;
}
}
}
for (int j = 0; j < Ai.cols(); ++j) {
const int xj_index = prog.FindDecisionVariableIndex(x(j));
for (Eigen::SparseMatrix<double>::InnerIterator it(Ai, j); it; ++it) {
const int Ai_row_count = it.row();
const bool needs_ub{!std::isinf(ub(Ai_row_count))};
const bool needs_lb{!std::isinf(lb(Ai_row_count))};
if (!needs_lb && !needs_ub) {
continue;
}
int row_index = starting_row_indices[Ai_row_count];
if (needs_lb) {
// If lb != -∞, then the constraint -aᵀx + s = lb will be added to
// the matrix A, in the row row_index.
A_triplets->emplace_back(row_index, xj_index, -it.value());
++row_index;
}
if (needs_ub) {
// If ub != ∞, then the constraint aᵀx + s = ub will be added to the
// matrix A, in the row row_index.
A_triplets->emplace_back(row_index, xj_index, it.value());
}
}
}
}
*A_row_count += *num_linear_constraint_rows;
}
void ParseQuadraticCosts(const MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* P_upper_triplets,
std::vector<double>* c, double* constant) {
for (const auto& cost : prog.quadratic_costs()) {
const auto var_indices = prog.FindDecisionVariableIndices(cost.variables());
for (int j = 0; j < cost.evaluator()->Q().cols(); ++j) {
for (int i = 0; i <= j; ++i) {
if (cost.evaluator()->Q()(i, j) != 0) {
// Since we allow duplicated variables in a quadratic cost, we need to
// handle this more carefully. If i != j but var_indices[i] ==
// var_indices[j], then it means that the cost is a diagonal term
// (Q(i, j) + Q(j, i)) * x[var_indices[i]]² = 2 * Q(i, j)*
// x[var_indices[i]]², not a cross term (Q(i, j) + Q(j, i)) *
// x[var_indices[i]] * x[var_indices[j]]. Hence we need a factor of 2
// for this special case.
const double factor =
(i != j && var_indices[i] == var_indices[j]) ? 2 : 1;
// Since we only add the upper diagonal entries, we need to branch
// based on whether var_indices[i] > var_indices[j]
int row_index = var_indices[i];
int col_index = var_indices[j];
if (var_indices[i] > var_indices[j]) {
row_index = var_indices[j];
col_index = var_indices[i];
}
P_upper_triplets->emplace_back(row_index, col_index,
factor * cost.evaluator()->Q()(i, j));
}
}
(*c)[var_indices[j]] += cost.evaluator()->b()(j);
}
*constant += cost.evaluator()->c();
}
}
void ParseL2NormCosts(const MathematicalProgram& prog,
int* num_solver_variables,
std::vector<Eigen::Triplet<double>>* A_triplets,
std::vector<double>* b, int* A_row_count,
std::vector<int>* second_order_cone_length,
std::vector<int>* lorentz_cone_y_start_indices,
std::vector<double>* cost_coeffs,
std::vector<int>* t_slack_indices) {
int t_slack_count = 0;
for (const auto& cost : prog.l2norm_costs()) {
const VectorXDecisionVariable& x = cost.variables();
t_slack_indices->push_back(t_slack_count + *num_solver_variables);
const Eigen::SparseMatrix<double>& C = cost.evaluator()->get_sparse_A();
const auto& d = cost.evaluator()->b();
// Add the constraint
// [0 -1] * [x] + s = [0]
// [-C 0] [t] [d]
A_triplets->emplace_back(*A_row_count, t_slack_indices->back(), -1);
b->push_back(0);
for (int k = 0; k < C.outerSize(); ++k) {
const int x_index = prog.FindDecisionVariableIndex(x(k));
for (Eigen::SparseMatrix<double>::InnerIterator it(C, k); it; ++it) {
A_triplets->emplace_back(*A_row_count + 1 + it.row(), x_index,
-it.value());
}
}
for (int i = 0; i < d.rows(); ++i) {
b->push_back(d(i));
}
// Add the cost to minimize t
cost_coeffs->push_back(1.0);
second_order_cone_length->push_back(1 + cost.evaluator()->b().rows());
lorentz_cone_y_start_indices->push_back(*A_row_count);
*num_solver_variables += 1;
*A_row_count += 1 + cost.evaluator()->b().rows();
}
}
void ParseSecondOrderConeConstraints(
const MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<int>* second_order_cone_length,
std::vector<int>* lorentz_cone_y_start_indices,
std::vector<int>* rotated_lorentz_cone_y_start_indices) {
// Our LorentzConeConstraint encodes that Ax + b is in Lorentz cone. We
// convert this to SCS form, as -Ax + s = b, s in Lorentz cone.
second_order_cone_length->reserve(
prog.lorentz_cone_constraints().size() +
prog.rotated_lorentz_cone_constraints().size());
lorentz_cone_y_start_indices->reserve(prog.lorentz_cone_constraints().size());
rotated_lorentz_cone_y_start_indices->reserve(
prog.rotated_lorentz_cone_constraints().size());
for (const auto& lorentz_cone_constraint : prog.lorentz_cone_constraints()) {
// x_indices[i] is the index of x(i)
const VectorXDecisionVariable& x = lorentz_cone_constraint.variables();
const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);
const Eigen::SparseMatrix<double>& Ai =
lorentz_cone_constraint.evaluator()->A();
const std::vector<Eigen::Triplet<double>> Ai_triplets =
math::SparseMatrixToTriplets(Ai);
for (const auto& Ai_triplet : Ai_triplets) {
A_triplets->emplace_back(Ai_triplet.row() + *A_row_count,
x_indices[Ai_triplet.col()],
-Ai_triplet.value());
}
const int num_Ai_rows = lorentz_cone_constraint.evaluator()->A().rows();
for (int i = 0; i < num_Ai_rows; ++i) {
b->push_back(lorentz_cone_constraint.evaluator()->b()(i));
}
second_order_cone_length->push_back(num_Ai_rows);
lorentz_cone_y_start_indices->push_back(*A_row_count);
*A_row_count += num_Ai_rows;
}
for (const auto& rotated_lorentz_cone :
prog.rotated_lorentz_cone_constraints()) {
const VectorXDecisionVariable& x = rotated_lorentz_cone.variables();
const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);
const Eigen::SparseMatrix<double> Ai =
rotated_lorentz_cone.evaluator()->A();
const Eigen::VectorXd& bi = rotated_lorentz_cone.evaluator()->b();
const std::vector<Eigen::Triplet<double>> Ai_triplets =
math::SparseMatrixToTriplets(Ai);
ParseRotatedLorentzConeConstraint(Ai_triplets, bi, x_indices, A_triplets, b,
A_row_count, second_order_cone_length,
rotated_lorentz_cone_y_start_indices);
}
}
void ParseRotatedLorentzConeConstraint(
const std::vector<Eigen::Triplet<double>>& A_cone_triplets,
const Eigen::Ref<const Eigen::VectorXd>& b_cone,
const std::vector<int>& x_indices,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<int>* second_order_cone_length,
std::optional<std::vector<int>*> rotated_lorentz_cone_y_start_indices) {
// Our RotatedLorentzConeConstraint encodes that Ax + b is in the rotated
// Lorentz cone, namely
// (a₀ᵀx + b₀) (a₁ᵀx + b₁) ≥ (a₂ᵀx + b₂)² + ... + (aₙ₋₁ᵀx + bₙ₋₁)²
// (a₀ᵀx + b₀) ≥ 0
// (a₁ᵀx + b₁) ≥ 0
// , where aᵢᵀ is the i'th row of A, bᵢ is the i'th row of b. Equivalently the
// vector
// [ 0.5(a₀ + a₁)ᵀx + 0.5(b₀ + b₁) ]
// [ 0.5(a₀ - a₁)ᵀx + 0.5(b₀ - b₁) ]
// [ a₂ᵀx + b₂ ]
// ...
// [ aₙ₋₁ᵀx + bₙ₋₁ ]
// is in the Lorentz cone. We convert this to the SCS form, that
// Cx + s = d
// s in Lorentz cone,
// where C = [ -0.5(a₀ + a₁)ᵀ ] d = [ 0.5(b₀ + b₁) ]
// [ -0.5(a₀ - a₁)ᵀ ] [ 0.5(b₀ - b₁) ]
// [ -a₂ᵀ ] [ b₂ ]
// ... ...
// [ -aₙ₋₁ᵀ ] [ bₙ₋₁]
for (const auto& Ai_triplet : A_cone_triplets) {
const int x_index = x_indices[Ai_triplet.col()];
if (Ai_triplet.row() == 0) {
A_triplets->emplace_back(*A_row_count, x_index,
-0.5 * Ai_triplet.value());
A_triplets->emplace_back(*A_row_count + 1, x_index,
-0.5 * Ai_triplet.value());
} else if (Ai_triplet.row() == 1) {
A_triplets->emplace_back(*A_row_count, x_index,
-0.5 * Ai_triplet.value());
A_triplets->emplace_back(*A_row_count + 1, x_index,
0.5 * Ai_triplet.value());
} else {
A_triplets->emplace_back(*A_row_count + Ai_triplet.row(), x_index,
-Ai_triplet.value());
}
}
b->push_back(0.5 * (b_cone(0) + b_cone(1)));
b->push_back(0.5 * (b_cone(0) - b_cone(1)));
for (int i = 2; i < b_cone.rows(); ++i) {
b->push_back(b_cone(i));
}
if (rotated_lorentz_cone_y_start_indices.has_value()) {
rotated_lorentz_cone_y_start_indices.value()->push_back(*A_row_count);
}
*A_row_count += b_cone.rows();
second_order_cone_length->push_back(b_cone.rows());
}
void ParseExponentialConeConstraints(
const MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count) {
for (const auto& binding : prog.exponential_cone_constraints()) {
// drake::solvers::ExponentialConstraint enforces that z = A * x + b is in
// the exponential cone (z₀ ≥ z₁*exp(z₂ / z₁)). This is different from the
// exponential cone used in SCS. In SCS, a vector s is in the exponential
// cone, if s₂≥ s₁*exp(s₀ / s₁). To transform drake's Exponential cone to
// SCS's exponential cone, we use
// -[A.row(2); A.row(1); A.row(0)] * x + s = [b(2); b(1); b(0)], and s is
// in SCS's exponential cone, where A = binding.evaluator()->A(), b =
// binding.evaluator()->b().
const int num_bound_variables = binding.variables().rows();
for (int i = 0; i < num_bound_variables; ++i) {
A_triplets->reserve(A_triplets->size() +
binding.evaluator()->A().nonZeros());
const int decision_variable_index =
prog.FindDecisionVariableIndex(binding.variables()(i));
for (Eigen::SparseMatrix<double>::InnerIterator it(
binding.evaluator()->A(), i);
it; ++it) {
// 2 - it.row() is used for reverse the row order, as mentioned in the
// function documentation above.
A_triplets->emplace_back(*A_row_count + 2 - it.row(),
decision_variable_index, -it.value());
}
}
// The exponential cone constraint is on a 3 x 1 vector, hence for each
// ExponentialConeConstraint, we append 3 rows to A and b.
b->reserve(b->size() + 3);
for (int i = 0; i < 3; ++i) {
b->push_back(binding.evaluator()->b()(2 - i));
}
*A_row_count += 3;
}
}
void ParsePositiveSemidefiniteConstraints(
const MathematicalProgram& prog, bool upper_triangular,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<int>* psd_cone_length) {
DRAKE_ASSERT(ssize(*b) == *A_row_count);
DRAKE_ASSERT(psd_cone_length != nullptr);
// Make sure that each triplet in A_triplets has row no larger than
// *A_row_count.
// Use kDrakeAssertIsArmed to bypass the entire for loop in the release mode.
if (kDrakeAssertIsArmed) {
for (const auto& A_triplet : *A_triplets) {
DRAKE_DEMAND(A_triplet.row() <= *A_row_count);
}
}
DRAKE_ASSERT(psd_cone_length->empty());
const double sqrt2 = std::sqrt(2);
for (const auto& psd_constraint : prog.positive_semidefinite_constraints()) {
// PositiveSemidefiniteConstraint encodes the matrix X being psd.
// We convert it to SCS/Clarabel form
// A * x + s = 0
// s in positive semidefinite cone.
// where A is a diagonal matrix, with its diagonal entries being the stacked
// column vector of the lower/upper triangular part of matrix
// ⎡ -1 -√2 -√2 ... -√2⎤
// ⎢-√2 -1 -√2 ... -√2⎥
// ⎢-√2 -√2 -1 ... -√2⎥
// ⎢ ... ⎥
// ⎣-√2 -√2 -√2 ... -1⎦
// The √2 scaling factor in the off-diagonal entries are required by SCS and
// Clarabel, as it uses only the lower triangular part (for SCS), or upper
// triangular part (for Clarabel) of the symmetric matrix, as explained in
// https://www.cvxgrp.org/scs/api/cones.html#semidefinite-cones and
// https://oxfordcontrol.github.io/ClarabelDocs/stable/examples/example_sdp.
// x is the stacked column vector of the lower triangular part of the
// symmetric matrix X.
const int X_rows = psd_constraint.evaluator()->matrix_rows();
int x_index_count = 0;
// The variables in the psd constraint are the stacked columns of the matrix
// X (in column major order).
const VectorXDecisionVariable& flat_X = psd_constraint.variables();
DRAKE_DEMAND(flat_X.rows() == X_rows * X_rows);
b->reserve(b->size() + X_rows * (X_rows + 1) / 2);
for (int j = 0; j < X_rows; ++j) {
const int i_start = upper_triangular ? 0 : j;
const int i_end = upper_triangular ? j + 1 : X_rows;
for (int i = i_start; i < i_end; ++i) {
const double scale_factor = i == j ? 1 : sqrt2;
A_triplets->emplace_back(
*A_row_count + x_index_count,
prog.FindDecisionVariableIndex(flat_X(j * X_rows + i)),
-scale_factor);
b->push_back(0);
++x_index_count;
}
}
(*A_row_count) += X_rows * (X_rows + 1) / 2;
psd_cone_length->push_back(X_rows);
}
for (const auto& lmi_constraint :
prog.linear_matrix_inequality_constraints()) {
// LinearMatrixInequalityConstraint encodes
// F₀ + x₁*F₁ + x₂*F₂ + ... + xₙFₙ is p.s.d
// We convert this to SCS/Clarabel form as
// A_cone * x + s = b_cone
// s in SCS/Clarabel positive semidefinite cone.
// For SCS, it uses the lower triangular of the symmetric psd matrix, hence
// ⎡ F₁(0, 0) F₂(0, 0) ... Fₙ(0, 0)⎤
// ⎢√2F₁(1, 0) √2F₂(1, 0) ... √2Fₙ(1, 0)⎥
// A_cone = - ⎢√2F₁(2, 0) √2F₂(2, 0) ... √2Fₙ(2, 0)⎥,
// ⎢ ... ⎥
// ⎣ F₁(m, m) F₂(m, m) ... Fₙ(m, m)⎦
//
// ⎡ F₀(0, 0)⎤
// ⎢√2F₀(1, 0)⎥
// b_cone = ⎢√2F₀(2, 0)⎥,
// ⎢ ... ⎥
// ⎣ F₀(m, m)⎦
// For Clarabel, it uses the upper triangular of the symmetric psd matrix,
// hence
// ⎡ F₁(0, 0) F₂(0, 0) ... Fₙ(0, 0)⎤
// ⎢√2F₁(0, 1) √2F₂(0, 1) ... √2Fₙ(0, 1)⎥
// A_cone = - ⎢√2F₁(1, 1) √2F₂(1, 1) ... √2Fₙ(1, 1)⎥,
// ⎢ ... ⎥
// ⎣ F₁(m, m) F₂(m, m) ... Fₙ(m, m)⎦
//
// ⎡ F₀(0, 0)⎤
// ⎢√2F₀(0, 1)⎥
// b_cone = ⎢√2F₀(1, 1)⎥,
// ⎢ ... ⎥
// ⎣ F₀(m, m)⎦
// For both SCS and Clarabel, we have
// x = [x₁; x₂; ... ; xₙ].
// As explained above, the off-diagonal rows are scaled by √2. Please refer
// to https://github.com/cvxgrp/scs about the scaling factor √2.
// Note that since all F matrices are symmetric, we don't need to
// differentiate between lower triangular or upper triangular version.
const std::vector<Eigen::MatrixXd>& F = lmi_constraint.evaluator()->F();
const VectorXDecisionVariable& x = lmi_constraint.variables();
const int F_rows = lmi_constraint.evaluator()->matrix_rows();
const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);
int A_cone_row_count = 0;
b->reserve(b->size() + F_rows * (F_rows + 1) / 2);
for (int j = 0; j < F_rows; ++j) {
const int i_start = upper_triangular ? 0 : j;
const int i_end = upper_triangular ? j + 1 : F_rows;
for (int i = i_start; i < i_end; ++i) {
const double scale_factor = i == j ? 1 : sqrt2;
for (int k = 1; k < static_cast<int>(F.size()); ++k) {
A_triplets->emplace_back(*A_row_count + A_cone_row_count,
x_indices[k - 1],
-scale_factor * F[k](i, j));
}
b->push_back(scale_factor * F[0](i, j));
++A_cone_row_count;
}
}
*A_row_count += F_rows * (F_rows + 1) / 2;
psd_cone_length->push_back(F_rows);
}
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/ipopt_solver.cc | #include "drake/solvers/ipopt_solver.h"
#include <algorithm>
#include <cstring>
#include <limits>
#include <memory>
#include <optional>
#include <unordered_map>
#include <utility>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
#include "drake/common/unused.h"
#include "drake/math/autodiff.h"
#include "drake/solvers/ipopt_solver_internal.h"
#include "drake/solvers/mathematical_program.h"
using Ipopt::SolverReturn;
namespace drake {
namespace solvers {
namespace {
void SetAppOptions(const SolverOptions& options, Ipopt::IpoptApplication* app) {
// Turn off the banner.
app->Options()->SetStringValue("sb", "yes");
// The default linear solver is MA27, but it is not freely redistributable so
// we cannot use it. MUMPS is the only compatible linear solver guaranteed to
// be available on both macOS and Ubuntu. In versions of IPOPT prior to 3.13,
// it would correctly determine that MUMPS was the only available solver, but
// its behavior changed to instead error having unsuccessfully tried to dlopen
// a nonexistent hsl library that would contain MA27.
app->Options()->SetStringValue("linear_solver", "mumps");
// The default tolerance.
const double tol = 1.05e-10; // Note: SNOPT is only 1e-6, but in #3712 we
// diagnosed that the CompareMatrices tolerance needed to be the sqrt of the
// constr_viol_tol
app->Options()->SetNumericValue("tol", tol);
app->Options()->SetNumericValue("constr_viol_tol", tol);
app->Options()->SetNumericValue("acceptable_tol", tol);
app->Options()->SetNumericValue("acceptable_constr_viol_tol", tol);
app->Options()->SetStringValue("hessian_approximation", "limited-memory");
// Note: 0 <= print_level <= 12, with higher numbers more verbose; 4 is very
// useful for debugging. Otherwise, we default to printing nothing. The user
// can always select an arbitrary print level, by setting the ipopt-specific
// option name directly.
const int verbose_level = 4;
const int print_level = options.get_print_to_console() ? verbose_level : 0;
app->Options()->SetIntegerValue("print_level", print_level);
const std::string& output_file = options.get_print_file_name();
if (!output_file.empty()) {
app->Options()->SetStringValue("output_file", output_file);
app->Options()->SetIntegerValue("file_print_level", verbose_level);
}
// The solver-specific options will trump our defaults.
const SolverId self = IpoptSolver::id();
for (const auto& [name, value] : options.GetOptionsDouble(self)) {
app->Options()->SetNumericValue(name, value);
}
for (const auto& [name, value] : options.GetOptionsInt(self)) {
app->Options()->SetIntegerValue(name, value);
}
for (const auto& [name, value] : options.GetOptionsStr(self)) {
app->Options()->SetStringValue(name, value);
}
}
} // namespace
const char* IpoptSolverDetails::ConvertStatusToString() const {
switch (status) {
case Ipopt::SolverReturn::SUCCESS: {
return "Success";
}
case Ipopt::SolverReturn::MAXITER_EXCEEDED: {
return "Max iteration exceeded";
}
case Ipopt::SolverReturn::CPUTIME_EXCEEDED: {
return "CPU time exceeded";
}
case Ipopt::SolverReturn::STOP_AT_TINY_STEP: {
return "Stop at tiny step";
}
case Ipopt::SolverReturn::STOP_AT_ACCEPTABLE_POINT: {
return "Stop at acceptable point";
}
case Ipopt::SolverReturn::LOCAL_INFEASIBILITY: {
return "Local infeasibility";
}
case Ipopt::SolverReturn::USER_REQUESTED_STOP: {
return "User requested stop";
}
case Ipopt::SolverReturn::FEASIBLE_POINT_FOUND: {
return "Feasible point found";
}
case Ipopt::SolverReturn::DIVERGING_ITERATES: {
return "Divergent iterates";
}
case Ipopt::SolverReturn::RESTORATION_FAILURE: {
return "Restoration failure";
}
case Ipopt::SolverReturn::ERROR_IN_STEP_COMPUTATION: {
return "Error in step computation";
}
case Ipopt::SolverReturn::INVALID_NUMBER_DETECTED: {
return "Invalid number detected";
}
case Ipopt::SolverReturn::TOO_FEW_DEGREES_OF_FREEDOM: {
return "Too few degrees of freedom";
}
case Ipopt::SolverReturn::INVALID_OPTION: {
return "Invalid option";
}
case Ipopt::SolverReturn::OUT_OF_MEMORY: {
return "Out of memory";
}
case Ipopt::SolverReturn::INTERNAL_ERROR: {
return "Internal error";
}
case Ipopt::SolverReturn::UNASSIGNED: {
return "Unassigned";
}
}
return "Unknown enumerated SolverReturn value.";
}
bool IpoptSolver::is_available() {
return true;
}
void IpoptSolver::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(
"IpoptSolver doesn't support the feature of variable scaling.");
}
Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory();
app->RethrowNonIpoptException(true);
SetAppOptions(merged_options, &(*app));
Ipopt::ApplicationReturnStatus status = app->Initialize();
if (status != Ipopt::Solve_Succeeded) {
result->set_solution_result(SolutionResult::kInvalidInput);
return;
}
Ipopt::SmartPtr<internal::IpoptSolver_NLP> nlp =
new internal::IpoptSolver_NLP(prog, initial_guess, result);
status = app->OptimizeTNLP(nlp);
// Set result.solver_details.
IpoptSolverDetails& solver_details =
result->SetSolverDetailsType<IpoptSolverDetails>();
solver_details.status = nlp->status();
solver_details.z_L = nlp->z_L();
solver_details.z_U = nlp->z_U();
solver_details.g = nlp->g();
solver_details.lambda = nlp->lambda();
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/snopt_solver.cc | #include "drake/solvers/snopt_solver.h"
#include <algorithm>
#include <array>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <unordered_map>
#include <utility>
#include <vector>
// NOLINTNEXTLINE(build/include)
#include "snopt.h"
#include "drake/common/scope_exit.h"
#include "drake/common/text_logging.h"
#include "drake/math/autodiff.h"
#include "drake/solvers/mathematical_program.h"
// TODO(jwnimmer-tri) Eventually resolve these warnings.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
// todo(sammy-tri) : return more information that just the solution (INFO,
// infeasible constraints, ...)
// todo(sammy-tri) : avoid all dynamic allocation
namespace {
// Fortran has a pool of integers, which it uses as file handles for debug
// output. When "Print file" output is enabled, we will need to tell SNOPT
// which integer to use for a given thread's debug output, so therefore we
// maintain a singleton pool of those integers here.
// See also http://fortranwiki.org/fortran/show/newunit.
class FortranUnitFactory {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FortranUnitFactory)
static FortranUnitFactory& singleton() {
static drake::never_destroyed<FortranUnitFactory> result;
return result.access();
}
// Default constructor; don't call this -- only use the singleton().
// (We can't mark this private, due to never_destroyed's use of it.)
FortranUnitFactory() {
// Populate the pool; we'll work from the back (i.e., starting with 10).
// The range 10..1000 is borrowed from SNOPT 7.6's snopt-interface code,
// also found at http://fortranwiki.org/fortran/show/newunit.
for (int i = 10; i < 1000; ++i) {
available_units_.push_front(i);
}
}
// Returns an available new unit.
int Allocate() {
std::lock_guard<std::mutex> guard(mutex_);
DRAKE_DEMAND(!available_units_.empty());
int result = available_units_.back();
available_units_.pop_back();
return result;
}
// Reclaims a unit, returning it to the pool.
void Release(int unit) {
DRAKE_DEMAND(unit != 0);
std::lock_guard<std::mutex> guard(mutex_);
available_units_.push_back(unit);
}
private:
std::mutex mutex_;
std::deque<int> available_units_;
};
// This struct is a helper to bridge the gap between SNOPT's 7.4 and 7.6 APIs.
// Its specializations provide static methods that express the SNOPT 7.6 APIs.
// When compiled using SNOPT 7.6, these static methods are mere aliases to the
// underlying SNOPT 7.6 functions. When compiled using SNOPT 7.4, these static
// methods rewrite the arguments and call the older 7.4 APIs.
template <bool is_snopt_76>
struct SnoptImpl {};
// This is the SNOPT 7.6 implementation. It just aliases the function pointers.
template <>
struct SnoptImpl<true> {
#pragma GCC diagnostic push // Silence spurious warnings from macOS llvm.
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wunused-const-variable"
static constexpr auto snend = ::f_snend;
static constexpr auto sninit = ::f_sninit;
static constexpr auto snkera = ::f_snkera;
static constexpr auto snmema = ::f_snmema;
static constexpr auto snseti = ::f_snseti;
static constexpr auto snsetr = ::f_snsetr;
static constexpr auto snset = ::f_snset;
#pragma GCC diagnostic pop
};
// This is the SNOPT 7.4 implementation.
//
// It re-spells the 7.6-style arguments into 7.4-style calls, with the most
// common change being that int and double are passed by-value in 7.6 and
// by-mutable-pointer in 7.4.
//
// Below, we use `Int* iw` as a template argument (instead of `int* iw`), so
// that SFINAE ignores the function bodies when the user has SNOPT 7.6.
template <>
struct SnoptImpl<false> {
// The unit number for our "Print file" log for the current thread. When the
// "Print file" option is not enabled, this is zero.
thread_local inline static int g_iprint;
template <typename Int>
static void snend(Int* iw, int leniw, double* rw, int lenrw) {
// Close the print file and then release its unit (if necessary).
Int iprint = g_iprint;
::f_snend(&iprint);
if (g_iprint) {
FortranUnitFactory::singleton().Release(g_iprint);
g_iprint = 0;
}
}
template <typename Int>
static void sninit(const char* name, int len, int summOn, Int* iw, int leniw,
double* rw, int lenrw) {
// Allocate a unit number for the "Print file" (if necessary); the code
// within f_sninit will open the file.
if (len == 0) {
g_iprint = 0;
} else {
g_iprint = FortranUnitFactory::singleton().Allocate();
}
Int iprint = g_iprint;
::f_sninit(name, &len, &iprint, &summOn, iw, &leniw, rw, &lenrw);
}
// Turn clang-format off for readability.
// clang-format off
template <typename Int>
static void snkera(
int start, const char* name,
int nf, int n, double objadd, int objrow,
snFunA usrfun, isnLog snLog, isnLog2 snLog2,
isqLog sqLog, isnSTOP snSTOP,
int* iAfun, int* jAvar, int neA, double* A,
int* iGfun, int* jGvar, int neG,
double* xlow, double* xupp,
double* flow, double* fupp,
double* x, int* xstate, double* xmul,
double* f, int* fstate, double* fmul,
int* inform, int* ns, int* ninf, double* sinf,
int* miniw, int* minrw,
int* iu, int leniu, double* ru, int lenru,
Int* iw, int leniw, double* rw, int lenrw) {
::f_snkera(
&start, name,
&nf, &n, &objadd, &objrow,
usrfun, snLog, snLog2, sqLog, snSTOP,
iAfun, jAvar, &neA, A,
iGfun, jGvar, &neG,
xlow, xupp,
flow, fupp,
x, xstate, xmul,
f, fstate, fmul,
inform, ns, ninf, sinf,
miniw, minrw,
iu, &leniu,
ru, &lenru,
iw, &leniw,
rw, &lenrw);
}
// clang-format on
template <typename Int>
static void snmema(int* info, int nf, int n, int neA, int neG, int* miniw,
int* minrw, Int* iw, int leniw, double* rw, int lenrw) {
::f_snmema(info, &nf, &n, &neA, &neG, miniw, minrw, iw, &leniw, rw, &lenrw);
}
template <typename Int>
static void snseti(const char* buffer, int len, int iopt, int* errors,
Int* iw, int leniw, double* rw, int lenrw) {
::f_snseti(buffer, &len, &iopt, errors, iw, &leniw, rw, &lenrw);
}
template <typename Int>
static void snsetr(const char* buffer, int len, double rvalue, int* errors,
Int* iw, int leniw, double* rw, int lenrw) {
::f_snsetr(buffer, &len, &rvalue, errors, iw, &leniw, rw, &lenrw);
}
template <typename Int>
static void snset(const char* buffer, int len, int* errors, Int* iw,
int leniw, double* rw, int lenrw) {
::f_snset(buffer, &len, errors, iw, &leniw, rw, &lenrw);
}
};
// Choose the correct SnoptImpl specialization.
#pragma GCC diagnostic push // Silence spurious warnings from macOS llvm.
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wunneeded-internal-declaration"
void f_sninit_76_prototype(const char*, int, int, int[], int, double[], int) {}
#pragma GCC diagnostic pop
const bool kIsSnopt76 =
std::is_same_v<decltype(&f_sninit), decltype(&f_sninit_76_prototype)>;
using Snopt = SnoptImpl<kIsSnopt76>;
} // namespace
namespace drake {
namespace solvers {
namespace {
// This class is used for passing additional info to the snopt_userfun, which
// evaluates the value and gradient of the cost and constraints. Apart from the
// standard information such as decision variable values, snopt_userfun could
// rely on additional information such as the cost gradient sparsity pattern.
//
// In order to use access class in SNOPT's userfun callback, we need to provide
// for a pointer to this object. SNOPT's C interface does not allow using the
// char workspace, as explained in http://ccom.ucsd.edu/~optimizers/usage/c/ --
// "due to the incompatibility of strings in Fortran/C, all character arrays
// are disabled." Therefore, we use the integer user data (`int iu[]`) instead.
class SnoptUserFunInfo {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SnoptUserFunInfo)
// Pointers to the parameters ('prog' and 'nonlinear_cost_gradient_indices')
// are retained internally, so the supplied objects must have lifetimes longer
// than the SnoptUserFuncInfo object.
explicit SnoptUserFunInfo(const MathematicalProgram* prog)
: this_pointer_as_int_array_(MakeThisAsInts()), prog_(*prog) {}
const MathematicalProgram& mathematical_program() const { return prog_; }
std::set<int>& nonlinear_cost_gradient_indices() {
return nonlinear_cost_gradient_indices_;
}
const std::set<int>& nonlinear_cost_gradient_indices() const {
return nonlinear_cost_gradient_indices_;
}
std::vector<int>& duplicate_to_G_index_map() {
return duplicate_to_G_index_map_;
}
const std::vector<int>& duplicate_to_G_index_map() const {
return duplicate_to_G_index_map_;
}
void set_lenG(int lenG) { lenG_ = lenG; }
[[nodiscard]] int lenG() const { return lenG_; }
// If and only if the userfun experiences an exception, the exception message
// will be stashed here. All callers of snOptA or similar must check this to
// find out if there were any errors.
std::optional<std::string>& userfun_error_message() {
return userfun_error_message_;
}
int* iu() const {
return const_cast<int*>(this_pointer_as_int_array_.data());
}
int leniu() const { return this_pointer_as_int_array_.size(); }
// Converts the `int iu[]` data back into a reference to this class.
static SnoptUserFunInfo& GetFrom(const int* iu, int leniu) {
DRAKE_ASSERT(iu != nullptr);
DRAKE_ASSERT(leniu == kIntCount);
SnoptUserFunInfo* result = nullptr;
std::copy(reinterpret_cast<const char*>(iu),
reinterpret_cast<const char*>(iu) + sizeof(result),
reinterpret_cast<char*>(&result));
DRAKE_ASSERT(result != nullptr);
return *result;
}
private:
// We need this many `int`s to store a pointer. Round up any fractional
// remainder.
static constexpr size_t kIntCount =
(sizeof(SnoptUserFunInfo*) + sizeof(int) - 1) / sizeof(int);
// Converts the `this` pointer into an integer array.
std::array<int, kIntCount> MakeThisAsInts() {
std::array<int, kIntCount> result;
result.fill(0);
const SnoptUserFunInfo* const value = this;
std::copy(reinterpret_cast<const char*>(&value),
reinterpret_cast<const char*>(&value) + sizeof(value),
reinterpret_cast<char*>(result.data()));
return result;
}
const std::array<int, kIntCount> this_pointer_as_int_array_;
const MathematicalProgram& prog_;
std::set<int> nonlinear_cost_gradient_indices_;
// When evaluating the nonlinear costs/constraints, the Binding could contain
// duplicated variables. We need to sum up the entries in the gradient vector
// corresponding to the same constraint and variables. We first evaluate all
// costs and constraints, not accounting for duplicated variable. We denote
// this gradient vector as G_w_duplicate. We then sum up the entries in
// G_w_duplicate that correspond to the same constraint and gradient, and
// denote the resulting gradient vector as G.
// duplicate_to_G_index_map_ has the same length as G_w_duplicate. We add
// G_w_duplicate[i] to G[duplicate_to_G_index_map[i]].
std::vector<int> duplicate_to_G_index_map_;
int lenG_;
std::optional<std::string> userfun_error_message_;
};
// Storage that we pass in and out of SNOPT APIs.
class WorkspaceStorage {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(WorkspaceStorage)
explicit WorkspaceStorage(const SnoptUserFunInfo* user_info)
: user_info_(user_info) {
DRAKE_DEMAND(user_info_ != nullptr);
iw_.resize(500);
rw_.resize(500);
}
int* iw() { return iw_.data(); }
int leniw() const { return iw_.size(); }
void resize_iw(int size) { iw_.resize(size); }
double* rw() { return rw_.data(); }
int lenrw() const { return rw_.size(); }
void resize_rw(int size) { rw_.resize(size); }
int* iu() { return user_info_->iu(); }
int leniu() const { return user_info_->leniu(); }
double* ru() { return nullptr; }
int lenru() const { return 0; }
private:
std::vector<int> iw_;
std::vector<double> rw_;
const SnoptUserFunInfo* const user_info_;
};
// Return the number of rows in the nonlinear constraint.
template <typename C>
int SingleNonlinearConstraintSize(const C& constraint) {
return constraint.num_constraints();
}
template <>
int SingleNonlinearConstraintSize<LinearComplementarityConstraint>(
const LinearComplementarityConstraint& constraint) {
return 1;
}
// Evaluate a single nonlinear constraints. For generic Constraint,
// QuadraticConstraint, LorentzConeConstraint, RotatedLorentzConeConstraint, we
// call Eval function of the constraint directly. For some other constraint,
// such as LinearComplementaryConstraint, we will evaluate its nonlinear
// constraint differently, than its Eval function.
template <typename C>
void EvaluateSingleNonlinearConstraint(
const C& constraint, const Eigen::Ref<const AutoDiffVecXd>& tx,
AutoDiffVecXd* ty) {
ty->resize(SingleNonlinearConstraintSize(constraint));
constraint.Eval(tx, ty);
}
template <>
void EvaluateSingleNonlinearConstraint<LinearComplementarityConstraint>(
const LinearComplementarityConstraint& constraint,
const Eigen::Ref<const AutoDiffVecXd>& tx, AutoDiffVecXd* ty) {
ty->resize(1);
(*ty)(0) = tx.dot(constraint.M().cast<AutoDiffXd>() * tx +
constraint.q().cast<AutoDiffXd>());
}
/*
* Evaluate the value and gradients of nonlinear constraints.
* The template type Binding is supposed to be a
* MathematicalProgram::Binding<Constraint> type.
* @param constraint_list A list of Binding<Constraint>
* @param F The value of the constraints
* @param G The value of the non-zero entries in the gradient
* @param constraint_index The starting index of the constraint_list(0) in the
* optimization problem.
* @param grad_index The starting index of the gradient of constraint_list(0)
* in the optimization problem.
* @param xvec the value of the decision variables.
*/
template <typename C>
void EvaluateNonlinearConstraints(
const MathematicalProgram& prog,
const std::vector<Binding<C>>& constraint_list, double F[],
std::vector<double>* G_w_duplicate, size_t* constraint_index,
size_t* grad_index, const Eigen::VectorXd& xvec) {
const auto& scale_map = prog.GetVariableScaling();
Eigen::VectorXd this_x;
for (const auto& binding : constraint_list) {
const auto& c = binding.evaluator();
int num_constraints = SingleNonlinearConstraintSize(*c);
const int num_variables = binding.GetNumElements();
this_x.resize(num_variables);
// binding_var_indices[i] is the index of binding.variables()(i) in prog's
// decision variables.
std::vector<int> binding_var_indices(num_variables);
for (int i = 0; i < num_variables; ++i) {
binding_var_indices[i] =
prog.FindDecisionVariableIndex(binding.variables()(i));
this_x(i) = xvec(binding_var_indices[i]);
}
// Scale this_x
auto this_x_scaled = math::InitializeAutoDiff(this_x);
for (int i = 0; i < num_variables; i++) {
auto it = scale_map.find(binding_var_indices[i]);
if (it != scale_map.end()) {
this_x_scaled(i) *= it->second;
}
}
AutoDiffVecXd ty;
ty.resize(num_constraints);
EvaluateSingleNonlinearConstraint(*c, this_x_scaled, &ty);
for (int i = 0; i < num_constraints; i++) {
F[(*constraint_index)++] = ty(i).value();
}
const std::optional<std::vector<std::pair<int, int>>>&
gradient_sparsity_pattern =
binding.evaluator()->gradient_sparsity_pattern();
if (gradient_sparsity_pattern.has_value()) {
for (const auto& nonzero_entry : gradient_sparsity_pattern.value()) {
(*G_w_duplicate)[(*grad_index)++] =
ty(nonzero_entry.first).derivatives().size() > 0
? ty(nonzero_entry.first).derivatives()(nonzero_entry.second)
: 0.0;
}
} else {
for (int i = 0; i < num_constraints; i++) {
if (ty(i).derivatives().size() > 0) {
for (int j = 0; j < num_variables; ++j) {
(*G_w_duplicate)[(*grad_index)++] = ty(i).derivatives()(j);
}
} else {
for (int j = 0; j < num_variables; ++j) {
(*G_w_duplicate)[(*grad_index)++] = 0.0;
}
}
}
}
}
}
// Find the variables with non-zero gradient in @p costs, and add the indices of
// these variable to cost_gradient_indices.
template <typename C>
void GetNonlinearCostNonzeroGradientIndices(
const MathematicalProgram& prog, const std::vector<Binding<C>>& costs,
std::set<int>* cost_gradient_indices) {
for (const auto& cost : costs) {
for (int i = 0; i < static_cast<int>(cost.GetNumElements()); ++i) {
cost_gradient_indices->insert(
prog.FindDecisionVariableIndex(cost.variables()(i)));
}
}
}
/*
* Loops through each nonlinear cost stored in MathematicalProgram, and obtains
* the indices of the non-zero gradient, in the summed cost.
*/
std::set<int> GetAllNonlinearCostNonzeroGradientIndices(
const MathematicalProgram& prog) {
// The nonlinear costs include the quadratic, L2, and generic costs. Linear
// costs are not included. In the future if we support more costs (like
// polynomial costs), we should add it here.
std::set<int> cost_gradient_indices;
GetNonlinearCostNonzeroGradientIndices(prog, prog.quadratic_costs(),
&cost_gradient_indices);
GetNonlinearCostNonzeroGradientIndices(prog, prog.l2norm_costs(),
&cost_gradient_indices);
GetNonlinearCostNonzeroGradientIndices(prog, prog.generic_costs(),
&cost_gradient_indices);
return cost_gradient_indices;
}
/*
* Evaluates all the nonlinear costs, adds the value of the costs to
* @p total_cost, and also adds the gradients to @p nonlinear_cost_gradients.
*/
template <typename C>
void EvaluateAndAddNonlinearCosts(
const MathematicalProgram& prog,
const std::vector<Binding<C>>& nonlinear_costs, const Eigen::VectorXd& x,
double* total_cost, std::vector<double>* nonlinear_cost_gradients) {
const auto& scale_map = prog.GetVariableScaling();
for (const auto& binding : nonlinear_costs) {
const auto& obj = binding.evaluator();
const int num_variables = binding.GetNumElements();
Eigen::VectorXd this_x(num_variables);
// binding_var_indices[i] is the index of binding.variables()(i) in prog's
// decision variables.
std::vector<int> binding_var_indices(num_variables);
for (int i = 0; i < num_variables; ++i) {
binding_var_indices[i] =
prog.FindDecisionVariableIndex(binding.variables()(i));
this_x(i) = x(binding_var_indices[i]);
}
AutoDiffVecXd ty(1);
// Scale this_x
auto this_x_scaled = math::InitializeAutoDiff(this_x);
for (int i = 0; i < num_variables; i++) {
auto it = scale_map.find(binding_var_indices[i]);
if (it != scale_map.end()) {
this_x_scaled(i) *= it->second;
}
}
obj->Eval(this_x_scaled, &ty);
*total_cost += ty(0).value();
if (ty(0).derivatives().size() > 0) {
for (int i = 0; i < num_variables; ++i) {
(*nonlinear_cost_gradients)[binding_var_indices[i]] +=
ty(0).derivatives()(i);
}
}
}
}
// Evaluates all nonlinear costs, including the quadratic and generic costs.
// SNOPT stores the value of the total cost in F[0], and the nonzero gradient
// in array G. After calling this function, G[0], G[1], ..., G[grad_index-1]
// will store the nonzero gradient of the cost.
void EvaluateAllNonlinearCosts(
const MathematicalProgram& prog, const Eigen::VectorXd& xvec,
const std::set<int>& nonlinear_cost_gradient_indices, double F[],
std::vector<double>* G_w_duplicate, size_t* grad_index) {
std::vector<double> cost_gradients(prog.num_vars(), 0);
// Quadratic costs.
EvaluateAndAddNonlinearCosts(prog, prog.quadratic_costs(), xvec, &(F[0]),
&cost_gradients);
// L2Norm costs.
EvaluateAndAddNonlinearCosts(prog, prog.l2norm_costs(), xvec, &(F[0]),
&cost_gradients);
// Generic costs.
EvaluateAndAddNonlinearCosts(prog, prog.generic_costs(), xvec, &(F[0]),
&cost_gradients);
for (const int cost_gradient_index : nonlinear_cost_gradient_indices) {
(*G_w_duplicate)[*grad_index] = cost_gradients[cost_gradient_index];
++(*grad_index);
}
}
void EvaluateCostsConstraints(const SnoptUserFunInfo& info, int n, double x[],
double F[], double G[]) {
const MathematicalProgram& current_problem = info.mathematical_program();
const auto& scale_map = current_problem.GetVariableScaling();
Eigen::VectorXd xvec(n);
for (int i = 0; i < n; i++) {
xvec(i) = x[i];
}
F[0] = 0.0;
memset(G, 0, info.lenG() * sizeof(double));
std::vector<double> G_w_duplicate(info.duplicate_to_G_index_map().size(), 0);
size_t grad_index = 0;
// Scale xvec
Eigen::VectorXd xvec_scaled = xvec;
for (const auto& member : scale_map) {
xvec_scaled(member.first) *= member.second;
}
current_problem.EvalVisualizationCallbacks(xvec_scaled);
EvaluateAllNonlinearCosts(current_problem, xvec,
info.nonlinear_cost_gradient_indices(), F,
&G_w_duplicate, &grad_index);
// The constraint index starts at 1 because the cost is the
// first row.
size_t constraint_index = 1;
// The gradient_index also starts after the cost.
EvaluateNonlinearConstraints(
current_problem, current_problem.generic_constraints(), F, &G_w_duplicate,
&constraint_index, &grad_index, xvec);
EvaluateNonlinearConstraints(
current_problem, current_problem.quadratic_constraints(), F,
&G_w_duplicate, &constraint_index, &grad_index, xvec);
EvaluateNonlinearConstraints(
current_problem, current_problem.lorentz_cone_constraints(), F,
&G_w_duplicate, &constraint_index, &grad_index, xvec);
EvaluateNonlinearConstraints(
current_problem, current_problem.rotated_lorentz_cone_constraints(), F,
&G_w_duplicate, &constraint_index, &grad_index, xvec);
EvaluateNonlinearConstraints(
current_problem, current_problem.linear_complementarity_constraints(), F,
&G_w_duplicate, &constraint_index, &grad_index, xvec);
for (int i = 0; i < static_cast<int>(info.duplicate_to_G_index_map().size());
++i) {
G[info.duplicate_to_G_index_map()[i]] += G_w_duplicate[i];
}
}
// This function is what SNOPT calls to compute the values and derivatives.
// Because SNOPT calls this using the C ABI we cannot throw any exceptions,
// otherwise macOS will immediately abort. Therefore, we need to catch all
// exceptions and manually shepherd them back to our C++ code that called
// into SNOPT.
void snopt_userfun(int* Status, int* n, double x[], int* needF, int* neF,
double F[], int* needG, int* neG, double G[], char* cu,
int* lencu, int iu[], int* leniu, double ru[], int* lenru) {
SnoptUserFunInfo& info = SnoptUserFunInfo::GetFrom(iu, *leniu);
try {
EvaluateCostsConstraints(info, *n, x, F, G);
} catch (const std::exception& e) {
info.userfun_error_message() = fmt::format(
"Exception while evaluating SNOPT costs and constraints: '{}'",
e.what());
// The SNOPT manual says "Set Status < -1 if you want snOptA to stop."
*Status = -2;
}
}
/*
* Updates the number of nonlinear constraints and the number of gradients by
* looping through the constraint list
* @tparam C A Constraint type. Note that some derived classes of Constraint
* is regarded as generic constraint by SNOPT solver, such as
* LorentzConeConstraint and RotatedLorentzConeConstraint, so @tparam C can also
* be these derived classes.
*/
template <typename C>
void UpdateNumNonlinearConstraintsAndGradients(
const std::vector<Binding<C>>& constraint_list,
int* num_nonlinear_constraints, int* max_num_gradients,
std::unordered_map<Binding<Constraint>, int>* constraint_dual_start_index) {
for (auto const& binding : constraint_list) {
auto const& c = binding.evaluator();
int n = c->num_constraints();
if (binding.evaluator()->gradient_sparsity_pattern().has_value()) {
*max_num_gradients += static_cast<int>(
binding.evaluator()->gradient_sparsity_pattern().value().size());
} else {
*max_num_gradients += n * binding.GetNumElements();
}
const Binding<Constraint> binding_cast =
internal::BindingDynamicCast<Constraint>(binding);
constraint_dual_start_index->emplace(binding_cast,
1 + *num_nonlinear_constraints);
*num_nonlinear_constraints += n;
}
}
// For linear complementary condition
// 0 <= x ⊥ Mx + q >= 0
// we add the nonlinear constraint xᵀ(Mx+q) = 0
// So we only add one row of nonlinear constraint, and update the gradient of
// this nonlinear constraint accordingly.
template <>
void UpdateNumNonlinearConstraintsAndGradients<LinearComplementarityConstraint>(
const std::vector<Binding<LinearComplementarityConstraint>>&
constraint_list,
int* num_nonlinear_constraints, int* max_num_gradients,
std::unordered_map<Binding<Constraint>, int>* constraint_dual_start_index) {
*num_nonlinear_constraints += static_cast<int>(constraint_list.size());
for (const auto& binding : constraint_list) {
*max_num_gradients += binding.evaluator()->M().rows();
}
}
template <typename C>
void UpdateConstraintBoundsAndGradients(
const MathematicalProgram& prog,
const std::vector<Binding<C>>& constraint_list, std::vector<double>* Flow,
std::vector<double>* Fupp, std::vector<int>* iGfun_w_duplicate,
std::vector<int>* jGvar_w_duplicate, size_t* constraint_index,
size_t* grad_index) {
for (auto const& binding : constraint_list) {
auto const& c = binding.evaluator();
int n = c->num_constraints();
auto const lb = c->lower_bound(), ub = c->upper_bound();
for (int i = 0; i < n; i++) {
const int constraint_index_i = *constraint_index + i;
(*Flow)[constraint_index_i] = lb(i);
(*Fupp)[constraint_index_i] = ub(i);
}
const std::vector<int> bound_var_indices_in_prog =
prog.FindDecisionVariableIndices(binding.variables());
const std::optional<std::vector<std::pair<int, int>>>&
gradient_sparsity_pattern =
binding.evaluator()->gradient_sparsity_pattern();
if (gradient_sparsity_pattern.has_value()) {
for (const auto& nonzero_entry : gradient_sparsity_pattern.value()) {
// Fortran is 1-indexed.
(*iGfun_w_duplicate)[*grad_index] =
1 + *constraint_index + nonzero_entry.first;
(*jGvar_w_duplicate)[*grad_index] =
1 + bound_var_indices_in_prog[nonzero_entry.second];
(*grad_index)++;
}
} else {
for (int i = 0; i < n; i++) {
for (int j = 0; j < static_cast<int>(binding.GetNumElements()); ++j) {
// Fortran is 1-indexed.
(*iGfun_w_duplicate)[*grad_index] =
1 + *constraint_index + i; // row order
(*jGvar_w_duplicate)[*grad_index] = 1 + bound_var_indices_in_prog[j];
(*grad_index)++;
}
}
}
(*constraint_index) += n;
}
}
// For linear complementary condition
// 0 <= x ⊥ Mx + q >= 0
// we add the nonlinear constraint xᵀ(Mx + q) = 0
// The bound of this constraint is 0. The indices of the non-zero gradient
// of this constraint is updated accordingly.
template <>
void UpdateConstraintBoundsAndGradients<LinearComplementarityConstraint>(
const MathematicalProgram& prog,
const std::vector<Binding<LinearComplementarityConstraint>>&
constraint_list,
std::vector<double>* Flow, std::vector<double>* Fupp,
std::vector<int>* iGfun_w_duplicate, std::vector<int>* jGvar_w_duplicate,
size_t* constraint_index, size_t* grad_index) {
for (const auto& binding : constraint_list) {
(*Flow)[*constraint_index] = 0;
(*Fupp)[*constraint_index] = 0;
for (int j = 0; j < binding.evaluator()->M().rows(); ++j) {
// Fortran is 1-indexed.
(*iGfun_w_duplicate)[*grad_index] = 1 + *constraint_index;
(*jGvar_w_duplicate)[*grad_index] =
1 + prog.FindDecisionVariableIndex(binding.variables()(j));
(*grad_index)++;
}
++(*constraint_index);
}
}
template <typename C>
Eigen::SparseMatrix<double> LinearEvaluatorA(const C& evaluator) {
if constexpr (std::is_same_v<C, LinearComplementarityConstraint>) {
// TODO(hongkai.dai): change LinearComplementarityConstraint to store a
// sparse matrix M, and change the return type here to const
// SparseMatrix<double>&.
return evaluator.M().sparseView();
} else {
return evaluator.get_sparse_A();
}
}
// Return the number of rows in the linear constraint
template <typename C>
int LinearConstraintSize(const C& constraint) {
return constraint.num_constraints();
}
// For linear complementary condition
// 0 <= x ⊥ Mx + q >= 0
// The linear constraint we add to the program is Mx >= -q
// This linear constraint has the same number of rows, as matrix M.
template <>
int LinearConstraintSize<LinearComplementarityConstraint>(
const LinearComplementarityConstraint& constraint) {
return constraint.M().rows();
}
template <typename C>
std::pair<Eigen::VectorXd, Eigen::VectorXd> LinearConstraintBounds(
const C& constraint) {
return std::make_pair(constraint.lower_bound(), constraint.upper_bound());
}
// For linear complementary condition
// 0 <= x ⊥ Mx + q >= 0
// we add the constraint Mx >= -q
template <>
std::pair<Eigen::VectorXd, Eigen::VectorXd>
LinearConstraintBounds<LinearComplementarityConstraint>(
const LinearComplementarityConstraint& constraint) {
return std::make_pair(
-constraint.q(),
Eigen::VectorXd::Constant(constraint.q().rows(),
std::numeric_limits<double>::infinity()));
}
void UpdateLinearCost(
const MathematicalProgram& prog,
std::unordered_map<int, double>* variable_to_coefficient_map,
double* linear_cost_constant_term) {
const auto& scale_map = prog.GetVariableScaling();
double scale = 1;
for (const auto& binding : prog.linear_costs()) {
*linear_cost_constant_term += binding.evaluator()->b();
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
const int variable_index =
prog.FindDecisionVariableIndex(binding.variables()(k));
// Scale the coefficient as well
auto it = scale_map.find(variable_index);
if (it != scale_map.end()) {
scale = it->second;
} else {
scale = 1;
}
(*variable_to_coefficient_map)[variable_index] +=
binding.evaluator()->a()(k) * scale;
}
}
}
template <typename C>
void UpdateLinearConstraint(const MathematicalProgram& prog,
const std::vector<Binding<C>>& linear_constraints,
std::vector<Eigen::Triplet<double>>* tripletList,
std::vector<double>* Flow,
std::vector<double>* Fupp, size_t* constraint_index,
size_t* linear_constraint_index) {
for (auto const& binding : linear_constraints) {
auto const& c = binding.evaluator();
int n = LinearConstraintSize(*c);
const Eigen::SparseMatrix<double> A_constraint = LinearEvaluatorA(*c);
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
for (Eigen::SparseMatrix<double>::InnerIterator it(A_constraint, k); it;
++it) {
tripletList->emplace_back(
*linear_constraint_index + it.row(),
prog.FindDecisionVariableIndex(binding.variables()(k)), it.value());
}
}
const auto bounds = LinearConstraintBounds(*c);
for (int i = 0; i < n; i++) {
const int constraint_index_i = *constraint_index + i;
(*Flow)[constraint_index_i] = bounds.first(i);
(*Fupp)[constraint_index_i] = bounds.second(i);
}
*constraint_index += n;
*linear_constraint_index += n;
}
}
using BoundingBoxDualIndices = std::pair<std::vector<int>, std::vector<int>>;
void SetVariableBounds(
const MathematicalProgram& prog, std::vector<double>* xlow,
std::vector<double>* xupp,
std::unordered_map<Binding<BoundingBoxConstraint>, BoundingBoxDualIndices>*
bb_con_dual_variable_indices) {
// Set up the lower and upper bounds.
for (auto const& binding : prog.bounding_box_constraints()) {
const auto& c = binding.evaluator();
const auto& lb = c->lower_bound();
const auto& ub = c->upper_bound();
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
const size_t vk_index =
prog.FindDecisionVariableIndex(binding.variables()(k));
(*xlow)[vk_index] = std::max(lb(k), (*xlow)[vk_index]);
(*xupp)[vk_index] = std::min(ub(k), (*xupp)[vk_index]);
}
}
// For linear complementary condition
// 0 <= x ⊥ Mx + q >= 0
// we add the bounding box constraint x >= 0
for (const auto& binding : prog.linear_complementarity_constraints()) {
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
const size_t vk_index =
prog.FindDecisionVariableIndex(binding.variables()(k));
(*xlow)[vk_index] = std::max((*xlow)[vk_index], 0.0);
}
}
for (const auto& binding : prog.bounding_box_constraints()) {
std::vector<int> lower_dual_indices(binding.evaluator()->num_constraints(),
-1);
std::vector<int> upper_dual_indices(binding.evaluator()->num_constraints(),
-1);
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
const int idx = prog.FindDecisionVariableIndex(binding.variables()(k));
if ((*xlow)[idx] == binding.evaluator()->lower_bound()(k)) {
lower_dual_indices[k] = idx;
}
if ((*xupp)[idx] == binding.evaluator()->upper_bound()(k)) {
upper_dual_indices[k] = idx;
}
}
bb_con_dual_variable_indices->emplace(
binding, std::make_pair(lower_dual_indices, upper_dual_indices));
}
const auto& scale_map = prog.GetVariableScaling();
// Scale lower and upper bounds
for (const auto& member : scale_map) {
(*xlow)[member.first] /= member.second;
(*xupp)[member.first] /= member.second;
}
}
void SetBoundingBoxConstraintDualSolution(
const MathematicalProgram& prog, const Eigen::VectorXd& xmul,
const std::unordered_map<Binding<BoundingBoxConstraint>,
BoundingBoxDualIndices>&
bb_con_dual_variable_indices,
MathematicalProgramResult* result) {
const auto& scale_map = prog.GetVariableScaling();
// If the variable x(i) is scaled by s, then its bounding box constraint
// becomes lower / s <= x(i) <= upper / s. Perturbing the bounds of the
// scaled constraint by eps is equivalent to perturbing the original bounds
// by s * eps. Hence the shadow cost of the original constraint should be
// divided by s.
Eigen::VectorXd xmul_scaled_back = xmul;
for (const auto& member : scale_map) {
xmul_scaled_back(member.first) /= member.second;
}
for (const auto& binding : prog.bounding_box_constraints()) {
std::vector<int> lower_dual_indices, upper_dual_indices;
std::tie(lower_dual_indices, upper_dual_indices) =
bb_con_dual_variable_indices.at(binding);
Eigen::VectorXd dual_solution =
Eigen::VectorXd::Zero(binding.GetNumElements());
for (int i = 0; i < static_cast<int>(binding.GetNumElements()); ++i) {
if (lower_dual_indices[i] != -1 && xmul(lower_dual_indices[i]) >= 0) {
// When xmul >= 0, Snopt thinks the lower bound is active.
dual_solution(i) = xmul_scaled_back(lower_dual_indices[i]);
} else if (upper_dual_indices[i] != -1 &&
xmul(upper_dual_indices[i]) <= 0) {
// When xmul <= 0, Snopt thinks the upper bound is active.
dual_solution(i) = xmul_scaled_back(upper_dual_indices[i]);
}
}
result->set_dual_solution(binding, dual_solution);
}
}
template <typename C>
void SetConstraintDualSolution(
const std::vector<Binding<C>>& bindings, const Eigen::VectorXd& Fmul,
const std::unordered_map<Binding<Constraint>, int>&
constraint_dual_start_index,
MathematicalProgramResult* result) {
for (const auto& binding : bindings) {
const Binding<Constraint> binding_cast =
internal::BindingDynamicCast<Constraint>(binding);
result->set_dual_solution(
binding, Fmul.segment(constraint_dual_start_index.at(binding),
binding.evaluator()->num_constraints()));
}
}
void SetConstraintDualSolutions(
const MathematicalProgram& prog, const Eigen::VectorXd& Fmul,
const std::unordered_map<Binding<Constraint>, int>&
constraint_dual_start_index,
MathematicalProgramResult* result) {
SetConstraintDualSolution(prog.generic_constraints(), Fmul,
constraint_dual_start_index, result);
SetConstraintDualSolution(prog.quadratic_constraints(), Fmul,
constraint_dual_start_index, result);
SetConstraintDualSolution(prog.lorentz_cone_constraints(), Fmul,
constraint_dual_start_index, result);
SetConstraintDualSolution(prog.rotated_lorentz_cone_constraints(), Fmul,
constraint_dual_start_index, result);
SetConstraintDualSolution(prog.rotated_lorentz_cone_constraints(), Fmul,
constraint_dual_start_index, result);
SetConstraintDualSolution(prog.linear_constraints(), Fmul,
constraint_dual_start_index, result);
SetConstraintDualSolution(prog.linear_equality_constraints(), Fmul,
constraint_dual_start_index, result);
}
SolutionResult MapSnoptInfoToSolutionResult(int snopt_info) {
SolutionResult solution_result{SolutionResult::kSolverSpecificError};
// Please refer to User's Guide for SNOPT Versions 7, section 8.6 on the
// meaning of these snopt_info.
if (snopt_info >= 1 && snopt_info <= 6) {
solution_result = SolutionResult::kSolutionFound;
} else {
log()->debug("Snopt returns code {}\n", snopt_info);
if (snopt_info >= 11 && snopt_info <= 16) {
solution_result = SolutionResult::kInfeasibleConstraints;
} else if (snopt_info >= 20 && snopt_info <= 22) {
solution_result = SolutionResult::kUnbounded;
} else if (snopt_info >= 30 && snopt_info <= 32) {
solution_result = SolutionResult::kIterationLimit;
} else if (snopt_info == 91) {
solution_result = SolutionResult::kInvalidInput;
}
}
return solution_result;
}
void SetMathematicalProgramResult(
const MathematicalProgram& prog, int snopt_status,
const Eigen::VectorXd& x_val,
const std::unordered_map<Binding<BoundingBoxConstraint>,
BoundingBoxDualIndices>&
bb_con_dual_variable_indices,
const std::unordered_map<Binding<Constraint>, int>&
constraint_dual_start_index,
double objective_constant, MathematicalProgramResult* result) {
SnoptSolverDetails& solver_details =
result->SetSolverDetailsType<SnoptSolverDetails>();
// Populate our results structure.
const SolutionResult solution_result =
MapSnoptInfoToSolutionResult(snopt_status);
result->set_solution_result(solution_result);
result->set_x_val(x_val);
SetBoundingBoxConstraintDualSolution(prog, solver_details.xmul,
bb_con_dual_variable_indices, result);
SetConstraintDualSolutions(prog, solver_details.Fmul,
constraint_dual_start_index, result);
if (solution_result == SolutionResult::kUnbounded) {
result->set_optimal_cost(MathematicalProgram::kUnboundedCost);
} else {
result->set_optimal_cost(solver_details.F(0) + objective_constant);
}
}
void UpdateNumConstraintsAndGradients(
const MathematicalProgram& prog,
const std::vector<Binding<LinearConstraint>>& linear_constraints,
int* num_nonlinear_constraints, int* num_linear_constraints,
int* max_num_gradients,
std::unordered_map<Binding<Constraint>, int>* constraint_dual_start_index) {
UpdateNumNonlinearConstraintsAndGradients(
prog.generic_constraints(), num_nonlinear_constraints, max_num_gradients,
constraint_dual_start_index);
UpdateNumNonlinearConstraintsAndGradients(
prog.quadratic_constraints(), num_nonlinear_constraints,
max_num_gradients, constraint_dual_start_index);
UpdateNumNonlinearConstraintsAndGradients(
prog.lorentz_cone_constraints(), num_nonlinear_constraints,
max_num_gradients, constraint_dual_start_index);
UpdateNumNonlinearConstraintsAndGradients(
prog.rotated_lorentz_cone_constraints(), num_nonlinear_constraints,
max_num_gradients, constraint_dual_start_index);
UpdateNumNonlinearConstraintsAndGradients(
prog.linear_complementarity_constraints(), num_nonlinear_constraints,
max_num_gradients, constraint_dual_start_index);
// Update linear constraints.
for (auto const& binding : linear_constraints) {
const Binding<Constraint> binding_cast =
internal::BindingDynamicCast<Constraint>(binding);
constraint_dual_start_index->emplace(
binding_cast, 1 + *num_nonlinear_constraints + *num_linear_constraints);
*num_linear_constraints += binding.evaluator()->num_constraints();
}
// For linear complementary condition
// 0 <= x ⊥ Mx + q >= 0
// The linear constraint we add is Mx + q >= 0, so we will append
// M.rows() rows to the linear constraints.
for (const auto& binding : prog.linear_complementarity_constraints()) {
*num_linear_constraints += binding.evaluator()->M().rows();
}
}
// The pair (iGfun_w_duplicate[i], jGvar_w_duplicate[i]) might contain
// duplicated entries. We move the duplication, such that (iGfun[i], jGvar[i])
// don't contain duplicated variables, and iGfun_w_duplicate[i] =
// iGfun[duplicate_to_G_index_map[i]], jGvar_w_duplicate[i] =
// jGvar[duplicate_to_G_index_map[i]].
void PruneGradientDuplication(int nx, const std::vector<int>& iGfun_w_duplicate,
const std::vector<int>& jGvar_w_duplicate,
std::vector<int>* duplicate_to_G_index_map,
std::vector<int>* iGfun,
std::vector<int>* jGvar) {
auto gradient_index = [nx](int row, int col) {
return row * nx + col;
};
std::unordered_map<int, int> gradient_index_to_G;
duplicate_to_G_index_map->reserve(iGfun_w_duplicate.size());
iGfun->reserve(iGfun_w_duplicate.size());
jGvar->reserve(jGvar_w_duplicate.size());
for (int i = 0; i < static_cast<int>(iGfun_w_duplicate.size()); ++i) {
const int index =
gradient_index(iGfun_w_duplicate[i], jGvar_w_duplicate[i]);
auto it = gradient_index_to_G.find(index);
if (it == gradient_index_to_G.end()) {
duplicate_to_G_index_map->push_back(iGfun->size());
gradient_index_to_G.emplace_hint(it, index, iGfun->size());
iGfun->push_back(iGfun_w_duplicate[i]);
jGvar->push_back(jGvar_w_duplicate[i]);
} else {
duplicate_to_G_index_map->push_back(it->second);
}
}
}
void SolveWithGivenOptions(
const MathematicalProgram& prog,
const Eigen::Ref<const Eigen::VectorXd>& x_init,
const std::unordered_map<std::string, std::string>& snopt_options_string,
const std::unordered_map<std::string, int>& snopt_options_int,
const std::unordered_map<std::string, double>& snopt_options_double,
const std::string& print_file_common, MathematicalProgramResult* result) {
SnoptSolverDetails& solver_details =
result->SetSolverDetailsType<SnoptSolverDetails>();
SnoptUserFunInfo user_info(&prog);
WorkspaceStorage storage(&user_info);
const auto& scale_map = prog.GetVariableScaling();
std::string print_file_name = print_file_common;
const auto print_file_it = snopt_options_string.find("Print file");
if (print_file_it != snopt_options_string.end()) {
print_file_name = print_file_it->second;
}
Snopt::sninit(print_file_name.c_str(), print_file_name.length(),
0 /* no summary */, storage.iw(), storage.leniw(), storage.rw(),
storage.lenrw());
ScopeExit guard([&storage]() {
Snopt::snend(storage.iw(), storage.leniw(), storage.rw(), storage.lenrw());
});
int nx = prog.num_vars();
std::vector<double> x(nx, 0.0);
std::vector<double> xlow(nx, -std::numeric_limits<double>::infinity());
std::vector<double> xupp(nx, std::numeric_limits<double>::infinity());
solver_details.xmul.resize(nx);
solver_details.xmul.setZero();
std::vector<int> xstate(nx, 0);
// Initialize the guess for x.
for (int i = 0; i < nx; ++i) {
if (!std::isnan(x_init(i))) {
x[i] = x_init(i);
} else {
x[i] = 0.0;
}
}
// Scale initial guess
for (const auto& member : scale_map) {
x[member.first] /= member.second;
}
// bb_con_dual_variable_indices[constraint] maps the bounding box constraint
// to the indices of its dual variables (one for lower bound and one for upper
// bound). If this constraint doesn't have a dual variable (because the bound
// is looser than some other bounding box constraint, hence this constraint
// can never be active), then the index is set to -1.
std::unordered_map<Binding<BoundingBoxConstraint>, BoundingBoxDualIndices>
bb_con_dual_variable_indices;
SetVariableBounds(prog, &xlow, &xupp, &bb_con_dual_variable_indices);
// constraint_dual_start_index[constraint] stores the starting index of
// the dual variables in Fmul.
std::unordered_map<Binding<Constraint>, int> constraint_dual_start_index;
// Update nonlinear constraints.
user_info.nonlinear_cost_gradient_indices() =
GetAllNonlinearCostNonzeroGradientIndices(prog);
int num_nonlinear_constraints = 0;
int max_num_gradients = user_info.nonlinear_cost_gradient_indices().size();
int num_linear_constraints = 0;
const auto linear_constraints = prog.GetAllLinearConstraints();
UpdateNumConstraintsAndGradients(prog, linear_constraints,
&num_nonlinear_constraints,
&num_linear_constraints, &max_num_gradients,
&constraint_dual_start_index);
// Update the bound of the constraint.
int nF = 1 + num_nonlinear_constraints + num_linear_constraints;
solver_details.F.resize(nF);
solver_details.F.setZero();
std::vector<double> Flow(nF, -std::numeric_limits<double>::infinity());
std::vector<double> Fupp(nF, std::numeric_limits<double>::infinity());
solver_details.Fmul.resize(nF);
solver_details.Fmul.setZero();
std::vector<int> Fstate(nF, 0);
// Set up the gradient sparsity pattern.
int lenG_w_duplicate = max_num_gradients;
std::vector<int> iGfun_w_duplicate(lenG_w_duplicate, 0);
std::vector<int> jGvar_w_duplicate(lenG_w_duplicate, 0);
size_t grad_index = 0;
for (const auto cost_gradient_index :
user_info.nonlinear_cost_gradient_indices()) {
// Fortran is 1-indexed.
iGfun_w_duplicate[grad_index] = 1;
jGvar_w_duplicate[grad_index] = 1 + cost_gradient_index;
++grad_index;
}
// constraint_index starts at 1 because row 0 is the cost.
size_t constraint_index = 1;
UpdateConstraintBoundsAndGradients(
prog, prog.generic_constraints(), &Flow, &Fupp, &iGfun_w_duplicate,
&jGvar_w_duplicate, &constraint_index, &grad_index);
UpdateConstraintBoundsAndGradients(
prog, prog.quadratic_constraints(), &Flow, &Fupp, &iGfun_w_duplicate,
&jGvar_w_duplicate, &constraint_index, &grad_index);
UpdateConstraintBoundsAndGradients(
prog, prog.lorentz_cone_constraints(), &Flow, &Fupp, &iGfun_w_duplicate,
&jGvar_w_duplicate, &constraint_index, &grad_index);
UpdateConstraintBoundsAndGradients(
prog, prog.rotated_lorentz_cone_constraints(), &Flow, &Fupp,
&iGfun_w_duplicate, &jGvar_w_duplicate, &constraint_index, &grad_index);
UpdateConstraintBoundsAndGradients(
prog, prog.linear_complementarity_constraints(), &Flow, &Fupp,
&iGfun_w_duplicate, &jGvar_w_duplicate, &constraint_index, &grad_index);
// Now find the sparsity pattern of the linear constraints/costs, and also
// update Flow and Fupp corresponding to the linear constraints.
// We use Eigen::Triplet to store the non-zero entries in the linear
// constraint
// http://eigen.tuxfamily.org/dox/group__TutorialSparse.html
typedef Eigen::Triplet<double> T;
double linear_cost_constant_term = 0;
std::unordered_map<int, double> variable_to_linear_cost_coefficient;
UpdateLinearCost(prog, &variable_to_linear_cost_coefficient,
&linear_cost_constant_term);
std::vector<T> linear_constraints_triplets;
linear_constraints_triplets.reserve(num_linear_constraints * prog.num_vars());
size_t linear_constraint_index = 0;
UpdateLinearConstraint(prog, linear_constraints, &linear_constraints_triplets,
&Flow, &Fupp, &constraint_index,
&linear_constraint_index);
UpdateLinearConstraint(prog, prog.linear_complementarity_constraints(),
&linear_constraints_triplets, &Flow, &Fupp,
&constraint_index, &linear_constraint_index);
// Scale the matrix in linear constraints
for (auto& triplet : linear_constraints_triplets) {
auto it = scale_map.find(triplet.col());
if (it != scale_map.end()) {
triplet = Eigen::Triplet<double>(triplet.row(), triplet.col(),
triplet.value() * (it->second));
}
}
Eigen::SparseMatrix<double> linear_constraints_A(nF - 1, prog.num_vars());
// setFromTriplets sums up the duplicated entries.
linear_constraints_A.setFromTriplets(linear_constraints_triplets.begin(),
linear_constraints_triplets.end());
int lenA = variable_to_linear_cost_coefficient.size() +
linear_constraints_A.nonZeros();
std::vector<double> A(lenA, 0.0);
std::vector<int> iAfun(lenA, 0);
std::vector<int> jAvar(lenA, 0);
size_t A_index = 0;
for (const auto& it : variable_to_linear_cost_coefficient) {
A[A_index] = it.second;
// Fortran uses 1-index.
iAfun[A_index] = 1;
jAvar[A_index] = it.first + 1;
A_index++;
}
for (int i = 0; i < linear_constraints_A.outerSize(); ++i) {
for (Eigen::SparseMatrix<double>::InnerIterator it(linear_constraints_A, i);
it; ++it) {
A[A_index] = it.value();
// Fortran uses 1-index
iAfun[A_index] = num_nonlinear_constraints + it.row() + 2;
jAvar[A_index] = it.col() + 1;
A_index++;
}
}
std::vector<int> iGfun;
std::vector<int> jGvar;
auto& duplicate_to_G_index_map = user_info.duplicate_to_G_index_map();
PruneGradientDuplication(nx, iGfun_w_duplicate, jGvar_w_duplicate,
&duplicate_to_G_index_map, &iGfun, &jGvar);
const int lenG = iGfun.size();
user_info.set_lenG(lenG);
for (const auto& it : snopt_options_double) {
int errors = 0;
Snopt::snsetr(it.first.c_str(), it.first.length(), it.second, &errors,
storage.iw(), storage.leniw(), storage.rw(), storage.lenrw());
if (errors > 0) {
throw std::runtime_error("Error setting Snopt double parameter " +
it.first);
}
}
for (const auto& it : snopt_options_int) {
int errors = 0;
Snopt::snseti(it.first.c_str(), it.first.length(), it.second, &errors,
storage.iw(), storage.leniw(), storage.rw(), storage.lenrw());
if (errors > 0) {
throw std::runtime_error("Error setting Snopt integer parameter " +
it.first);
}
}
for (const auto& it : snopt_options_string) {
int errors = 0;
auto option_string = it.first + " " + it.second;
if (it.first == "Print file") {
// Already handled during sninit, above
continue;
}
Snopt::snset(option_string.c_str(), option_string.length(), &errors,
storage.iw(), storage.leniw(), storage.rw(), storage.lenrw());
if (errors > 0) {
throw std::runtime_error("Error setting Snopt string parameter " +
it.first);
}
}
int Cold = 0;
double objective_constant = linear_cost_constant_term;
// The index of the objective row among all function evaluation F (notice that
// due to SNOPT using Fortran, this is 1-indexed).
int ObjRow = 1;
int nS = 0;
int nInf{0};
double sInf{0.0};
// Reallocate int and real workspace.
int miniw, minrw;
int snopt_status{0};
Snopt::snmema(&snopt_status, nF, nx, lenA, lenG, &miniw, &minrw, storage.iw(),
storage.leniw(), storage.rw(), storage.lenrw());
// TODO(jwnimmer-tri) Check snopt_status for errors.
if (miniw > storage.leniw()) {
storage.resize_iw(miniw);
const std::string option = "Total int workspace";
int errors;
Snopt::snseti(option.c_str(), option.length(), storage.leniw(), &errors,
storage.iw(), storage.leniw(), storage.rw(), storage.lenrw());
// TODO(hongkai.dai): report the error in SnoptSolverDetails.
}
if (minrw > storage.lenrw()) {
storage.resize_rw(minrw);
const std::string option = "Total real workspace";
int errors;
Snopt::snseti(option.c_str(), option.length(), storage.lenrw(), &errors,
storage.iw(), storage.leniw(), storage.rw(), storage.lenrw());
// TODO(hongkai.dai): report the error in SnoptSolverDetails.
}
// Actual solve.
const char problem_name[] = "drake_problem";
// clang-format off
Snopt::snkera(Cold, problem_name, nF, nx, objective_constant, ObjRow,
snopt_userfun,
nullptr /* isnLog snLog */, nullptr /* isnLog2 snLog2 */,
nullptr /* isqLog sqLog */, nullptr /* isnSTOP snSTOP */,
iAfun.data(), jAvar.data(), lenA, A.data(),
iGfun.data(), jGvar.data(), lenG,
xlow.data(), xupp.data(),
Flow.data(), Fupp.data(),
x.data(), xstate.data(), solver_details.xmul.data(),
solver_details.F.data(), Fstate.data(),
solver_details.Fmul.data(),
&snopt_status, &nS, &nInf, &sInf, &miniw, &minrw,
storage.iu(), storage.leniu(),
storage.ru(), storage.lenru(),
storage.iw(), storage.leniw(),
storage.rw(), storage.lenrw());
// clang-format on
if (user_info.userfun_error_message().has_value()) {
throw std::runtime_error(*user_info.userfun_error_message());
}
Eigen::VectorXd x_val = Eigen::Map<Eigen::VectorXd>(x.data(), nx);
// Scale solution back
for (const auto& member : scale_map) {
x_val(member.first) *= member.second;
}
solver_details.info = snopt_status;
SetMathematicalProgramResult(
prog, snopt_status, x_val, bb_con_dual_variable_indices,
constraint_dual_start_index, objective_constant, result);
}
} // namespace
bool SnoptSolver::is_available() {
return true;
}
void SnoptSolver::DoSolve(const MathematicalProgram& prog,
const Eigen::VectorXd& initial_guess,
const SolverOptions& merged_options,
MathematicalProgramResult* result) const {
// Call SNOPT.
std::unordered_map<std::string, int> int_options =
merged_options.GetOptionsInt(id());
// If "Timing level" is not zero, then snopt periodically calls etime to
// determine it's usage of cpu time (which on Linux calls getrusage in the
// libgfortran implementation). Unfortunately getrusage is called using
// RUSAGE_SELF, which has unfortunate consenquences when using threads,
// namely (1) It returns the total count of CPU usage for all threads, so
// the result is garbage, and (2) on Linux the kernel holds a process wide
// lock inside getrusage when RUSAGE_SELF is specified, so other threads
// using snopt end up blocking on their getrusage calls. Under the theory
// that a user who actually wants this behavior will turn it on
// deliberately, set "Timing level" to zero if the user hasn't requested
// another value.
const std::string kTimingLevel = "Timing level";
if (!int_options.contains(kTimingLevel)) {
int_options[kTimingLevel] = 0;
}
SolveWithGivenOptions(prog, initial_guess, merged_options.GetOptionsStr(id()),
int_options, merged_options.GetOptionsDouble(id()),
merged_options.get_print_file_name(), result);
}
bool SnoptSolver::is_bounded_lp_broken() {
return true;
}
} // namespace solvers
} // namespace drake
#pragma GCC diagnostic pop // "-Wunused-parameter"
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/sparse_and_dense_matrix.h | #pragma once
#include <mutex>
#include <Eigen/Core>
#include <Eigen/SparseCore>
#include "drake/common/drake_copyable.h"
namespace drake {
namespace solvers {
namespace internal {
/*
* This class is typically used in cost and constraint class to store a sparse
* matrix and an optional dense matrix. It also provides setter/getter for the
* matrix.
*/
class SparseAndDenseMatrix {
public:
// Delete these constructors for thread safety.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SparseAndDenseMatrix)
explicit SparseAndDenseMatrix(const Eigen::SparseMatrix<double>& sparse);
explicit SparseAndDenseMatrix(Eigen::MatrixXd dense);
SparseAndDenseMatrix& operator=(const Eigen::SparseMatrix<double>& sparse);
SparseAndDenseMatrix& operator=(Eigen::MatrixXd dense);
~SparseAndDenseMatrix();
[[nodiscard]] const Eigen::SparseMatrix<double>& get_as_sparse() const {
return sparse_;
}
// Getter for the dense matrix. If the class is constructed from a dense
// matrix, or GetAsDense() function has been called before, then this is a
// quick operation. Otherwise this function will internally create a dense
// matrix.
[[nodiscard]] const Eigen::MatrixXd& GetAsDense() const;
// Returns true if all element in the matrix is finite. False otherwise.
[[nodiscard]] bool IsFinite() const;
// Returns true if the dense matrix has been constructed.
[[nodiscard]] bool is_dense_constructed() const;
private:
Eigen::SparseMatrix<double> sparse_;
// If dense_.size() == 0, then we only use sparse_;
Eigen::MatrixXd dense_;
mutable std::mutex mutex_;
};
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/scs_solver.h | #pragma once
#include <string>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/solver_base.h"
namespace drake {
namespace solvers {
/**
* The SCS solver details after calling Solve() function. The user can call
* MathematicalProgramResult::get_solver_details<ScsSolver>() to obtain the
* details.
*/
struct ScsSolverDetails {
/// The status of the solver at termination. Please refer to
/// https://github.com/cvxgrp/scs/blob/master/include/glbopts.h
/// Note that the SCS code on github master might be slightly more up-to-date
/// than the version used in Drake.
int scs_status{};
/// These are the information returned by SCS at termination, please refer to
/// "SCS_INFO" struct in
/// https://github.com/cvxgrp/scs/blob/master/include/scs.h Number of
/// iterations taken at termination.
/// Equal to SCS_INFO.iter
int iter{};
/// Primal objective value at termination.
/// Equal to SCS_INFO.pobj
double primal_objective{};
/// Dual objective value at termination.
/// Equal to SCS_INFO.dobj
double dual_objective{};
/// Primal equality residue.
/// Equal to SCS_INFO.res_pri
double primal_residue{};
/// infeasibility certificate residue.
/// Equal to SCS_INFO.res_infeas
double residue_infeasibility{};
/// unbounded certificate residue.
/// Equal to SCS_INFO.res_unbdd_a
double residue_unbounded_a{};
/// unbounded certificate residue.
/// Equal to SCS_INFO.res_unbdd_p
double residue_unbounded_p{};
/// duality gap.
/// Equal to SCS_INFO.gap.
double duality_gap{};
/// Time taken for SCS to setup in milliseconds.
/// Equal to SCS_INFO.setup_time.
double scs_setup_time{};
/// Time taken for SCS to solve in millisecond.
/// Equal to SCS_INFO.solve_time.
double scs_solve_time{};
/// The dual variable values at termination.
Eigen::VectorXd y;
/// The primal equality constraint slack, namely
/// Ax + s = b where x is the primal variable.
Eigen::VectorXd s;
};
class ScsSolver final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ScsSolver)
/// Type of details stored in MathematicalProgramResult.
using Details = ScsSolverDetails;
ScsSolver();
~ScsSolver() final;
// TODO(hongkai.dai): add function to set the verbosity through SolverOptions
// or MathematicalProgram.
/// @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&);
static std::string UnsatisfiedProgramAttributes(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/moby_lcp_solver.h | // Adapted with permission from code by Evan Drumwright
// (https://github.com/edrumwri).
#pragma once
#include <fstream>
#include <limits>
#include <string>
#include <vector>
#include <Eigen/SparseCore>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/solver_base.h"
// TODO(jwnimmer-tri): This class should be renamed MobyLcpSolver to comply with
// style guide.
namespace drake {
namespace solvers {
/// Non-template class for MobyLcpSolver<T> constants.
class MobyLcpSolverId {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MobyLcpSolverId);
MobyLcpSolverId() = delete;
/// @return same as SolverInterface::solver_id()
static SolverId id();
};
/// A class for solving Linear Complementarity Problems (LCPs). Solving a LCP
/// requires finding a solution to the problem:<pre>
/// Mz + q = w
/// z ≥ 0
/// w ≥ 0
/// zᵀw = 0
/// </pre>
/// (where M ∈ ℝⁿˣⁿ and q ∈ ℝⁿ are problem inputs and z ∈ ℝⁿ and w ∈ ℝⁿ are
/// unknown vectors) or correctly reporting that such a solution does not exist.
/// In spite of their linear structure, solving LCPs is NP-Hard [Cottle 1992].
/// However, some LCPs are significantly easier to solve. For instance, it can
/// be seen that the LCP is solvable in worst-case polynomial time for the case
/// of symmetric positive-semi-definite M by formulating it as the following
/// convex quadratic program:<pre>
/// minimize: f(z) = zᵀw = zᵀ(Mz + q)
/// subject to: z ≥ 0
/// Mz + q ≥ 0
/// </pre>
/// Note that this quadratic program's (QP) objective function at the minimum
/// z cannot be less than zero, and the LCP is only solved if the objective
/// function at the minimum is equal to zero. Since the seminal result of
/// Karmarkar, it has been known that convex QPs are solvable in polynomial
/// time [Karmarkar 1984].
///
/// The difficulty of solving an LCP is characterized by the properties of its
/// particular matrix, namely the class of matrices it belongs to. Classes
/// include, for example, Q, Q₀, P, P₀, copositive, and Z matrices.
/// [Cottle 1992] and [Murty 1998] (see pp. 224-230 in the latter) describe
/// relevant matrix classes in more detail.
///
/// * [Cottle 1992] R. Cottle, J.-S. Pang, and R. Stone. The Linear
/// Complementarity Problem. Academic Press, 1992.
/// * [Karmarkar 1984] N. Karmarkar. A New Polynomial-Time Algorithm for
/// Linear Programming. Combinatorica, 4(4), pp. 373-395.
/// * [Murty 1988] K. Murty. Linear Complementarity, Linear and Nonlinear
/// Programming. Heldermann Verlag, 1988.
template <class T>
class MobyLCPSolver final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MobyLCPSolver)
MobyLCPSolver();
~MobyLCPSolver() final;
void SetLoggingEnabled(bool enabled);
/// 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>() *
(10 * std::numeric_limits<double>::epsilon());
}
/// Fast pivoting algorithm for LCPs of the form M = PAPᵀ, q = Pb, where
/// b ∈ ℝᵐ, P ∈ ℝⁿˣᵐ, and A ∈ ℝᵐˣᵐ (where A is positive definite). Therefore,
/// q is in the range of P and M is positive semi-definite. An LCP of this
/// form is also guaranteed to have a solution [Cottle 1992].
///
/// This particular implementation focuses on the case where the solution
/// requires few nonzero nonbasic variables, meaning that few z variables
/// need be nonzero to find a solution to Mz + q = w. This algorithm, which is
/// based off of Dantzig's Principle Pivoting Method I [Cottle 1992] is
/// described in [Drumwright 2015]. This algorithm is able to use "warm"
/// starting- a solution to a "nearby" LCP can be used to find the solution to
/// a given LCP more quickly.
///
/// Although this solver is theoretically guaranteed to give a solution to
/// the LCPs described above, accumulated floating point error from pivoting
/// operations could cause the solver to fail. Additionally, the solver can be
/// applied with some success to problems outside of its guaranteed matrix
/// class. For these reasons, the solver returns a flag indicating
/// success/failure.
/// @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 z's value as a starting
/// solution. If the solver fails (returns `false`), `z` will
/// be set to the zero vector.
/// @param[in] zero_tol The tolerance for testing against zero. If the
/// tolerance is negative (default) the solver will determine a
/// generally reasonable tolerance.
/// @throws std::exception if M is non-square or M's dimensions do not
/// equal q's dimension.
/// @returns `true` if the solver succeeded and `false` otherwise.
///
/// * [Cottle 1992] R. Cottle, J.-S. Pang, and R. Stone. The Linear
/// Complementarity Problem. Academic Press, 1992.
/// * [Drumwright 2015] E. Drumwright. Rapidly computable viscous friction
/// and no-slip rigid contact models. arXiv:
/// 1504.00719v1. 2015.
bool SolveLcpFast(const MatrixX<T>& M, const VectorX<T>& q, VectorX<T>* z,
const T& zero_tol = T(-1)) const;
/// Regularized version of the fast pivoting algorithm for LCPs of the form
/// M = PAPᵀ, q = Pb, where b ∈ ℝᵐ, P ∈ ℝⁿˣᵐ, and A ∈ ℝᵐˣᵐ (where A is
/// positive definite). Therefore, q is in the range of P and M is positive
/// semi-definite. Please see SolveLcpFast() for more documentation about the
/// particular algorithm.
///
/// This implementation wraps that algorithm with a Tikhonov-type
/// regularization approach. Specifically, this implementation repeatedly
/// attempts to solve the LCP:<pre>
/// (M + Iα)z + q = w
/// z ≥ 0
/// w ≥ 0
/// zᵀw = 0
/// </pre>
/// where I is the identity matrix and α ≪ 1, using geometrically increasing
/// values of α, until the LCP is solved. Cottle et al. describe how, for
/// sufficiently large α, the LCP will always be solvable [Cottle 1992], p.
/// 493.
///
/// Although this solver is theoretically guaranteed to give a solution to
/// the LCPs described above, accumulated floating point error from pivoting
/// operations could cause the solver to fail. Additionally, the solver can be
/// applied with some success to problems outside of its guaranteed matrix
/// class. For these reasons, the solver returns a flag indicating
/// success/failure.
/// @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 z's value as a starting
/// solution.
/// @param[in] min_exp The minimum exponent for computing α over [10ᵝ, 10ᵞ] in
/// steps of 10ᵟ, where β is the minimum exponent, γ is the
/// maximum exponent, and δ is the stepping exponent.
/// @param[in] step_exp The stepping exponent for computing α over [10ᵝ, 10ᵞ]
/// in steps of 10ᵟ, where β is the minimum exponent, γ is
/// the maximum exponent, and δ is the stepping exponent.
/// @param[in] max_exp The maximum exponent for computing α over [10ᵝ, 10ᵞ] in
/// steps of 10ᵟ, where β is the minimum exponent, γ is the
/// maximum exponent, and δ is the stepping exponent.
/// @param[in] zero_tol The tolerance for testing against zero. If the
/// tolerance is negative (default) the solver will determine a
/// generally reasonable tolerance.
/// @throws std::exception if M is non-square or M's dimensions do not
/// equal q's dimension.
/// @returns `true` if the solver succeeded and `false` if the solver did not
/// find a solution for α = 10ᵞ.
/// @sa SolveLcpFast()
///
/// * [Cottle, 1992] R. Cottle, J.-S. Pang, and R. Stone. The Linear
/// Complementarity Problem. Academic Press, 1992.
bool SolveLcpFastRegularized(const MatrixX<T>& M, const VectorX<T>& q,
VectorX<T>* z, int min_exp = -20,
unsigned step_exp = 4, int max_exp = 20,
const T& zero_tol = T(-1)) const;
/// 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. Lemke's Algorithm is described in [Cottle 1992],
/// Section 4.4. This implementation was adapted from the LEMKE Library
/// [LEMKE] for Matlab; this particular implementation fixes a bug
/// in LEMKE that could occur when multiple indices passed the minimum ratio
/// test.
///
/// Although this solver is theoretically guaranteed to give a solution to
/// the LCPs described above, accumulated floating point error from pivoting
/// operations could cause the solver to fail. Additionally, the solver can be
/// applied with some success to problems outside of its guaranteed matrix
/// classes. For these reasons, the solver returns a flag indicating
/// success/failure.
/// @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 z's value as a starting
/// solution. **This warmstarting is generally not
/// recommended**: it has a predisposition to lead to a failing
/// pivoting sequence. If the solver fails (returns `false`),
/// `z` will be set to the zero vector.
/// @param[in] zero_tol The tolerance for testing against zero. If the
/// tolerance is negative (default) the solver will determine a
/// generally reasonable tolerance.
/// @param[in] piv_tol The tolerance for testing against zero, specifically
/// used for the purpose of finding variables for pivoting. If the
/// tolerance is negative (default) the solver will determine a
/// generally reasonable tolerance.
/// @returns `true` if the solver **believes** it has computed a solution
/// (which it determines by the ability to "pivot out" the
/// "artificial" variable (see [Cottle 1992]) and `false` otherwise.
/// @warning The caller should verify that the algorithm has solved the LCP to
/// the desired tolerances on returns indicating success.
/// @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.
/// * [LEMKE] P. Fackler and M. Miranda. LEMKE.
/// http://people.sc.fsu.edu/~burkardt/m\_src/lemke/lemke.m
bool SolveLcpLemke(const MatrixX<T>& M, const VectorX<T>& q, VectorX<T>* z,
const T& piv_tol = T(-1), const T& zero_tol = T(-1)) const;
/// 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. Lemke's Algorithm is described in [Cottle 1992],
/// Section 4.4.
///
/// This implementation wraps that algorithm with a Tikhonov-type
/// regularization approach. Specifically, this implementation repeatedly
/// attempts to solve the LCP:<pre>
/// (M + Iα)z + q = w
/// z ≥ 0
/// w ≥ 0
/// zᵀw = 0
/// </pre>
/// where I is the identity matrix and α ≪ 1, using geometrically increasing
/// values of α, until the LCP is solved. See SolveLcpFastRegularized() for
/// description of the regularization process and the function parameters,
/// which are identical. See SolveLcpLemke() for a description of Lemke's
/// Algorithm. See SolveLcpFastRegularized() for a description of all
/// calling parameters other than @p z, which apply equally well to this
/// function.
/// @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 z's value as a starting
/// solution. **This warmstarting is generally not
/// recommended**: it has a predisposition to lead to a failing
/// pivoting sequence.
///
/// @sa SolveLcpFastRegularized()
/// @sa SolveLcpLemke()
///
/// * [Cottle 1992] R. Cottle, J.-S. Pang, and R. Stone. The Linear
/// Complementarity Problem. Academic Press, 1992.
bool SolveLcpLemkeRegularized(const MatrixX<T>& M, const VectorX<T>& q,
VectorX<T>* z, int min_exp = -20,
unsigned step_exp = 1, int max_exp = 1,
const T& piv_tol = T(-1),
const T& zero_tol = T(-1)) const;
/// Returns the number of pivoting operations made by the last LCP solve.
int get_num_pivots() const { return pivots_; }
/// Resets the number of pivoting operations made by the last LCP solver to
/// zero.
void reset_num_pivots() { pivots_ = 0; }
/// @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;
void ClearIndexVectors() const;
template <typename MatrixType, typename Scalar>
void FinishLemkeSolution(const MatrixType& M, const VectorX<Scalar>& q,
const VectorX<Scalar>& x, VectorX<Scalar>* z) const;
// TODO(sammy-tri) replace this with a proper logging hookup
std::ostream& Log() const;
bool log_enabled_{false};
mutable std::ofstream null_stream_;
// Records the number of pivoting operations used during the last solve.
mutable unsigned pivots_{0};
// NOTE: The temporaries below are stored in the class to minimize
// allocations; all are marked 'mutable' as they do not affect the
// semantic const'ness of the class under its methods.
// Vectors which correspond to indices into other data.
mutable std::vector<unsigned> all_, tlist_, bas_, nonbas_, j_;
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/csdp_solver_error_handling.cc | #include "drake/solvers/csdp_solver_error_handling.h"
namespace drake {
namespace solvers {
namespace internal {
std::jmp_buf& get_per_thread_csdp_jmp_buf() {
static thread_local std::jmp_buf per_thread_buffer;
return per_thread_buffer;
}
} // namespace internal
} // namespace solvers
} // namespace drake
extern "C" {
// The library code in CSDP calls the C exit() function. Since no library
// should do that, our CSDP package.BUILD.bazel rule uses the preprocessor
// to re-route that call into this function instead.
void drake_csdp_cpp_wrapper_exit(int) {
std::jmp_buf& env = drake::solvers::internal::get_per_thread_csdp_jmp_buf();
std::longjmp(env, 1);
}
} // extern C
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/create_constraint.h | #pragma once
#include <limits>
#include <memory>
#include <optional>
#include <set>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include "drake/common/eigen_types.h"
#include "drake/common/symbolic/expression.h"
#include "drake/solvers/binding.h"
#include "drake/solvers/constraint.h"
namespace drake {
namespace solvers {
namespace internal {
// TODO(eric.cousineau): Use Eigen::Ref more pervasively when no temporaries
// are allocated (or if it doesn't matter if they are).
/**
* The resulting constraint may be a BoundingBoxConstraint, LinearConstraint,
* LinearEqualityConstraint, or ExpressionConstraint, depending on the
* arguments. Constraints of the form x == 1 (which could be created as a
* BoundingBoxConstraint or LinearEqualityConstraint) will be
* constructed as a LinearEqualityConstraint.
*/
[[nodiscard]] Binding<Constraint> ParseConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub);
/*
* Assist MathematicalProgram::AddLinearConstraint(...).
*/
[[nodiscard]] inline Binding<Constraint> ParseConstraint(
const symbolic::Expression& e, const double lb, const double ub) {
return ParseConstraint(Vector1<symbolic::Expression>(e), Vector1<double>(lb),
Vector1<double>(ub));
}
/**
* Parses the constraint lb <= e <= ub to linear constraint types, including
* BoundingBoxConstraint, LinearEqualityConstraint, and LinearConstraint. If @p
* e is not a linear expression, then returns a null pointer.
* If the constraint lb <= e <= ub can be parsed as a BoundingBoxConstraint,
* then we return a BoundingBoxConstraint pointer. For example, the constraint
* 1 <= 2 * x + 3 <= 4 is equivalent to the bounding box constraint -1 <= x <=
* 0.5. Hence we will return the BoundingBoxConstraint in this case.
*/
[[nodiscard]] std::unique_ptr<Binding<Constraint>> MaybeParseLinearConstraint(
const symbolic::Expression& e, double lb, double ub);
/*
* Creates a constraint that should satisfy the formula `f`.
* @throws exception if `f` is always false (for example 1 >= 2).
* @note if `f` is always true, then returns an empty BoundingBoxConstraint
* binding.
*/
[[nodiscard]] Binding<Constraint> ParseConstraint(const symbolic::Formula& f);
/*
* Creates a constraint that enforces all `formulas` to be satisfied.
* @throws exception if any of `formulas` is always false (for example 1 >= 2).
* @note If any entry in `formulas` is always true, then that entry is ignored.
* If all entries in `formulas` are true, then returns an empty
* BoundingBoxConstraint binding.
*/
[[nodiscard]] Binding<Constraint> ParseConstraint(
const Eigen::Ref<const MatrixX<symbolic::Formula>>& formulas);
/*
* Assist functionality for ParseLinearEqualityConstraint(...).
*/
[[nodiscard]] Binding<LinearEqualityConstraint> DoParseLinearEqualityConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v,
const Eigen::Ref<const Eigen::VectorXd>& b);
/*
* Assist MathematicalProgram::AddLinearEqualityConstraint(...).
*/
inline Binding<LinearEqualityConstraint> ParseLinearEqualityConstraint(
const symbolic::Expression& e, double b) {
return DoParseLinearEqualityConstraint(Vector1<symbolic::Expression>(e),
Vector1d(b));
}
/*
* Creates a constraint to satisfy all entries in `formulas`.
* @throws exception if any of `formulas` is always false (for example 1 == 2)
* @note If any entry in `formulas` is always true, then that entry is ignored;
* if all entries in `formulas` are always true, then returns an empty linear
* equality constraint binding.
*/
[[nodiscard]] Binding<LinearEqualityConstraint> ParseLinearEqualityConstraint(
const std::set<symbolic::Formula>& formulas);
/*
*
* Creates a linear equality constraint satisfying the formula `f`.
* @throws exception if `f` is always false (for example 1 == 2)
* @note if `f` is always true, then returns an empty linear equality constraint
* binding.
*/
[[nodiscard]] Binding<LinearEqualityConstraint> ParseLinearEqualityConstraint(
const symbolic::Formula& f);
/*
* Assist MathematicalProgram::AddLinearEqualityConstraint(...).
*/
template <typename DerivedV, typename DerivedB>
[[nodiscard]] typename std::enable_if_t<
is_eigen_vector_expression_double_pair<DerivedV, DerivedB>::value,
Binding<LinearEqualityConstraint>>
ParseLinearEqualityConstraint(const Eigen::MatrixBase<DerivedV>& V,
const Eigen::MatrixBase<DerivedB>& b) {
return DoParseLinearEqualityConstraint(V, b);
}
/*
* Assist MathematicalProgram::AddLinearEqualityConstraint(...).
*/
template <typename DerivedV, typename DerivedB>
[[nodiscard]] typename std::enable_if_t<
is_eigen_nonvector_expression_double_pair<DerivedV, DerivedB>::value,
Binding<LinearEqualityConstraint>>
ParseLinearEqualityConstraint(const Eigen::MatrixBase<DerivedV>& V,
const Eigen::MatrixBase<DerivedB>& B,
bool lower_triangle = false) {
if (lower_triangle) {
DRAKE_DEMAND(V.rows() == V.cols() && B.rows() == B.cols());
}
DRAKE_DEMAND(V.rows() == B.rows() && V.cols() == B.cols());
// Form the flatten version of V and B, when lower_triangle = false,
// the flatten version is just to concatenate each column of the matrix;
// otherwise the flatten version is to concatenate each column of the
// lower triangular part of the matrix.
const int V_rows = DerivedV::RowsAtCompileTime != Eigen::Dynamic
? static_cast<int>(DerivedV::RowsAtCompileTime)
: static_cast<int>(DerivedB::RowsAtCompileTime);
const int V_cols = DerivedV::ColsAtCompileTime != Eigen::Dynamic
? static_cast<int>(DerivedV::ColsAtCompileTime)
: static_cast<int>(DerivedB::ColsAtCompileTime);
if (lower_triangle) {
constexpr int V_triangular_size =
V_rows != Eigen::Dynamic ? (V_rows + 1) * V_rows / 2 : Eigen::Dynamic;
int V_triangular_size_dynamic = V.rows() * (V.rows() + 1) / 2;
Eigen::Matrix<symbolic::Expression, V_triangular_size, 1> flat_lower_V(
V_triangular_size_dynamic);
Eigen::Matrix<double, V_triangular_size, 1> flat_lower_B(
V_triangular_size_dynamic);
int V_idx = 0;
for (int j = 0; j < V.cols(); ++j) {
for (int i = j; i < V.rows(); ++i) {
flat_lower_V(V_idx) = V(i, j);
flat_lower_B(V_idx) = B(i, j);
++V_idx;
}
}
return DoParseLinearEqualityConstraint(flat_lower_V, flat_lower_B);
} else {
const int V_size = V_rows != Eigen::Dynamic && V_cols != Eigen::Dynamic
? V_rows * V_cols
: Eigen::Dynamic;
Eigen::Matrix<symbolic::Expression, V_size, 1> flat_V(V.size());
Eigen::Matrix<double, V_size, 1> flat_B(V.size());
int V_idx = 0;
for (int j = 0; j < V.cols(); ++j) {
for (int i = 0; i < V.rows(); ++i) {
flat_V(V_idx) = V(i, j);
flat_B(V_idx) = B(i, j);
++V_idx;
}
}
return DoParseLinearEqualityConstraint(flat_V, flat_B);
}
}
/**
* Assists MathematicalProgram::AddConstraint(...) to create a quadratic
* constraint binding.
*/
[[nodiscard]] Binding<QuadraticConstraint> ParseQuadraticConstraint(
const symbolic::Expression& e, double lower_bound, double upper_bound,
std::optional<QuadraticConstraint::HessianType> hessian_type =
std::nullopt);
/*
* Assist MathematicalProgram::AddPolynomialConstraint(...).
* @note Non-symbolic, but this seems to have a separate purpose than general
* construction.
*/
[[nodiscard]] std::shared_ptr<Constraint> MakePolynomialConstraint(
const VectorXPoly& polynomials,
const std::vector<Polynomiald::VarType>& poly_vars,
const Eigen::VectorXd& lb, const Eigen::VectorXd& ub);
/*
* Assist MathematicalProgram::AddLorentzConeConstraint(...).
*/
[[nodiscard]] Binding<LorentzConeConstraint> ParseLorentzConeConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v,
LorentzConeConstraint::EvalType eval_type =
LorentzConeConstraint::EvalType::kConvexSmooth);
/*
* Assist MathematicalProgram::AddLorentzConeConstraint(...).
*/
[[nodiscard]] Binding<LorentzConeConstraint> ParseLorentzConeConstraint(
const symbolic::Expression& linear_expr,
const symbolic::Expression& quadratic_expr, double tol = 0,
LorentzConeConstraint::EvalType eval_type =
LorentzConeConstraint::EvalType::kConvexSmooth);
/*
* Assist MathematicalProgram::AddRotatedLorentzConeConstraint(...)
*/
[[nodiscard]] Binding<RotatedLorentzConeConstraint>
ParseRotatedLorentzConeConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v);
/*
* Assist MathematicalProgram::AddRotatedLorentzConeConstraint(...)
*/
[[nodiscard]] Binding<RotatedLorentzConeConstraint>
ParseRotatedLorentzConeConstraint(const symbolic::Expression& linear_expr1,
const symbolic::Expression& linear_expr2,
const symbolic::Expression& quadratic_expr,
double tol = 0);
/** For a convex quadratic constraint 0.5xᵀQx + bᵀx + c <= 0, we parse it as a
* rotated Lorentz cone constraint [-bᵀx-c, 1, Fx] is in the rotated Lorentz
* cone where FᵀF = 0.5 * Q
* @param zero_tol The tolerance to determine if Q is a positive semidefinite
* matrix. Check math::DecomposePSDmatrixIntoXtransposeTimesX for a detailed
* explanation. zero_tol should be non-negative. @default is 0.
* @throw exception if this quadratic constraint is not convex (Q is not
* positive semidefinite)
*
* You could refer to
* https://docs.mosek.com/latest/pythonapi/advanced-toconic.html for derivation.
*/
[[nodiscard]] std::shared_ptr<RotatedLorentzConeConstraint>
ParseQuadraticAsRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double c, double zero_tol = 0.);
// TODO(eric.cousineau): Implement this if variable creation is separated.
// Format would be (tuple(linear_binding, psd_binding), new_vars)
// ParsePositiveSemidefiniteConstraint(
// const Eigen::Ref<MatrixX<symbolic::Expression>>& e) {
// // ...
// return std::make_tuple(linear_binding, psd_binding);
// }
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/no_snopt.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/snopt_solver.h"
/* clang-format on */
#include <stdexcept>
namespace drake {
namespace solvers {
bool SnoptSolver::is_available() {
return false;
}
void SnoptSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&,
const SolverOptions&,
MathematicalProgramResult*) const {
throw std::runtime_error(
"The SNOPT bindings were not compiled. You'll need to use a different "
"solver.");
}
bool SnoptSolver::is_bounded_lp_broken() {
throw std::runtime_error(
"The SNOPT bindings were not compiled. You'll need to use a different "
"solver.");
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/snopt_solver.h | #pragma once
#include <string>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/solver_base.h"
namespace drake {
namespace solvers {
/**
* The SNOPT solver details after calling Solve() function. The user can call
* MathematicalProgramResult::get_solver_details<SnoptSolver>() to obtain the
* details.
*/
struct SnoptSolverDetails {
/**
* The snopt INFO field. Please refer to section 8.6
* in "User's Guide for SNOPT Version 7: Software for Large-Scale Nonlinear
* Programming" (https://web.stanford.edu/group/SOL/guides/sndoc7.pdf) by
* Philip E. Gill to interpret the INFO field.
*/
int info{};
/** The final value of the dual variables for the bound constraint x_lower <=
* x <= x_upper.
*/
Eigen::VectorXd xmul;
/** The final value of the vector of problem functions F(x).
*/
Eigen::VectorXd F;
/** The final value of the dual variables (Lagrange multipliers) for the
* general constraints F_lower <= F(x) <= F_upper.
*/
Eigen::VectorXd Fmul;
};
/**
* An implementation of SolverInterface for the commercially-licensed SNOPT
* solver (https://ccom.ucsd.edu/~optimizers/solvers/snopt/).
*
* Builds of Drake from source do not compile SNOPT by default, so therefore
* SolverInterface::available() will return false. You must opt-in to build
* SNOPT per the documentation at https://drake.mit.edu/bazel.html#snopt.
*
* <a href="https://drake.mit.edu/installation.html">Drake's
* pre-compiled binary releases</a> do incorporate SNOPT, so therefore
* SolverInterface::available() will return true.
* Thanks to Philip E. Gill and Elizabeth Wong for their kind support.
*
* There is no license configuration required to use SNOPT, but you may set the
* environtment variable `DRAKE_SNOPT_SOLVER_ENABLED` to "0" to force-disable
* SNOPT, in which case SolverInterface::enabled() will return false.
*/
class SnoptSolver final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SnoptSolver)
/// Type of details stored in MathematicalProgramResult.
using Details = SnoptSolverDetails;
SnoptSolver();
~SnoptSolver() final;
/// For some reason, SNOPT 7.4 fails to detect a simple LP being unbounded.
static bool is_bounded_lp_broken();
/// @name Static versions of the instance methods with similar names.
//@{
static SolverId id();
static bool is_available();
/// Returns true iff the environment variable DRAKE_SNOPT_SOLVER_ENABLED is
/// unset or set to anything other than "0".
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/decision_variable.cc | #include "drake/solvers/decision_variable.h"
namespace drake {
namespace solvers {
VectorXDecisionVariable ConcatenateVariableRefList(
const VariableRefList& var_list) {
int dim = 0;
for (const auto& var : var_list) {
dim += var.size();
}
VectorXDecisionVariable stacked_var(dim);
int var_count = 0;
for (const auto& var : var_list) {
stacked_var.segment(var_count, var.rows()) = var;
var_count += var.rows();
}
return stacked_var;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mosek_solver_internal.h | #pragma once
// For external users, please do not include this header file. It only exists so
// that we can expose the internals to mosek_solver_internal_test.cc
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <mosek.h>
#include "drake/solvers/constraint.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mathematical_program_result.h"
namespace drake {
namespace solvers {
namespace internal {
// Mosek treats psd matrix variables in a special manner.
// Check https://docs.mosek.com/10.1/capi/tutorial-sdo-shared.html for more
// details. To summarize, Mosek stores a positive semidefinite (psd) matrix
// variable as a "bar var" (as called in Mosek's API, for example
// https://docs.mosek.com/10.1/capi/tutorial-sdo-shared.html). Inside Mosek, it
// accesses each of the psd matrix variable with a unique ID. Moreover, the
// Mosek user cannot access the entries of the psd matrix variable individually;
// instead, the user can only access the matrix X̅ as a whole. To impose
// linear constraints on psd matrix variable X̅ entries, the user must specify a
// "coefficient matrix" A̅ that multiplies X̅ (using the matrix inner product) to
// yield the linear constraint lower ≤ <A̅, X̅> ≤ upper. For example, to impose
// the constraint X̅(0, 0) + X̅(1, 0) = 1, where X̅ is a 2 x 2 psd matrix, Mosek
// requires the user to write it as <A̅, X̅> = 1, where
// A̅ = ⌈1 0.5⌉
// ⌊0.5 0⌋
// On the other hand, drake::solvers::MathematicalProgram doesn't treat psd
// matrix variables in a special manner.
// MatrixVariableEntry stores the data needed to refer to a particular entry of
// a Mosek matrix variable.
class MatrixVariableEntry {
public:
typedef size_t Id;
MatrixVariableEntry(MSKint64t bar_matrix_index, MSKint32t row_index,
MSKint32t col_index, int num_matrix_rows)
: bar_matrix_index_{bar_matrix_index},
row_index_{row_index},
col_index_{col_index},
num_matrix_rows_{num_matrix_rows},
id_{get_next_id()} {
// Mosek only stores the lower triangular part of the symmetric matrix.
DRAKE_ASSERT(row_index_ >= col_index_);
}
MSKint64t bar_matrix_index() const { return bar_matrix_index_; }
MSKint32t row_index() const { return row_index_; }
MSKint32t col_index() const { return col_index_; }
int num_matrix_rows() const { return num_matrix_rows_; }
Id id() const { return id_; }
// Returns the index of the entry in a vector formed by stacking the lower
// triangular part of the symmetric matrix column by column.
int IndexInLowerTrianglePart() const {
return (2 * num_matrix_rows_ - col_index_ + 1) * col_index_ / 2 +
row_index_ - col_index_;
}
private:
static size_t get_next_id();
MSKint64t bar_matrix_index_;
MSKint32t row_index_;
MSKint32t col_index_;
int num_matrix_rows_;
Id id_;
};
// Mosek stores dual variable in different categories, called slc, suc, slx, sux
// and snx. Refer to
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getsolution
// for more information.
enum class DualVarType {
kLinearConstraint, ///< Corresponds to Mosek's slc and suc.
kVariableBound, ///< Corresponds to Mosek's slx and sux.
kNonlinearConic, ///< Corresponds to Mosek's snx.
};
struct ConstraintDualIndex {
// Type of the dual variable.
DualVarType type;
// Index of the dual variable. We will use -1 to indicate that a constraint
// can never be active.
int index{};
};
using ConstraintDualIndices = std::vector<ConstraintDualIndex>;
template <typename ConstraintType>
using DualMap =
std::unordered_map<Binding<ConstraintType>, ConstraintDualIndices>;
enum class LinearConstraintBoundType {
kEquality,
kInequality,
};
// Mosek treats matrix variables (variables in the psd matrix) in a special
// manner, while MathematicalProgram doesn't. Hence we need to pick out the
// variables in prog.positive_semidefinite_constraint(), record how they will
// be stored in Mosek, and also how the remaining non-matrix variable will be
// stored in Mosek. Note that we only loop through
// PositiveSemidefiniteConstraint, not LinearMatrixInequalityConstraint.
struct MapDecisionVariableToMosekVariable {
public:
explicit MapDecisionVariableToMosekVariable(const MathematicalProgram& prog);
std::unordered_map<int, MatrixVariableEntry>
decision_variable_to_mosek_matrix_variable{};
std::unordered_map<int, int> decision_variable_to_mosek_nonmatrix_variable{};
// Multiple entries in Mosek matrix variables could correspond to the same
// decision variable. We will need to add linear equality constraints to
// equate these entries.
std::unordered_map<int, std::vector<MatrixVariableEntry>>
matrix_variable_entries_for_same_decision_variable{};
};
// MosekSolverProgram is a temporary object used by our MosekSolver
// implementation that is created (and destroyed) once per Solve() operation. It
// provides individual, program-specific helper functions to translate a
// MathematicalProgram into Mosek's API. We've separated it from
// MosekSolver::DoSolve both to make it easier to understand and to unit test
// each function one by one.
class MosekSolverProgram {
public:
MosekSolverProgram(const MathematicalProgram& prog, MSKenv_t env);
~MosekSolverProgram();
// If a matrix variable entry X̅(m, n) appears in a cost or a constraint
// (except the psd constraint), then we need a matrix Eₘₙ stored inside Mosek,
// such that <Eₘₙ, X̅> = X̅(m, n). In this function we add the symmetric matrix
// Eₘₙ into Mosek, and record the index of Eₘₙ in Mosek.
// @param[out] E_idx The index of Eₘₙ for @p matrix_variable_entry.
MSKrescodee AddMatrixVariableEntryCoefficientMatrixIfNonExistent(
const MatrixVariableEntry& matrix_variable_entry, MSKint64t* E_index);
// Add the product c * X̅(i, j) to a constraint.
// This function should be called only if that Mosek matrix variable X̅ appear
// only once in this constraint. Otherwise we should call
// AddLinearConstraintToMosek, which first collects all the
// entries X̅(i, j) belonging to this matrix variable X̅ in this constraint, and
// then forms a matrix A, such that <A, X̅> contains the weighted sum of all
// entries of X̅ in this constraint.
MSKrescodee AddScalarTimesMatrixVariableEntryToMosek(
MSKint32t constraint_index,
const MatrixVariableEntry& matrix_variable_entry, MSKrealt scalar);
// Determine the sense of each constraint. The sense can be equality
// constraint, less than, greater than, or bounded on both side.
MSKrescodee SetMosekLinearConstraintBound(
int linear_constraint_index, double lower, double upper,
LinearConstraintBoundType bound_type);
// Add the linear constraint lower <= A * decision_vars + B * slack_vars <=
// upper.
MSKrescodee AddLinearConstraintToMosek(
const MathematicalProgram& prog, const Eigen::SparseMatrix<double>& A,
const Eigen::SparseMatrix<double>& B, const Eigen::VectorXd& lower,
const Eigen::VectorXd& upper,
const VectorX<symbolic::Variable>& decision_vars,
const std::vector<MSKint32t>& slack_vars_mosek_indices,
LinearConstraintBoundType bound_type);
// Convert the expression A * decicion_vars + B * slack_vars to Mosek affine
// expression format
// ∑ⱼ fᵢⱼ xⱼ + ∑ⱼ<F̅ᵢⱼ, X̅ⱼ>
// Please refer to
// https://docs.mosek.com/latest/capi/tutorial-acc-optimizer.html for an
// introduction on Mosek affine expression, and
// https://docs.mosek.com/latest/capi/tutorial-sdo-shared.html for the affine
// expression with matrix variables.
// F̅ᵢⱼ is a weighted sum of the symmetric matrix E stored inside Mosek.
// bar_F[i][j] stores the indices of E and the weights of E.
// namely F̅ᵢⱼ = ∑ₖbar_F[i][j][k].second* E[bar_F[i][j][k].first]
MSKrescodee ParseLinearExpression(
const solvers::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,
std::vector<MSKint32t>* F_subi, std::vector<MSKint32t>* F_subj,
std::vector<MSKrealt>* F_valij,
std::vector<std::unordered_map<
MSKint64t, std::pair<std::vector<MSKint64t>, std::vector<MSKrealt>>>>*
bar_F);
// Same as ParseLinearExpression, but assumes that each entry in
// `decision_vars` is unique.
MSKrescodee ParseLinearExpressionNoDuplication(
const solvers::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,
std::vector<MSKint32t>* F_subi, std::vector<MSKint32t>* F_subj,
std::vector<MSKrealt>* F_valij,
std::vector<std::unordered_map<
MSKint64t, std::pair<std::vector<MSKint64t>, std::vector<MSKrealt>>>>*
bar_F);
// Add LinearConstraints and LinearEqualityConstraints to the Mosek task.
// @param[out] dual_indices maps each linear constraint to its dual variable
// indices.
template <typename C>
MSKrescodee AddLinearConstraintsFromBindings(
const std::vector<Binding<C>>& constraint_list,
LinearConstraintBoundType bound_type, const MathematicalProgram& prog,
std::unordered_map<Binding<C>, ConstraintDualIndices>* dual_indices);
// @param[out] lin_eq_con_dual_indices maps each linear equality constraint to
// its dual variable indices.
MSKrescodee AddLinearConstraints(
const MathematicalProgram& prog,
std::unordered_map<Binding<LinearConstraint>, ConstraintDualIndices>*
linear_con_dual_indices,
std::unordered_map<Binding<LinearEqualityConstraint>,
ConstraintDualIndices>* lin_eq_con_dual_indices);
// Add the bounds on the decision variables in @p prog. Note that if a
// decision variable in positive definite matrix has a bound, we need to add
// new linear constraint to Mosek to bound that variable.
// @param[out] dual_indices Map each bounding box constraint to its dual
// variable indices.
MSKrescodee AddBoundingBoxConstraints(
const MathematicalProgram& prog,
std::unordered_map<Binding<BoundingBoxConstraint>,
std::pair<ConstraintDualIndices,
ConstraintDualIndices>>* dual_indices);
// Add the quadratic constraints in @p prog.
// @param[out] dual_indices Map each quadratic constraint to its dual variable
// index.
MSKrescodee AddQuadraticConstraints(
const MathematicalProgram& prog,
std::unordered_map<Binding<QuadraticConstraint>, MSKint64t>*
dual_indices);
/**
Adds the constraint that A * decision_vars + B * slack_vars + c is in an
affine cone.
@param[out] acc_index The index of the newly added affine cone.
*/
MSKrescodee AddAffineConeConstraint(
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 Eigen::VectorXd& c, MSKdomaintypee cone_type, MSKint64t* acc_index);
/*
* This is the helper function to add three types of conic constraints
* 1. A Lorentz cone constraint:
* z = A*x+b
* z0 >= sqrt(z1^2 + .. zN^2)
* 2. A rotated Lorentz cone constraint:
* z = A*x+b
* z0*z1 >= z2^2 + .. + zN^2,
* z0 >= 0, z1 >=0
* 3. An exonential cone constraint:
* z = A*x+b
* z0 >= z1 * exp(z2 / z1)
* @param[out] acc_indices Maps each conic constraint to its Affine Cone
* Constraint indices.
*/
template <typename C>
MSKrescodee AddConeConstraints(
const MathematicalProgram& prog,
const std::vector<Binding<C>>& cone_constraints,
std::unordered_map<Binding<C>, MSKint64t>* acc_indices);
// @param[out] psd_barvar_indices maps each psd constraint to Mosek matrix
// variable
MSKrescodee AddPositiveSemidefiniteConstraints(
const MathematicalProgram& prog,
std::unordered_map<Binding<PositiveSemidefiniteConstraint>, MSKint32t>*
psd_barvar_indices);
// Add linear matrix inequality (LMI) constraints as affine cone constraints
// (acc), return the indices of the added affine cone constraints.
MSKrescodee AddLinearMatrixInequalityConstraint(
const MathematicalProgram& prog,
std::unordered_map<Binding<LinearMatrixInequalityConstraint>, MSKint64t>*
lmi_acc_indices);
MSKrescodee AddLinearCost(const Eigen::SparseVector<double>& linear_coeff,
const VectorX<symbolic::Variable>& linear_vars,
const MathematicalProgram& prog);
MSKrescodee AddQuadraticCostAsLinearCost(
const Eigen::SparseMatrix<double>& Q_lower,
const VectorX<symbolic::Variable>& quadratic_vars,
const MathematicalProgram& prog);
MSKrescodee AddQuadraticCost(
const Eigen::SparseMatrix<double>& Q_quadratic_vars,
const VectorX<symbolic::Variable>& quadratic_vars,
const MathematicalProgram& prog);
// Adds the L2 norm cost min |C*x+d|₂ to Mosek.
MSKrescodee AddL2NormCost(const Eigen::SparseMatrix<double>& C,
const Eigen::VectorXd& d,
const VectorX<symbolic::Variable>& x,
const MathematicalProgram& prog);
MSKrescodee AddCosts(const MathematicalProgram& prog);
// @param[out] with_integer_or_binary_variables True if the program has
// integer or binary variables.
MSKrescodee SpecifyVariableType(const MathematicalProgram& prog,
bool* with_integer_or_binary_variables);
// Some entries in Mosek matrix variables might correspond to the same
// decision variable in MathematicalProgram. Add the equality constraint
// between these matrix variable entries.
MSKrescodee
AddEqualityConstraintBetweenMatrixVariablesForSameDecisionVariable();
// @param[in/out] result Update the dual solution for psd constraints in
// result.
MSKrescodee SetPositiveSemidefiniteConstraintDualSolution(
const MathematicalProgram& prog,
const std::unordered_map<Binding<PositiveSemidefiniteConstraint>,
MSKint32t>& psd_barvar_indices,
MSKsoltypee whichsol, MathematicalProgramResult* result) const;
// @param[in/out] result Update the dual solution in result.
MSKrescodee SetDualSolution(
MSKsoltypee which_sol, const MathematicalProgram& prog,
const std::unordered_map<
Binding<BoundingBoxConstraint>,
std::pair<ConstraintDualIndices, ConstraintDualIndices>>&
bb_con_dual_indices,
const DualMap<LinearConstraint>& linear_con_dual_indices,
const DualMap<LinearEqualityConstraint>& lin_eq_con_dual_indices,
const std::unordered_map<Binding<QuadraticConstraint>, MSKint64t>&
quadratic_constraint_dual_indices,
const std::unordered_map<Binding<LorentzConeConstraint>, MSKint64t>&
lorentz_cone_acc_indices,
const std::unordered_map<Binding<RotatedLorentzConeConstraint>,
MSKint64t>& rotated_lorentz_cone_acc_indices,
const std::unordered_map<Binding<ExponentialConeConstraint>, MSKint64t>&
exp_cone_acc_indices,
const std::unordered_map<Binding<PositiveSemidefiniteConstraint>,
MSKint32t>& psd_barvar_indices,
MathematicalProgramResult* result) const;
// @param[out] print_to_console Set to true if solver options requires
// printing the log to the console.
// @param[out] print_file_name Set to the name of the print file store in
// solver options. If solver options doesn't store the print file name, then
// set *print_file_name to an empty string.
// @param[out] msk_writedata If solver options stores the file for writing
// data, then put the file name to msk_writedata for later use.
MSKrescodee UpdateOptions(const SolverOptions& solver_options,
SolverId mosek_id, bool* print_to_console,
std::string* print_file_name,
std::optional<std::string>* msk_writedata);
MSKtask_t task() const { return task_; }
// For each entry of the matrix variable X̅ᵢ(m,n), if this entry is also used
// in the cost or constraint, then we will use the term <E̅ₘₙ,X̅ᵢ>, where
// the inner product <E̅ₘₙ, X̅ᵢ> = X̅ᵢ(m,n). The "selection matrix" E̅ₘₙ helps
// to select the (m, n)'th entry of the psd matrix variable. E̅ₘₙ is stored
// inside Mosek with a unique ID.
// matrix_variable_entry_to_selection_matrix_id maps the matrix variable
// entry to the ID of E̅ₘₙ.
// TODO(hongkai.dai): do not map the matrix variable entry to the selection
// matrix, instead maps the tuple (matrix_size, row_index, column_index) to
// the selection matrix. This will create fewer selection matrices, when
// multiple matrix variables have the same size.
const std::unordered_map<MatrixVariableEntry::Id, MSKint64t>&
matrix_variable_entry_to_selection_matrix_id() const {
return matrix_variable_entry_to_selection_matrix_id_;
}
const std::unordered_map<int, MatrixVariableEntry>&
decision_variable_to_mosek_matrix_variable() const {
return map_decision_var_to_mosek_var_
.decision_variable_to_mosek_matrix_variable;
}
const std::unordered_map<int, int>&
decision_variable_to_mosek_nonmatrix_variable() const {
return map_decision_var_to_mosek_var_
.decision_variable_to_mosek_nonmatrix_variable;
}
const std::unordered_map<int, std::vector<MatrixVariableEntry>>&
matrix_variable_entries_for_same_decision_variable() const {
return map_decision_var_to_mosek_var_
.matrix_variable_entries_for_same_decision_variable;
}
private:
MSKtask_t task_{nullptr};
std::unordered_map<MatrixVariableEntry::Id, MSKint64t>
matrix_variable_entry_to_selection_matrix_id_{};
const MapDecisionVariableToMosekVariable map_decision_var_to_mosek_var_;
};
template <typename C>
MSKrescodee MosekSolverProgram::AddLinearConstraintsFromBindings(
const std::vector<Binding<C>>& constraint_list,
LinearConstraintBoundType bound_type, const MathematicalProgram& prog,
std::unordered_map<Binding<C>, ConstraintDualIndices>* dual_indices) {
MSKrescodee rescode{MSK_RES_OK};
for (const auto& binding : constraint_list) {
const auto& constraint = binding.evaluator();
const Eigen::SparseMatrix<double>& A = constraint->get_sparse_A();
const Eigen::VectorXd& lb = constraint->lower_bound();
const Eigen::VectorXd& ub = constraint->upper_bound();
Eigen::SparseMatrix<double> B_zero(A.rows(), 0);
B_zero.setZero();
int num_linear_constraints{-1};
rescode = MSK_getnumcon(task_, &num_linear_constraints);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = AddLinearConstraintToMosek(prog, A, B_zero, lb, ub,
binding.variables(), {}, bound_type);
if (rescode != MSK_RES_OK) {
return rescode;
}
ConstraintDualIndices constraint_dual_indices(lb.rows());
for (int i = 0; i < lb.rows(); ++i) {
constraint_dual_indices[i].type = DualVarType::kLinearConstraint;
constraint_dual_indices[i].index = num_linear_constraints + i;
}
dual_indices->emplace(binding, constraint_dual_indices);
}
return rescode;
}
template <typename C>
MSKrescodee MosekSolverProgram::AddConeConstraints(
const MathematicalProgram& prog,
const std::vector<Binding<C>>& cone_constraints,
std::unordered_map<Binding<C>, MSKint64t>* acc_indices) {
static_assert(std::is_same_v<C, LorentzConeConstraint> ||
std::is_same_v<C, RotatedLorentzConeConstraint> ||
std::is_same_v<C, ExponentialConeConstraint>,
"Should be either Lorentz cone constraint, rotated Lorentz "
"cone or exponential cone constraint");
const bool is_rotated_cone = std::is_same_v<C, RotatedLorentzConeConstraint>;
MSKrescodee rescode = MSK_RES_OK;
for (auto const& binding : cone_constraints) {
MSKint64t acc_index;
if (is_rotated_cone) {
// Drake's RotatedLorentzConeConstraint imposes z₀ * z₁ ≥ z₂² + z₃² + ...
// zₙ₋₁² where z being an affine expression of x, while Mosek's rotated
// quadratic cone imposes 2 * z₀ * z₁ ≥ z₂² + z₃² + ... zₙ₋₁² (notice the
// factor of 2). Hence we will impose the constraint that the vector
// ⌈0.5*(A.row(0)*x + b(0))⌉
// | A.row(1)*x + b(1) |
// | ... |
// ⌊ A.row(n-1)*x + b(n-1)⌋
// is in Mosek's rotated quadratic cone. Namely we multiply 0.5 to the
// first row of A, b.
Eigen::SparseMatrix<double> A = binding.evaluator()->A();
for (int k = 0; k < A.outerSize(); ++k) {
for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it) {
if (it.row() == 0) {
it.valueRef() *= 0.5;
}
}
}
Eigen::VectorXd b = binding.evaluator()->b();
b(0) *= 0.5;
rescode = this->AddAffineConeConstraint(
prog, A, Eigen::SparseMatrix<double>(A.rows(), 0),
binding.variables(), {}, b, MSK_DOMAIN_RQUADRATIC_CONE, &acc_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
} else {
MSKdomaintypee cone_type;
if (std::is_same_v<C, LorentzConeConstraint>) {
cone_type = MSK_DOMAIN_QUADRATIC_CONE;
} else if (std::is_same_v<C, ExponentialConeConstraint>) {
cone_type = MSK_DOMAIN_PRIMAL_EXP_CONE;
}
rescode = this->AddAffineConeConstraint(
prog, binding.evaluator()->A(),
Eigen::SparseMatrix<double>(binding.evaluator()->A().rows(), 0),
binding.variables(), {}, binding.evaluator()->b(), cone_type,
&acc_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
}
acc_indices->emplace(binding, acc_index);
}
return rescode;
}
// @param slx Mosek dual variables for variable lower bound. See
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getslx
// @param sux Mosek dual variables for variable upper bound. See
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getsux
// @param slc Mosek dual variables for linear constraint lower bound. See
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getslc
// @param suc Mosek dual variables for linear constraint upper bound. See
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getsuc
void SetBoundingBoxDualSolution(
const std::vector<Binding<BoundingBoxConstraint>>& constraints,
const std::vector<MSKrealt>& slx, const std::vector<MSKrealt>& sux,
const std::vector<MSKrealt>& slc, const std::vector<MSKrealt>& suc,
const std::unordered_map<
Binding<BoundingBoxConstraint>,
std::pair<ConstraintDualIndices, ConstraintDualIndices>>&
bb_con_dual_indices,
MathematicalProgramResult* result);
template <typename C>
void SetLinearConstraintDualSolution(
const std::vector<Binding<C>>& bindings, const std::vector<MSKrealt>& slc,
const std::vector<MSKrealt>& suc,
const std::unordered_map<Binding<C>, ConstraintDualIndices>&
linear_con_dual_indices,
MathematicalProgramResult* result) {
for (const auto& binding : bindings) {
const ConstraintDualIndices duals = linear_con_dual_indices.at(binding);
Eigen::VectorXd dual_sol =
Eigen::VectorXd::Zero(binding.evaluator()->num_constraints());
for (int i = 0; i < dual_sol.rows(); ++i) {
DRAKE_DEMAND(duals[i].type == DualVarType::kLinearConstraint);
// Mosek defines all dual solutions as non-negative. However we use
// "reduced cost" as the dual solution, so the dual solution for a
// lower bound should be non-negative, while the dual solution for
// an upper bound should be non-positive.
if (slc[duals[i].index] > suc[duals[i].index]) {
dual_sol[i] = slc[duals[i].index];
} else {
dual_sol[i] = -suc[duals[i].index];
}
}
result->set_dual_solution(binding, dual_sol);
}
}
// @param slc Mosek dual variables for linear and quadratic constraint lower
// bound. See
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getslc
// @param suc Mosek dual variables for linear and quadratic constraint upper
// bound. See
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getsuc
void SetQuadraticConstraintDualSolution(
const std::vector<Binding<QuadraticConstraint>>& constraints,
const std::vector<MSKrealt>& slc, const std::vector<MSKrealt>& suc,
const std::unordered_map<Binding<QuadraticConstraint>, MSKint64t>&
quadratic_constraint_dual_indices,
MathematicalProgramResult* result);
/*
* Sets the dual solution for the affine cone constraints.
* @param bindings The constraint for which the dual solution will be set.
* @param task The Mosek task.
* @param whichsol The solution type. See
* https://docs.mosek.com/latest/capi/constants.html#mosek.soltype
* @param acc_indices Maps each constraint to the affine cone constraint
* indices.
* @param[out] result The dual solution in `result` will be set.
*/
template <typename C>
MSKrescodee SetAffineConeConstraintDualSolution(
const std::vector<Binding<C>>& bindings, MSKtask_t task,
MSKsoltypee whichsol,
const std::unordered_map<Binding<C>, MSKint64t>& acc_indices,
MathematicalProgramResult* result) {
for (const auto& binding : bindings) {
const MSKint64t acc_index = acc_indices.at(binding);
MSKint64t acc_dim;
auto rescode = MSK_getaccn(task, acc_index, &acc_dim);
if (rescode != MSK_RES_OK) {
return rescode;
}
Eigen::VectorXd dual_sol = Eigen::VectorXd::Zero(acc_dim);
rescode = MSK_getaccdoty(task, whichsol, acc_index, dual_sol.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
if constexpr (std::is_same_v<C, RotatedLorentzConeConstraint>) {
// Drake's rotated Lorentz cone constraint on z = Ax+b is
// K_drake={ z | z₀z₁≥ z₂² + ... zₙ₋₁², z₀≥0, z₁≥0}
// On the other hand, Mosek's rotated Lorentz cone constraint has a
// multiplier of 2
// K_mosek={ z | 2z₀z₁≥ z₂² + ... zₙ₋₁², z₀≥0, z₁≥0} Hence
// we can write K_drake = C*K_mosek where C = diag([2, 1, ..., 1]). By
// duality we know K_drake_dual = C⁻ᵀ*K_mosek_dual, where K_drake_dual is
// the dual cone of K_drake, likewise K_mosek_dual is the dual cone of
// K_mosek.
dual_sol(0) *= 0.5;
}
result->set_dual_solution(binding, dual_sol);
}
return MSK_RES_OK;
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/linear_system_solver.cc | #include "drake/solvers/linear_system_solver.h"
#include <cstring>
#include <initializer_list>
#include <limits>
#include <memory>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
LinearSystemSolver::LinearSystemSolver()
: SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied,
&UnsatisfiedProgramAttributes) {}
LinearSystemSolver::~LinearSystemSolver() = default;
bool LinearSystemSolver::is_available() {
return true;
}
bool LinearSystemSolver::is_enabled() {
return true;
}
void LinearSystemSolver::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(
"LinearSystemSolver doesn't support the feature of variable scaling.");
}
// The initial guess doesn't help us, and we don't offer any tuning options.
unused(initial_guess, merged_options);
size_t num_constraints = 0;
for (auto const& binding : prog.linear_equality_constraints()) {
num_constraints += binding.evaluator()->get_sparse_A().rows();
}
DRAKE_ASSERT(prog.generic_constraints().empty());
DRAKE_ASSERT(prog.generic_costs().empty());
DRAKE_ASSERT(prog.quadratic_costs().empty());
DRAKE_ASSERT(prog.linear_constraints().empty());
DRAKE_ASSERT(prog.bounding_box_constraints().empty());
DRAKE_ASSERT(prog.linear_complementarity_constraints().empty());
Eigen::MatrixXd Aeq = Eigen::MatrixXd::Zero(num_constraints, prog.num_vars());
// TODO(naveenoid) : use a sparse matrix here?
Eigen::VectorXd beq(num_constraints);
size_t constraint_index = 0;
for (auto const& binding : prog.linear_equality_constraints()) {
auto const& c = binding.evaluator();
size_t n = c->get_sparse_A().rows();
for (int i = 0; i < static_cast<int>(binding.GetNumElements()); ++i) {
const int variable_index =
prog.FindDecisionVariableIndex(binding.variables()(i));
for (Eigen::SparseMatrix<double>::InnerIterator it(c->get_sparse_A(), i);
it; ++it) {
Aeq(constraint_index + it.row(), variable_index) = it.value();
}
}
beq.segment(constraint_index, n) =
c->lower_bound(); // = c->upper_bound() since it's an equality
// constraint
constraint_index += n;
}
// least-squares solution
const Eigen::VectorXd least_square_sol =
Aeq.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(beq);
result->set_x_val(least_square_sol);
if (beq.isApprox(Aeq * least_square_sol)) {
result->set_optimal_cost(0.);
result->set_solution_result(SolutionResult::kSolutionFound);
} else {
result->set_optimal_cost(MathematicalProgram::kGlobalInfeasibleCost);
result->set_solution_result(SolutionResult::kInfeasibleConstraints);
}
}
SolverId LinearSystemSolver::id() {
static const never_destroyed<SolverId> singleton{"Linear system"};
return singleton.access();
}
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});
const ProgramAttributes& required_capabilities = prog.required_capabilities();
const bool capabilities_match = AreRequiredAttributesSupported(
required_capabilities, solver_capabilities.access(), explanation);
if (!capabilities_match || required_capabilities.empty()) {
if (explanation) {
if (required_capabilities.empty()) {
*explanation =
" a LinearEqualityConstraint is required but has not been declared";
}
*explanation = fmt::format(
"LinearSystemSolver is unable to solve because {}.", *explanation);
}
return false;
}
if (explanation) {
explanation->clear();
}
return true;
}
} // namespace
bool LinearSystemSolver::ProgramAttributesSatisfied(
const MathematicalProgram& prog) {
return CheckAttributes(prog, nullptr);
}
std::string LinearSystemSolver::UnsatisfiedProgramAttributes(
const MathematicalProgram& prog) {
std::string explanation;
CheckAttributes(prog, &explanation);
return explanation;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/integer_optimization_util.h | #pragma once
#include "drake/solvers/binding.h"
#include "drake/solvers/constraint.h"
namespace drake {
namespace solvers {
/**
* Adds linear constraints, such that when b1, b2, b1_and_b2 satisfy the
* constraints, and b1, b2 take binary values, it is guaranteed that
* b1_and_b2 = b1 ∧ b2 (b1 and b2).
* The constraints are
* <pre>
* b1_and_b2 >= b1 + b2 - 1
* b1_and_b2 <= b1
* b1_and_b2 <= b2
* 0 <= b1_and_b2 <= 1
* </pre>
* @param b1 An expression that should only take a binary value.
* @param b2 An expression that should only take a binary value.
* @param b1_and_b2 Should be the logical and between `b1` and `b2`.
* @return The newly added constraints, such that when b1, b2, b1_and_b2 satisfy
* the constraints, it is guaranteed that b1_and_b2 = b1 ∧ b2.
* @pre b1, b2, b1_and_b2 are all linear expressions.
*/
[[nodiscard]] Binding<LinearConstraint> CreateLogicalAndConstraint(
const symbolic::Expression& b1, const symbolic::Expression& b2,
const symbolic::Expression& b1_and_b2);
/**
* Adds linear constraints, such that when b1, b2, b1_or_b2 satisfy the
* constraints, and b1, b2 take binary values, it is guaranteed that
* b1_or_b2 = b1 ∨ b2 (b1 or b2).
* The constraints are
* <pre>
* b1_or_b2 <= b1 + b2
* b1_or_b2 >= b1
* b1_or_b2 >= b2
* 0 <= b1_or_b2 <= 1
* </pre>
* @param b1 An expression that should only take a binary value.
* @param b2 An expression that should only take a binary value.
* @param b1_or_b2 Should be the logical or between `b1` and `b2`.
* @return The newly added constraints, such that when b1, b2, b1_or_b2 satisfy
* the constraints, it is guaranteed that b1_or_b2 = b1 ∨ b2.
* @pre b1, b2, b1_or_b2 are all linear expressions.
*/
[[nodiscard]] Binding<LinearConstraint> CreateLogicalOrConstraint(
const symbolic::Expression& b1, const symbolic::Expression& b2,
const symbolic::Expression& b1_or_b2);
/**
* Add linear constraints, such that when b1, b2, b1_xor_b2 satisfy the
* constraints, and b1, b2 take binary values, it is guaranteed that
* b1_xor_b2 = b1 ⊕ b2 (b1 exclusive xor b2).
* The constraints are
* <pre>
* b1_xor_b2 <= b1 + b2
* b1_xor_b2 >= b1 - b2
* b1_xor_b2 >= b2 - b1
* b1_xor_b2 <= 2 - b1 - b2
* 0 <= b1_xor_b2 <= 1
* </pre>
* @param b1 An expression that should only take a binary value.
* @param b2 An expression that should only take a binary value.
* @param b1_xor_b2 Should be the logical exclusive or between `b1` and `b2`.
* @return The newly added constraints, such that when b1, b2, b1_xor_b2 satisfy
* the constraints, it is guaranteed that b1_xor_b2 = b1 ⊕ b2.
* @pre b1, b2, b1_xor_b2 are all linear expressions.
*/
[[nodiscard]] Binding<LinearConstraint> CreateLogicalXorConstraint(
const symbolic::Expression& b1, const symbolic::Expression& b2,
const symbolic::Expression& b1_xor_b2);
/** Create linear constraints such that, when these constraints are satisfied,
* match = 1 if and only if code == expected, otherwise match = 0
* @param code code(i) should only take binary values.
* @param expected The expected matched value for code.
* @param match an expression that takes binary value, representing if
* code == expected
* @return the linear constraints.
*
* This function is useful integer optimization, for example, if we have a
* constraint match = ((b1 == 0) && (b2 == 1) && (b3 == 1)), we can call the
* function CreateBinaryCodeMatchConstraint({b1, b2, b3}, {0, 1, 1}, match) to
* create the constraint.
*/
[[nodiscard]] Binding<LinearConstraint> CreateBinaryCodeMatchConstraint(
const VectorX<symbolic::Expression>& code,
const Eigen::Ref<const Eigen::VectorXi>& expected,
const symbolic::Expression& match);
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/equality_constrained_qp_solver.h | #pragma once
#include <string>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/solver_base.h"
namespace drake {
namespace solvers {
/**
* Solves a quadratic program with equality constraint.
*
* This program doesn't depend on the initial guess.
*
* The user can set the following options:
*
* - FeasibilityTolOptionName(). The feasible solution (both primal and dual
* variables) should satisfy their constraints, with error no larger than
* this value. The default is Eigen::dummy_precision().
*/
class EqualityConstrainedQPSolver final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(EqualityConstrainedQPSolver)
EqualityConstrainedQPSolver();
~EqualityConstrainedQPSolver() final;
/// @returns string key for SolverOptions to set the feasibility tolerance.
static std::string FeasibilityTolOptionName();
/// @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/sparse_and_dense_matrix.cc | #include "drake/solvers/sparse_and_dense_matrix.h"
#include <utility>
namespace drake {
namespace solvers {
namespace internal {
SparseAndDenseMatrix::SparseAndDenseMatrix(
const Eigen::SparseMatrix<double>& sparse)
: sparse_(sparse), dense_(0, 0) {}
SparseAndDenseMatrix::SparseAndDenseMatrix(Eigen::MatrixXd dense)
: sparse_(dense.sparseView()), dense_(std::move(dense)) {}
SparseAndDenseMatrix& SparseAndDenseMatrix::operator=(Eigen::MatrixXd dense) {
this->dense_ = std::move(dense);
this->sparse_ = this->dense_.sparseView();
return *this;
}
SparseAndDenseMatrix& SparseAndDenseMatrix::operator=(
const Eigen::SparseMatrix<double>& sparse) {
this->sparse_ = sparse;
this->dense_.resize(0, 0);
return *this;
}
SparseAndDenseMatrix::~SparseAndDenseMatrix() {}
const Eigen::MatrixXd& SparseAndDenseMatrix::GetAsDense() const {
if (is_dense_constructed()) {
return dense_;
} else {
// Modifies the dense_ field. For thread-safety, use a std::mutex.
std::lock_guard<std::mutex> guard(mutex_);
const_cast<SparseAndDenseMatrix*>(this)->dense_ = sparse_.toDense();
return dense_;
}
}
bool SparseAndDenseMatrix::IsFinite() const {
for (int k = 0; k < sparse_.outerSize(); ++k) {
for (Eigen::SparseMatrix<double>::InnerIterator it(sparse_, k); it; ++it) {
if (!std::isfinite(it.value())) {
return false;
}
}
}
return true;
}
bool SparseAndDenseMatrix::is_dense_constructed() const {
return dense_.size() != 0;
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/aggregate_costs_constraints.h | #pragma once
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "drake/solvers/binding.h"
#include "drake/solvers/constraint.h"
#include "drake/solvers/cost.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
/** Given many linear costs, aggregate them into
*
* aᵀ*x + b,
* @param linear_costs the linear costs to be aggregated.
* @param linear_coeff[out] a in the documentation above.
* @param vars[out] x in the documentation above.
* @param constant_cost[out] b in the documentation above.
*/
void AggregateLinearCosts(const std::vector<Binding<LinearCost>>& linear_costs,
Eigen::SparseVector<double>* linear_coeff,
VectorX<symbolic::Variable>* vars,
double* constant_cost);
/** Given many linear and quadratic costs, aggregate them into
*
* 0.5*x₁ᵀQx₁ + bᵀx₂ + c
* where x₁ and x₂ don't need to be the same.
* @param quadratic_costs The quadratic costs to be aggregated.
* @param linear_costs The linear costs to be aggregated.
* @param Q_lower[out] The lower triangular part of the matrix Q.
* @param quadratic_vars[out] x₁ in the documentation above.
* @param linear_coeff[out] b in the documentation above.
* @param linear_vars[out] x₂ in the documentation above.
* @param constant_cost[out] c in the documentation above.
*/
void AggregateQuadraticAndLinearCosts(
const std::vector<Binding<QuadraticCost>>& quadratic_costs,
const std::vector<Binding<LinearCost>>& linear_costs,
Eigen::SparseMatrix<double>* Q_lower,
VectorX<symbolic::Variable>* quadratic_vars,
Eigen::SparseVector<double>* linear_coeff,
VectorX<symbolic::Variable>* linear_vars, double* constant_cost);
/**
* Stores the lower and upper bound of a variable.
*/
struct Bound {
/** Lower bound. */
double lower{};
/** Upper bound. */
double upper{};
};
/**
* Aggregates many bounding box constraints, returns the intersection (the
* tightest bounds) of these constraints.
* @param bounding_box_constraints The constraints to be aggregated.
* @retval aggregated_bounds aggregated_bounds[var.get_id()] returns the
* (lower, upper) bounds of that variable as the tightest bounds of @p
* bounding_box_constraints.
*/
[[nodiscard]] std::unordered_map<symbolic::Variable, Bound>
AggregateBoundingBoxConstraints(
const std::vector<Binding<BoundingBoxConstraint>>&
bounding_box_constraints);
/**
* Aggregates all the BoundingBoxConstraints inside @p prog, returns the
* intersection of the bounding box constraints as the lower and upper bound for
* each variable in @p prog.
* @param prog The optimization program containing decision variables and
* BoundingBoxConstraints.
* @param[out] lower (*lower)[i] is the lower bound of
* prog.decision_variable(i).
* @param[out] upper (*upper)[i] is the upper bound of
* prog.decision_variable(i).
*/
void AggregateBoundingBoxConstraints(const MathematicalProgram& prog,
Eigen::VectorXd* lower,
Eigen::VectorXd* upper);
/**
* Overloads AggregateBoundingBoxConstraints, but the type of lower and upper
* are std::vector<double>.
*/
void AggregateBoundingBoxConstraints(const MathematicalProgram& prog,
std::vector<double>* lower,
std::vector<double>* upper);
/**
For linear expression A * vars where `vars` might contain duplicated entries,
rewrite this linear expression as A_new * vars_new where vars_new doesn't
contain duplicated entries.
*/
void AggregateDuplicateVariables(const Eigen::SparseMatrix<double>& A,
const VectorX<symbolic::Variable>& vars,
Eigen::SparseMatrix<double>* A_new,
VectorX<symbolic::Variable>* vars_new);
namespace internal {
// Returns the first non-convex quadratic cost among @p quadratic_costs. If all
// quadratic costs are convex, then return a nullptr.
[[nodiscard]] const Binding<QuadraticCost>* FindNonconvexQuadraticCost(
const std::vector<Binding<QuadraticCost>>& quadratic_costs);
// Returns the first non-convex quadratic constraint among @p
// quadratic_constraints. If all quadratic constraints are convex, then returns
// a nullptr.
[[nodiscard]] const Binding<QuadraticConstraint>*
FindNonconvexQuadraticConstraint(
const std::vector<Binding<QuadraticConstraint>>& quadratic_constraints);
// If the program is compatible with this solver (the solver meets the required
// capabilities of the program, and the program is convex), 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 CheckConvexSolverAttributes(const MathematicalProgram& prog,
const ProgramAttributes& solver_capabilities,
std::string_view solver_name,
std::string* explanation);
// Aggregates all prog.linear_costs(), such that the aggregated linear cost is
// ∑ᵢ (*c)[i] * prog.decision_variable(i) + *constant
// @note c and constant might not be zero. This function adds
// prog.linear_costs() to the coefficient c and constant.
// @pre c->size() >= prog.num_vars();
void ParseLinearCosts(const MathematicalProgram& prog, std::vector<double>* c,
double* constant);
// Parses all prog.linear_equality_constraints() to
// A*x = b
// Some convex solvers (like SCS and Clarabel) aggregates all constraints in the
// form of
// A*x + s = b
// s in K
// This function appends all prog.linear_equality_constraints() to the existing
// A*x+s=b.
// @param[in/out] A_triplets The triplets on the non-zero entries in A.
// prog.linear_equality_constraints() will be appended to A_triplets.
// @param[in/out] b The righthand side of A*x=b.
// prog.linear_equality_constraints() will be appended to b.
// @param[in/out] A_row_count The number of rows in A before and after calling
// this function.
// @param[out] linear_eq_y_start_indices 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.
// @param[out] num_linear_equality_constraints_rows The number of new rows
// appended to A*x+s=b in all prog.linear_equality_constraints(). Note
// num_linear_equality_constraints_rows is A_row_count AFTER calling this
// function minus A_row_count BEFORE calling this function.
void ParseLinearEqualityConstraints(
const solvers::MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<int>* linear_eq_y_start_indices,
int* num_linear_equality_constraints_rows);
// Parses all prog.linear_constraints() to
// A*x + s = b
// s in the nonnegative orthant cone.
// Some convex solvers (like SCS and Clarabel) aggregates all constraints in the
// form of
// A*x + s = b
// s in K
// This function appends all prog.linear_constraints() to the existing
// A*x+s=b.
// @param[in/out] A_triplets The triplets on the non-zero entries in A.
// prog.linear_constraints() will be appended to A_triplets.
// @param[in/out] b The righthand side of A*x+s=b.
// prog.linear_equality_constraints() will be appended to b.
// @param[in/out] A_row_count The number of rows in A before and after calling
// this function.
// @param[out] linear_constraint_dual_indices
// linear_constraint_dual_indices[i][j].first/linear_constraint_dual_indices[i][j].second
// 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.
// @param[out] num_linear_constraint_rows The number of new rows appended to
// A*x+s = b in all
// prog.linear_equality_constraints()
void ParseLinearConstraints(const solvers::MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets,
std::vector<double>* b, int* A_row_count,
std::vector<std::vector<std::pair<int, int>>>*
linear_constraint_dual_indices,
int* num_linear_constraint_rows);
// Aggregates all quadratic prog.quadratic_costs() and add the aggregated cost
// to 0.5*x'P*x + c'*x + constant. where x is prog.decision_variables().
void ParseQuadraticCosts(const MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* P_upper_triplets,
std::vector<double>* c, double* constant);
// Parse a L2NormCost |Cx+d|₂ to Clarabel/SCS format.
// We need to
// 1. Append a slack variable t.
// 2. Impose the constraint t >= |Cx+d|₂ as a Lorentz cone constraint.
// 3. Add the cost t.
// For the second step, we formulate it as
// [ 0 -1] * [x] + s = [0] (1)
// [-C 0] [t] [d]
// s is in Lorentz cone. (2)
// @param[in] prog We parse all prog.l2norm_costs().
// @param[in/out] num_solver_variables The number of variables in the solver
// before/after parsing this L2NormCost. The new slack variable t will be
// appended after the existing variables in the solver.
// @param[in/out] A_triplets We append the left hand side of the linear
// constraints (1) to A_triplets.
// @param[in/out] b We append the right hand side of the linear constraints (1)
// to b.
// @param[in/out] A_row_count The number of rows in A before/after appending the
// second order cone constraints.
// @param[in/out] second_order_cone_length The dimension of each second order
// cone in the overall program.
// @param[in/out] lorentz_cone_y_start_indices The starting indices of s in each
// Lorentz cone constraints, before/after calling this function. We append the
// indices of the dual variables for the Lorentz cone constraint to
// lorentz_cone_y_start_indices.
// @param[out] cost_coeffs The coefficient of each variable in the cost.
// @param[out] t_slack_indices The index of the new variable t in the solver
// (such as Clarabel or SCS, not in the MathematicalProgram object).
void ParseL2NormCosts(const MathematicalProgram& prog,
int* num_solver_variables,
std::vector<Eigen::Triplet<double>>* A_triplets,
std::vector<double>* b, int* A_row_count,
std::vector<int>* second_order_cone_length,
std::vector<int>* lorentz_cone_y_start_indices,
std::vector<double>* cost_coeffs,
std::vector<int>* t_slack_indices);
// Parse all second order cone constraints (including both Lorentz cone and
// rotated Lorentz cone constraint) to the form A*x+s=b, s in K where K is the
// Cartesian product of Lorentz cone {s | sqrt(s₁²+...+sₙ₋₁²) ≤ s₀}
// @param[in/out] A_triplets We append the second order cone constraints to
// A_triplets.
// @param[in/out] b We append the second order cone constraints to b.
// @param[in/out] The number of rows in A before/after appending the second
// order cone constraints.
// @param[out] second_order_cone_length The lengths of each second order cone s
// in K in the Cartesian product K.
// @param[out] lorentz_cone_y_start_indices 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].
// @param[out] rotated_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 we assume the Cartesian
// product K doesn't contain 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.
void ParseSecondOrderConeConstraints(
const MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<int>* second_order_cone_length,
std::vector<int>* lorentz_cone_y_start_indices,
std::vector<int>* rotated_lorentz_cone_y_start_indices);
// Add a rotated Lorentz cone constraint that A_cone * x + b_cone is in the
// rotated Lorentz cone.
//
// We add these rotated Lorentz cones in the form A*x+s=b and s in K, where K is
// the Cartesian product of Lorentz cones.
// @param A_cone_triplets The triplets of non-zero entries in A_cone.
// @param b_cone A_cone * x + b_cone is in the rotated Lorentz cone.
// @param x_indices The index of the variables.
// @param A_triplets[in/out] The non-zero entry triplet in A before and after
// adding the Lorentz cone.
// @param b[in/out] The right-hand side vector b before and after adding the
// Lorentz cone.
// @param A_row_count[in/out] The number of rows in A before and after adding
// the Lorentz cone.
// @param second_order_cone_length[in/out] The length of each Lorentz cone
// before and after adding the Lorentz cone constraint.
// @param rotated_lorentz_cone_y_start_indices[in/out] The starting index of y
// corresponds to this rotated Lorentz cone. If set to nullopt, then we don't
// modify rotated_lorentz_cone_y_start_indices.
void ParseRotatedLorentzConeConstraint(
const std::vector<Eigen::Triplet<double>>& A_cone_triplets,
const Eigen::Ref<const Eigen::VectorXd>& b_cone,
const std::vector<int>& x_indices,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<int>* second_order_cone_length,
std::optional<std::vector<int>*> rotated_lorentz_cone_y_start_indices);
// Parses all prog.exponential_cone_constraints() to
// A*x + s = b
// s in the exponential cone.
// Some convex solvers (like SCS and Clarabel) aggregates all constraints in the
// form of
// A*x + s = b
// s in K
// Note that the definition of SCS/Clarabel's exponential cone is different from
// Drake's definition. In SCS/Clarabel, a vector s is in the exponential cone if
// s₂≥ s₁*exp(s₀ / s₁). In Drake, a vector z is in the exponential cone if z₀ ≥
// z₁ * exp(z₂ / z₁). Note that the index 0 and 2 is swapped. This function
// appends all prog.exponential_cone_constraints() to the existing A*x+s=b.
// @param[in/out] A_triplets The triplets on the non-zero entries in A.
// prog.exponential_cone_constraints() will be appended to A_triplets.
// @param[in/out] b The righthand side of A*x+s=b.
// prog.exponential_cone_constraints() will be appended to b.
// @param[in/out] A_row_count The number of rows in A before and after calling
// this function.
void ParseExponentialConeConstraints(
const MathematicalProgram& prog,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count);
// This function parses prog.positive_semidefinite_constraints() and
// prog.linear_matrix_inequality_constraints() into SCS/Clarabel format.
// A * x + s = b
// s in K
// Note that the SCS/Clarabel solver defines its psd cone with a √2 scaling on
// the off-diagonal terms in the positive semidefinite matrix. Refer to
// https://www.cvxgrp.org/scs/api/cones.html#semidefinite-cones and
// https://oxfordcontrol.github.io/ClarabelDocs/stable/examples/example_sdp/ for
// an explanation.
// @param[in] upper_triangular Whether we use the upper triangular or lower
// triangular part of the symmetric matrix. SCS uses the lower triangular part,
// and Clarabel uses the upper triangular part.
// @param[in/out] A_triplets The triplets on the non-zero entries in A.
// prog.positive_semidefinite_constraints() and
// prog.linear_matrix_inequality_constraints() will be appended to A_triplets.
// @param[in/out] b The righthand side of A*x+s=b.
// prog.positive_semidefinite_constraints() and
// prog.linear_matrix_inequality_constraints() will be appended to b.
// @param[in/out] A_row_count The number of rows in A before and after calling
// this function.
// @param[out] psd_cone_length The length of all the psd cones from
// prog.positive_semidefinite_constraints() and
// prog.linear_matrix_inequality_constraints().
void ParsePositiveSemidefiniteConstraints(
const MathematicalProgram& prog, bool upper_triangular,
std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b,
int* A_row_count, std::vector<int>* psd_cone_length);
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mosek_solver.h | #pragma once
#include <memory>
#include <string>
#include <Eigen/Core>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/mathematical_program_result.h"
#include "drake/solvers/solver_base.h"
namespace drake {
namespace solvers {
/**
* The MOSEK™ solver details after calling Solve() function. The user can call
* MathematicalProgramResult::get_solver_details<MosekSolver>() to obtain the
* details.
*/
struct MosekSolverDetails {
/// The MOSEK™ optimization time. Please refer to MSK_DINF_OPTIMIZER_TIME in
/// https://docs.mosek.com/10.1/capi/constants.html?highlight=msk_dinf_optimizer_time
double optimizer_time{};
/// The response code returned from MOSEK™ solver. Check
/// https://docs.mosek.com/10.1/capi/response-codes.html for the meaning on
/// the response code.
int rescode{};
/// The solution status after solving the problem. Check
/// https://docs.mosek.com/10.1/capi/accessing-solution.html and
/// https://docs.mosek.com/10.1/capi/constants.html#mosek.solsta for the
/// meaning on the solution status.
int solution_status{};
};
// Note: we use ascii (TM) instead of the unicode symbol ™ in the first line
// because the first line is used for hover tooltips in the autogenerated
// doxygen links and was resulting in garbled text around all links to
// MosekSolver.
/**
* An implementation of SolverInterface for the commercially-licensed MOSEK
* (TM) solver (https://www.mosek.com/).
*
* Drake downloads and builds MOSEK™ automatically, but to enable it you must
* set the location of your license file as described in the documentation at
* https://drake.mit.edu/bazel.html#mosek.
*
* The MOSEKLM_LICENSE_FILE environment variable controls whether or not
* SolverInterface::enabled() returns true. Iff it is set to any non-empty
* value, then the solver is enabled; otherwise, the solver is not enabled.
*
* @note MOSEK™ only cares about the initial guess of integer variables. The
* initial guess of continuous variables are not passed to MOSEK™. If all the
* integer variables are set to some integer values, then MOSEK™ will be forced
* to compute the remaining continuous variable values as the initial guess.
* (MOSEK™ might change the values of the integer/binary variables in the
* subsequent iterations.) If the specified integer solution is infeasible or
* incomplete, MOSEK™ will simply ignore it. For more details, check
* https://docs.mosek.com/10.1/capi/tutorial-mio-shared.html?highlight=initial
*
* MOSEK™ supports many solver parameters. You can refer to the full list of
* parameters in
* https://docs.mosek.com/10.1/capi/param-groups.html#doc-param-groups. On top
* of these parameters, we also provide the following additional parameters
*
* - "writedata"
* set to a file name so that MOSEK™ solver will write the
* optimization model to this file. check
* https://docs.mosek.com/10.1/capi/solver-io.html#saving-a-problem-to-a-file
* for more details. The supported file extensions are listed in
* https://docs.mosek.com/10.1/capi/supported-file-formats.html#doc-shared-file-formats.
* Set this parameter to "" if you don't want to write to a file. Default is
* not to write to a file.
*/
class MosekSolver final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MosekSolver)
/// Type of details stored in MathematicalProgramResult.
using Details = MosekSolverDetails;
MosekSolver();
~MosekSolver() final;
/**
* This type contains a valid MOSEK license environment, and is only to be
* used from AcquireLicense().
*/
class License;
/**
* This acquires a MOSEK™ license environment shared among all MosekSolver
* instances; the environment will stay valid as long as at least one
* shared_ptr returned by this function is alive.
* Call this ONLY if you must use different MathematicalProgram
* instances at different instances in time, and repeatedly acquiring the
* license is costly (e.g., requires contacting a license server).
* @return A shared pointer to a license environment that will stay valid
* as long as any shared_ptr returned by this function is alive. If MOSEK™ is
* not available in your build, this will return a null (empty) shared_ptr.
* @throws std::exception if MOSEK™ is available but a license cannot be
* obtained.
*/
static std::shared_ptr<License> AcquireLicense();
/// @name Static versions of the instance methods with similar names.
//@{
static SolverId id();
static bool is_available();
/// Returns true iff the environment variable MOSEKLM_LICENSE_FILE has been
/// set to a non-empty value.
static bool is_enabled();
static bool ProgramAttributesSatisfied(const MathematicalProgram&);
static std::string UnsatisfiedProgramAttributes(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;
// Note that this is mutable to allow latching the allocation of mosek_env_
// during the first call of Solve() (which avoids grabbing a MOSEK™ license
// before we know that we actually want one).
mutable std::shared_ptr<License> license_;
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solver_base.cc | #include "drake/solvers/solver_base.h"
#include <limits>
#include <utility>
#include <fmt/format.h>
#include "drake/common/drake_assert.h"
#include "drake/common/nice_type_name.h"
namespace drake {
namespace solvers {
SolverBase::SolverBase(
const SolverId& id, std::function<bool()> available,
std::function<bool()> enabled,
std::function<bool(const MathematicalProgram&)> are_satisfied,
std::function<std::string(const MathematicalProgram&)> explain_unsatisfied)
: solver_id_(id),
default_available_(std::move(available)),
default_enabled_(std::move(enabled)),
default_are_satisfied_(std::move(are_satisfied)),
default_explain_unsatisfied_(std::move(explain_unsatisfied)) {}
SolverBase::~SolverBase() = default;
MathematicalProgramResult SolverBase::Solve(
const MathematicalProgram& prog,
const std::optional<Eigen::VectorXd>& initial_guess,
const std::optional<SolverOptions>& solver_options) const {
MathematicalProgramResult result;
this->Solve(prog, initial_guess, solver_options, &result);
return result;
}
namespace {
std::string ShortName(const SolverInterface& solver) {
return NiceTypeName::RemoveNamespaces(NiceTypeName::Get(solver));
}
} // namespace
void SolverBase::Solve(const MathematicalProgram& prog,
const std::optional<Eigen::VectorXd>& initial_guess,
const std::optional<SolverOptions>& solver_options,
MathematicalProgramResult* result) const {
*result = {};
if (!available()) {
const std::string name = ShortName(*this);
throw std::invalid_argument(fmt::format(
"{} cannot Solve because {}::available() is false, i.e.,"
" {} has not been compiled as part of this binary."
" Refer to the {} class overview documentation for how to compile it.",
name, name, name, name));
}
if (!enabled()) {
const std::string name = ShortName(*this);
throw std::invalid_argument(fmt::format(
"{} cannot Solve because {}::enabled() is false, i.e.,"
" {} has not been properly configured for use."
" Typically this means that an environment variable has not been set."
" Refer to the {} class overview documentation for how to enable it.",
name, name, name, name));
}
if (!AreProgramAttributesSatisfied(prog)) {
throw std::invalid_argument(ExplainUnsatisfiedProgramAttributes(prog));
}
result->set_solver_id(solver_id());
result->set_decision_variable_index(prog.decision_variable_index());
const Eigen::VectorXd& x_init =
initial_guess ? *initial_guess : prog.initial_guess();
if (x_init.rows() != prog.num_vars()) {
throw std::invalid_argument(
fmt::format("Solve expects initial guess of size {}, got {}.",
prog.num_vars(), x_init.rows()));
}
if (!solver_options) {
DoSolve(prog, x_init, prog.solver_options(), result);
} else {
SolverOptions merged_options = *solver_options;
merged_options.Merge(prog.solver_options());
DoSolve(prog, x_init, merged_options, result);
}
}
bool SolverBase::available() const {
DRAKE_DEMAND(default_available_ != nullptr);
return default_available_();
}
bool SolverBase::enabled() const {
DRAKE_DEMAND(default_enabled_ != nullptr);
return default_enabled_();
}
bool SolverBase::AreProgramAttributesSatisfied(
const MathematicalProgram& prog) const {
DRAKE_DEMAND(default_are_satisfied_ != nullptr);
return default_are_satisfied_(prog);
}
std::string SolverBase::ExplainUnsatisfiedProgramAttributes(
const MathematicalProgram& prog) const {
if (default_explain_unsatisfied_ != nullptr) {
return default_explain_unsatisfied_(prog);
}
if (AreProgramAttributesSatisfied(prog)) {
return {};
}
return fmt::format("{} is unable to solve a MathematicalProgram with {}.",
ShortName(*this), to_string(prog.required_capabilities()));
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/integer_optimization_util.cc | #include "drake/solvers/integer_optimization_util.h"
#include "drake/solvers/binding.h"
#include "drake/solvers/create_constraint.h"
namespace drake {
namespace solvers {
Binding<LinearConstraint> CreateLogicalAndConstraint(
const symbolic::Expression& b1, const symbolic::Expression& b2,
const symbolic::Expression& b1_and_b2) {
return internal::BindingDynamicCast<LinearConstraint>(
// clang-format off
internal::ParseConstraint(b1_and_b2 >= b1 + b2 - 1 &&
b1_and_b2 <= b1 &&
b1_and_b2 <= b2 &&
0 <= b1_and_b2 &&
b1_and_b2 <= 1));
// clang-format on
}
Binding<LinearConstraint> CreateLogicalOrConstraint(
const symbolic::Expression& b1, const symbolic::Expression& b2,
const symbolic::Expression& b1_or_b2) {
return internal::BindingDynamicCast<LinearConstraint>(
// clang-format off
internal::ParseConstraint(b1_or_b2 <= b1 + b2 &&
b1_or_b2 >= b1 &&
b1_or_b2 >= b2 &&
0 <= b1_or_b2 &&
b1_or_b2 <= 1));
// clang-format on
}
Binding<LinearConstraint> CreateLogicalXorConstraint(
const symbolic::Expression& b1, const symbolic::Expression& b2,
const symbolic::Expression& b1_xor_b2) {
return internal::BindingDynamicCast<LinearConstraint>(
// clang-format off
internal::ParseConstraint(b1_xor_b2 <= b1 + b2 &&
b1_xor_b2 >= b1 - b2 &&
b1_xor_b2 >= b2 - b1 &&
b1_xor_b2 <= 2 - b1 - b2 &&
0 <= b1_xor_b2 &&
b1_xor_b2 <= 1));
// clang-format on
}
Binding<LinearConstraint> CreateBinaryCodeMatchConstraint(
const VectorX<symbolic::Expression>& code,
const Eigen::Ref<const Eigen::VectorXi>& expected,
const symbolic::Expression& match) {
DRAKE_ASSERT(code.rows() == expected.rows());
// match_element(i) = 1 <=> code(i) = expected(i).
// We then take the conjunction
// match = match_element(0) && match_element(1) && ... && match_element(n)
// This conjunction can be transformed to the following constraints
// match >= match_element(0) + match_element(1) + ... + match_element(n) - n
// match <= match_element(i) ∀i
// 0 <= match <= 1
VectorX<symbolic::Expression> match_element(code.rows());
symbolic::Formula f = match >= 0 && match <= 1;
for (int i = 0; i < code.rows(); ++i) {
// match_element(i) = 1 iff code(i) == expected(i)
if (expected(i) == 1) {
match_element(i) = code(i);
} else if (expected(i) == 0) {
match_element(i) = 1 - code(i);
} else {
throw std::logic_error("expected should only contain either 0 or 1.");
}
f = f && match <= match_element(i);
}
f = f && match >= match_element.sum() - (code.rows() - 1);
return internal::BindingDynamicCast<LinearConstraint>(
internal::ParseConstraint(f));
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/rotation_constraint.cc | #include "drake/solvers/rotation_constraint.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include "drake/common/symbolic/expression.h"
using drake::symbolic::Expression;
using Eigen::MatrixXi;
using Eigen::VectorXd;
using std::numeric_limits;
namespace drake {
namespace solvers {
MatrixDecisionVariable<3, 3> NewRotationMatrixVars(MathematicalProgram* prog,
const std::string& name) {
MatrixDecisionVariable<3, 3> R = prog->NewContinuousVariables<3, 3>(name);
// Forall i,j, -1 <= R(i,j) <=1.
prog->AddBoundingBoxConstraint(-1, 1, R);
// -1 <= trace(R) <= 3.
// Proof sketch:
// orthonormal => |lambda_i|=1.
// R is real => eigenvalues either real or appear in complex conj pairs.
// Case 1: All real (lambda_i \in {-1,1}).
// det(R)=lambda_1*lambda_2*lambda_3=1 => lambda_1=lambda_2, lambda_3=1.
// Case 2: Two imaginary, pick conj(lambda_1) = lambda_2.
// => lambda_1*lambda_2 = 1. => lambda_3 = 1.
// and also => lambda_1 + lambda_2 = 2*Re(lambda_1) \in [-2,2].
prog->AddLinearConstraint(Eigen::RowVector3d::Ones(), -1, 3, R.diagonal());
return R;
}
void AddBoundingBoxConstraintsImpliedByRollPitchYawLimits(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
RollPitchYawLimits limits) {
// Based on the RPY to Rotation Matrix conversion:
// [ cp*cy, cy*sp*sr - cr*sy, sr*sy + cr*cy*sp]
// [ cp*sy, cr*cy + sp*sr*sy, cr*sp*sy - cy*sr]
// [ -sp, cp*sr, cp*cr]
// where cz = cos(z) and sz = sin(z), and using
// kRoll_NegPI_2_to_PI_2 = 1 << 1, // => cos(r)>=0
// kRoll_0_to_PI = 1 << 2, // => sin(r)>=0
// kPitch_NegPI_2_to_PI_2 = 1 << 3, // => cos(p)>=0
// kPitch_0_to_PI = 1 << 4, // => sin(p)>=0
// kYaw_NegPI_2_to_PI_2 = 1 << 5, // => cos(y)>=0
// kYaw_0_to_PI = 1 << 6, // => sin(y)>=0
if ((limits & kPitch_NegPI_2_to_PI_2) && (limits & kYaw_NegPI_2_to_PI_2))
prog->AddBoundingBoxConstraint(0, 1, R(0, 0));
if ((limits & kPitch_NegPI_2_to_PI_2) && (limits & kYaw_0_to_PI))
prog->AddBoundingBoxConstraint(0, 1, R(1, 0));
if (limits & kPitch_0_to_PI) prog->AddBoundingBoxConstraint(-1, 0, R(2, 0));
if ((limits & kRoll_NegPI_2_to_PI_2) && (limits & kYaw_NegPI_2_to_PI_2) &&
(limits & kPitch_0_to_PI) && (limits & kRoll_0_to_PI) &&
(limits & kYaw_0_to_PI))
prog->AddBoundingBoxConstraint(0, 1, R(1, 1));
if ((limits & kPitch_NegPI_2_to_PI_2) && (limits & kRoll_0_to_PI))
prog->AddBoundingBoxConstraint(0, 1, R(2, 1));
if ((limits & kRoll_0_to_PI) && (limits & kYaw_0_to_PI) &&
(limits & kRoll_NegPI_2_to_PI_2) && (limits & kYaw_NegPI_2_to_PI_2) &&
(limits & kPitch_0_to_PI))
prog->AddBoundingBoxConstraint(0, 1, R(0, 2));
if ((limits & kPitch_NegPI_2_to_PI_2) && (limits & kRoll_NegPI_2_to_PI_2))
prog->AddBoundingBoxConstraint(0, 1, R(2, 2));
}
void AddBoundingBoxConstraintsImpliedByRollPitchYawLimitsToBinary(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& B,
RollPitchYawLimits limits) {
if ((limits & kPitch_NegPI_2_to_PI_2) && (limits & kYaw_NegPI_2_to_PI_2))
prog->AddBoundingBoxConstraint(1, 1, B(0, 0));
if ((limits & kPitch_NegPI_2_to_PI_2) && (limits & kYaw_0_to_PI))
prog->AddBoundingBoxConstraint(1, 1, B(1, 0));
if (limits & kPitch_0_to_PI) prog->AddBoundingBoxConstraint(0, 0, B(2, 0));
if ((limits & kRoll_NegPI_2_to_PI_2) && (limits & kYaw_NegPI_2_to_PI_2) &&
(limits & kPitch_0_to_PI) && (limits & kRoll_0_to_PI) &&
(limits & kYaw_0_to_PI))
prog->AddBoundingBoxConstraint(1, 1, B(1, 1));
if ((limits & kPitch_NegPI_2_to_PI_2) && (limits & kRoll_0_to_PI))
prog->AddBoundingBoxConstraint(1, 1, B(2, 1));
if ((limits & kRoll_0_to_PI) && (limits & kYaw_0_to_PI) &&
(limits & kRoll_NegPI_2_to_PI_2) && (limits & kYaw_NegPI_2_to_PI_2) &&
(limits & kPitch_0_to_PI))
prog->AddBoundingBoxConstraint(1, 1, B(0, 2));
if ((limits & kPitch_NegPI_2_to_PI_2) && (limits & kRoll_NegPI_2_to_PI_2))
prog->AddBoundingBoxConstraint(1, 1, B(2, 2));
}
void AddRotationMatrixSpectrahedralSdpConstraint(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R) {
// Equation 10 in
// Semidefinite descriptions of the convex hull of rotation matrices
// by James Saunderson, Pablo Parrilo and Alan Willsky
Matrix4<symbolic::Expression> M;
// clang-format off
M << 1 - R(0, 0) - R(1, 1) + R(2, 2), R(0, 2) + R(2, 0), R(0, 1) - R(1, 0), R(1, 2) + R(2, 1), // #NOLINT
R(0, 2) + R(2, 0), 1 + R(0, 0) - R(1, 1) - R(2, 2), R(1, 2) - R(2, 1), R(0, 1) + R(1, 0), // #NOLINT
R(0, 1) - R(1, 0), R(1, 2) - R(2, 1), 1 + R(0, 0) + R(1, 1) + R(2, 2), R(2, 0) - R(0, 2), // #NOLINT
R(1, 2) + R(2, 1), R(0, 1) + R(1, 0), R(2, 0) - R(0, 2), 1 - R(0, 0) + R(1, 1) - R(2, 2); // #NOLINT
// clang-format on
prog->AddPositiveSemidefiniteConstraint(M);
}
namespace {
void AddOrthogonalConstraint(
MathematicalProgram* prog,
const Eigen::Ref<const VectorDecisionVariable<3>>& v1,
const Eigen::Ref<const VectorDecisionVariable<3>>& v2) {
// We do this by introducing
// |v1+v2|^2 = v1'v1 + 2v1'v2 + v2'v2 <= 2
// |v1-v2|^2 = v1'v1 - 2v1'v2 + v2'v2 <= 2
// This is tight when v1'v1 = 1 and v2'v2 = 1.
// TODO(russt): Consider generalizing this to |v1+alpha*v2|^2 <= 1+alpha^2,
// for any real-valued alpha. When |R1|<|R2|<=1 or |R2|<|R1|<=1,
// different alphas represent different constraints.
// |v1+v2|^2 <= 2
// Implemented as a Lorenz cone using z = [ sqrt(2); v1+v2 ].
Vector4<symbolic::Expression> z;
z << std::sqrt(2), v1 + v2;
prog->AddLorentzConeConstraint(z);
// |v1-v2|^2 <= 2
// Implemented as a Lorenz cone using z = [ sqrt(2); v1-v2 ].
z.tail<3>() = v1 - v2;
prog->AddLorentzConeConstraint(z);
}
} // namespace
void AddRotationMatrixOrthonormalSocpConstraint(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R) {
// All columns should be unit length (but we can only write Ri'Ri<=1),
// implemented as a rotated Lorenz cone with z = Ax+b = [1;1;R.col(i)].
Eigen::Matrix<double, 5, 3> A = Eigen::Matrix<double, 5, 3>::Zero();
A.bottomRows<3>() = Eigen::Matrix3d::Identity();
Eigen::Matrix<double, 5, 1> b;
b << 1, 1, 0, 0, 0;
for (int i = 0; i < 3; i++) {
prog->AddRotatedLorentzConeConstraint(A, b, R.col(i));
prog->AddRotatedLorentzConeConstraint(A, b, R.row(i).transpose());
}
AddOrthogonalConstraint(prog, R.col(0), R.col(1)); // R0'*R1 = 0.
AddOrthogonalConstraint(prog, R.col(1), R.col(2)); // R1'*R2 = 0.
AddOrthogonalConstraint(prog, R.col(0), R.col(2)); // R0'*R2 = 0.
// Same for the rows
AddOrthogonalConstraint(prog, R.row(0).transpose(), R.row(1).transpose());
AddOrthogonalConstraint(prog, R.row(1).transpose(), R.row(2).transpose());
AddOrthogonalConstraint(prog, R.row(0).transpose(), R.row(2).transpose());
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/osqp_solver_common.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/osqp_solver.h"
/* clang-format on */
#include "drake/common/never_destroyed.h"
#include "drake/solvers/aggregate_costs_constraints.h"
#include "drake/solvers/mathematical_program.h"
// This file contains implementations that are common to both the available and
// unavailable flavor of this class.
namespace drake {
namespace solvers {
OsqpSolver::OsqpSolver()
: SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied,
&UnsatisfiedProgramAttributes) {}
OsqpSolver::~OsqpSolver() = default;
SolverId OsqpSolver::id() {
static const never_destroyed<SolverId> singleton{"OSQP"};
return singleton.access();
}
bool OsqpSolver::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::kLinearCost, ProgramAttribute::kQuadraticCost,
ProgramAttribute::kLinearConstraint,
ProgramAttribute::kLinearEqualityConstraint});
const ProgramAttributes& required_capabilities = prog.required_capabilities();
const bool capabilities_match = AreRequiredAttributesSupported(
required_capabilities, solver_capabilities.access(), explanation);
if (!capabilities_match) {
if (explanation) {
*explanation = fmt::format("OsqpSolver is unable to solve because {}.",
*explanation);
}
return false;
}
if (!required_capabilities.contains(ProgramAttribute::kQuadraticCost)) {
if (explanation) {
*explanation =
"OsqpSolver is unable to solve because a QuadraticCost is required"
" but has not been declared; OSQP works best with a quadratic cost."
" Please use a different solver such as CLP (for linear programming)"
" or IPOPT/SNOPT (for nonlinear programming) if you don't want to add"
" a quadratic cost to this program.";
}
return false;
}
const Binding<QuadraticCost>* nonconvex_quadratic_cost =
internal::FindNonconvexQuadraticCost(prog.quadratic_costs());
if (nonconvex_quadratic_cost != nullptr) {
if (explanation) {
*explanation =
"OsqpSolver is unable to solve because the quadratic cost " +
nonconvex_quadratic_cost->to_string() +
" is non-convex. Either change this cost to a convex one, or switch "
"to a different solver like SNOPT/IPOPT/NLOPT.";
}
return false;
}
if (explanation) {
explanation->clear();
}
return true;
}
} // namespace
bool OsqpSolver::ProgramAttributesSatisfied(const MathematicalProgram& prog) {
return CheckAttributes(prog, nullptr);
}
std::string OsqpSolver::UnsatisfiedProgramAttributes(
const MathematicalProgram& prog) {
std::string explanation;
CheckAttributes(prog, &explanation);
return explanation;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/semidefinite_relaxation.h | #pragma once
#include <memory>
#include <vector>
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
// TODO(russt): Add an option for using diagonal dominance and/or
// scaled-diagonal dominance instead of the PSD constraint.
// TODO(russt): Consider adding Y as an optional argument return value, to help
// users know the decision variables associated with Y.
/** Constructs a new MathematicalProgram which represents the semidefinite
programming convex relaxation of the (likely nonconvex) program `prog`. This
method currently supports only linear and quadratic costs and constraints, but
may be extended in the future with broader support.
See https://underactuated.mit.edu/optimization.html#sdp_relaxation for
references and examples.
Note: Currently, programs using LinearEqualityConstraint will give tighter
relaxations than programs using LinearConstraint or BoundingBoxConstraint,
even if lower_bound == upper_bound. Prefer LinearEqualityConstraint.
@throws std::exception if `prog` has costs and constraints which are not
linear nor quadratic.
*/
std::unique_ptr<MathematicalProgram> MakeSemidefiniteRelaxation(
const MathematicalProgram& prog);
/** A version of MakeSemidefiniteRelaxation that allows for specifying the
* sparsity of the relaxation.
*
* For each group in @p variable_groups, the costs and constraints whose
* variables are a subset of the group will be jointly relaxed into a single,
* dense semidefinite program in the same manner as
* MakeSemidefiniteRelaxation(prog).
*
* Each of these semidefinite relaxations are aggregated into a
* single program, and their semidefinite variables are made to agree where the
* variable groups overlap.
*
* The returned program will always have the same number of PSD variables as
* variable groups.
*
* Costs and constraints whose variables are not a subset of any of the groups
* are not relaxed and are simply added to the aggregated program. If these
* costs and constraints are non-convex, then this method will throw.
*
* As an example, consider the following program.
* min x₂ᵀ * Q * x₂ subject to
* x₁ + x₂ ≤ 1
* x₂ + x₃ ≤ 2
* x₁ + x₃ ≤ 3
*
* And suppose we call
* MakeSemidefiniteRelaxation(prog, std::vector<Variables>{{x₁, x₂}, {x₂,x₃}}).
*
* The resulting relaxation would have two semidefinite variables, namely:
* [U₁, U₂, x₁] [W₁, W₂, x₂]
* [U₂, U₃, x₂], [W₂, W₃, x₃]
* [x₁ᵀ, x₂ᵀ, 1] [x₂ᵀ, x₃ᵀ, 1]
*
* The first semidefinite variable would be associated to the semidefinite
* relaxation of the subprogram:
* min x₁ᵀ * Q * x₁ subject to
* x₁ + x₂ ≤ 1
* And the implied constraints from x₁ + x₂ ≤ 1 would be added to the first
* semidefinite variable. These implied constraints are additional constraints
* that can be placed on the matrix
* [U₁, U₂, x₁]
* [U₂, U₃, x₂]
* [x₁ᵀ, x₂ᵀ, 1]
* which are redundant in the non-convex program, but are not redundant in the
* semidefinite relaxation. See
* https://underactuated.mit.edu/optimization.html#sdp_relaxation for references
* and examples.
*
* The second semidefinite variable would be associated to the semidefinite
* relaxation of the subprogram:
* min x₂ᵀ * Q * x₂ subject to
* x₂ + x₃ ≤ 2
* And the implied constraints from x₂ + x₃ ≤ 2 would be added to the second
* semidefinite variable.
*
* Since the constraint x₁ + x₃ ≤ 3 is not a subset of any of the variable
* groups, it will be added to the overall relaxation, but will not be used to
* generate implied constraints on any semidefinite variable.
*
* The total relaxation would also include an equality constraint that U₃ == W₁
* so that the quadratic relaxation of x₂ is consistent between the two
* semidefinite variables.
*
* Note:
* 1) Costs are only associated to a single variable group, so that the
* resulting aggregated program has a relaxed cost with the same scaling.
* 2) The homogenization variable "1" is re-used in every semidefinite variable.
*
* @throw std::exception if there is a non-convex cost or constraint whose
* variables do not intersect with any of the variable groups.
*/
std::unique_ptr<MathematicalProgram> MakeSemidefiniteRelaxation(
const MathematicalProgram& prog,
const std::vector<symbolic::Variables>& variable_groups);
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/cost.cc | #include "drake/solvers/cost.h"
#include <memory>
#include "drake/common/symbolic/latex.h"
#include "drake/math/autodiff_gradient.h"
#include "drake/math/differentiable_norm.h"
#include "drake/solvers/constraint.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::make_shared;
using std::shared_ptr;
namespace drake {
namespace solvers {
namespace {
std::ostream& DisplayCost(const Cost& cost, std::ostream& os,
const std::string& name,
const VectorX<symbolic::Variable>& vars) {
os << name;
// Append the expression.
VectorX<symbolic::Expression> e;
cost.Eval(vars, &e);
DRAKE_DEMAND(e.size() == 1);
os << " " << e[0];
// Append the description (when provided).
const std::string& description = cost.get_description();
if (!description.empty()) {
os << " described as '" << description << "'";
}
return os;
}
std::string ToLatexCost(const Cost& cost,
const VectorX<symbolic::Variable>& vars,
int precision) {
VectorX<symbolic::Expression> e;
cost.Eval(vars, &e);
DRAKE_DEMAND(e.size() == 1);
std::string latex = symbolic::ToLatex(e[0], precision);
return latex;
}
} // namespace
template <typename DerivedX, typename U>
void LinearCost::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<U>* y) const {
y->resize(1);
(*y)(0) = a_.dot(x) + b_;
}
void LinearCost::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void LinearCost::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void LinearCost::DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& LinearCost::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayCost(*this, os, "LinearCost", vars);
}
std::string LinearCost::DoToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const {
return ToLatexCost(*this, vars, precision);
}
template <typename DerivedX, typename U>
void QuadraticCost::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<U>* y) const {
y->resize(1);
*y = .5 * x.transpose() * Q_ * x + b_.transpose() * x;
(*y)(0) += c_;
}
void QuadraticCost::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void QuadraticCost::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
// Specialized evaluation of cost and gradient
const MatrixXd dx = math::ExtractGradient(x);
const Eigen::VectorXd x_val = drake::math::ExtractValue(x);
const Eigen::RowVectorXd xT_times_Q = x_val.transpose() * Q_;
const Vector1d result(.5 * xT_times_Q.dot(x_val) + b_.dot(x_val) + c_);
const Eigen::RowVectorXd dy = xT_times_Q + b_.transpose();
// If dx is the identity matrix (very common here), then skip the chain rule
// multiplication dy * dx
if (dx.rows() == x.size() && dx.cols() == x.size() &&
dx == MatrixXd::Identity(x.size(), x.size())) {
*y = math::InitializeAutoDiff(result, dy);
} else {
*y = math::InitializeAutoDiff(result, dy * dx);
}
}
void QuadraticCost::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& QuadraticCost::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayCost(*this, os, "QuadraticCost", vars);
}
std::string QuadraticCost::DoToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const {
return ToLatexCost(*this, vars, precision);
}
bool QuadraticCost::CheckHessianPsd() {
Eigen::LDLT<Eigen::MatrixXd> ldlt_solver;
ldlt_solver.compute(Q_);
return ldlt_solver.isPositive();
}
shared_ptr<QuadraticCost> MakeQuadraticErrorCost(
const Eigen::Ref<const MatrixXd>& Q,
const Eigen::Ref<const VectorXd>& x_desired) {
const double c = x_desired.dot(Q * x_desired);
return make_shared<QuadraticCost>(2 * Q, -2 * Q * x_desired, c);
}
shared_ptr<QuadraticCost> Make2NormSquaredCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b) {
const double c = b.dot(b);
return make_shared<QuadraticCost>(2 * A.transpose() * A,
-2 * A.transpose() * b, c,
true /* Hessian is psd */);
}
L1NormCost::L1NormCost(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b)
: Cost(A.cols()), A_(A), b_(b) {
DRAKE_DEMAND(A_.rows() == b_.rows());
}
void L1NormCost::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != A_.cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
if (new_A.rows() != new_b.rows()) {
throw std::runtime_error("A and b must have the same number of rows.");
}
A_ = new_A;
b_ = new_b;
}
void L1NormCost::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
y->resize(1);
(*y)(0) = (A_ * x + b_).lpNorm<1>();
}
void L1NormCost::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
y->resize(1);
(*y)(0) = (A_ * x + b_).lpNorm<1>();
}
void L1NormCost::DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
y->resize(1);
(*y)(0) = (A_ * x + b_).cwiseAbs().sum();
}
std::ostream& L1NormCost::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayCost(*this, os, "L1NormCost", vars);
}
std::string L1NormCost::DoToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const {
return fmt::format("\\left|{}\\right|_1",
symbolic::ToLatex((A_ * vars + b_).eval(), precision));
}
L2NormCost::L2NormCost(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b)
: Cost(A.cols()), A_(A), b_(b) {
DRAKE_DEMAND(A_.get_as_sparse().rows() == b_.rows());
}
L2NormCost::L2NormCost(const Eigen::SparseMatrix<double>& A,
const Eigen::Ref<const Eigen::VectorXd>& b)
: Cost(A.cols()), A_(A), b_(b) {
DRAKE_DEMAND(A_.get_as_sparse().rows() == b_.rows());
}
void L2NormCost::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != A_.get_as_sparse().cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
if (new_A.rows() != new_b.rows()) {
throw std::runtime_error("A and b must have the same number of rows.");
}
A_ = new_A;
b_ = new_b;
}
void L2NormCost::UpdateCoefficients(
const Eigen::SparseMatrix<double>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != A_.get_as_sparse().cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
if (new_A.rows() != new_b.rows()) {
throw std::runtime_error("A and b must have the same number of rows.");
}
A_ = new_A;
b_ = new_b;
}
void L2NormCost::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
y->resize(1);
(*y)(0) = (A_.GetAsDense() * x + b_).norm();
}
void L2NormCost::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
y->resize(1);
(*y)(0) = math::DifferentiableNorm(A_.GetAsDense() * x + b_);
}
void L2NormCost::DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
y->resize(1);
(*y)(0) = sqrt((A_.GetAsDense() * x + b_).squaredNorm());
}
std::ostream& L2NormCost::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayCost(*this, os, "L2NormCost", vars);
}
std::string L2NormCost::DoToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const {
return fmt::format(
"\\left|{}\\right|_2",
symbolic::ToLatex((A_.GetAsDense() * vars + b_).eval(), precision));
}
LInfNormCost::LInfNormCost(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b)
: Cost(A.cols()), A_(A), b_(b) {
DRAKE_DEMAND(A_.rows() == b_.rows());
}
void LInfNormCost::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != A_.cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
if (new_A.rows() != new_b.rows()) {
throw std::runtime_error("A and b must have the same number of rows.");
}
A_ = new_A;
b_ = new_b;
}
void LInfNormCost::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
y->resize(1);
(*y)(0) = (A_ * x + b_).lpNorm<Eigen::Infinity>();
}
void LInfNormCost::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
y->resize(1);
(*y)(0) = (A_ * x + b_).lpNorm<Eigen::Infinity>();
}
void LInfNormCost::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
y->resize(1);
(*y)(0) = (A_ * x + b_).cwiseAbs().maxCoeff();
}
std::ostream& LInfNormCost::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayCost(*this, os, "LInfNormCost", vars);
}
std::string LInfNormCost::DoToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const {
return fmt::format("\\left|{}\\right|_\\infty",
symbolic::ToLatex((A_ * vars + b_).eval(), precision));
}
PerspectiveQuadraticCost::PerspectiveQuadraticCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b)
: Cost(A.cols()), A_(A), b_(b) {
DRAKE_DEMAND(A_.rows() >= 2);
DRAKE_DEMAND(A_.rows() == b_.rows());
}
void PerspectiveQuadraticCost::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != A_.cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
if (new_A.rows() != new_b.rows()) {
throw std::runtime_error("A and b must have the same number of rows.");
}
A_ = new_A;
b_ = new_b;
}
template <typename DerivedX, typename U>
void PerspectiveQuadraticCost::DoEvalGeneric(
const Eigen::MatrixBase<DerivedX>& x, VectorX<U>* y) const {
y->resize(1);
VectorX<U> z = A_ * x.template cast<U>() + b_;
(*y)(0) = z.tail(z.size() - 1).squaredNorm() / z(0);
}
void PerspectiveQuadraticCost::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void PerspectiveQuadraticCost::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void PerspectiveQuadraticCost::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& PerspectiveQuadraticCost::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayCost(*this, os, "PerspectiveQuadraticCost", vars);
}
std::string PerspectiveQuadraticCost::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
return ToLatexCost(*this, vars, precision);
}
ExpressionCost::ExpressionCost(const symbolic::Expression& e)
: Cost(e.GetVariables().size()),
/* We reuse the Constraint evaluator's implementation. */
evaluator_(std::make_unique<ExpressionConstraint>(
Vector1<symbolic::Expression>{e},
/* The ub, lb are unused but still required. */
Vector1d(0.0), Vector1d(0.0))) {}
const VectorXDecisionVariable& ExpressionCost::vars() const {
return dynamic_cast<const ExpressionConstraint&>(*evaluator_).vars();
}
const symbolic::Expression& ExpressionCost::expression() const {
return dynamic_cast<const ExpressionConstraint&>(*evaluator_)
.expressions()
.coeffRef(0);
}
void ExpressionCost::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
evaluator_->Eval(x, y);
}
void ExpressionCost::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
evaluator_->Eval(x, y);
}
void ExpressionCost::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
evaluator_->Eval(x, y);
}
std::ostream& ExpressionCost::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayCost(*this, os, "ExpressionCost", vars);
}
std::string ExpressionCost::DoToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const {
return ToLatexCost(*this, vars, precision);
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/get_program_type.h | #pragma once
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
/** Returns the type of the optimization program (LP, QP, etc), based on the
* properties of its cost/constraints/variables.
* Each mathematical program should be characterized by a unique type. If a
* program can be characterized as either type A or type B (for example, a
* program with linear constraint and linear costs can be characterized as
* either an LP or an SDP), then we choose the type corresponding to a smaller
* set of programs (LP in this case).
*/
[[nodiscard]] ProgramType GetProgramType(const MathematicalProgram& prog);
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/sos_basis_generator.cc | #include "drake/solvers/sos_basis_generator.h"
#include <vector>
#include <Eigen/Core>
#include "drake/solvers/integer_inequality_solver.h"
namespace drake {
namespace solvers {
namespace {
// Anonymous namespace containing collection of utility functions
using Variable = symbolic::Variable;
using Monomial = symbolic::Monomial;
using Variables = symbolic::Variables;
using MonomialVector = VectorX<symbolic::Monomial>;
using Exponent = Eigen::RowVectorXi;
using ExponentList = Eigen::Matrix<int, -1, -1, Eigen::RowMajor>;
// Given a list of exponents and variables, returns a vector of monomials.
// Ex: if exponents = [0, 1;1, 2], and vars = [x(0), x(1)], then the vector
// [x(1); x(0)* x(1)²] is returned.
MonomialVector ExponentsToMonomials(const ExponentList& exponents,
const drake::VectorX<Variable>& vars) {
MonomialVector monomials(exponents.rows());
for (int i = 0; i < exponents.rows(); i++) {
monomials(i) = Monomial(vars, exponents.row(i));
}
return monomials;
}
// Returns a list of all exponents that appear in a polynomial p.
// E.g., given p = 1 + 2x₀² + 3x₀*x₁², returns [0, 0; 2, 0; 1, 2];
ExponentList GetPolynomialExponents(const drake::symbolic::Polynomial& p) {
const Variables& indeterminates{p.indeterminates()};
ExponentList exponents(p.monomial_to_coefficient_map().size(),
indeterminates.size());
int row = 0;
for (const auto& m : p.monomial_to_coefficient_map()) {
int col = 0;
for (const auto& var : indeterminates) {
exponents(row, col++) = m.first.degree(var);
}
row++;
}
return exponents;
}
ExponentList VerticalStack(const ExponentList& A, const ExponentList& B) {
DRAKE_ASSERT(A.cols() == B.cols());
if (A.rows() == 0) {
return B;
}
if (B.rows() == 0) {
return A;
}
ExponentList Y(A.rows() + B.rows(), B.cols());
Y << A, B;
return Y;
}
ExponentList PairwiseSums(const ExponentList& exponents) {
int n = exponents.rows();
ExponentList sums((n * n - n) / 2, exponents.cols());
int cnt = 0;
for (int i = 0; i < n; i++) {
// Note: counter starts at i+1 to omit a+b when a = b.
for (int j = i + 1; j < n; j++) {
sums.row(cnt++) = exponents.row(i) + exponents.row(j);
}
}
return sums;
}
// Returns true if the first num_rows of A contains B.
bool ContainsExponent(const ExponentList& A, int num_rows, const Exponent& B) {
DRAKE_ASSERT(B.rows() == 1 && B.cols() == A.cols());
DRAKE_ASSERT((num_rows >= 0) && (num_rows <= A.rows()));
for (int i = 0; i < num_rows; i++) {
if (A.row(i) == B) {
return true;
}
}
return false;
}
/* Intersection(A, B) removes duplicate rows from B and any row that doesn't
* also appear in A. For example, given A = [1, 0; 0, 1; 1, 1] and B = [1, 0;
* 1, 1; 1, 1;], it overwrites B with [1, 0; 1, 1]. */
void Intersection(const ExponentList& A, ExponentList* B) {
DRAKE_ASSERT(A.cols() == B->cols());
int index = 0;
for (int i = 0; i < B->rows(); i++) {
if ((ContainsExponent(A, A.rows(), B->row(i))) &&
!(ContainsExponent(*B, index, B->row(i)))) {
B->row(index++) = B->row(i);
}
}
B->conservativeResize(index, Eigen::NoChange);
}
/* Removes exponents of the monomials that aren't diagonally-consistent with
* respect to the polynomial p and the given monomial basis. A monomial is
* diagonally-consistent if its square appears in p, or its square equals a
* product of monomials in the basis; see, e.g., "Pre- and Post-Processing
* Sum-of-Squares Programs in Practice Johan Löfberg, IEEE Transactions on
* Automatic Control, 2009." After execution, all exponents of inconsistent
* monomials are removed from exponents_of_basis.
*/
void RemoveDiagonallyInconsistentExponents(const ExponentList& exponents_of_p,
ExponentList* exponents_of_basis) {
while (1) {
int num_exponents = exponents_of_basis->rows();
ExponentList valid_squares =
VerticalStack(PairwiseSums(*exponents_of_basis), exponents_of_p);
(*exponents_of_basis) = (*exponents_of_basis) * 2;
Intersection(valid_squares, exponents_of_basis);
(*exponents_of_basis) = (*exponents_of_basis) / 2;
if (exponents_of_basis->rows() == num_exponents) {
break;
}
}
return;
}
struct Hyperplanes {
Eigen::MatrixXi normal_vectors; // Each row contains a normal vector.
Eigen::VectorXi max_dot_product;
Eigen::VectorXi min_dot_product;
};
// Finding random supporting hyperplanes of 1/2 P, where P is the Newton
// polytope of the polynomial p (i.e., the convex hull of its exponents).
Hyperplanes RandomSupportingHyperplanes(const ExponentList& exponents_of_p,
unsigned int seed) {
Hyperplanes H;
// get_random() samples uniformly between normal_vector_component_min/max.
// Current values of min and max set heuristically.
const int normal_vector_component_min = -10;
const int normal_vector_component_max = 10;
std::default_random_engine generator(seed);
std::uniform_int_distribution<int> distribution(normal_vector_component_min,
normal_vector_component_max);
auto get_random = [&]() {
return distribution(generator);
};
// Number of hyperplanes currently picked heuristically.
int num_hyperplanes = 10 * exponents_of_p.cols();
H.normal_vectors = Eigen::MatrixXi(num_hyperplanes, exponents_of_p.cols());
for (int i = 0; i < H.normal_vectors.cols(); i++) {
H.normal_vectors.col(i)
<< Eigen::VectorXi::NullaryExpr(num_hyperplanes, get_random);
}
Eigen::MatrixXi dot_products = H.normal_vectors * exponents_of_p.transpose();
H.max_dot_product = dot_products.rowwise().maxCoeff() / 2;
H.min_dot_product = dot_products.rowwise().minCoeff() / 2;
return H;
}
// Generates the supporting hyperplanes of the Newton polytope that
// are induced by the total degree ordering.
Hyperplanes DegreeInducedHyperplanes(const ExponentList& exponents_of_p) {
Hyperplanes H;
// The hyperplane for total degree.
H.normal_vectors.resize(1, exponents_of_p.cols());
H.normal_vectors.setConstant(1);
Eigen::MatrixXi dot_products = H.normal_vectors * exponents_of_p.transpose();
H.max_dot_product = dot_products.rowwise().maxCoeff() / 2;
H.min_dot_product = dot_products.rowwise().minCoeff() / 2;
return H;
}
ExponentList EnumerateInitialSet(const ExponentList& exponents_of_p) {
Eigen::VectorXi lower_bounds = exponents_of_p.colwise().minCoeff() / 2;
Eigen::VectorXi upper_bounds = exponents_of_p.colwise().maxCoeff() / 2;
Hyperplanes hyperplanes = DegreeInducedHyperplanes(exponents_of_p);
// We check the inequalities in two batches to allow for internal
// infeasibility propagation inside of EnumerateIntegerSolutions,
// which is done only if A has a column that is elementwise nonnegative
// or nonpositive. (This condition never holds if we check the
// inequalities in one batch, since A = [normal_vectors;-normal_vectors].)
ExponentList basis_exponents_1 = drake::solvers::EnumerateIntegerSolutions(
hyperplanes.normal_vectors, hyperplanes.max_dot_product, lower_bounds,
upper_bounds);
ExponentList basis_exponents = drake::solvers::EnumerateIntegerSolutions(
-hyperplanes.normal_vectors, -hyperplanes.min_dot_product, lower_bounds,
upper_bounds);
Intersection(basis_exponents_1, &basis_exponents);
return basis_exponents;
}
// This function removes an element alpha from "basis" if a randomly generated
// hyperplane separates 2*alpha from the Newton polytope of the polynomial p.
// Note that this function is actually deterministic since the seed for
// the random number generator is set to predetermined constants.
void RemoveWithRandomSeparatingHyperplanes(const ExponentList& exponents_of_p,
ExponentList* basis) {
// Declare this outside the main loop to avoid repeated dynamic memory
// allocation.
Eigen::MatrixXi dot_products;
int random_seed = 0;
while (1) {
int next_basis_size = 0;
int current_basis_size = basis->rows();
auto H = RandomSupportingHyperplanes(exponents_of_p, random_seed++);
// Remove monomials that the hyperplanes separate from the
// Newton polytope.
dot_products = (*basis) * H.normal_vectors.transpose();
for (int i = 0; i < current_basis_size; i++) {
bool keep_monomial = true;
for (int j = 0; j < dot_products.cols(); j++) {
if (dot_products(i, j) > H.max_dot_product(j) ||
dot_products(i, j) < H.min_dot_product(j)) {
keep_monomial = false;
break;
}
}
if (keep_monomial) {
basis->row(next_basis_size++) = basis->row(i);
}
}
basis->conservativeResize(next_basis_size, basis->cols());
// Quit if the basis is now empty or if its size wasn't reduced
// enough.
constexpr double kMinimumPercentReduction = .1;
if (next_basis_size >
current_basis_size * (1.0 - kMinimumPercentReduction) ||
next_basis_size == 0) {
break;
}
}
return;
}
ExponentList ConstructMonomialBasis(const ExponentList& exponents_of_p) {
auto basis_exponents = EnumerateInitialSet(exponents_of_p);
RemoveWithRandomSeparatingHyperplanes(exponents_of_p, &basis_exponents);
RemoveDiagonallyInconsistentExponents(exponents_of_p, &basis_exponents);
return basis_exponents;
}
} // namespace
MonomialVector ConstructMonomialBasis(const drake::symbolic::Polynomial& p) {
const Variables& indeterminates{p.indeterminates()};
if (indeterminates.empty()) {
// p is a constant.
return Vector1<Monomial>(Monomial());
}
drake::VectorX<Variable> vars(indeterminates.size());
int cnt = 0;
for (auto& var : indeterminates) {
vars(cnt++) = var;
}
auto polynomial_exponents = GetPolynomialExponents(p);
auto basis_exponents = ConstructMonomialBasis(polynomial_exponents);
auto monomial_basis = ExponentsToMonomials(basis_exponents, vars);
return monomial_basis;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/get_program_type.cc | #include "drake/solvers/get_program_type.h"
#include <initializer_list>
#include <vector>
#include "drake/common/never_destroyed.h"
#include "drake/solvers/program_attribute.h"
namespace drake {
namespace solvers {
namespace {
// The requirements of a type of optimization program based on its attributes.
// The requirements are that the program attributes
// 1. is a subset of @p acceptable_attributes.
// 2. must include all of @p must_include_attributes.
// 3. must include at least one of @p must_include_one_of.
// If must_include_one_of is empty, then we ignore this condition.
struct Requirements {
ProgramAttributes acceptable;
ProgramAttributes must_include;
ProgramAttributes must_include_one_of;
};
// Check if @p program_attributes satisfies @p requirements.
bool SatisfiesProgramType(const Requirements& requirements,
const ProgramAttributes& program_attributes) {
// Check if program_attributes is a subset of acceptable_attributes
for (const auto attribute : program_attributes) {
if (!requirements.acceptable.contains(attribute)) {
return false;
}
}
// Check if program_attributes include must_include_attributes
for (const auto& must_include_attr : requirements.must_include) {
if (!program_attributes.contains(must_include_attr)) {
return false;
}
}
bool include_one_of = requirements.must_include_one_of.empty() ? true : false;
for (const auto& include : requirements.must_include_one_of) {
if (program_attributes.contains(include)) {
include_one_of = true;
break;
}
}
if (!include_one_of) {
return false;
}
return true;
}
const Requirements& GetRequirementsLP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
ProgramAttributes attributes{std::initializer_list<ProgramAttribute>{
ProgramAttribute::kLinearCost, ProgramAttribute::kLinearConstraint,
ProgramAttribute::kLinearEqualityConstraint}};
return Requirements{.acceptable = attributes,
.must_include = {},
.must_include_one_of = attributes};
}()};
return requirements.access();
}
const Requirements& GetRequirementsQP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
const Requirements& lp_requirements = GetRequirementsLP();
ProgramAttributes acceptable = lp_requirements.acceptable;
acceptable.emplace(ProgramAttribute::kQuadraticCost);
return Requirements{.acceptable = acceptable,
.must_include = {ProgramAttribute::kQuadraticCost},
.must_include_one_of = {}};
}()};
return requirements.access();
}
const Requirements& GetRequirementsSOCP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
const Requirements& lp_requirements = GetRequirementsLP();
ProgramAttributes acceptable = lp_requirements.acceptable;
acceptable.emplace(ProgramAttribute::kLorentzConeConstraint);
acceptable.emplace(ProgramAttribute::kRotatedLorentzConeConstraint);
return Requirements{.acceptable = acceptable,
.must_include = {},
.must_include_one_of = {
ProgramAttribute::kLorentzConeConstraint,
ProgramAttribute::kRotatedLorentzConeConstraint}};
}()};
return requirements.access();
}
const Requirements& GetRequirementsSDP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
const Requirements& socp_requirements = GetRequirementsSOCP();
ProgramAttributes acceptable = socp_requirements.acceptable;
acceptable.emplace(ProgramAttribute::kPositiveSemidefiniteConstraint);
return Requirements{
.acceptable = acceptable,
.must_include = {ProgramAttribute::kPositiveSemidefiniteConstraint},
.must_include_one_of = {}};
}()};
return requirements.access();
}
const Requirements& GetRequirementsGP() {
static const drake::never_destroyed<Requirements> requirements{Requirements{
.acceptable = {ProgramAttribute::kLinearCost,
ProgramAttribute::kExponentialConeConstraint},
.must_include = {ProgramAttribute::kExponentialConeConstraint},
.must_include_one_of = {}}};
return requirements.access();
}
const Requirements& GetRequirementsCGP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
const Requirements& sdp_requirements = GetRequirementsSDP();
ProgramAttributes acceptable = sdp_requirements.acceptable;
acceptable.emplace(ProgramAttribute::kExponentialConeConstraint);
ProgramAttributes must_include_one_of = sdp_requirements.acceptable;
must_include_one_of.erase(ProgramAttribute::kLinearCost);
return Requirements{
.acceptable = acceptable,
.must_include = {ProgramAttribute::kExponentialConeConstraint},
.must_include_one_of = must_include_one_of};
}()};
return requirements.access();
}
const Requirements& GetRequirementsQuadraticCostConicProgram() {
static const drake::never_destroyed<Requirements> requirements{[]() {
const Requirements& cgp_requirements = GetRequirementsCGP();
ProgramAttributes acceptable = cgp_requirements.acceptable;
acceptable.emplace(ProgramAttribute::kQuadraticCost);
return Requirements{.acceptable = acceptable,
.must_include = {ProgramAttribute::kQuadraticCost},
.must_include_one_of = {
// All nonlinear convex conic constraints.
ProgramAttribute::kLorentzConeConstraint,
ProgramAttribute::kRotatedLorentzConeConstraint,
ProgramAttribute::kPositiveSemidefiniteConstraint,
ProgramAttribute::kExponentialConeConstraint}};
}()};
return requirements.access();
}
const Requirements& GetRequirementsLCP() {
static const drake::never_destroyed<Requirements> requirements{Requirements{
.acceptable = {ProgramAttribute::kLinearComplementarityConstraint},
.must_include = {ProgramAttribute::kLinearComplementarityConstraint},
.must_include_one_of = {}}};
return requirements.access();
}
// Returns the requirements of a mixed-integer optimization program.
// Append kBinaryVariable to acceptable and must_include.
// Retain must_include_one_of.
Requirements MixedIntegerRequirements(
const Requirements& continuous_requirements) {
Requirements mip_requirements = continuous_requirements;
mip_requirements.acceptable.emplace(ProgramAttribute::kBinaryVariable);
mip_requirements.must_include.emplace(ProgramAttribute::kBinaryVariable);
return mip_requirements;
}
const Requirements& GetRequirementsMILP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
return MixedIntegerRequirements(GetRequirementsLP());
}()};
return requirements.access();
}
const Requirements& GetRequirementsMIQP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
return MixedIntegerRequirements(GetRequirementsQP());
}()};
return requirements.access();
}
const Requirements& GetRequirementsMISOCP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
return MixedIntegerRequirements(GetRequirementsSOCP());
}()};
return requirements.access();
}
const Requirements& GetRequirementsMISDP() {
static const drake::never_destroyed<Requirements> requirements{[]() {
return MixedIntegerRequirements(GetRequirementsSDP());
}()};
return requirements.access();
}
bool AllQuadraticCostsConvex(
const std::vector<Binding<QuadraticCost>>& quadratic_costs) {
return std::all_of(quadratic_costs.begin(), quadratic_costs.end(),
[](const Binding<QuadraticCost>& quadratic_cost) {
return quadratic_cost.evaluator()->is_convex();
});
}
bool IsNLP(const MathematicalProgram& prog) {
// A program is a nonlinear program (NLP) if it satisfies all the following
// conditions:
// 1. It has no binary variables.
// 2. It is not an LCP (A program with only linear complementarity
// constraints).
// 3. It has at least one of : generic costs, generic constraints, non-convex
// quadratic cost, linear complementarity constraints, quadratic constraints.
const bool has_generic_cost =
prog.required_capabilities().contains(ProgramAttribute::kGenericCost);
const bool has_nonconvex_quadratic_cost =
!AllQuadraticCostsConvex(prog.quadratic_costs());
const bool has_generic_constraint = prog.required_capabilities().contains(
ProgramAttribute::kGenericConstraint);
const bool has_quadratic_constraint =
prog.required_capabilities().count(
ProgramAttribute::kQuadraticConstraint) > 0;
const bool no_binary_variable = prog.required_capabilities().count(
ProgramAttribute::kBinaryVariable) == 0;
const bool has_linear_complementarity_constraint =
prog.required_capabilities().count(
ProgramAttribute::kLinearComplementarityConstraint) > 0;
const bool is_LCP =
SatisfiesProgramType(GetRequirementsLCP(), prog.required_capabilities());
return no_binary_variable && !is_LCP &&
(has_generic_cost || has_nonconvex_quadratic_cost ||
has_generic_constraint || has_quadratic_constraint ||
has_linear_complementarity_constraint);
}
} // namespace
ProgramType GetProgramType(const MathematicalProgram& prog) {
if (SatisfiesProgramType(GetRequirementsLP(), prog.required_capabilities())) {
return ProgramType::kLP;
} else if (SatisfiesProgramType(GetRequirementsQP(),
prog.required_capabilities()) &&
AllQuadraticCostsConvex(prog.quadratic_costs())) {
return ProgramType::kQP;
} else if (SatisfiesProgramType(GetRequirementsSOCP(),
prog.required_capabilities())) {
return ProgramType::kSOCP;
} else if (SatisfiesProgramType(GetRequirementsSDP(),
prog.required_capabilities())) {
return ProgramType::kSDP;
} else if (SatisfiesProgramType(GetRequirementsGP(),
prog.required_capabilities())) {
// TODO(hongkai.dai): support more general type of geometric programming,
// with constraints on posynomials.
return ProgramType::kGP;
} else if (SatisfiesProgramType(GetRequirementsCGP(),
prog.required_capabilities())) {
return ProgramType::kCGP;
} else if (SatisfiesProgramType(GetRequirementsMILP(),
prog.required_capabilities())) {
return ProgramType::kMILP;
} else if (SatisfiesProgramType(GetRequirementsMIQP(),
prog.required_capabilities()) &&
AllQuadraticCostsConvex(prog.quadratic_costs())) {
return ProgramType::kMIQP;
} else if (SatisfiesProgramType(GetRequirementsMISOCP(),
prog.required_capabilities())) {
return ProgramType::kMISOCP;
} else if (SatisfiesProgramType(GetRequirementsMISDP(),
prog.required_capabilities())) {
return ProgramType::kMISDP;
} else if (SatisfiesProgramType(GetRequirementsQuadraticCostConicProgram(),
prog.required_capabilities()) &&
AllQuadraticCostsConvex(prog.quadratic_costs())) {
return ProgramType::kQuadraticCostConicConstraint;
} else if (SatisfiesProgramType(GetRequirementsLCP(),
prog.required_capabilities())) {
return ProgramType::kLCP;
} else if (IsNLP(prog)) {
return ProgramType::kNLP;
} else {
return ProgramType::kUnknown;
}
DRAKE_UNREACHABLE();
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/scs_clarabel_common.cc | #include "drake/solvers/scs_clarabel_common.h"
#include "drake/common/ssize.h"
namespace drake {
namespace solvers {
namespace internal {
void SetDualSolution(
const MathematicalProgram& prog,
const Eigen::Ref<const Eigen::VectorXd>& dual,
const std::vector<std::vector<std::pair<int, int>>>&
linear_constraint_dual_indices,
const std::vector<int>& linear_eq_y_start_indices,
const std::vector<int>& lorentz_cone_y_start_indices,
const std::vector<int>& rotated_lorentz_cone_y_start_indices,
MathematicalProgramResult* result) {
for (int i = 0; i < ssize(prog.linear_constraints()); ++i) {
Eigen::VectorXd lin_con_dual = Eigen::VectorXd::Zero(
prog.linear_constraints()[i].evaluator()->num_constraints());
for (int j = 0; j < lin_con_dual.rows(); ++j) {
if (linear_constraint_dual_indices[i][j].first != -1) {
// lower bound is not infinity.
// The shadow price for the lower bound is positive. SCS and Clarabel
// dual for the positive cone is also positive, so we add the
// SCS/Clarabel dual.
lin_con_dual[j] += dual(linear_constraint_dual_indices[i][j].first);
}
if (linear_constraint_dual_indices[i][j].second != -1) {
// upper bound is not infinity.
// The shadow price for the upper bound is negative. SCS and Clarabel
// dual for the positive cone is positive, so we subtract the
// SCS/Clarabel dual.
lin_con_dual[j] -= dual(linear_constraint_dual_indices[i][j].second);
}
}
result->set_dual_solution(prog.linear_constraints()[i], lin_con_dual);
}
for (int i = 0;
i < static_cast<int>(prog.linear_equality_constraints().size()); ++i) {
// Notice that we have a negative sign in front of y.
// This is because in SCS/Clarabel, for a problem with the linear equality
// constraint
// min cᵀx
// s.t A*x=b
// SCS/Clarabel formulates the dual problem as
// max -bᵀy
// s.t Aᵀy = -c
// Note that there is a negation sign before b and c in SCS/Clarabel dual
// problem, which is different from the standard formulation (no negation
// sign). Hence the dual variable y for the linear equality constraint is
// the negation of the shadow price.
result->set_dual_solution(
prog.linear_equality_constraints()[i],
-dual.segment(linear_eq_y_start_indices[i],
prog.linear_equality_constraints()[i]
.evaluator()
->num_constraints()));
}
for (int i = 0; i < static_cast<int>(prog.lorentz_cone_constraints().size());
++i) {
result->set_dual_solution(
prog.lorentz_cone_constraints()[i],
dual.segment(
lorentz_cone_y_start_indices[i],
prog.lorentz_cone_constraints()[i].evaluator()->A().rows()));
}
for (int i = 0;
i < static_cast<int>(prog.rotated_lorentz_cone_constraints().size());
++i) {
// SCS/Clarabel doesn't provide rotated Lorentz cone constraint, it only
// supports Lorentz cone constraint. Hence if Drake says "x in rotated
// Lorentz cone constraint", we then take a linear transformation xbar = C*x
// such that xbar is in the Lorentz cone constraint. By duality we know that
// if y is the dual variable for the Lorentz cone constraint, then Cᵀy is
// the dual variable for the rotated Lorentz cone constraint. The linear
// transformation is C = [0.5 0.5 0 0 ... 0]
// [0.5 -0.5 0 0 ... 0]
// [ 0 0 1 0 ... 0]
// [ 0 0 0 1 ... 0]
// ...
// [ 0 0 0 0 ... 1]
// Namely if x is in the rotated Lorentz cone, then
// [(x₀+x₁)/2, (x₀ − x₁)/2, x₂, ..., xₙ₋₁] is in the Lorentz cone.
// Note that C = Cᵀ
const auto& lorentz_cone_dual = dual.segment(
rotated_lorentz_cone_y_start_indices[i],
prog.rotated_lorentz_cone_constraints()[i].evaluator()->A().rows());
Eigen::VectorXd rotated_lorentz_cone_dual = lorentz_cone_dual;
rotated_lorentz_cone_dual(0) =
(lorentz_cone_dual(0) + lorentz_cone_dual(1)) / 2;
rotated_lorentz_cone_dual(1) =
(lorentz_cone_dual(0) - lorentz_cone_dual(1)) / 2;
result->set_dual_solution(prog.rotated_lorentz_cone_constraints()[i],
rotated_lorentz_cone_dual);
}
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/minimum_value_constraint.h | #pragma once
#include <functional>
#include <utility>
#include <vector>
#include "drake/solvers/constraint.h"
namespace drake {
namespace solvers {
/** Computes the penalty function φ(x) and its derivatives dφ(x)/dx. Valid
penalty functions must meet the following criteria:
1. φ(x) ≥ 0 ∀ x ∈ ℝ.
2. dφ(x)/dx ≤ 0 ∀ x ∈ ℝ.
3. φ(x) = 0 ∀ x ≥ 0.
4. dφ(x)/dx < 0 ∀ x < 0.
If `dpenalty_dx` is nullptr, the function should only compute φ(x). */
using MinimumValuePenaltyFunction =
std::function<void(double x, double* penalty, double* dpenalty_dx)>;
/** A hinge loss function smoothed by exponential function. This loss
function is differentiable everywhere. The formulation is described in
section II.C of [2].
The penalty is
<pre class="unicode-art">
⎧ 0 if x ≥ 0
φ(x) = ⎨
⎩ -x exp(1/x) if x < 0.
</pre>
[2] "Whole-body Motion Planning with Centroidal Dynamics and Full
Kinematics" by Hongkai Dai, Andres Valenzuela and Russ Tedrake, IEEE-RAS
International Conference on Humanoid Robots, 2014. */
void ExponentiallySmoothedHingeLoss(double x, double* penalty,
double* dpenalty_dx);
/** A linear hinge loss, smoothed with a quadratic loss near the origin. The
formulation is in equation (6) of [1].
The penalty is
<pre class="unicode-art">
⎧ 0 if x ≥ 0
φ(x) = ⎨ x²/2 if -1 < x < 0
⎩ -0.5 - x if x ≤ -1.
</pre>
[1] "Loss Functions for Preference Levels: Regression with Discrete Ordered
Labels." by Jason Rennie and Nathan Srebro, Proceedings of IJCAI
multidisciplinary workshop on Advances in Preference Handling. */
void QuadraticallySmoothedHingeLoss(double x, double* penalty,
double* dpenalty_dx);
/** Constrain min(v) >= lb where v=f(x). Namely all elements of the
vector `v` returned by the user-provided function f(x) to be no smaller than a
specified value `lb`.
The formulation of the constraint is
<pre>
SmoothOverMax( φ((vᵢ - v_influence)/(v_influence - lb)) / φ(-1) ) ≤ 1
</pre>
where vᵢ is the i-th value returned by the user-provided function, `lb` is
the minimum allowable value. v_influence is the "influence value" (the
value below which an element influences the constraint or, conversely, the
value above which an element is ignored), φ is a
solvers::MinimumValuePenaltyFunction, and SmoothOverMax(v) is a smooth, over
approximation of max(v) (i.e. SmoothOverMax(v) >= max(v), for all v). We
require that lb < v_influence. The input scaling (vᵢ -
v_influence)/(v_influence - lb) ensures that at the boundary of the feasible
set (when vᵢ == lb), we evaluate the penalty function at -1, where it is
required to have a non-zero gradient. The user-provided function may return a
vector with up to `max_num_values` elements. If it returns a vector with fewer
than `max_num_values` elements, the remaining elements are assumed to be
greater than the "influence value". */
class MinimumValueLowerBoundConstraint final : public solvers::Constraint {
public:
/** Constructs a MinimumValueLowerBoundConstraint.
min(v) >= lb
And we set ub to infinity in min(v) <= ub.
@param num_vars The number of inputs to `value_function`
@param minimum_value The minimum allowed value, lb, for all elements
of the vector returned by `value_function`.
@param influence_value_offset The difference between the
influence value, v_influence, and the minimum value, lb (see class
documentation). This value must be finite and strictly positive, as it is
used to scale the values returned by `value_function`. Smaller values may
decrease the amount of computation required for each constraint evaluation
if `value_function` can quickly determine that some elements will be larger
than the influence value and skip the computation associated with those
elements.
@param max_num_values The maximum number of elements in the vector returned
by `value_function`.
@param value_function User-provided function that takes a `num_vars`-element
vector and the influence distance as inputs and returns a vector with up to
`max_num_values` elements. The function can omit from the return vector any
elements larger than the provided influence distance.
@param value_function_double Optional user-provide function that computes
the same values as `value_function` but for double rather than AutoDiffXd.
If omitted, `value_function` will be called (and the gradients discarded)
when this constraint is evaluated for doubles.
@pre `value_function_double(ExtractValue(x), v_influence) ==
ExtractValue(value_function(x, v_influence))` for all x.
@pre `value_function(x).size() <= max_num_values` for all x.
@throws std::exception if influence_value_offset = ∞.
@throws std::exception if influence_value_offset ≤ 0.
*/
MinimumValueLowerBoundConstraint(
int num_vars, double minimum_value_lower, double influence_value_offset,
int max_num_values,
std::function<AutoDiffVecXd(const Eigen::Ref<const AutoDiffVecXd>&,
double)>
value_function,
std::function<VectorX<double>(const Eigen::Ref<const VectorX<double>>&,
double)>
value_function_double = {});
~MinimumValueLowerBoundConstraint() override {}
/** Getter for the lower bound on the minimum value. */
double minimum_value_lower() const { return minimum_value_lower_; }
/** Getter for the influence value. */
double influence_value() const { return influence_value_; }
/** Getter for maximum number of values expected from value_function. */
int max_num_values() const { return max_num_values_; }
/** Setter for the penalty function. */
void set_penalty_function(MinimumValuePenaltyFunction new_penalty_function);
private:
template <typename T>
void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x,
VectorX<T>* y) const;
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const override {
throw std::logic_error(
"MinimumValueLowerBoundConstraint::DoEval() does not work for "
"symbolic "
"variables.");
}
std::function<AutoDiffVecXd(const AutoDiffVecXd&, double)> value_function_;
std::function<VectorX<double>(const VectorX<double>&, double)>
value_function_double_;
const double minimum_value_lower_;
const double influence_value_;
/** Stores the value of
1 / φ((vₘᵢₙ - v_influence)/(v_influence - vₘᵢₙ)) = 1 / φ(-1). This is
used to scale the output of the penalty function to be 1 when v == vₘᵢₙ. */
double penalty_output_scaling_;
const int max_num_values_{};
MinimumValuePenaltyFunction penalty_function_{};
};
/** Constrain min(v) <= ub where v=f(x). Namely at least one element of the
vector `v` returned by the user-provided function f(x) to be no larger than a
specified value `ub`.
The formulation of the constraint is
<pre>
SmoothUnderMax( φ((vᵢ - v_influence)/(v_influence - ub)) / φ(-1) ) ≥ 1
</pre>
where vᵢ is the i-th value returned by the user-provided function, `ub` is the
upper bound for the min(v). (Note that `ub` is NOT the upper bound of `v`).
v_influence is the "influence value" (the value below which an element
influences the constraint or, conversely, the value above which an element is
ignored), φ is a solvers::MinimumValuePenaltyFunction. SmoothUnderMax(x) is a
smooth, under approximation of max(v) (i.e. SmoothUnderMax(v) <= max(v) for
all v). We require that ub < v_influence. The input scaling (vᵢ -
v_influence)/(v_influence - ub) ensures that at the boundary of the feasible
set (when vᵢ == ub), we evaluate the penalty function at -1, where it is
required to have a non-zero gradient. The user-provided function may return a
vector with up to `max_num_values` elements. If it returns a vector with fewer
than `max_num_values` elements, the remaining elements are assumed to be
greater than the "influence value". */
class MinimumValueUpperBoundConstraint final : public solvers::Constraint {
public:
/** Constructs a MinimumValueUpperBoundConstraint.
min(v) <= ub
@param num_vars The number of inputs to `value_function`
@param minimum_value_upper The upper bound on the minimum allowed value for
all elements of the vector returned by `value_function`, namely
min(value_function(x)) <= minimum_value_upper
@param influence_value_offset The difference between the
influence value, v_influence, and minimum_value_upper. This value must be
finite and strictly positive, as it is used to scale the values returned by
`value_function`. Larger values may increase the possibility of finding a
solution to the constraint. With a small v_influence, the value_function
will ignore the entries with value less than v_influence. While it is
possible that by changing x, that value (that currently been ignored) can
decrease to below ub with a different x, by using a small v_influence, the
gradient of that entry is never considered if the entry is ignored. We
strongly suggest using a larger `v_influence` compared to the one used in
MinimumValueConstraint when constraining min(v) >= lb.
@param max_num_values The maximum number of elements in the vector returned
by `value_function`.
@param value_function User-provided function that takes a `num_vars`-element
vector and the influence distance as inputs and returns a vector with up to
`max_num_values` elements. The function can omit from the return vector any
elements larger than the provided influence distance.
@param value_function_double Optional user-provide function that computes
the same values as `value_function` but for double rather than AutoDiffXd.
If omitted, `value_function` will be called (and the gradients discarded)
when this constraint is evaluated for doubles.
@pre `value_function_double(ExtractValue(x), v_influence) ==
ExtractValue(value_function(x, v_influence))` for all x.
@pre `value_function(x).size() <= max_num_values` for all x.
@throws std::exception if influence_value_offset = ∞.
@throws std::exception if influence_value_offset ≤ 0.
*/
MinimumValueUpperBoundConstraint(
int num_vars, double minimum_value_upper, double influence_value_offset,
int max_num_values,
std::function<AutoDiffVecXd(const Eigen::Ref<const AutoDiffVecXd>&,
double)>
value_function,
std::function<VectorX<double>(const Eigen::Ref<const VectorX<double>>&,
double)>
value_function_double = {});
~MinimumValueUpperBoundConstraint() override {}
/** Getter for the upper bound on the minimum value. */
double minimum_value_upper() const { return minimum_value_upper_; }
/** Getter for the influence value. */
double influence_value() const { return influence_value_; }
/** Getter for maximum number of values expected from value_function. */
int max_num_values() const { return max_num_values_; }
/** Setter for the penalty function. */
void set_penalty_function(MinimumValuePenaltyFunction new_penalty_function);
private:
template <typename T>
void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x,
VectorX<T>* y) const;
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const override {
throw std::logic_error(
"MinimumValueUpperBoundConstraint::DoEval() does not work for "
"symbolic "
"variables.");
}
std::function<AutoDiffVecXd(const AutoDiffVecXd&, double)> value_function_;
std::function<VectorX<double>(const VectorX<double>&, double)>
value_function_double_;
const double minimum_value_upper_;
const double influence_value_;
/** Stores the value of
1 / φ((vₘᵢₙ - v_influence)/(v_influence - vₘᵢₙ)) = 1 / φ(-1). This is
used to scale the output of the penalty function to be 1 when v == vₘᵢₙ. */
double penalty_output_scaling_;
const int max_num_values_{};
MinimumValuePenaltyFunction penalty_function_{};
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mixed_integer_rotation_constraint_internal.cc | #include "drake/solvers/mixed_integer_rotation_constraint_internal.h"
#include <algorithm>
#include <array>
#include <limits>
#include "drake/common/drake_assert.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/solve.h"
namespace drake {
namespace solvers {
namespace internal {
namespace {
// Given two coordinates, find the (positive) third coordinate on that
// intersects with the unit circle.
double Intercept(double x, double y) {
DRAKE_ASSERT(x * x + y * y <= 1);
return std::sqrt(1 - x * x - y * y);
}
} // namespace
std::vector<Eigen::Vector3d> ComputeBoxEdgesAndSphereIntersection(
const Eigen::Vector3d& bmin, const Eigen::Vector3d& bmax) {
// Assumes the positive orthant (and bmax > bmin).
DRAKE_ASSERT(bmin(0) >= 0 && bmin(1) >= 0 && bmin(2) >= 0);
DRAKE_ASSERT(bmax(0) > bmin(0) && bmax(1) > bmin(1) && bmax(2) > bmin(2));
// Assumes the unit circle intersects the box.
DRAKE_ASSERT(bmin.lpNorm<2>() <= 1);
DRAKE_ASSERT(bmax.lpNorm<2>() >= 1);
std::vector<Eigen::Vector3d> intersections;
if (bmin.lpNorm<2>() == 1) {
// Then only the min corner intersects.
intersections.push_back(bmin);
return intersections;
}
if (bmax.lpNorm<2>() == 1) {
// Then only the max corner intersects.
intersections.push_back(bmax);
return intersections;
}
// The box has at most 12 edges, each edge can intersect with the unit sphere
// at most once, since the box is in the first orthant.
intersections.reserve(12);
// 1. Loop through each vertex of the box, add it to intersections if
// the vertex is on the sphere.
for (int i = 0; i < 8; ++i) {
Eigen::Vector3d vertex{};
for (int axis = 0; axis < 3; ++axis) {
vertex(axis) = i & (1 << axis) ? bmin(axis) : bmax(axis);
}
if (vertex.norm() == 1) {
intersections.push_back(vertex);
}
}
// 2. Loop through each edge, find the intersection between each edge and the
// unit sphere, if one exists.
for (int axis = 0; axis < 3; ++axis) {
// axis = 0 means edges along x axis;
// axis = 1 means edges along y axis;
// axis = 2 means edges along z axis;
int fixed_axis1 = (axis + 1) % 3;
int fixed_axis2 = (axis + 2) % 3;
// 4 edges along each axis;
// First finds the two end points on the edge.
Eigen::Vector3d pt_closer, pt_farther;
pt_closer(axis) = bmin(axis);
pt_farther(axis) = bmax(axis);
std::array<double, 2> fixed_axis1_val = {
{bmin(fixed_axis1), bmax(fixed_axis1)}};
std::array<double, 2> fixed_axis2_val = {
{bmin(fixed_axis2), bmax(fixed_axis2)}};
for (double val1 : fixed_axis1_val) {
pt_closer(fixed_axis1) = val1;
pt_farther(fixed_axis1) = pt_closer(fixed_axis1);
for (double val2 : fixed_axis2_val) {
pt_closer(fixed_axis2) = val2;
pt_farther(fixed_axis2) = pt_closer(fixed_axis2);
// Determines if there is an intersecting point between the edge and the
// sphere. If the intersecting point is not the vertex of the box, then
// push this intersecting point to intersections directly.
if (pt_closer.norm() < 1 && pt_farther.norm() > 1) {
Eigen::Vector3d pt_intersect{};
pt_intersect(fixed_axis1) = pt_closer(fixed_axis1);
pt_intersect(fixed_axis2) = pt_closer(fixed_axis2);
pt_intersect(axis) =
Intercept(pt_intersect(fixed_axis1), pt_intersect(fixed_axis2));
intersections.push_back(pt_intersect);
}
}
}
}
return intersections;
}
/**
* Compute the outward unit length normal of the triangle, with the three
* vertices being `pt0`, `pt1` and `pt2`.
* @param pt0 A vertex of the triangle, in the first orthant (+++).
* @param pt1 A vertex of the triangle, in the first orthant (+++).
* @param pt2 A vertex of the triangle, in the first orthant (+++).
* @param n The unit length normal vector of the triangle, pointing outward from
* the origin.
* @param d The intersecpt of the plane. Namely nᵀ * x = d for any point x on
* the triangle.
*/
void ComputeTriangleOutwardNormal(const Eigen::Vector3d& pt0,
const Eigen::Vector3d& pt1,
const Eigen::Vector3d& pt2,
Eigen::Vector3d* n, double* d) {
DRAKE_DEMAND((pt0.array() >= 0).all());
DRAKE_DEMAND((pt1.array() >= 0).all());
DRAKE_DEMAND((pt2.array() >= 0).all());
*n = (pt2 - pt0).cross(pt1 - pt0);
// If the three points are almost colinear, then throw an error.
double n_norm = n->norm();
if (n_norm < 1E-3) {
throw std::runtime_error("The points are almost colinear.");
}
*n = (*n) / n_norm;
if (n->sum() < 0) {
(*n) *= -1;
}
*d = pt0.dot(*n);
DRAKE_DEMAND((n->array() >= 0).all());
}
bool AreAllVerticesCoPlanar(const std::vector<Eigen::Vector3d>& pts,
Eigen::Vector3d* n, double* d) {
DRAKE_DEMAND(pts.size() >= 3);
ComputeTriangleOutwardNormal(pts[0], pts[1], pts[2], n, d);
// Determine if the other vertices are on the plane nᵀ * x = d.
bool pts_on_plane = true;
for (int i = 3; i < static_cast<int>(pts.size()); ++i) {
if (std::abs(n->dot(pts[i]) - *d) > 1E-10) {
pts_on_plane = false;
n->setZero();
*d = 0;
break;
}
}
return pts_on_plane;
}
void ComputeHalfSpaceRelaxationForBoxSphereIntersection(
const std::vector<Eigen::Vector3d>& pts, Eigen::Vector3d* n, double* d) {
DRAKE_DEMAND(pts.size() >= 3);
// We first prove that for a given normal vector n, and ANY unit
// length vector v within the intersection region between the
// surface of the unit sphere and the interior of the axis-aligned
// box, the minimal of nᵀ * v, always occurs at one of the vertex of
// the intersection region, if the box and the vector n are in the
// same orthant. Namely min nᵀ * v = min(nᵀ * pts.col(i))
// To see this, for any vector v in the intersection region, suppose
// it is on an arc, aligned with one axis. Without loss of
// generality we assume the aligned axis is x axis, namely
// v(0) = t, box_min(0) <= t <= box_max(0)
// and v(1)² + v(2)² = 1 - t², with the bounds
// box_min(1) <= v(1) <= box_max(1)
// box_min(2) <= v(2) <= box_max(2)
// And the inner product nᵀ * v =
// n(0) * t + s * (n(1) * cos(α) + n(2) * sin(α))
// where we define s = sqrt(1 - t²)
// Using the property of trigonometric function, we know that
// the minimal of (n(1) * cos(α) + n(2) * sin(α)) is obtained at
// the boundary of α. Thus we know that the minimal of nᵀ * v is
// always obtained at one of the vertex pts.col(i).
// To find the tightest bound d satisfying nᵀ * v >= d for all
// vector v in the intersection region, we use the fact that for
// a given normal vector n, the minimal of nᵀ * v is always obtained
// at one of the vertices pts.col(i), and formulate the following
// SOCP to find the normal vector n
// max d
// s.t d <= nᵀ * pts.col(i)
// nᵀ * n <= 1
// First compute a plane coinciding with a triangle, formed by 3 vertices
// in the intersection region. If all the vertices are on that plane, then the
// normal of the plane is n, and we do not need to run the optimization.
// If there are only 3 vertices in the intersection region, then the normal
// vector n is the normal of the triangle, formed by these three vertices.
bool pts_on_plane = AreAllVerticesCoPlanar(pts, n, d);
if (pts_on_plane) {
return;
}
// If there are more than 3 vertices in the intersection region, and these
// vertices are not co-planar, then we find the normal vector `n` through an
// optimization, whose formulation is mentioned above.
MathematicalProgram prog_normal;
auto n_var = prog_normal.NewContinuousVariables<3>();
auto d_var = prog_normal.NewContinuousVariables<1>();
prog_normal.AddLinearCost(-d_var(0));
for (const auto& pt : pts) {
prog_normal.AddLinearConstraint(n_var.dot(pt) >= d_var(0));
}
// TODO(hongkai.dai): This optimization is expensive, especially if we have
// multiple rotation matrices, all relaxed with the same number of binary
// variables per half axis, the result `n` and `d` are the same. Should
// consider hard-coding the result, to avoid repeated computation.
Vector4<symbolic::Expression> lorentz_cone_vars;
lorentz_cone_vars << 1, n_var;
prog_normal.AddLorentzConeConstraint(lorentz_cone_vars);
const auto result = Solve(prog_normal);
DRAKE_DEMAND(result.is_success());
*n = result.GetSolution(n_var);
*d = result.GetSolution(d_var(0));
DRAKE_DEMAND((*n)(0) > 0 && (*n)(1) > 0 && (*n)(2) > 0);
DRAKE_DEMAND(*d > 0 && *d < 1);
}
void ComputeInnerFacetsForBoxSphereIntersection(
const std::vector<Eigen::Vector3d>& pts,
Eigen::Matrix<double, Eigen::Dynamic, 3>* A, Eigen::VectorXd* b) {
for (const auto& pt : pts) {
DRAKE_DEMAND((pt.array() >= 0).all());
}
A->resize(0, 3);
b->resize(0);
// Loop through each triangle, formed by connecting the vertices of the
// intersection region. We write the plane coinciding with the triangle as
// cᵀ * x >= d. If all the vertices of the intersection region satisfies
// cᵀ * pts[i] >= d, then we know the intersection region satisfies
// cᵀ * x >= d for all x being a point in the intersection region. Here we
// use the proof in the ComputeHalfSpaceRelaxationForBoxSphereIntersection(),
// that the minimal value of cᵀ * x over all x inside the intersection
// region, occurs at one of the vertex of the intersection region.
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) {
// First compute the triangle formed by vertices pts[i], pts[j] and
// pts[k].
Eigen::Vector3d c;
double d;
ComputeTriangleOutwardNormal(pts[i], pts[j], pts[k], &c, &d);
// A halfspace cᵀ * x >= d is valid, if all vertices pts[l] satisfy
// cᵀ * pts[l] >= d.
bool is_valid_halfspace = true;
// Now check if the other vertices pts[l] satisfies cᵀ * pts[l] >= d.
for (int l = 0; l < static_cast<int>(pts.size()); ++l) {
if ((l != i) && (l != j) && (l != k)) {
if (c.dot(pts[l]) < d - 1E-10) {
is_valid_halfspace = false;
break;
}
}
}
// If all vertices pts[l] satisfy cᵀ * pts[l] >= d, then add this
// constraint to A * x <= b
if (is_valid_halfspace) {
A->conservativeResize(A->rows() + 1, Eigen::NoChange);
b->conservativeResize(b->rows() + 1, Eigen::NoChange);
A->row(A->rows() - 1) = -c.transpose();
(*b)(b->rows() - 1) = -d;
}
}
}
}
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mathematical_program_result.h | #pragma once
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <typeinfo>
#include <unordered_map>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include "drake/common/symbolic/expression.h"
#include "drake/common/symbolic/polynomial.h"
#include "drake/common/value.h"
#include "drake/solvers/binding.h"
#include "drake/solvers/constraint.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/solution_result.h"
#include "drake/solvers/solver_id.h"
namespace drake {
namespace solvers {
/**
* Retrieve the value of a single variable @p var from @p variable_values.
* @param var The variable whose value is going to be retrieved. @p var.get_id()
* must be a key in @p variable_index.
* @param variable_index maps the variable ID to its index in @p
* variable_values.
* @param variable_values The values of all variables.
* @return variable_values(variable_index[var.get_id()]) if
* var.get_id() is a valid key of @p variable_index.
* @throws std::exception if var.get_id() is not a valid key of @p
* variable_index.
* @pre All the mapped value in variable_index is in the range [0,
* variable_values.rows())
*/
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);
/**
* Overload GetVariableValue() function, but for an Eigen matrix of decision
* variables.
*/
template <typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Derived::Scalar, symbolic::Variable>,
MatrixLikewise<double, Derived>>
GetVariableValue(
const Eigen::MatrixBase<Derived>& var,
const std::optional<std::unordered_map<symbolic::Variable::Id, int>>&
variable_index,
const Eigen::Ref<const Eigen::VectorXd>& variable_values) {
MatrixLikewise<double, Derived> value(var.rows(), var.cols());
for (int i = 0; i < var.rows(); ++i) {
for (int j = 0; j < var.cols(); ++j) {
value(i, j) =
GetVariableValue(var(i, j), variable_index, variable_values);
}
}
return value;
}
/**
* The result returned by MathematicalProgram::Solve(). It stores the
* solvers::SolutionResult (whether the program is solved to optimality,
* detected infeasibility, etc), the optimal value for the decision variables,
* the optimal cost, and solver specific details.
*/
class MathematicalProgramResult final {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(MathematicalProgramResult)
/**
* Constructs the result.
* @note The solver_details is set to nullptr.
*/
MathematicalProgramResult();
/** Returns true if the optimization problem is solved successfully; false
* otherwise.
* For more information on the solution status, the user could call
* get_solver_details() to obtain the solver-specific solution status.
*/
[[nodiscard]] bool is_success() const;
/**
* Sets decision_variable_index mapping, that maps each decision variable to
* its index in the aggregated vector containing all decision variables in
* MathematicalProgram. Initialize x_val to NAN.
*/
void set_decision_variable_index(
std::unordered_map<symbolic::Variable::Id, int> decision_variable_index) {
decision_variable_index_ = std::move(decision_variable_index);
x_val_ =
Eigen::VectorXd::Constant(decision_variable_index_->size(),
std::numeric_limits<double>::quiet_NaN());
}
/** Gets decision_variable_index. */
const std::optional<std::unordered_map<symbolic::Variable::Id, int>>&
get_decision_variable_index() const {
return decision_variable_index_;
}
/** Sets SolutionResult. */
void set_solution_result(SolutionResult solution_result) {
solution_result_ = solution_result;
}
/** Gets the decision variable values. */
const Eigen::VectorXd& get_x_val() const { return x_val_; }
/** Gets SolutionResult. */
SolutionResult get_solution_result() const { return solution_result_; }
/** Sets the decision variable values. */
void set_x_val(const Eigen::VectorXd& x_val);
/** Sets the dual solution associated with a given constraint. */
template <typename C>
void set_dual_solution(
const Binding<C>& constraint,
const Eigen::Ref<const Eigen::VectorXd>& dual_solution) {
const Binding<Constraint> constraint_cast =
internal::BindingDynamicCast<Constraint>(constraint);
dual_solutions_.emplace(constraint_cast, dual_solution);
}
/** Gets the optimal cost. */
double get_optimal_cost() const { return optimal_cost_; }
/** Sets the optimal cost. */
void set_optimal_cost(double optimal_cost) { optimal_cost_ = optimal_cost; }
/** Gets the solver ID. */
const SolverId& get_solver_id() const { return solver_id_; }
/** Sets the solver ID. */
void set_solver_id(const SolverId& solver_id) { solver_id_ = solver_id; }
/** Gets the solver details for the `Solver` that solved the program. Throws
* an error if the solver_details has not been set. */
template <typename Solver>
const typename Solver::Details& get_solver_details() const {
return get_abstract_solver_details()
.template get_value<typename Solver::Details>();
}
/** (Advanced.) Gets the type-erased solver details. Most users should use
* get_solver_details() instead. Throws an error if the solver_details has
* not been set. */
[[nodiscard]] const AbstractValue& get_abstract_solver_details() const;
/** (Advanced.) Forces the solver_details to be stored using the given
* type `T`. Typically, only an implementation of SolverInterface will
* call this method.
* If the storage was already typed as T, this is a no-op.
* If there were not any solver_details previously, or if it was of a
* different type, initializes the storage to a default-constructed T.
* Returns a reference to the mutable solver_details object.
* The reference remains valid until the next call to this method, or
* until this MathematicalProgramResult is destroyed. */
template <typename T>
T& SetSolverDetailsType() {
// Leave the storage alone if it already has the correct type.
if (!solver_details_ ||
(solver_details_->static_type_info() != typeid(T))) {
solver_details_ = std::make_unique<Value<T>>();
}
return solver_details_->get_mutable_value<T>();
}
/**
* Gets the solution of all decision variables.
*/
[[nodiscard]] const Eigen::VectorXd& GetSolution() const { return x_val_; }
/**
* Gets the solution of an Eigen matrix of decision variables.
* @tparam Derived An Eigen matrix containing Variable.
* @param var The decision variables.
* @return The value of the decision variable after solving the problem.
*/
template <typename Derived>
[[nodiscard]] typename std::enable_if_t<
std::is_same_v<typename Derived::Scalar, symbolic::Variable>,
MatrixLikewise<double, Derived>>
GetSolution(const Eigen::MatrixBase<Derived>& var) const {
return GetVariableValue(var, decision_variable_index_, x_val_);
}
/**
* Gets the solution of a single decision variable.
* @param var The decision variable.
* @return The value of the decision variable after solving the problem.
* @throws std::exception if `var` is not captured in the mapping @p
* decision_variable_index, as the input argument of
* set_decision_variable_index().
*/
[[nodiscard]] double GetSolution(const symbolic::Variable& var) const;
/** Resets the solution of a single decision variable that is already
registered with this result.
@throws std::exception if `var` is not captured in the mapping @p
decision_variable_index, as the input argument of
set_decision_variable_index(). */
void SetSolution(const symbolic::Variable& var, double value);
/**
* Substitutes the value of all decision variables into the Expression.
* @param e The decision variable.
* @return the Expression that is the result of the substitution.
*/
[[nodiscard]] symbolic::Expression GetSolution(
const symbolic::Expression& e) const;
/**
* Substitutes the value of all decision variables into the coefficients of
* the symbolic polynomial.
* @param p A symbolic polynomial. Its indeterminates can't intersect with the
* set of decision variables of the MathematicalProgram from which this result
* is obtained.
* @return the symbolic::Polynomial as the result of the substitution.
*/
[[nodiscard]] symbolic::Polynomial GetSolution(
const symbolic::Polynomial& p) const;
/**
* Substitutes the value of all decision variables into the
* Matrix<Expression>.
* @tparam Derived An Eigen matrix containing Expression.
* @return the Matrix<Expression> that is the result of the substitution.
*
* @exclude_from_pydrake_mkdoc{Including this confuses mkdoc, resulting in
* doc_was_unable_to_choose_unambiguous_name. }
*/
template <typename Derived>
[[nodiscard]] typename std::enable_if_t<
std::is_same_v<typename Derived::Scalar, symbolic::Expression>,
MatrixLikewise<symbolic::Expression, Derived>>
GetSolution(const Eigen::MatrixBase<Derived>& m) const {
MatrixLikewise<symbolic::Expression, Derived> value(m.rows(), m.cols());
for (int i = 0; i < m.rows(); ++i) {
for (int j = 0; j < m.cols(); ++j) {
value(i, j) = GetSolution(m(i, j));
}
}
return value;
}
// TODO(hongkai.dai): add the interpretation for other type of constraints
// when we implement them.
/**
* Gets the dual solution associated with a constraint.
*
* For constraints in the form lower <= f(x) <= upper (including linear
* inequality, linear equality, bounding box constraints, and general
* nonlinear constraints), we interpret the dual variable value as the "shadow
* price" of the original problem. Namely if we change the constraint bound by
* one unit (each unit is infinitesimally small), the change of the optimal
* cost is the value of the dual solution times the unit. Mathematically
* dual_solution = ∂optimal_cost / ∂bound.
*
* For a linear equality constraint Ax = b where b ∈ ℝⁿ, the vector of dual
* variables has n rows, and dual_solution(i) is the value of the dual
* variable for the constraint A(i,:)*x = b(i).
*
* For a linear inequality constraint lower <= A*x <= upper where lower and
* upper ∈ ℝⁿ, dual_solution also has n rows. dual_solution(i) is the value of
* the dual variable for constraint lower(i) <= A(i,:)*x <= upper(i). If
* neither side of the constraint is active, then dual_solution(i) is 0. If
* the left hand-side lower(i) <= A(i, :)*x is active (meaning lower(i) = A(i,
* :)*x at the solution), then dual_solution(i) is non-negative (because the
* objective is to minimize a cost, increasing the lower bound means the
* constraint set is tighter, hence the optimal solution cannot decrease. Thus
* the shadow price is non-negative). If the right hand-side A(i,
* :)*x<=upper(i) is active (meaning A(i,:)*x=upper(i) at the solution), then
* dual_solution(i) is non-positive.
*
* For a bounding box constraint lower <= x <= upper, the interpretation of
* the dual solution is the same as the linear inequality constraint.
*
* For a Lorentz cone or rotated Lorentz cone constraint that Ax + b is in
* the cone, depending on the solver, the dual solution has different
* meanings:
* 1. If the solver is Gurobi, then the user can only obtain the dual solution
* by explicitly setting the options for computing dual solution.
* @code
* auto constraint = prog.AddLorentzConeConstraint(...);
* GurobiSolver solver;
* // Explicitly tell the solver to compute the dual solution for Lorentz
* // cone or rotated Lorentz cone constraint, check
* // https://www.gurobi.com/documentation/10.1/refman/qcpdual.html for
* // more information.
* SolverOptions options;
* options.SetOption(GurobiSolver::id(), "QCPDual", 1);
* MathematicalProgramResult result = solver.Solve(prog, {}, options);
* Eigen::VectorXd dual_solution = result.GetDualSolution(constraint);
* @endcode
* The dual solution has size 1, dual_solution(0) is the shadow price for
* the constraint z₁² + ... +zₙ² ≤ z₀² for Lorentz cone constraint, and
* the shadow price for the constraint z₂² + ... +zₙ² ≤ z₀z₁ for rotated
* Lorentz cone constraint, where z is the slack variable representing z =
* A*x+b and z in the Lorentz cone/rotated Lorentz cone.
* 2. For nonlinear solvers like IPOPT, the dual solution for Lorentz cone
* constraint (with EvalType::kConvex) is the shadow price for
* z₀ - sqrt(z₁² + ... +zₙ²) ≥ 0, where z = Ax+b.
* 3. For other convex conic solver such as SCS, MOSEK™, CSDP, etc, the dual
* solution to the (rotated) Lorentz cone constraint doesn't have the
* "shadow price" interpretation, but should lie in the dual cone, and
* satisfy the KKT condition. For more information, refer to
* https://docs.mosek.com/10.1/capi/prob-def-conic.html#duality-for-conic-optimization
* as an explanation.
*
* The interpretation for the dual variable to conic constraint x ∈ K can be
* different. Here K is a convex cone, including exponential cone, power
* cone, psd cone, etc. When the problem is solved by a convex solver (like
* SCS, MOSEK™, CSDP, etc), often it has a dual variable z ∈ K*, where K* is
* the dual cone. Here the dual variable DOESN'T have the interpretation of
* "shadow price", but should satisfy the KKT condition, while the dual
* variable stays inside the dual cone.
*
* When K is a psd cone, the returned dual solution is the lower triangle of
* the dual symmetric psd matrix. Namely for the primal problem
*
* min trace(C*X)
* s.t A(X) = b
* X is psd
*
* the dual is
*
* max b'*y
* s.t A'(y) - C = Z
* Z is psd.
*
* We return the lower triangular part of Z. You can call
* drake::math::ToSymmetricMatrixFromLowerTriangularColumns to get the matrix
* Z.
*/
template <typename C>
[[nodiscard]] Eigen::VectorXd GetDualSolution(
const Binding<C>& constraint) const {
const Binding<Constraint> constraint_cast =
internal::BindingDynamicCast<Constraint>(constraint);
auto it = dual_solutions_.find(constraint_cast);
if (it == dual_solutions_.end()) {
// Throws a more meaningful error message when the user wants to retrieve
// a dual solution from a Gurobi result for a program containing second
// order cone constraints, but forgot to explicitly turn on the flag to
// compute Gurobi QCP dual.
if (solver_id_.name() == "Gurobi") {
throw std::invalid_argument(fmt::format(
"You used {} to solve this optimization problem. If the problem is "
"solved to optimality and doesn't contain binary/integer "
"variables, but you failed to get the dual solution, "
"check that you have explicitly told Gurobi solver to "
"compute the dual solution for the second order cone constraints "
"by setting the solver options. One example is as follows: "
"SolverOptions options; "
"options.SetOption(GurobiSolver::id(), \"QCPDual\", 1); "
"auto result=Solve(prog, std::nullopt, options);",
solver_id_.name()));
}
throw std::invalid_argument(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.",
solver_id_.name()));
} else {
return it->second;
}
}
/**
* Evaluate a Binding at the solution.
* @param binding A binding between a constraint/cost and the variables.
* @pre The binding.variables() must be the within the decision variables in
* the MathematicalProgram that generated this %MathematicalProgramResult.
* @pre The user must have called set_decision_variable_index() function.
*/
template <typename Evaluator>
Eigen::VectorXd EvalBinding(const Binding<Evaluator>& binding) const {
DRAKE_ASSERT(decision_variable_index_.has_value());
Eigen::VectorXd binding_x(binding.GetNumElements());
for (int i = 0; i < binding_x.rows(); ++i) {
binding_x(i) =
x_val_(decision_variable_index_->at(binding.variables()(i).get_id()));
}
Eigen::VectorXd binding_y(binding.evaluator()->num_outputs());
binding.evaluator()->Eval(binding_x, &binding_y);
return binding_y;
}
/**
* @anchor solution_pools
* @name Solution Pools
* Some solvers (like Gurobi, Cplex, etc) can store a pool of (suboptimal)
* solutions for mixed integer programming model.
* @{
*/
/**
* Gets the suboptimal solution corresponding to a matrix of decision
* variables. See @ref solution_pools "solution pools"
* @param var The decision variables.
* @param solution_number The index of the sub-optimal solution.
* @pre @p solution_number should be in the range [0,
* num_suboptimal_solution()).
* @return The suboptimal values of the decision variables after solving the
* problem.
*/
template <typename Derived>
[[nodiscard]] typename std::enable_if_t<
std::is_same_v<typename Derived::Scalar, symbolic::Variable>,
MatrixLikewise<double, Derived>>
GetSuboptimalSolution(const Eigen::MatrixBase<Derived>& var,
int solution_number) const {
return GetVariableValue(var, decision_variable_index_,
suboptimal_x_val_[solution_number]);
}
/**
* Gets the suboptimal solution of a decision variable. See @ref
* solution_pools "solution pools"
* @param var The decision variable.
* @param solution_number The index of the sub-optimal solution.
* @pre @p solution_number should be in the range [0,
* num_suboptimal_solution()).
* @return The suboptimal value of the decision variable after solving the
* problem.
*/
[[nodiscard]] double GetSuboptimalSolution(const symbolic::Variable& var,
int solution_number) const;
/**
* Number of suboptimal solutions stored inside MathematicalProgramResult.
* See @ref solution_pools "solution pools".
*/
[[nodiscard]] int num_suboptimal_solution() const {
return static_cast<int>(suboptimal_x_val_.size());
}
/**
* Gets the suboptimal objective value. See @ref solution_pools "solution
* pools".
* @param solution_number The index of the sub-optimal solution. @pre @p
* solution_number should be in the range [0, num_suboptimal_solution()).
*/
[[nodiscard]] double get_suboptimal_objective(int solution_number) const {
return suboptimal_objectives_[solution_number];
}
/**
* Adds the suboptimal solution to the result. See @ref solution_pools
* "solution pools".
* @param suboptimal_objective The objective value computed from this
* suboptimal solution.
* @param suboptimal_x The values of the decision variables in this suboptimal
* solution.
*/
void AddSuboptimalSolution(double suboptimal_objective,
const Eigen::VectorXd& suboptimal_x);
//@}
/** @anchor get_infeasible_constraints
* @name Get infeasible constraints
* Some solvers (e.g. SNOPT) provide a "best-effort solution" even when they
* determine that a problem is infeasible. This method will return the
* descriptions corresponding to the constraints for which `CheckSatisfied`
* evaluates to false given the reported solution. This can be very useful
* for debugging. Note that this feature is available only when the
* optimization problem is solved through certain solvers (like SNOPT, IPOPT)
* which provide a "best-effort solution". Some solvers (like Gurobi) don't
* return the "best-effort solution" when the problem is infeasible, and this
* feature is hence unavailable.
*/
//@{
/**
* See @ref get_infeasible_constraints for more information.
* @param prog The MathematicalProgram that was solved to obtain `this`
* MathematicalProgramResult.
* @param tolerance A positive tolerance to check the constraint violation.
* If no tolerance is provided, this method will attempt to obtain the
* constraint tolerance from the solver, or insert a conservative default
* tolerance.
*
* Note: Currently most constraints have the empty string as the
* description, so the NiceTypeName of the Constraint is used instead. Use
* e.g.
* `prog.AddConstraint(x == 1).evaluator().set_description(str)`
* to make this method more specific/useful. */
[[nodiscard]] std::vector<std::string> GetInfeasibleConstraintNames(
const MathematicalProgram& prog,
std::optional<double> tolerance = std::nullopt) const;
/**
* See @ref get_infeasible_constraints for more information.
* @param prog The MathematicalProgram that was solved to obtain `this`
* MathematicalProgramResult.
* @param tolerance A positive tolerance to check the constraint violation.
* If no tolerance is provided, this method will attempt to obtain the
* constraint tolerance from the solver, or insert a conservative default
* tolerance.
* @return infeasible_bindings A vector of all infeasible bindings
* (constraints together with the associated variables) at the best-effort
* solution.
*/
[[nodiscard]] std::vector<Binding<Constraint>> GetInfeasibleConstraints(
const MathematicalProgram& prog,
std::optional<double> tolerance = std::nullopt) const;
// @}
private:
std::optional<std::unordered_map<symbolic::Variable::Id, int>>
decision_variable_index_{};
SolutionResult solution_result_{};
Eigen::VectorXd x_val_;
double optimal_cost_{};
SolverId solver_id_;
copyable_unique_ptr<AbstractValue> solver_details_;
// Some solvers (like Gurobi, Cplex, etc) can store a pool of (suboptimal)
// solutions for mixed integer programming model.
// suboptimal_objectives_[i] is the objective value computed with the
// suboptimal solution suboptimal_x_val_[i].
std::vector<Eigen::VectorXd> suboptimal_x_val_{};
std::vector<double> suboptimal_objectives_{};
// Stores the dual variable solutions for each constraint.
std::unordered_map<Binding<Constraint>, Eigen::VectorXd> dual_solutions_{};
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mosek_solver_internal.cc | #include "drake/solvers/mosek_solver_internal.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <limits>
#include "drake/common/fmt_ostream.h"
#include "drake/common/never_destroyed.h"
#include "drake/math/quadratic_form.h"
#include "drake/solvers/aggregate_costs_constraints.h"
namespace drake {
namespace solvers {
namespace internal {
// Given a vector of triplets (which might contain duplicated entries in the
// matrix), returns the vector of rows, columns and values.
void ConvertTripletsToVectors(
const std::vector<Eigen::Triplet<double>>& triplets, int matrix_rows,
int matrix_cols, std::vector<MSKint32t>* row_indices,
std::vector<MSKint32t>* col_indices, std::vector<MSKrealt>* values) {
// column major sparse matrix
Eigen::SparseMatrix<double> A(matrix_rows, matrix_cols);
A.setFromTriplets(triplets.begin(), triplets.end());
const int num_nonzeros = A.nonZeros();
DRAKE_ASSERT(row_indices && row_indices->empty());
DRAKE_ASSERT(col_indices && col_indices->empty());
DRAKE_ASSERT(values && values->empty());
row_indices->reserve(num_nonzeros);
col_indices->reserve(num_nonzeros);
values->reserve(num_nonzeros);
for (int i = 0; i < A.outerSize(); ++i) {
for (Eigen::SparseMatrix<double>::InnerIterator it(A, i); it; ++it) {
row_indices->push_back(it.row());
col_indices->push_back(it.col());
values->push_back(it.value());
}
}
}
size_t MatrixVariableEntry::get_next_id() {
static never_destroyed<std::atomic<int>> next_id(0);
return next_id.access()++;
}
MosekSolverProgram::MosekSolverProgram(const MathematicalProgram& prog,
MSKenv_t env)
: map_decision_var_to_mosek_var_{prog} {
// Create the optimization task.
// task is initialized as a null pointer, same as in Mosek's documentation
// https://docs.mosek.com/10.1/capi/design.html#hello-world-in-mosek
task_ = nullptr;
MSK_maketask(env, 0,
map_decision_var_to_mosek_var_
.decision_variable_to_mosek_nonmatrix_variable.size(),
&task_);
}
MosekSolverProgram::~MosekSolverProgram() {
MSK_deletetask(&task_);
}
MSKrescodee
MosekSolverProgram::AddMatrixVariableEntryCoefficientMatrixIfNonExistent(
const MatrixVariableEntry& matrix_variable_entry, MSKint64t* E_index) {
MSKrescodee rescode{MSK_RES_OK};
auto it = matrix_variable_entry_to_selection_matrix_id_.find(
matrix_variable_entry.id());
if (it != matrix_variable_entry_to_selection_matrix_id_.end()) {
*E_index = it->second;
} else {
const MSKint32t row = matrix_variable_entry.row_index();
const MSKint32t col = matrix_variable_entry.col_index();
const MSKrealt val = row == col ? 1.0 : 0.5;
rescode =
MSK_appendsparsesymmat(task_, matrix_variable_entry.num_matrix_rows(),
1, &row, &col, &val, E_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
matrix_variable_entry_to_selection_matrix_id_.emplace_hint(
it, matrix_variable_entry.id(), *E_index);
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddScalarTimesMatrixVariableEntryToMosek(
MSKint32t constraint_index,
const MatrixVariableEntry& matrix_variable_entry, MSKrealt scalar) {
MSKrescodee rescode{MSK_RES_OK};
MSKint64t E_index;
rescode = AddMatrixVariableEntryCoefficientMatrixIfNonExistent(
matrix_variable_entry, &E_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = MSK_putbaraij(task_, constraint_index,
matrix_variable_entry.bar_matrix_index(), 1, &E_index,
&scalar);
return rescode;
}
// Determine the sense of each constraint. The sense can be equality constraint,
// less than, greater than, or bounded on both side.
MSKrescodee MosekSolverProgram::SetMosekLinearConstraintBound(
int linear_constraint_index, double lower, double upper,
LinearConstraintBoundType bound_type) {
MSKrescodee rescode{MSK_RES_OK};
switch (bound_type) {
case LinearConstraintBoundType::kEquality: {
rescode = MSK_putconbound(task_, linear_constraint_index, MSK_BK_FX,
lower, lower);
if (rescode != MSK_RES_OK) {
return rescode;
}
break;
}
case LinearConstraintBoundType::kInequality: {
if (std::isinf(lower) && std::isinf(upper)) {
DRAKE_DEMAND(lower < 0 && upper > 0);
rescode = MSK_putconbound(task_, linear_constraint_index, MSK_BK_FR,
-MSK_INFINITY, MSK_INFINITY);
} else if (std::isinf(lower) && !std::isinf(upper)) {
rescode = MSK_putconbound(task_, linear_constraint_index, MSK_BK_UP,
-MSK_INFINITY, upper);
} else if (!std::isinf(lower) && std::isinf(upper)) {
rescode = MSK_putconbound(task_, linear_constraint_index, MSK_BK_LO,
lower, MSK_INFINITY);
} else {
rescode = MSK_putconbound(task_, linear_constraint_index, MSK_BK_RA,
lower, upper);
}
if (rescode != MSK_RES_OK) {
return rescode;
}
break;
}
}
return rescode;
}
// Add the linear constraint lower <= A * decision_vars + B * slack_vars <=
// upper.
MSKrescodee MosekSolverProgram::AddLinearConstraintToMosek(
const MathematicalProgram& prog, const Eigen::SparseMatrix<double>& A,
const Eigen::SparseMatrix<double>& B, const Eigen::VectorXd& lower,
const Eigen::VectorXd& upper,
const VectorX<symbolic::Variable>& decision_vars,
const std::vector<MSKint32t>& slack_vars_mosek_indices,
LinearConstraintBoundType bound_type) {
MSKrescodee rescode{MSK_RES_OK};
DRAKE_ASSERT(lower.rows() == upper.rows());
DRAKE_ASSERT(A.rows() == lower.rows() && A.cols() == decision_vars.rows());
DRAKE_ASSERT(B.rows() == lower.rows() &&
B.cols() == static_cast<int>(slack_vars_mosek_indices.size()));
int num_mosek_constraint{};
rescode = MSK_getnumcon(task_, &num_mosek_constraint);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = MSK_appendcons(task_, lower.rows());
if (rescode != MSK_RES_OK) {
return rescode;
}
for (int i = 0; i < lower.rows(); ++i) {
// It is important that AddLinearConstraintToMosek keeps the order of the
// linear constraint the same as in lower <= A * decision_vars + B *
// slack_vars <= upper. When we specify the dual variable indices, we rely
// on this order.
rescode = SetMosekLinearConstraintBound(num_mosek_constraint + i, lower(i),
upper(i), bound_type);
if (rescode != MSK_RES_OK) {
return rescode;
}
}
// (A * decision_vars + B * slack_var)(i) = (Aₓ * x)(i) + ∑ⱼ <A̅ᵢⱼ, X̅ⱼ>
// where we decompose [decision_vars; slack_var] to Mosek nonmatrix variable
// x and Mosek matrix variable X̅.
// Ax_subi, Ax_subj, Ax_valij are the triplets format of matrix Aₓ.
std::vector<MSKint32t> Ax_subi, Ax_subj;
std::vector<MSKrealt> Ax_valij;
std::vector<std::unordered_map<
MSKint64t, std::pair<std::vector<MSKint64t>, std::vector<MSKrealt>>>>
bar_A;
rescode =
ParseLinearExpression(prog, A, B, decision_vars, slack_vars_mosek_indices,
&Ax_subi, &Ax_subj, &Ax_valij, &bar_A);
if (rescode != MSK_RES_OK) {
return rescode;
}
if (!bar_A.empty()) {
for (int i = 0; i < lower.rows(); ++i) {
for (const auto& [j, sub_weights] : bar_A[i]) {
// Now compute the matrix A̅ᵢⱼ.
const std::vector<MSKint64t>& sub = sub_weights.first;
const std::vector<MSKrealt>& weights = sub_weights.second;
rescode = MSK_putbaraij(task_, num_mosek_constraint + i, j, sub.size(),
sub.data(), weights.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
}
}
}
// Add num_mosek_constraint to each entry of Ax_subi;
for (int i = 0; i < static_cast<int>(Ax_subi.size()); ++i) {
Ax_subi[i] += num_mosek_constraint;
}
rescode = MSK_putaijlist(task_, Ax_subi.size(), Ax_subi.data(),
Ax_subj.data(), Ax_valij.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
int num_mosek_constraints_after{};
rescode = MSK_getnumcon(task_, &num_mosek_constraints_after);
if (rescode != MSK_RES_OK) {
return rescode;
}
DRAKE_DEMAND(num_mosek_constraints_after ==
num_mosek_constraint + lower.rows());
return rescode;
}
MSKrescodee MosekSolverProgram::ParseLinearExpression(
const solvers::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,
std::vector<MSKint32t>* F_subi, std::vector<MSKint32t>* F_subj,
std::vector<MSKrealt>* F_valij,
std::vector<std::unordered_map<
MSKint64t, std::pair<std::vector<MSKint64t>, std::vector<MSKrealt>>>>*
bar_F) {
// First check if decision_vars contains duplication.
// Since the duplication doesn't happen very often, we focus on improving the
// speed of the no-duplication case.
const symbolic::Variables decision_vars_set(decision_vars);
if (static_cast<int>(decision_vars_set.size()) == decision_vars.rows()) {
return this->ParseLinearExpressionNoDuplication(
prog, A, B, decision_vars, slack_vars_mosek_indices, F_subi, F_subj,
F_valij, bar_F);
} else {
Eigen::SparseMatrix<double> A_unique;
VectorX<symbolic::Variable> unique_decision_vars;
AggregateDuplicateVariables(A, decision_vars, &A_unique,
&unique_decision_vars);
return this->ParseLinearExpressionNoDuplication(
prog, A_unique, B, unique_decision_vars, slack_vars_mosek_indices,
F_subi, F_subj, F_valij, bar_F);
}
}
MSKrescodee MosekSolverProgram::ParseLinearExpressionNoDuplication(
const solvers::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,
std::vector<MSKint32t>* F_subi, std::vector<MSKint32t>* F_subj,
std::vector<MSKrealt>* F_valij,
std::vector<std::unordered_map<
MSKint64t, std::pair<std::vector<MSKint64t>, std::vector<MSKrealt>>>>*
bar_F) {
MSKrescodee rescode{MSK_RES_OK};
DRAKE_ASSERT(A.rows() == B.rows());
DRAKE_ASSERT(A.cols() == decision_vars.rows());
DRAKE_ASSERT(B.cols() == static_cast<int>(slack_vars_mosek_indices.size()));
// (A * decision_vars + B * slack_var)(i) = (F * x)(i) + ∑ⱼ <F̅ᵢⱼ, X̅ⱼ>
// where we decompose [decision_vars; slack_var] to Mosek nonmatrix variable
// x and Mosek matrix variable X̅.
F_subi->reserve(A.nonZeros() + B.nonZeros());
F_subj->reserve(A.nonZeros() + B.nonZeros());
F_valij->reserve(A.nonZeros() + B.nonZeros());
// mosek_matrix_variable_entries stores all the matrix variables used in this
// newly added linear constraint.
// mosek_matrix_variable_entries[j] contains all the entries in that matrix
// variable X̅ⱼ that show up in this new linear constraint.
// This map is used to compute the symmetric matrix F̅ᵢⱼA̅ᵢⱼ in the term
// <F̅ᵢⱼA̅ᵢⱼ, X̅ⱼ>.
std::unordered_map<MSKint64t, std::vector<MatrixVariableEntry>>
mosek_matrix_variable_entries;
if (A.nonZeros() != 0) {
std::vector<int> decision_var_indices(decision_vars.rows());
// decision_vars[mosek_matrix_variable_in_decision_var[i]] is a Mosek matrix
// variable.
std::vector<int> mosek_matrix_variable_in_decision_var;
mosek_matrix_variable_in_decision_var.reserve(decision_vars.rows());
for (int i = 0; i < decision_vars.rows(); ++i) {
decision_var_indices[i] =
prog.FindDecisionVariableIndex(decision_vars(i));
const auto it_mosek_matrix_variable =
decision_variable_to_mosek_matrix_variable().find(
decision_var_indices[i]);
if (it_mosek_matrix_variable !=
decision_variable_to_mosek_matrix_variable().end()) {
// This decision variable is a matrix variable.
// Denote the matrix variables as X̅. Add the corresponding matrix
// E̅ₘₙ, such that <E̅ₘₙ, X̅> = X̅(m, n) if such matrix has not been
// added to Mosek yet.
mosek_matrix_variable_in_decision_var.push_back(i);
const MatrixVariableEntry& matrix_variable_entry =
it_mosek_matrix_variable->second;
MSKint64t E_mn_index;
rescode = AddMatrixVariableEntryCoefficientMatrixIfNonExistent(
matrix_variable_entry, &E_mn_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
mosek_matrix_variable_entries[matrix_variable_entry.bar_matrix_index()]
.push_back(matrix_variable_entry);
} else {
const int mosek_nonmatrix_variable =
decision_variable_to_mosek_nonmatrix_variable().at(
decision_var_indices[i]);
for (Eigen::SparseMatrix<double>::InnerIterator it(A, i); it; ++it) {
F_subi->push_back(it.row());
F_subj->push_back(mosek_nonmatrix_variable);
F_valij->push_back(it.value());
}
}
}
if (!mosek_matrix_variable_entries.empty()) {
bar_F->resize(A.rows());
for (int col_index : mosek_matrix_variable_in_decision_var) {
const MatrixVariableEntry& matrix_variable_entry =
decision_variable_to_mosek_matrix_variable().at(
decision_var_indices[col_index]);
for (Eigen::SparseMatrix<double>::InnerIterator it(A, col_index); it;
++it) {
// If we denote m = matrix_variable_entry.row_index(), n =
// matrix_variable_entry.col_index(), then
// bar_F[i][j] = \sum_{col_index} A(i, col_index) * Emn, where j =
// matrix_variable_entry.bar_matrix_index().
auto it_bar_F =
(*bar_F)[it.row()].find(matrix_variable_entry.bar_matrix_index());
if (it_bar_F != (*bar_F)[it.row()].end()) {
it_bar_F->second.first.push_back(
matrix_variable_entry_to_selection_matrix_id_.at(
matrix_variable_entry.id()));
it_bar_F->second.second.push_back(it.value());
} else {
(*bar_F)[it.row()].emplace_hint(
it_bar_F, matrix_variable_entry.bar_matrix_index(),
std::pair<std::vector<MSKint64t>, std::vector<MSKrealt>>(
{matrix_variable_entry_to_selection_matrix_id_.at(
matrix_variable_entry.id())},
{it.value()}));
}
}
}
}
}
if (B.nonZeros() != 0) {
for (int i = 0; i < B.cols(); ++i) {
for (Eigen::SparseMatrix<double>::InnerIterator it(B, i); it; ++it) {
F_subi->push_back(it.row());
F_subj->push_back(slack_vars_mosek_indices[i]);
F_valij->push_back(it.value());
}
}
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddLinearConstraints(
const MathematicalProgram& prog,
std::unordered_map<Binding<LinearConstraint>, ConstraintDualIndices>*
linear_con_dual_indices,
std::unordered_map<Binding<LinearEqualityConstraint>,
ConstraintDualIndices>* lin_eq_con_dual_indices) {
MSKrescodee rescode = AddLinearConstraintsFromBindings(
prog.linear_equality_constraints(), LinearConstraintBoundType::kEquality,
prog, lin_eq_con_dual_indices);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = AddLinearConstraintsFromBindings(
prog.linear_constraints(), LinearConstraintBoundType::kInequality, prog,
linear_con_dual_indices);
if (rescode != MSK_RES_OK) {
return rescode;
}
return rescode;
}
// Add the bounds on the decision variables in @p prog. Note that if a decision
// variable in positive definite matrix has a bound, we need to add new linear
// constraint to Mosek to bound that variable.
MSKrescodee MosekSolverProgram::AddBoundingBoxConstraints(
const MathematicalProgram& prog,
std::unordered_map<Binding<BoundingBoxConstraint>,
std::pair<ConstraintDualIndices, ConstraintDualIndices>>*
dual_indices) {
int num_decision_vars = prog.num_vars();
std::vector<double> x_lb;
std::vector<double> x_ub;
AggregateBoundingBoxConstraints(prog, &x_lb, &x_ub);
auto add_variable_bound_in_mosek = [this](int mosek_var_index, double lower,
double upper) {
MSKrescodee rescode_bound{MSK_RES_OK};
if (std::isinf(lower) && std::isinf(upper)) {
rescode_bound = MSK_putvarbound(this->task_, mosek_var_index, MSK_BK_FR,
-MSK_INFINITY, MSK_INFINITY);
} else if (std::isinf(lower) && !std::isinf(upper)) {
rescode_bound = MSK_putvarbound(this->task_, mosek_var_index, MSK_BK_UP,
-MSK_INFINITY, upper);
} else if (!std::isinf(lower) && std::isinf(upper)) {
rescode_bound = MSK_putvarbound(this->task_, mosek_var_index, MSK_BK_LO,
lower, MSK_INFINITY);
} else {
rescode_bound = MSK_putvarbound(this->task_, mosek_var_index, MSK_BK_RA,
lower, upper);
}
return rescode_bound;
};
MSKrescodee rescode = MSK_RES_OK;
// bounded_matrix_var_indices[i] is the index of the variable
// bounded_matrix_vars[i] in prog.
std::vector<int> bounded_matrix_var_indices;
bounded_matrix_var_indices.reserve(prog.num_vars());
for (int i = 0; i < num_decision_vars; i++) {
auto it1 = decision_variable_to_mosek_nonmatrix_variable().find(i);
if (it1 != decision_variable_to_mosek_nonmatrix_variable().end()) {
// The variable is not a matrix variable in Mosek.
const int mosek_var_index = it1->second;
rescode = add_variable_bound_in_mosek(mosek_var_index, x_lb[i], x_ub[i]);
if (rescode != MSK_RES_OK) {
return rescode;
}
} else {
const double lower = x_lb[i];
const double upper = x_ub[i];
if (!(std::isinf(lower) && std::isinf(upper))) {
bounded_matrix_var_indices.push_back(i);
}
}
}
// The bounded variable is a matrix variable in Mosek.
// Add the constraint lower ≤ <A̅ₘₙ, X̅> ≤ upper, where <A̅ₘₙ, X̅> = X̅(m, n)
const int bounded_matrix_var_count =
static_cast<int>(bounded_matrix_var_indices.size());
Eigen::VectorXd bounded_matrix_vars_lower(bounded_matrix_var_count);
Eigen::VectorXd bounded_matrix_vars_upper(bounded_matrix_var_count);
VectorX<symbolic::Variable> bounded_matrix_vars(bounded_matrix_var_count);
// var_in_bounded_matrix_vars[var.get_id()] is the index of a variable var in
// bounded_matrix_vars, namely
// bounded_matrix_vars[var_in_bounded_matrix_vars[var.get_id()] = var
std::unordered_map<symbolic::Variable::Id, int> var_in_bounded_matrix_vars;
var_in_bounded_matrix_vars.reserve(bounded_matrix_var_count);
for (int i = 0; i < bounded_matrix_var_count; ++i) {
bounded_matrix_vars_lower(i) = x_lb[bounded_matrix_var_indices[i]];
bounded_matrix_vars_upper(i) = x_ub[bounded_matrix_var_indices[i]];
bounded_matrix_vars(i) =
prog.decision_variable(bounded_matrix_var_indices[i]);
var_in_bounded_matrix_vars.emplace(
prog.decision_variable(bounded_matrix_var_indices[i]).get_id(), i);
}
Eigen::SparseMatrix<double> A_eye(bounded_matrix_var_count,
bounded_matrix_var_count);
A_eye.setIdentity();
Eigen::SparseMatrix<double> B_zero(bounded_matrix_var_count, 0);
B_zero.setZero();
// Make sure after calling AddLinearConstraintToMosek, the number of newly
// added linear constraints is bounded_matrix_var_count. This is important
// because we determine the index of the dual variable for bounds on matrix
// variables based on the order of adding linear constraints in
// AddLinearConstraintToMosek.
int num_linear_constraints_before = 0;
rescode = MSK_getnumcon(this->task_, &num_linear_constraints_before);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = AddLinearConstraintToMosek(
prog, A_eye, B_zero, bounded_matrix_vars_lower, bounded_matrix_vars_upper,
bounded_matrix_vars, {}, LinearConstraintBoundType::kInequality);
if (rescode != MSK_RES_OK) {
return rescode;
}
int num_linear_constraints_after = 0;
rescode = MSK_getnumcon(this->task_, &num_linear_constraints_after);
if (rescode != MSK_RES_OK) {
return rescode;
}
DRAKE_DEMAND(num_linear_constraints_after ==
num_linear_constraints_before + bounded_matrix_var_count);
// Add dual variables.
for (const auto& binding : prog.bounding_box_constraints()) {
ConstraintDualIndices lower_bound_duals(binding.variables().rows());
ConstraintDualIndices upper_bound_duals(binding.variables().rows());
for (int i = 0; i < binding.variables().rows(); ++i) {
const int var_index =
prog.FindDecisionVariableIndex(binding.variables()(i));
auto it1 =
decision_variable_to_mosek_nonmatrix_variable().find(var_index);
int dual_variable_index_if_active = -1;
if (it1 != decision_variable_to_mosek_nonmatrix_variable().end()) {
// Add the dual variables for the constraint registered as bounds on
// Mosek non-matrix variables.
lower_bound_duals[i].type = DualVarType::kVariableBound;
upper_bound_duals[i].type = DualVarType::kVariableBound;
dual_variable_index_if_active = it1->second;
} else {
// This variable is a Mosek matrix variable. The bound on this variable
// is imposed as a linear constraint.
DRAKE_DEMAND(
decision_variable_to_mosek_matrix_variable().contains(var_index));
lower_bound_duals[i].type = DualVarType::kLinearConstraint;
upper_bound_duals[i].type = DualVarType::kLinearConstraint;
const int linear_constraint_index =
num_linear_constraints_before +
var_in_bounded_matrix_vars.at(binding.variables()(i).get_id());
dual_variable_index_if_active = linear_constraint_index;
}
if (binding.evaluator()->lower_bound()(i) == x_lb[var_index]) {
// The lower bound can be active.
lower_bound_duals[i].index = dual_variable_index_if_active;
} else {
// The lower bound can't be active.
lower_bound_duals[i].index = -1;
}
if (binding.evaluator()->upper_bound()(i) == x_ub[var_index]) {
// The upper bound can be active.
upper_bound_duals[i].index = dual_variable_index_if_active;
} else {
// The upper bound can't be active.
upper_bound_duals[i].index = -1;
}
}
dual_indices->try_emplace(binding, lower_bound_duals, upper_bound_duals);
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddQuadraticConstraints(
const MathematicalProgram& prog,
std::unordered_map<Binding<QuadraticConstraint>, MSKint64t>* dual_indices) {
MSKrescodee rescode = MSK_RES_OK;
int num_existing_constraints = 0;
rescode = MSK_getnumcon(task_, &num_existing_constraints);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = MSK_appendcons(task_, prog.quadratic_constraints().size());
if (rescode != MSK_RES_OK) {
return rescode;
}
// We count the total number of non-zero entries in all Hessian matrices
// of the quadratic constraint.
int nnz_hessian = 0;
// We also count the total number of non-zero entries in all the linear
// coefficients of the quadratic constraint.
int nnz_linear = 0;
for (const auto& constraint : prog.quadratic_constraints()) {
for (int i = 0; i < constraint.variables().rows(); ++i) {
for (int j = 0; j <= i; ++j) {
if (constraint.evaluator()->Q()(i, j) != 0) {
++nnz_hessian;
}
}
if (constraint.evaluator()->b()(i) != 0) {
++nnz_linear;
}
}
}
// Mosek represents the Hessian matrix using the tuple (qcsubk, qcsubi,
// qcsubj, qcval). Where qcsubk is the index of the constraint, (qcsubi[i],
// qcsubj[i], qcval[i]) is the (row_index, column_index, value) of the
// lower-diagonal entries of the Hessian matrices.
std::vector<MSKint32t> qcsubk, qcsubi, qcsubj;
std::vector<MSKrealt> qcval;
qcsubk.reserve(nnz_hessian);
qcsubi.reserve(nnz_hessian);
qcsubj.reserve(nnz_hessian);
qcval.reserve(nnz_hessian);
// Store all the linear entries in all quadratic constraints into
// A * decision_vars, where A is a sparse matrix, whose non-zero entries is
// recorded by A_triplets;
std::vector<Eigen::Triplet<double>> A_triplets;
A_triplets.reserve(nnz_linear);
for (int constraint_count = 0;
constraint_count < static_cast<int>(prog.quadratic_constraints().size());
++constraint_count) {
const Binding<QuadraticConstraint>& constraint =
prog.quadratic_constraints()[constraint_count];
// Find the variable index in mosek
std::vector<int> decision_variable_in_mosek_index(
constraint.variables().rows());
// If any decision variable is a Mosek matrix variable, then we throw an
// error. Mosek doesn't support a matrix variable in quadratic constraint
// yet.
for (int i = 0; i < constraint.variables().rows(); ++i) {
const int decision_var_index =
prog.FindDecisionVariableIndex(constraint.variables()(i));
if (decision_variable_to_mosek_matrix_variable().count(
decision_var_index) > 0) {
throw std::runtime_error(fmt::format(
"MosekSolverProgram::AddQuaraticConstraint(): variable {} shows up "
"in the quadratic constraint {}, but this "
"variable also shows up in the matrix PSD constraint. Mosek "
"doesn't support a matrix variable in the quadratic constraint yet",
prog.decision_variable(decision_var_index).get_name(), constraint));
} else {
decision_variable_in_mosek_index[i] =
decision_variable_to_mosek_nonmatrix_variable().at(
decision_var_index);
}
}
for (int j = 0; j < constraint.variables().rows(); ++j) {
for (int i = j; i < constraint.variables().rows(); ++i) {
if (constraint.evaluator()->Q()(i, j) != 0) {
qcsubk.push_back(num_existing_constraints + constraint_count);
qcsubi.push_back(decision_variable_in_mosek_index[i]);
qcsubj.push_back(decision_variable_in_mosek_index[j]);
if (i == j) {
qcval.push_back(constraint.evaluator()->Q()(i, j));
} else {
if (decision_variable_in_mosek_index[i] !=
decision_variable_in_mosek_index[j]) {
qcval.push_back(constraint.evaluator()->Q()(i, j));
} else {
// decision_var[i] and decision_var[j] are the same variable. This
// should not be added as an off-diagonal term, but a diagonal
// term in the Hessian matrix in Mosek. Namely we add (Q()(i, j) +
// Q()(j, i)) * decision_var[i] * decision_var[j] = (Q()(i, j) +
// Q()(j, i)) * decision_var[i] * decision_var[i], namely the
// coefficient is for the diagonal term is 2 * Q()(i, j).
// Consider an example:
// x' * Q * x with x = [var[0], var[0]]. This is equivalent to
// (Q(0, 0) + Q(1, 1) + Q(0, 1) + Q(1, 0)) * var[0] * var[0].
// Notice that both Q(0, 1) and Q(1, 0) appear in the coefficients
// of the square term var[0] * var[0].
qcval.push_back(2 * constraint.evaluator()->Q()(i, j));
}
}
}
}
}
// Set the linear terms.
for (int i = 0; i < constraint.variables().rows(); ++i) {
if (constraint.evaluator()->b()(i) != 0) {
A_triplets.emplace_back(constraint_count,
decision_variable_in_mosek_index[i],
constraint.evaluator()->b()(i));
}
}
// Set dual variable index.
dual_indices->emplace(constraint,
num_existing_constraints + constraint_count);
// Set constraint bounds.
MSKboundkeye bound_key{MSK_BK_FR};
const double& lb = constraint.evaluator()->lower_bound()(0);
const double& ub = constraint.evaluator()->upper_bound()(0);
if (std::isfinite(lb) && std::isfinite(ub)) {
if (lb == ub) {
bound_key = MSK_BK_FX;
} else {
bound_key = MSK_BK_RA;
}
} else if (std::isfinite(lb)) {
bound_key = MSK_BK_LO;
} else if (std::isfinite(ub)) {
bound_key = MSK_BK_UP;
} else {
bound_key = MSK_BK_FR;
}
// Pre-allocate the size for the Q matrix according to
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.putqcon
rescode = MSK_putmaxnumqnz(task_, qcsubi.size());
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = MSK_putconbound(
task_, num_existing_constraints + constraint_count, bound_key, lb, ub);
if (rescode != MSK_RES_OK) {
return rescode;
}
}
// Set the Hessian of all the quadratic constraints.
// Note that MSK_putqcon will handle duplicated entries automatically.
rescode = MSK_putqcon(task_, qcsubi.size(), qcsubk.data(), qcsubi.data(),
qcsubj.data(), qcval.data());
// Set the linear coefficients of all the quadratic constraints.
int num_mosek_vars;
rescode = MSK_getnumvar(task_, &num_mosek_vars);
if (rescode != MSK_RES_OK) {
return rescode;
}
Eigen::SparseMatrix<double, Eigen::ColMajor> A(
prog.quadratic_constraints().size(), num_mosek_vars);
A.setFromTriplets(A_triplets.begin(), A_triplets.end());
for (int i = 0; i < A.cols(); ++i) {
for (Eigen::SparseMatrix<double, Eigen::ColMajor>::InnerIterator it(A, i);
it; ++it) {
rescode = MSK_putaij(task_, num_existing_constraints + it.row(), it.col(),
it.value());
if (rescode != MSK_RES_OK) {
return rescode;
}
}
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddAffineConeConstraint(
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 Eigen::VectorXd& c, MSKdomaintypee cone_type, MSKint64t* acc_index) {
MSKrescodee rescode = MSK_RES_OK;
std::vector<MSKint32t> F_subi;
std::vector<MSKint32t> F_subj;
std::vector<MSKrealt> F_valij;
std::vector<std::unordered_map<
MSKint64t, std::pair<std::vector<MSKint64t>, std::vector<MSKrealt>>>>
bar_F;
// Get the dimension of this affine expression.
const int afe_dim = A.rows();
this->ParseLinearExpression(prog, A, B, decision_vars,
slack_vars_mosek_indices, &F_subi, &F_subj,
&F_valij, &bar_F);
// Get the total number of affine expressions.
MSKint64t num_afe{0};
rescode = MSK_getnumafe(task_, &num_afe);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = MSK_appendafes(task_, afe_dim);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Now increase F_subi by num_afe and add F matrix to Mosek affine
// expressions.
std::vector<MSKint64t> F_subi_increased(F_subi.size());
for (int i = 0; i < static_cast<int>(F_subi.size()); ++i) {
F_subi_increased[i] = F_subi[i] + num_afe;
}
rescode = MSK_putafefentrylist(task_, F_subi_increased.size(),
F_subi_increased.data(), F_subj.data(),
F_valij.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
// Add g vector.
rescode = MSK_putafegslice(task_, num_afe, num_afe + afe_dim, c.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
// Now handle the part in the affine expression that involves the mosek matrix
// variables.
// bar_F is non-empty only if this affine expression involves the mosek matrix
// variables. We need to check if bar_F is non-empty, so that we can call
// bar_F[i] in the inner loop.
if (!bar_F.empty()) {
for (int i = 0; i < afe_dim; ++i) {
for (const auto& [j, sub_weights] : bar_F[i]) {
const std::vector<MSKint64t>& sub = sub_weights.first;
rescode = MSK_putafebarfentry(task_, num_afe + i, j, sub.size(),
sub.data(), sub_weights.second.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
}
}
}
// Create the domain.
MSKint64t dom_idx;
switch (cone_type) {
case MSK_DOMAIN_QUADRATIC_CONE: {
rescode = MSK_appendquadraticconedomain(task_, afe_dim, &dom_idx);
break;
}
case MSK_DOMAIN_RQUADRATIC_CONE: {
rescode = MSK_appendrquadraticconedomain(task_, afe_dim, &dom_idx);
break;
}
case MSK_DOMAIN_PRIMAL_EXP_CONE: {
rescode = MSK_appendprimalexpconedomain(task_, &dom_idx);
break;
}
case MSK_DOMAIN_SVEC_PSD_CONE: {
rescode = MSK_appendsvecpsdconedomain(task_, afe_dim, &dom_idx);
break;
}
default: {
throw std::runtime_error("MosekSolverProgram: unsupported cone type.");
}
}
if (rescode != MSK_RES_OK) {
return rescode;
}
// Obtain the affine cone index.
rescode = MSK_getnumacc(task_, acc_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Add the actual affine cone constraint.
rescode = MSK_appendaccseq(task_, dom_idx, afe_dim, num_afe, nullptr);
if (rescode != MSK_RES_OK) {
return rescode;
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddPositiveSemidefiniteConstraints(
const MathematicalProgram& prog,
std::unordered_map<Binding<PositiveSemidefiniteConstraint>, MSKint32t>*
psd_barvar_indices) {
MSKrescodee rescode = MSK_RES_OK;
// First get the current number of bar matrix vars before appending the new
// ones.
MSKint32t numbarvar;
rescode = MSK_getnumbarvar(task_, &numbarvar);
if (rescode != MSK_RES_OK) {
return rescode;
}
std::vector<MSKint32t> bar_var_dimension;
bar_var_dimension.reserve(prog.positive_semidefinite_constraints().size());
int psd_count = 0;
for (const auto& binding : prog.positive_semidefinite_constraints()) {
bar_var_dimension.push_back(binding.evaluator()->matrix_rows());
psd_barvar_indices->emplace(binding, numbarvar + psd_count);
psd_count++;
}
rescode = MSK_appendbarvars(task_, bar_var_dimension.size(),
bar_var_dimension.data());
return rescode;
}
MSKrescodee MosekSolverProgram::AddLinearMatrixInequalityConstraint(
const MathematicalProgram& prog,
std::unordered_map<Binding<LinearMatrixInequalityConstraint>, MSKint64t>*
acc_indices) {
// Use Mosek's "affine cone constraint". See
// https://docs.mosek.com/latest/capi/tutorial-sdo-shared.html#example-sdo-lmi-linear-matrix-inequalities-and-the-vectorized-semidefinite-domain
// for more details.
DRAKE_ASSERT(acc_indices != nullptr);
MSKrescodee rescode = MSK_RES_OK;
const double sqrt2 = std::sqrt(2);
// For each LMI constraint, to impose the LMI that
// F0 + x1 * F1 + x2 * F2 + ... + xk * Fk is psd,
// Mosek takes the lower triangular part of the psd matrix, scales the
// off-diagonal terms by sqrt(2), and impose that the concatenation of the
// scaled lower triangular part is in the SVEC_PSD_CONE.
// We write the concatenated scaled lower-triangular part of
// F0 + x1 * F1 + x2 * F2 + ... + xk * Fk
// as
// A * x + c
// where A is a sparse matrix.
std::vector<Eigen::Triplet<double>> A_triplets;
for (const auto& binding : prog.linear_matrix_inequality_constraints()) {
// Allocate memory for A_triplets. We allocate the maximal memory by
// assuming that A is dense.
// TODO(hongkai.dai): change LinearMatrixInequalityConstraint::F() to return
// a vector of sparse matrices, and call std::vector::reserve here to
// reserve the right amount of memory.
A_triplets.reserve((binding.evaluator()->matrix_rows() + 1) *
binding.evaluator()->matrix_rows() *
binding.variables().rows());
int A_row_index = 0;
Eigen::VectorXd c(binding.evaluator()->matrix_rows() *
(binding.evaluator()->matrix_rows() + 1) / 2);
for (int j = 0; j < binding.evaluator()->matrix_rows(); ++j) {
for (int i = j; i < binding.evaluator()->matrix_rows(); ++i) {
const double scaling_factor = i == j ? 1 : sqrt2;
c(A_row_index) = binding.evaluator()->F().at(0)(i, j) * scaling_factor;
for (int k = 1; k < ssize(binding.evaluator()->F()); ++k) {
if (binding.evaluator()->F()[k](i, j) != 0) {
A_triplets.emplace_back(
A_row_index, k - 1,
binding.evaluator()->F()[k](i, j) * scaling_factor);
}
}
++A_row_index;
}
}
Eigen::SparseMatrix<double> A(c.rows(),
binding.evaluator()->F().size() - 1);
A.setFromTriplets(A_triplets.begin(), A_triplets.end());
MSKint64t acc_index;
rescode = this->AddAffineConeConstraint(
prog, A, Eigen::SparseMatrix<double>(A.rows(), 0), binding.variables(),
{}, c, MSK_DOMAIN_SVEC_PSD_CONE, &acc_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
acc_indices->emplace(binding, acc_index);
A_triplets.clear();
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddLinearCost(
const Eigen::SparseVector<double>& linear_coeff,
const VectorX<symbolic::Variable>& linear_vars,
const MathematicalProgram& prog) {
MSKrescodee rescode = MSK_RES_OK;
// The cost linear_coeff' * linear_vars could be written as
// c' * x + ∑ᵢ <C̅ᵢ, X̅ᵢ>, where X̅ᵢ is the i'th matrix variable stored
// inside Mosek, x are the non-matrix variables in Mosek. Mosek API
// requires adding the cost for matrix and non-matrix variables separately.
int num_bar_var = 0;
rescode = MSK_getnumbarvar(task_, &num_bar_var);
if (rescode != MSK_RES_OK) {
return rescode;
}
std::vector<std::vector<Eigen::Triplet<double>>> C_bar_lower_triplets(
num_bar_var);
for (Eigen::SparseVector<double>::InnerIterator it(linear_coeff); it; ++it) {
const symbolic::Variable& var = linear_vars(it.row());
const int var_index = prog.FindDecisionVariableIndex(var);
auto it1 = decision_variable_to_mosek_nonmatrix_variable().find(var_index);
if (it1 != decision_variable_to_mosek_nonmatrix_variable().end()) {
// This variable is a non-matrix variable.
rescode =
MSK_putcj(task_, static_cast<MSKint32t>(it1->second), it.value());
if (rescode != MSK_RES_OK) {
return rescode;
}
} else {
// Aggregate the matrix C̅ᵢ
auto it2 = decision_variable_to_mosek_matrix_variable().find(var_index);
DRAKE_DEMAND(it2 != decision_variable_to_mosek_matrix_variable().end());
C_bar_lower_triplets[it2->second.bar_matrix_index()].emplace_back(
it2->second.row_index(), it2->second.col_index(),
it2->second.row_index() == it2->second.col_index() ? it.value()
: it.value() / 2);
}
}
// Add the cost ∑ᵢ <C̅ᵢ, X̅ᵢ>
for (int i = 0; i < num_bar_var; ++i) {
if (C_bar_lower_triplets[i].size() > 0) {
int matrix_rows{0};
rescode = MSK_getdimbarvarj(task_, i, &matrix_rows);
if (rescode != MSK_RES_OK) {
return rescode;
}
std::vector<MSKint32t> Ci_bar_lower_rows, Ci_bar_lower_cols;
std::vector<MSKrealt> Ci_bar_lower_values;
ConvertTripletsToVectors(C_bar_lower_triplets[i], matrix_rows,
matrix_rows, &Ci_bar_lower_rows,
&Ci_bar_lower_cols, &Ci_bar_lower_values);
MSKint64t Ci_bar_index{0};
// Create the sparse matrix C̅ᵢ.
rescode = MSK_appendsparsesymmat(
task_, matrix_rows, Ci_bar_lower_rows.size(),
Ci_bar_lower_rows.data(), Ci_bar_lower_cols.data(),
Ci_bar_lower_values.data(), &Ci_bar_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Now add the cost <C̅ᵢ, X̅ᵢ>
const MSKrealt weight{1.0};
rescode = MSK_putbarcj(task_, i, 1, &Ci_bar_index, &weight);
}
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddQuadraticCostAsLinearCost(
const Eigen::SparseMatrix<double>& Q_lower,
const VectorX<symbolic::Variable>& quadratic_vars,
const MathematicalProgram& prog) {
// We can add the quaratic cost 0.5 * quadratic_vars' * Q * quadratic_vars as
// a linear cost with a rotated Lorentz cone constraint. To do so, we
// introduce a slack variable s, with the rotated Lorentz cone constraint
// 2s >= | L * quadratic_vars|²,
// where L'L = Q. We then minimize s.
MSKrescodee rescode = MSK_RES_OK;
// Unfortunately the sparse Cholesky decomposition in Eigen requires GPL
// license, which is incompatible with Drake's license, so we convert the
// sparse Q_lower matrix to a dense matrix, and use the dense Cholesky
// decomposition instead.
const Eigen::MatrixXd L = math::DecomposePSDmatrixIntoXtransposeTimesX(
Eigen::MatrixXd(Q_lower), std::numeric_limits<double>::epsilon());
MSKint32t num_mosek_vars = 0;
rescode = MSK_getnumvar(task_, &num_mosek_vars);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Add a new variable s.
rescode = MSK_appendvars(task_, 1);
if (rescode != MSK_RES_OK) {
return rescode;
}
const MSKint32t s_index = num_mosek_vars;
// Put bound on s as s >= 0.
rescode = MSK_putvarbound(task_, s_index, MSK_BK_LO, 0, MSK_INFINITY);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Add the constraint that
// [ 1] = [0 0] * [s] + [1]
// [ s] = [1 0] [x] [0]
// [L*x] [0 L] [0]
// is in the rotated Lorentz cone, where we denote x = quadratic_vars.
// First add the affine expression
// [0 0] * [s] + [1]
// [1 0] * [x] [0]
// [0 L] [0]
// L_bar = [0]
// [0]
// [L]
Eigen::MatrixXd L_bar = Eigen::MatrixXd::Zero(L.rows() + 2, L.cols());
L_bar.bottomRows(L.rows()) = L;
const Eigen::SparseMatrix<double> L_bar_sparse = L_bar.sparseView();
// s_coeff = [0;1;...;0]
Eigen::SparseMatrix<double> s_coeff(L.rows() + 2, 1);
std::array<Eigen::Triplet<double>, 1> s_coeff_triplets;
s_coeff_triplets[0] = Eigen::Triplet<double>(1, 0, 1);
s_coeff.setFromTriplets(s_coeff_triplets.begin(), s_coeff_triplets.end());
MSKint64t acc_index;
// g = [1;0;0;...;0]
Eigen::VectorXd g = Eigen::VectorXd::Zero(L.rows() + 2);
g(0) = 1;
std::vector<MSKint32t> slack_vars(1);
slack_vars[0] = s_index;
rescode = this->AddAffineConeConstraint(
prog, L_bar_sparse, s_coeff, quadratic_vars, slack_vars, g,
MSK_DOMAIN_RQUADRATIC_CONE, &acc_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Now add the linear cost on s
rescode = MSK_putcj(task_, s_index, 1.);
if (rescode != MSK_RES_OK) {
return rescode;
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddQuadraticCost(
const Eigen::SparseMatrix<double>& Q_quadratic_vars,
const VectorX<symbolic::Variable>& quadratic_vars,
const MathematicalProgram& prog) {
MSKrescodee rescode = MSK_RES_OK;
// Add the quadratic cost 0.5 * quadratic_vars' * Q_quadratic_vars *
// quadratic_vars to Mosek. Q_lower_triplets correspond to the matrix that
// multiplies with all the non-matrix decision variables in Mosek, not with
// `quadratic_vars`. We need to map each variable in `quadratic_vars` to its
// index in Mosek non-matrix variables.
std::vector<int> var_indices(quadratic_vars.rows());
for (int i = 0; i < quadratic_vars.rows(); ++i) {
var_indices[i] = decision_variable_to_mosek_nonmatrix_variable().at(
prog.FindDecisionVariableIndex(quadratic_vars(i)));
}
std::vector<Eigen::Triplet<double>> Q_lower_triplets;
for (int j = 0; j < Q_quadratic_vars.outerSize(); ++j) {
for (Eigen::SparseMatrix<double>::InnerIterator it(Q_quadratic_vars, j); it;
++it) {
Q_lower_triplets.emplace_back(var_indices[it.row()],
var_indices[it.col()], it.value());
}
}
std::vector<MSKint32t> qrow, qcol;
std::vector<double> qval;
const int xDim = decision_variable_to_mosek_nonmatrix_variable().size();
ConvertTripletsToVectors(Q_lower_triplets, xDim, xDim, &qrow, &qcol, &qval);
const int Q_nnz = static_cast<int>(qrow.size());
rescode = MSK_putqobj(task_, Q_nnz, qrow.data(), qcol.data(), qval.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddL2NormCost(
const Eigen::SparseMatrix<double>& C, const Eigen::VectorXd& d,
const VectorX<symbolic::Variable>& x, const MathematicalProgram& prog) {
// We will take the following steps:
// 1. Add a slack variable t.
// 2. Add the affine cone constraint
// [0 1] * [x] + [0] is in Lorentz cone.
// [C 0] [t] [d]
// 3. Add the cost min t.
MSKrescodee rescode = MSK_RES_OK;
// Add a slack variable t.
MSKint32t num_mosek_vars = 0;
rescode = MSK_getnumvar(task_, &num_mosek_vars);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = MSK_appendvars(task_, 1);
if (rescode != MSK_RES_OK) {
return rescode;
}
const MSKint32t t_index = num_mosek_vars;
// Put the bound on t as t >= 0.
rescode = MSK_putvarbound(task_, t_index, MSK_BK_LO, 0, MSK_INFINITY);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Add the constraint that
// [0 1] * [x] + [0]
// [C 0] [t] [d]
// is in Lorentz cone.
//
// We use A = [0] and B = [1]
// [C] [0]
std::vector<Eigen::Triplet<double>> A_triplets;
A_triplets.reserve(C.nonZeros());
for (int i = 0; i < C.outerSize(); ++i) {
for (Eigen::SparseMatrix<double>::InnerIterator it(C, i); it; ++it) {
A_triplets.emplace_back(it.row() + 1, it.col(), it.value());
}
}
Eigen::SparseMatrix<double> A(C.rows() + 1, C.cols());
A.setFromTriplets(A_triplets.begin(), A_triplets.end());
std::array<Eigen::Triplet<double>, 1> B_triplets;
B_triplets[0] = Eigen::Triplet<double>(0, 0, 1);
Eigen::SparseMatrix<double> B(C.rows() + 1, 1);
B.setFromTriplets(B_triplets.begin(), B_triplets.end());
MSKint64t acc_index;
Eigen::VectorXd offset(1 + C.rows());
offset(0) = 0;
offset.tail(C.rows()) = d;
rescode = this->AddAffineConeConstraint(
prog, A, B, x, std::vector<MSKint32t>{{t_index}}, offset,
MSK_DOMAIN_QUADRATIC_CONE, &acc_index);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Add the linear cost min t.
rescode = MSK_putcj(task_, t_index, 1.0);
if (rescode != MSK_RES_OK) {
return rescode;
}
return rescode;
}
MSKrescodee MosekSolverProgram::AddCosts(const MathematicalProgram& prog) {
// Add the cost in the form 0.5 * x' * Q_all * x + linear_coeff' * x + ∑ᵢ <C̅ᵢ,
// X̅ᵢ>, where X̅ᵢ is the i'th matrix variable stored inside Mosek.
// First aggregate all the linear and quadratic costs.
Eigen::SparseMatrix<double> Q_lower;
VectorX<symbolic::Variable> quadratic_vars;
Eigen::SparseVector<double> linear_coeff;
VectorX<symbolic::Variable> linear_vars;
double constant_cost;
AggregateQuadraticAndLinearCosts(prog.quadratic_costs(), prog.linear_costs(),
&Q_lower, &quadratic_vars, &linear_coeff,
&linear_vars, &constant_cost);
MSKrescodee rescode = MSK_RES_OK;
// Add linear cost.
rescode = AddLinearCost(linear_coeff, linear_vars, prog);
if (rescode != MSK_RES_OK) {
return rescode;
}
if (!prog.quadratic_costs().empty()) {
if (prog.quadratic_constraints().empty() &&
prog.lorentz_cone_constraints().empty() &&
prog.rotated_lorentz_cone_constraints().empty() &&
prog.linear_matrix_inequality_constraints().empty() &&
prog.positive_semidefinite_constraints().empty() &&
prog.exponential_cone_constraints().empty() &&
prog.l2norm_costs().empty()) {
// This is a QP, add the quadratic cost.
rescode = AddQuadraticCost(Q_lower, quadratic_vars, prog);
if (rescode != MSK_RES_OK) {
return rescode;
}
} else {
// Not a QP, now convert the quadratic cost to a linear cost with a
// second-order cone constraint.
rescode = AddQuadraticCostAsLinearCost(Q_lower, quadratic_vars, prog);
if (rescode != MSK_RES_OK) {
return rescode;
}
}
}
// Now add all the L2NormCost.
for (const auto& l2norm_cost : prog.l2norm_costs()) {
rescode = this->AddL2NormCost(l2norm_cost.evaluator()->get_sparse_A(),
l2norm_cost.evaluator()->b(),
l2norm_cost.variables(), prog);
if (rescode != MSK_RES_OK) {
return rescode;
}
}
// Provide constant / fixed cost.
MSK_putcfix(task_, constant_cost);
return rescode;
}
MSKrescodee MosekSolverProgram::SpecifyVariableType(
const MathematicalProgram& prog, bool* with_integer_or_binary_variables) {
MSKrescodee rescode = MSK_RES_OK;
for (const auto& decision_variable_mosek_variable :
decision_variable_to_mosek_nonmatrix_variable()) {
const int mosek_variable_index = decision_variable_mosek_variable.second;
switch (prog.decision_variable(decision_variable_mosek_variable.first)
.get_type()) {
case MathematicalProgram::VarType::INTEGER: {
rescode = MSK_putvartype(task_, mosek_variable_index, MSK_VAR_TYPE_INT);
if (rescode != MSK_RES_OK) {
return rescode;
}
*with_integer_or_binary_variables = true;
break;
}
case MathematicalProgram::VarType::BINARY: {
*with_integer_or_binary_variables = true;
rescode = MSK_putvartype(task_, mosek_variable_index, MSK_VAR_TYPE_INT);
if (rescode != MSK_RES_OK) {
return rescode;
}
double xi_lb = NAN;
double xi_ub = NAN;
MSKboundkeye bound_key;
rescode = MSK_getvarbound(task_, mosek_variable_index, &bound_key,
&xi_lb, &xi_ub);
if (rescode != MSK_RES_OK) {
return rescode;
}
xi_lb = std::max(0.0, xi_lb);
xi_ub = std::min(1.0, xi_ub);
rescode = MSK_putvarbound(task_, mosek_variable_index, MSK_BK_RA, xi_lb,
xi_ub);
if (rescode != MSK_RES_OK) {
return rescode;
}
break;
}
case MathematicalProgram::VarType::CONTINUOUS: {
// Do nothing.
break;
}
case MathematicalProgram::VarType::BOOLEAN: {
throw std::runtime_error(
"Boolean variables should not be used with Mosek 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 Mosek solver.");
}
}
for (const auto& decision_variable_mosek_matrix_variable :
decision_variable_to_mosek_matrix_variable()) {
const auto& decision_variable =
prog.decision_variable(decision_variable_mosek_matrix_variable.first);
if (decision_variable.get_type() !=
MathematicalProgram::VarType::CONTINUOUS) {
throw std::invalid_argument("The variable " +
decision_variable.get_name() +
"is a positive semidefinite matrix variable, "
"but it doesn't have continuous type.");
}
}
return rescode;
}
MapDecisionVariableToMosekVariable::MapDecisionVariableToMosekVariable(
const MathematicalProgram& prog) {
// Each PositiveSemidefiniteConstraint will add one matrix variable to Mosek.
int psd_constraint_count = 0;
for (const auto& psd_constraint : prog.positive_semidefinite_constraints()) {
// The bounded variables of a psd constraint is the "flat" version of the
// symmetrix matrix variables, stacked column by column. We only need to
// store the lower triangular part of this symmetric matrix in Mosek.
const int matrix_rows = psd_constraint.evaluator()->matrix_rows();
for (int j = 0; j < matrix_rows; ++j) {
for (int i = j; i < matrix_rows; ++i) {
const MatrixVariableEntry matrix_variable_entry(psd_constraint_count, i,
j, matrix_rows);
const int decision_variable_index = prog.FindDecisionVariableIndex(
psd_constraint.variables()(j * matrix_rows + i));
auto it = decision_variable_to_mosek_matrix_variable.find(
decision_variable_index);
if (it == decision_variable_to_mosek_matrix_variable.end()) {
// This variable has not been registered as a mosek matrix variable
// before.
decision_variable_to_mosek_matrix_variable.emplace_hint(
it, decision_variable_index, matrix_variable_entry);
} else {
// This variable has been registered as a mosek matrix variable
// already. This matrix variable entry will be registered into
// matrix_variable_entries_for_same_decision_variable.
auto it_same_decision_variable =
matrix_variable_entries_for_same_decision_variable.find(
decision_variable_index);
if (it_same_decision_variable !=
matrix_variable_entries_for_same_decision_variable.end()) {
it_same_decision_variable->second.push_back(matrix_variable_entry);
} else {
matrix_variable_entries_for_same_decision_variable.emplace_hint(
it_same_decision_variable, decision_variable_index,
std::vector<MatrixVariableEntry>(
{it->second, matrix_variable_entry}));
}
}
}
}
psd_constraint_count++;
}
// All the non-matrix variables in @p prog is stored in another vector inside
// Mosek.
int nonmatrix_variable_count = 0;
for (int i = 0; i < prog.num_vars(); ++i) {
if (!decision_variable_to_mosek_matrix_variable.contains(i)) {
decision_variable_to_mosek_nonmatrix_variable.emplace(
i, nonmatrix_variable_count++);
}
}
DRAKE_DEMAND(
static_cast<int>(decision_variable_to_mosek_matrix_variable.size() +
decision_variable_to_mosek_nonmatrix_variable.size()) ==
prog.num_vars());
}
MSKrescodee MosekSolverProgram::
AddEqualityConstraintBetweenMatrixVariablesForSameDecisionVariable() {
MSKrescodee rescode{MSK_RES_OK};
for (const auto& pair :
matrix_variable_entries_for_same_decision_variable()) {
int num_mosek_constraint;
rescode = MSK_getnumcon(task_, &num_mosek_constraint);
if (rescode != MSK_RES_OK) {
return rescode;
}
const auto& matrix_variable_entries = pair.second;
const int num_matrix_variable_entries =
static_cast<int>(matrix_variable_entries.size());
DRAKE_ASSERT(num_matrix_variable_entries >= 2);
rescode = MSK_appendcons(task_, num_matrix_variable_entries - 1);
if (rescode != MSK_RES_OK) {
return rescode;
}
for (int i = 1; i < num_matrix_variable_entries; ++i) {
const int linear_constraint_index = num_mosek_constraint + i - 1;
if (matrix_variable_entries[0].bar_matrix_index() !=
matrix_variable_entries[i].bar_matrix_index()) {
// We add the constraint X̅ᵢ(m, n) - X̅ⱼ(p, q) = 0 where the index of
// the bar matrix is different (i ≠ j).
rescode = AddScalarTimesMatrixVariableEntryToMosek(
linear_constraint_index, matrix_variable_entries[0], 1.0);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = AddScalarTimesMatrixVariableEntryToMosek(
linear_constraint_index, matrix_variable_entries[i], -1.0);
if (rescode != MSK_RES_OK) {
return rescode;
}
} else {
// We add the constraint that X̅ᵢ(m, n) - X̅ᵢ(p, q) = 0, where the index
// of the bar matrix (i) are the same. So the constraint is written as
// <A, X̅ᵢ> = 0, where
// A(m, n) = 1 if m == n else 0.5
// A(p, q) = -1 if p == q else -0.5
std::array<MSKint64t, 2> E_indices{};
rescode = AddMatrixVariableEntryCoefficientMatrixIfNonExistent(
matrix_variable_entries[0], &(E_indices[0]));
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = AddMatrixVariableEntryCoefficientMatrixIfNonExistent(
matrix_variable_entries[i], &(E_indices[1]));
if (rescode != MSK_RES_OK) {
return rescode;
}
// weights[0] = A(m, n), weights[1] = A(p, q).
std::array<MSKrealt, 2> weights{};
weights[0] = matrix_variable_entries[0].row_index() ==
matrix_variable_entries[0].col_index()
? 1.0
: 0.5;
weights[1] = matrix_variable_entries[i].row_index() ==
matrix_variable_entries[i].col_index()
? -1.0
: -0.5;
rescode = MSK_putbaraij(task_, linear_constraint_index,
matrix_variable_entries[0].bar_matrix_index(),
2, E_indices.data(), weights.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
}
rescode = SetMosekLinearConstraintBound(
linear_constraint_index, 0, 0, LinearConstraintBoundType::kEquality);
if (rescode != MSK_RES_OK) {
return rescode;
}
}
}
return rescode;
}
MSKrescodee MosekSolverProgram::SetPositiveSemidefiniteConstraintDualSolution(
const MathematicalProgram& prog,
const std::unordered_map<Binding<PositiveSemidefiniteConstraint>,
MSKint32t>& psd_barvar_indices,
MSKsoltypee whichsol, MathematicalProgramResult* result) const {
MSKrescodee rescode = MSK_RES_OK;
for (const auto& psd_constraint : prog.positive_semidefinite_constraints()) {
// Get the bar index of the Mosek matrix var.
const auto it = psd_barvar_indices.find(psd_constraint);
if (it == psd_barvar_indices.end()) {
throw std::runtime_error(
"SetPositiveSemidefiniteConstraintDualSolution: this positive "
"semidefinite constraint has not been "
"registered in Mosek as a matrix variable. This should not happen, "
"please post an issue on Drake: "
"https://github.com/RobotLocomotion/drake/issues/new.");
}
const auto bar_index = it->second;
// barsj stores the lower triangular values of the psd matrix (as the dual
// solution).
std::vector<MSKrealt> barsj(
psd_constraint.evaluator()->matrix_rows() *
(psd_constraint.evaluator()->matrix_rows() + 1) / 2);
rescode = MSK_getbarsj(task_, whichsol, bar_index, barsj.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
// Copy barsj to dual_lower. We don't use barsj directly since MSKrealt
// might be a different data type from double.
Eigen::VectorXd dual_lower(barsj.size());
for (int i = 0; i < dual_lower.rows(); ++i) {
dual_lower(i) = barsj[i];
}
result->set_dual_solution(psd_constraint, dual_lower);
}
return rescode;
}
namespace {
// Throws a runtime error if the mosek option is set incorrectly.
template <typename T>
void ThrowForInvalidOption(MSKrescodee rescode, const std::string& option,
const T& val) {
if (rescode != MSK_RES_OK) {
const std::string mosek_version =
fmt::format("{}.{}", MSK_VERSION_MAJOR, MSK_VERSION_MINOR);
throw std::runtime_error(fmt::format(
"MosekSolver(): cannot set Mosek option '{option}' to value '{value}', "
"response code {code}, check "
"https://docs.mosek.com/{version}/capi/response-codes.html for the "
"meaning of the response code, check "
"https://docs.mosek.com/{version}/capi/param-groups.html for allowable "
"values in C++, or "
"https://docs.mosek.com/{version}/pythonapi/param-groups.html "
"for allowable values in python.",
fmt::arg("option", option), fmt::arg("value", val),
fmt::arg("code", fmt_streamed(rescode)),
fmt::arg("version", mosek_version)));
}
}
// This function is used to print information for each iteration to the console,
// it will show PRSTATUS, PFEAS, DFEAS, etc. For more information, check out
// https://docs.mosek.com/10.1/capi/solver-io.html. This printstr is copied
// directly from https://docs.mosek.com/10.1/capi/solver-io.html#stream-logging.
void MSKAPI printstr(void*, const char str[]) {
printf("%s", str);
}
} // namespace
MSKrescodee MosekSolverProgram::UpdateOptions(
const SolverOptions& merged_options, const SolverId mosek_id,
bool* print_to_console, std::string* print_file_name,
std::optional<std::string>* msk_writedata) {
MSKrescodee rescode{MSK_RES_OK};
for (const auto& double_options : merged_options.GetOptionsDouble(mosek_id)) {
if (rescode == MSK_RES_OK) {
rescode = MSK_putnadouparam(task_, double_options.first.c_str(),
double_options.second);
ThrowForInvalidOption(rescode, double_options.first,
double_options.second);
}
}
for (const auto& int_options : merged_options.GetOptionsInt(mosek_id)) {
if (rescode == MSK_RES_OK) {
rescode = MSK_putnaintparam(task_, int_options.first.c_str(),
int_options.second);
ThrowForInvalidOption(rescode, int_options.first, int_options.second);
}
}
for (const auto& str_options : merged_options.GetOptionsStr(mosek_id)) {
if (rescode == MSK_RES_OK) {
if (str_options.first == "writedata") {
if (str_options.second != "") {
msk_writedata->emplace(str_options.second);
}
} else {
rescode = MSK_putnastrparam(task_, str_options.first.c_str(),
str_options.second.c_str());
ThrowForInvalidOption(rescode, str_options.first, str_options.second);
}
}
}
// log file.
*print_to_console = merged_options.get_print_to_console();
*print_file_name = merged_options.get_print_file_name();
// Refer to https://docs.mosek.com/10.1/capi/solver-io.html#stream-logging
// for Mosek stream logging.
// First we check if the user wants to print to both the console and the file.
// If true, throw an error BEFORE we create the log file through
// MSK_linkfiletotaskstream. Otherwise we might create the log file but cannot
// close it.
if (*print_to_console && !print_file_name->empty()) {
throw std::runtime_error(
"MosekSolver::Solve(): cannot print to both the console and the log "
"file.");
} else if (*print_to_console) {
if (rescode == MSK_RES_OK) {
rescode =
MSK_linkfunctotaskstream(task_, MSK_STREAM_LOG, nullptr, printstr);
}
} else if (!print_file_name->empty()) {
if (rescode == MSK_RES_OK) {
rescode = MSK_linkfiletotaskstream(task_, MSK_STREAM_LOG,
print_file_name->c_str(), 0);
}
}
return rescode;
}
MSKrescodee MosekSolverProgram::SetDualSolution(
MSKsoltypee which_sol, const MathematicalProgram& prog,
const std::unordered_map<
Binding<BoundingBoxConstraint>,
std::pair<ConstraintDualIndices, ConstraintDualIndices>>&
bb_con_dual_indices,
const DualMap<LinearConstraint>& linear_con_dual_indices,
const DualMap<LinearEqualityConstraint>& lin_eq_con_dual_indices,
const std::unordered_map<Binding<QuadraticConstraint>, MSKint64t>&
quadratic_constraint_dual_indices,
const std::unordered_map<Binding<LorentzConeConstraint>, MSKint64t>&
lorentz_cone_acc_indices,
const std::unordered_map<Binding<RotatedLorentzConeConstraint>, MSKint64t>&
rotated_lorentz_cone_acc_indices,
const std::unordered_map<Binding<ExponentialConeConstraint>, MSKint64t>&
exp_cone_acc_indices,
const std::unordered_map<Binding<PositiveSemidefiniteConstraint>,
MSKint32t>& psd_barvar_indices,
MathematicalProgramResult* result) const {
// TODO(hongkai.dai): support other types of constraints, like linear
// constraint, second order cone constraint, etc.
MSKrescodee rescode{MSK_RES_OK};
if (which_sol == MSK_SOL_ITG) {
// Mosek cannot return dual solution if the solution type is MSK_SOL_ITG
// (which stands for mixed integer optimizer), see
// https://docs.mosek.com/10.1/capi/accessing-solution.html#available-solutions
return rescode;
}
int num_mosek_vars{0};
rescode = MSK_getnumvar(task_, &num_mosek_vars);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Mosek dual variables for variable lower bounds (slx) and upper bounds
// (sux). Refer to
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getsolution
// for more explanation.
std::vector<MSKrealt> slx(num_mosek_vars);
std::vector<MSKrealt> sux(num_mosek_vars);
rescode = MSK_getslx(task_, which_sol, slx.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = MSK_getsux(task_, which_sol, sux.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
int num_linear_constraints{0};
rescode = MSK_getnumcon(task_, &num_linear_constraints);
if (rescode != MSK_RES_OK) {
return rescode;
}
// Mosek dual variables for linear constraints lower bounds (slc) and upper
// bounds (suc). Refer to
// https://docs.mosek.com/10.1/capi/alphabetic-functionalities.html#mosek.task.getsolution
// for more explanation.
std::vector<MSKrealt> slc(num_linear_constraints);
std::vector<MSKrealt> suc(num_linear_constraints);
rescode = MSK_getslc(task_, which_sol, slc.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = MSK_getsuc(task_, which_sol, suc.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
// Set the duals for the bounding box constraint.
SetBoundingBoxDualSolution(prog.bounding_box_constraints(), slx, sux, slc,
suc, bb_con_dual_indices, result);
// Set the duals for the linear constraint.
SetLinearConstraintDualSolution(prog.linear_constraints(), slc, suc,
linear_con_dual_indices, result);
// Set the duals for the linear equality constraint.
SetLinearConstraintDualSolution(prog.linear_equality_constraints(), slc, suc,
lin_eq_con_dual_indices, result);
SetQuadraticConstraintDualSolution(prog.quadratic_constraints(), slc, suc,
quadratic_constraint_dual_indices, result);
// Set the duals for the nonlinear conic constraint.
// Mosek provides the dual solution for nonlinear conic constraints only if
// the program is solved through interior point approach.
if (which_sol == MSK_SOL_ITR) {
std::vector<MSKrealt> snx(num_mosek_vars);
rescode = MSK_getsnx(task_, which_sol, snx.data());
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = SetAffineConeConstraintDualSolution(
prog.lorentz_cone_constraints(), task_, which_sol,
lorentz_cone_acc_indices, result);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = SetAffineConeConstraintDualSolution(
prog.rotated_lorentz_cone_constraints(), task_, which_sol,
rotated_lorentz_cone_acc_indices, result);
if (rescode != MSK_RES_OK) {
return rescode;
}
rescode = SetAffineConeConstraintDualSolution(
prog.exponential_cone_constraints(), task_, which_sol,
exp_cone_acc_indices, result);
if (rescode != MSK_RES_OK) {
return rescode;
}
}
rescode = SetPositiveSemidefiniteConstraintDualSolution(
prog, psd_barvar_indices, which_sol, result);
if (rescode != MSK_RES_OK) {
return rescode;
}
return rescode;
}
void SetBoundingBoxDualSolution(
const std::vector<Binding<BoundingBoxConstraint>>& constraints,
const std::vector<MSKrealt>& slx, const std::vector<MSKrealt>& sux,
const std::vector<MSKrealt>& slc, const std::vector<MSKrealt>& suc,
const std::unordered_map<
Binding<BoundingBoxConstraint>,
std::pair<ConstraintDualIndices, ConstraintDualIndices>>&
bb_con_dual_indices,
MathematicalProgramResult* result) {
auto set_dual_sol = [](int mosek_dual_lower_index, int mosek_dual_upper_index,
const std::vector<MSKrealt>& mosek_dual_lower,
const std::vector<MSKrealt>& mosek_dual_upper,
double* dual_sol) {
const double dual_lower = mosek_dual_lower_index == -1
? 0.
: mosek_dual_lower[mosek_dual_lower_index];
const double dual_upper = mosek_dual_upper_index == -1
? 0.
: mosek_dual_upper[mosek_dual_upper_index];
// Mosek defines all dual solutions as non-negative. However we use
// "reduced cost" as the dual solution, so the dual solution for a
// lower bound should be non-negative, while the dual solution for
// an upper bound should be non-positive.
if (dual_lower > dual_upper) {
// We use the larger dual as the active one.
*dual_sol = dual_lower;
} else {
*dual_sol = -dual_upper;
}
};
for (const auto& binding : constraints) {
ConstraintDualIndices lower_bound_duals, upper_bound_duals;
std::tie(lower_bound_duals, upper_bound_duals) =
bb_con_dual_indices.at(binding);
Eigen::VectorXd dual_sol =
Eigen::VectorXd::Zero(binding.evaluator()->num_vars());
for (int i = 0; i < binding.variables().rows(); ++i) {
switch (lower_bound_duals[i].type) {
case DualVarType::kVariableBound: {
set_dual_sol(lower_bound_duals[i].index, upper_bound_duals[i].index,
slx, sux, &(dual_sol(i)));
break;
}
case DualVarType::kLinearConstraint: {
set_dual_sol(lower_bound_duals[i].index, upper_bound_duals[i].index,
slc, suc, &(dual_sol(i)));
break;
}
default: {
throw std::runtime_error(
"The dual variable for a BoundingBoxConstraint lower bound can "
"only be slx or slc.");
}
}
}
result->set_dual_solution(binding, dual_sol);
}
}
void SetQuadraticConstraintDualSolution(
const std::vector<Binding<QuadraticConstraint>>& constraints,
const std::vector<MSKrealt>& slc, const std::vector<MSKrealt>& suc,
const std::unordered_map<Binding<QuadraticConstraint>, MSKint64t>&
quadratic_constraint_dual_indices,
MathematicalProgramResult* result) {
for (const auto& constraint : constraints) {
const double& lb = constraint.evaluator()->lower_bound()(0);
const double& ub = constraint.evaluator()->upper_bound()(0);
double dual_val{0};
const int dual_index = quadratic_constraint_dual_indices.at(constraint);
if (std::isfinite(lb) && std::isfinite(ub)) {
throw std::runtime_error(
"Cannot set the dual variable for this quadratic constraint in "
"Mosek. The quadratic constraint has finite lower and upper bound, "
"hence it cannot be convex.");
} else if (std::isfinite(lb)) {
dual_val = slc[dual_index];
} else if (std::isfinite(ub)) {
// Mosek defines all dual solutions as non-negative. However we use
// "reduced cost" as the dual solution, so the dual solution for a
// lower bound should be non-negative, while the dual solution for
// an upper bound should be non-positive. Hence we flip the sign of the
// dual solution when the quadratic constraint has an upper bound.
dual_val = -suc[dual_index];
}
result->set_dual_solution(constraint, Vector1d(dual_val));
}
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/linear_system_solver.h | #pragma once
#include <string>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/solver_base.h"
namespace drake {
namespace solvers {
/** Finds the least-square solution to the linear system A * x = b. */
class LinearSystemSolver final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearSystemSolver)
LinearSystemSolver();
~LinearSystemSolver() 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&);
static std::string UnsatisfiedProgramAttributes(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/csdp_solver_common.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/csdp_solver.h"
/* clang-format on */
#include "drake/common/never_destroyed.h"
#include "drake/solvers/mathematical_program.h"
// This file contains implementations that are common to both the available and
// unavailable flavor of this class.
namespace drake {
namespace solvers {
CsdpSolver::CsdpSolver()
: SolverBase(id(), &is_available, &is_enabled,
&ProgramAttributesSatisfied) {}
CsdpSolver::~CsdpSolver() = default;
SolverId CsdpSolver::id() {
static const never_destroyed<SolverId> singleton{"CSDP"};
return singleton.access();
}
bool CsdpSolver::is_enabled() {
return true;
}
bool CsdpSolver::ProgramAttributesSatisfied(const MathematicalProgram& prog) {
static const never_destroyed<ProgramAttributes> solver_capabilities(
std::initializer_list<ProgramAttribute>{
ProgramAttribute::kLinearCost, ProgramAttribute::kLinearConstraint,
ProgramAttribute::kLinearEqualityConstraint,
ProgramAttribute::kLorentzConeConstraint,
ProgramAttribute::kRotatedLorentzConeConstraint,
ProgramAttribute::kPositiveSemidefiniteConstraint});
return AreRequiredAttributesSupported(prog.required_capabilities(),
solver_capabilities.access());
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solver_type_converter.cc | #include "drake/solvers/solver_type_converter.h"
#include "drake/common/drake_assert.h"
#include "drake/solvers/clp_solver.h"
#include "drake/solvers/csdp_solver.h"
#include "drake/solvers/equality_constrained_qp_solver.h"
#include "drake/solvers/gurobi_solver.h"
#include "drake/solvers/ipopt_solver.h"
#include "drake/solvers/linear_system_solver.h"
#include "drake/solvers/moby_lcp_solver.h"
#include "drake/solvers/mosek_solver.h"
#include "drake/solvers/nlopt_solver.h"
#include "drake/solvers/osqp_solver.h"
#include "drake/solvers/scs_solver.h"
#include "drake/solvers/snopt_solver.h"
#include "drake/solvers/unrevised_lemke_solver.h"
namespace drake {
namespace solvers {
SolverId SolverTypeConverter::TypeToId(SolverType solver_type) {
switch (solver_type) {
case SolverType::kClp:
return ClpSolver::id();
case SolverType::kCsdp:
return CsdpSolver::id();
case SolverType::kEqualityConstrainedQP:
return EqualityConstrainedQPSolver::id();
case SolverType::kGurobi:
return GurobiSolver::id();
case SolverType::kIpopt:
return IpoptSolver::id();
case SolverType::kLinearSystem:
return LinearSystemSolver::id();
case SolverType::kMobyLCP:
return MobyLcpSolverId::id();
case SolverType::kMosek:
return MosekSolver::id();
case SolverType::kNlopt:
return NloptSolver::id();
case SolverType::kOsqp:
return OsqpSolver::id();
case SolverType::kSnopt:
return SnoptSolver::id();
case SolverType::kScs:
return ScsSolver::id();
case SolverType::kUnrevisedLemke:
return UnrevisedLemkeSolverId::id();
}
DRAKE_UNREACHABLE();
}
std::optional<SolverType> SolverTypeConverter::IdToType(SolverId solver_id) {
if (solver_id == ClpSolver::id()) {
return SolverType::kClp;
} else if (solver_id == CsdpSolver::id()) {
return SolverType::kCsdp;
} else if (solver_id == EqualityConstrainedQPSolver::id()) {
return SolverType::kEqualityConstrainedQP;
} else if (solver_id == GurobiSolver::id()) {
return SolverType::kGurobi;
} else if (solver_id == IpoptSolver::id()) {
return SolverType::kIpopt;
} else if (solver_id == LinearSystemSolver::id()) {
return SolverType::kLinearSystem;
} else if (solver_id == MobyLcpSolverId::id()) {
return SolverType::kMobyLCP;
} else if (solver_id == MosekSolver::id()) {
return SolverType::kMosek;
} else if (solver_id == NloptSolver::id()) {
return SolverType::kNlopt;
} else if (solver_id == SnoptSolver::id()) {
return SolverType::kSnopt;
} else if (solver_id == OsqpSolver::id()) {
return SolverType::kOsqp;
} else if (solver_id == ScsSolver::id()) {
return SolverType::kScs;
} else if (solver_id == UnrevisedLemkeSolverId::id()) {
return SolverType::kUnrevisedLemke;
} else {
return std::nullopt;
}
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/gurobi_solver_internal.cc | #include "drake/solvers/gurobi_solver_internal.h"
#include <limits>
#include "drake/solvers/aggregate_costs_constraints.h"
namespace drake {
namespace solvers {
namespace internal {
namespace {
const double kInf = std::numeric_limits<double>::infinity();
} // namespace
int AddLinearConstraintNoDuplication(
const MathematicalProgram& prog, GRBmodel* model,
const Eigen::SparseMatrix<double>& A, const Eigen::VectorXd& lb,
const Eigen::VectorXd& ub, const VectorXDecisionVariable& vars,
bool is_equality, int* num_gurobi_linear_constraints) {
Eigen::SparseMatrix<double, Eigen::RowMajor> A_row_major = A;
const std::vector<int> var_index = prog.FindDecisionVariableIndices(vars);
// If this linear constraint is an equality constraint, we know that we can
// pass in A * vars = lb directly to Gurobi.
if (is_equality) {
std::vector<int> nonzero_col_index;
nonzero_col_index.reserve(A_row_major.nonZeros());
std::vector<char> sense(A.rows(), GRB_EQUAL);
for (int i = 0; i < A.nonZeros(); ++i) {
nonzero_col_index.push_back(
var_index[*(A_row_major.innerIndexPtr() + i)]);
}
*num_gurobi_linear_constraints += A.rows();
int error =
GRBaddconstrs(model, A_row_major.rows(), A_row_major.nonZeros(),
A_row_major.outerIndexPtr(), nonzero_col_index.data(),
A_row_major.valuePtr(), sense.data(),
const_cast<double*>(lb.data()), nullptr);
return error;
}
// Now handle the inequality constraints.
// Each row of linear constraint in Gurobi is in the form
// aᵀx ≤ b or aᵀx ≥ b or aᵀx=b, namely it doesn't accept imposing both the
// lower and the upper bound for a linear expression in one row. So for
// the constraint lb(i) <= A.row(i).dot(vars) <= ub(i), there are 4 situations
// 1. If both lb(i) and ub(i) are infinity, then we don't add any constraints
// to Gurobi.
// 2. If lb(i) is finite and ub(i) is infinity, then we add one constraint
// A.row(i).dot(vars) >= lb(i) to Gurobi.
// 3. If ub(i) is finite but lb(i) is -infinity, then we add one constraint
// A.row(i).dot(vars) <= ub(i) to Gurobi.
// 4. If both lb(i) and ub(i) are finite, then we add two constraints
// A.row(i).dot(vars) >= lb(i) and A.row(i).dot(vars) <= ub(i) to Gurobi.
// As a result, we add the constraint A_gurobi * vars <= rhs to Gurobi.
// Each row of A introduces at most two constraints in Gurobi, so we reserve 2
// * A.rows().
std::vector<double> rhs;
rhs.reserve(A.rows() * 2);
std::vector<char> sense;
sense.reserve(A.rows() * 2);
// The matrix A_gurobi is stored in Compressed Sparse Row (CSR) format, using
// three vectors cbeg, cind and cval. Please refer to
// https://www.gurobi.com/documentation/10.0/refman/c_addconstrs.html for the
// meaning of these three vectors. The non-zero entries in the i'th row of
// A_gurobi is stored in the chunk cind[cbeg[i]:cbeg[i+1]] and
// cval[cbeg[i]:cbeg[i+1]]
std::vector<int> cbeg;
cbeg.reserve(A.rows() * 2 + 1);
cbeg.push_back(0);
std::vector<int> cind;
cind.reserve(A.nonZeros() * 2);
std::vector<double> cval;
cval.reserve(A.nonZeros() * 2);
int A_gurobi_rows = 0;
// Add A_row_major.row(i) * vars ≥ bound (or ≤ bound) to the CSR format cbeg,
// cind, cva, also update rhs, sense and A_gurobi_rows.
auto add_gurobi_row = [&A_row_major, &var_index, &cbeg, &rhs, &sense, &cind,
&cval,
&A_gurobi_rows](int i, double bound, char row_sense) {
cbeg.push_back(cbeg.back() + *(A_row_major.outerIndexPtr() + i + 1) -
*(A_row_major.outerIndexPtr() + i));
rhs.push_back(bound);
sense.push_back(row_sense);
for (int j = *(A_row_major.outerIndexPtr() + i);
j < *(A_row_major.outerIndexPtr() + i + 1); ++j) {
cind.push_back(var_index[*(A_row_major.innerIndexPtr() + j)]);
cval.push_back(*(A_row_major.valuePtr() + j));
}
A_gurobi_rows++;
};
for (int i = 0; i < A_row_major.rows(); ++i) {
if (!std::isinf(lb(i))) {
// Add A_row_major.row(i) * vars >= lb(i)
add_gurobi_row(i, lb(i), GRB_GREATER_EQUAL);
}
if (!std::isinf(ub(i))) {
// Add A_row_major.row(i) * vars <= ub(i)
add_gurobi_row(i, ub(i), GRB_LESS_EQUAL);
}
}
*num_gurobi_linear_constraints += A_gurobi_rows;
int error =
GRBaddconstrs(model, A_gurobi_rows, cbeg.back(), cbeg.data(), cind.data(),
cval.data(), sense.data(), rhs.data(), nullptr);
return error;
}
int AddLinearConstraint(const MathematicalProgram& prog, GRBmodel* model,
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& lb, const Eigen::VectorXd& ub,
const VectorXDecisionVariable& vars, bool is_equality,
int* num_gurobi_linear_constraints) {
const symbolic::Variables vars_set(vars);
if (static_cast<int>(vars_set.size()) == vars.rows()) {
return AddLinearConstraintNoDuplication(prog, model, A, lb, ub, vars,
is_equality,
num_gurobi_linear_constraints);
} else {
Eigen::SparseMatrix<double> A_new;
VectorX<symbolic::Variable> vars_new;
AggregateDuplicateVariables(A, vars, &A_new, &vars_new);
return AddLinearConstraintNoDuplication(prog, model, A_new, lb, ub,
vars_new, is_equality,
num_gurobi_linear_constraints);
}
}
namespace {
// Drake's MathematicalProgram imposes the second order cone constraint in the
// form "A*x+b is in cone". On the other hand, Gurobi imposes the second order
// cone in this form "z is in cone". So we consider to add the linear equality
// constraint z-A*x=b. We write z-A*x in the form of M * [x;z], where
// M = [-A I].
void ConvertSecondOrderConeLinearConstraint(
const Eigen::SparseMatrix<double>& A, const std::vector<int>& xz_indices,
std::vector<Eigen::Triplet<double>>* M_triplets) {
M_triplets->clear();
M_triplets->reserve(A.nonZeros() + A.rows());
for (int i = 0; i < A.outerSize(); ++i) {
for (Eigen::SparseMatrix<double>::InnerIterator it(A, i); it; ++it) {
M_triplets->emplace_back(it.row(), xz_indices[it.col()], -it.value());
}
}
for (int i = 0; i < A.rows(); ++i) {
M_triplets->emplace_back(i, xz_indices[A.cols() + i], 1);
}
}
// Gurobi uses a matrix Q to differentiate Lorentz cone and rotated Lorentz
// cone constraint.
// https://www.gurobi.com/documentation/10.0/refman/c_addqconstr.html
// For Lorentz cone constraint,
// Q = [-1 0 0 ... 0]
// [ 0 1 0 ... 0]
// [ 0 0 1 ... 0]
// ...
// [ 0 0 0 ... 1]
// namely Q = diag([-1; 1; 1; ...; 1], so
// z' * Q * z = z(1)^2 + ... + z(n-1)^2 - z(0)^2.
// For rotated Lorentz cone constraint
// Q = [0 -1 0 0 ... 0]
// [0 0 0 0 ... 0]
// [0 0 1 0 ... 0]
// [0 0 0 1 ... 0]
// ...
// [0 0 0 0 ... 1]
// so z' * Q * z = z(2)^2 + ... + z(n-1)^2 - z(0) * z(1).
// Note that Q in the rotated Lorentz cone case is not symmetric (following the
// example https://www.gurobi.com/documentation/current/examples/qcp_c_c.html).
// We will store Q in a sparse format.
// qrow stores the row indices of the non-zero entries of Q.
// qcol stores the column indices of the non-zero entries of Q.
// qval stores the value of the non-zero entries of Q.
// GRBaddqconstr expects this qrow/qcol/qval format instead of
// Eigen::SparseMatrix format.
void CalcSecondOrderConeQ(bool is_rotated_cone,
const std::vector<int>& z_indices,
std::vector<int>* qrow, std::vector<int>* qcol,
std::vector<double>* qval) {
const int num_z = z_indices.size();
const size_t num_Q_nonzero = is_rotated_cone ? num_z - 1 : num_z;
qrow->clear();
qcol->clear();
qval->clear();
qrow->reserve(num_Q_nonzero);
qcol->reserve(num_Q_nonzero);
qval->reserve(num_Q_nonzero);
for (int i = 0; i < num_z - 2; ++i) {
const int zi_index = z_indices[i + 2];
qrow->push_back(zi_index);
qcol->push_back(zi_index);
qval->push_back(1.0);
}
const int z0_index = z_indices[0];
const int z1_index = z_indices[1];
if (is_rotated_cone) {
qrow->push_back(z0_index);
qcol->push_back(z1_index);
qval->push_back(-1);
} else {
qrow->push_back(z0_index);
qcol->push_back(z0_index);
qval->push_back(-1);
qrow->push_back(z1_index);
qcol->push_back(z1_index);
qval->push_back(1);
}
}
} // namespace
template <typename C>
int AddSecondOrderConeConstraints(
const MathematicalProgram& prog,
const std::vector<Binding<C>>& second_order_cone_constraints,
const std::vector<std::vector<int>>& second_order_cone_new_variable_indices,
GRBmodel* model, int* num_gurobi_linear_constraints) {
static_assert(
std::is_same_v<C, LorentzConeConstraint> ||
std::is_same_v<C, RotatedLorentzConeConstraint>,
"Expects either LorentzConeConstraint or RotatedLorentzConeConstraint");
bool is_rotated_cone = std::is_same_v<C, RotatedLorentzConeConstraint>;
DRAKE_ASSERT(second_order_cone_constraints.size() ==
second_order_cone_new_variable_indices.size());
int second_order_cone_count = 0;
int num_gurobi_vars;
int error = GRBgetintattr(model, "NumVars", &num_gurobi_vars);
DRAKE_ASSERT(!error);
for (const auto& binding : second_order_cone_constraints) {
const auto& A = binding.evaluator()->A();
const auto& b = binding.evaluator()->b();
int num_x = A.cols();
int num_z = A.rows();
// Add the constraint z - A*x = b
// xz_indices records the indices of [x; z] in Gurobi.
std::vector<int> xz_indices(num_x + num_z, 0);
for (int i = 0; i < num_x; ++i) {
xz_indices[i] = prog.FindDecisionVariableIndex(binding.variables()(i));
}
for (int i = 0; i < num_z; ++i) {
xz_indices[num_x + i] =
second_order_cone_new_variable_indices[second_order_cone_count][i];
}
// z - A*x will be written as M * [x; z], where M = [-A I].
// Gurobi expects M in compressed sparse row format, so we will first find
// out the non-zero entries in each row of M.
std::vector<Eigen::Triplet<double>> M_triplets;
ConvertSecondOrderConeLinearConstraint(A, xz_indices, &M_triplets);
Eigen::SparseMatrix<double, Eigen::RowMajor> M(num_z, num_gurobi_vars);
// Eigen::SparseMatrix::setFromTriplets will automatically group the sum of
// the values in M_triplets that correspond to the same entry in the sparse
// matrix.
M.setFromTriplets(M_triplets.begin(), M_triplets.end());
std::vector<char> sense(num_z, GRB_EQUAL);
error = GRBaddconstrs(model, num_z, M.nonZeros(), M.outerIndexPtr(),
M.innerIndexPtr(), M.valuePtr(), sense.data(),
const_cast<double*>(b.data()), nullptr);
DRAKE_ASSERT(!error);
*num_gurobi_linear_constraints += num_z;
// Gurobi uses a matrix Q to differentiate Lorentz cone and rotated Lorentz
// cone constraint.
// https://www.gurobi.com/documentation/10.0/refman/c_addqconstr.html
std::vector<int> qrow;
std::vector<int> qcol;
std::vector<double> qval;
CalcSecondOrderConeQ(
is_rotated_cone,
second_order_cone_new_variable_indices[second_order_cone_count], &qrow,
&qcol, &qval);
const size_t num_Q_nonzero = qrow.size();
error =
GRBaddqconstr(model, 0, nullptr, nullptr, num_Q_nonzero, qrow.data(),
qcol.data(), qval.data(), GRB_LESS_EQUAL, 0.0, NULL);
if (error) {
return error;
}
++second_order_cone_count;
}
return 0;
}
template <typename C>
void AddSecondOrderConeVariables(
const std::vector<Binding<C>>& second_order_cones,
std::vector<bool>* is_new_variable, int* num_gurobi_vars,
std::vector<std::vector<int>>* second_order_cone_variable_indices,
std::vector<char>* gurobi_var_type, std::vector<double>* xlow,
std::vector<double>* xupp) {
static_assert(
std::is_same_v<C, LorentzConeConstraint> ||
std::is_same_v<C, RotatedLorentzConeConstraint>,
"Expects LorentzConeConstraint and RotatedLorentzConeConstraint.");
bool is_rotated_cone = std::is_same_v<C, RotatedLorentzConeConstraint>;
int num_new_second_order_cone_var = 0;
second_order_cone_variable_indices->resize(second_order_cones.size());
// The newly added variable z for the Lorentz cone constraint is appended
// to the existing variables. So increment the variable indices
// accordingly.
int lorentz_cone_count = 0;
for (const auto& binding : second_order_cones) {
int num_new_lorentz_cone_var_i = binding.evaluator()->A().rows();
(*second_order_cone_variable_indices)[lorentz_cone_count].resize(
num_new_lorentz_cone_var_i);
for (int i = 0; i < num_new_lorentz_cone_var_i; ++i) {
(*second_order_cone_variable_indices)[lorentz_cone_count][i] =
*num_gurobi_vars + num_new_second_order_cone_var + i;
}
num_new_second_order_cone_var += num_new_lorentz_cone_var_i;
++lorentz_cone_count;
}
*num_gurobi_vars += num_new_second_order_cone_var;
is_new_variable->resize(*num_gurobi_vars, true);
// Newly added variable z is continuous variable.
gurobi_var_type->resize(*num_gurobi_vars, GRB_CONTINUOUS);
// For Lorentz cone constraint, z(0) >= 0.
// For rotated Lorentz cone constraint, z(0) >= 0, z(1) >= 0.
xlow->resize(*num_gurobi_vars, -std::numeric_limits<double>::infinity());
xupp->resize(*num_gurobi_vars, std::numeric_limits<double>::infinity());
for (int i = 0; i < static_cast<int>(second_order_cones.size()); ++i) {
xlow->at((*second_order_cone_variable_indices)[i][0]) = 0;
if (is_rotated_cone) {
xlow->at((*second_order_cone_variable_indices)[i][1]) = 0;
}
}
}
void AddL2NormCostVariables(
const std::vector<Binding<L2NormCost>>& l2_norm_costs,
std::vector<bool>* is_new_variable, int* num_gurobi_vars,
std::vector<std::vector<int>>* lorentz_cone_variable_indices,
std::vector<char>* gurobi_var_type, std::vector<double>* xlow,
std::vector<double>* xupp) {
for (const auto& l2_norm_cost : l2_norm_costs) {
// z is of size l2_norm_cost.A().rows() + 1
for (int i = 0; i < 1 + l2_norm_cost.evaluator()->get_sparse_A().rows();
++i) {
is_new_variable->push_back(true);
gurobi_var_type->push_back(GRB_CONTINUOUS);
}
lorentz_cone_variable_indices->emplace_back(
1 + l2_norm_cost.evaluator()->get_sparse_A().rows(), 0);
for (int i = 0; i < 1 + l2_norm_cost.evaluator()->get_sparse_A().rows();
++i) {
lorentz_cone_variable_indices->back()[i] = *num_gurobi_vars + i;
}
// For Lorentz cone constraint z(0) >= 0.
xlow->push_back(0);
xupp->push_back(kInf);
for (int i = 0; i < l2_norm_cost.evaluator()->get_sparse_A().rows(); ++i) {
xlow->push_back(-kInf);
xupp->push_back(kInf);
}
*num_gurobi_vars += 1 + l2_norm_cost.evaluator()->get_sparse_A().rows();
}
}
int AddL2NormCosts(const MathematicalProgram& prog,
const std::vector<std::vector<int>>&
l2norm_costs_lorentz_cone_variable_indices,
GRBmodel* model, int* num_gurobi_linear_constraints) {
DRAKE_ASSERT(prog.l2norm_costs().size() ==
l2norm_costs_lorentz_cone_variable_indices.size());
int num_gurobi_vars;
int error = GRBgetintattr(model, "NumVars", &num_gurobi_vars);
DRAKE_ASSERT(!error);
// We declare the vectors here outside of the for loop, so that we can re-use
// the heap memory of these vectors in each iteration of the for loop.
// We will impose the linear equality constraint z[1:] - Cx = d.
// xz_indices records the indices of [x;z[1:]] in Gurobi.
// M_triplets records the non-zero entries in M = [-C I].
// sense records the sign (=, <= or >=) in Gurobi model's linear constraints.
// qrow, qcol, qval stores the row, column and value of the Q matrix in the
// second order cone constraint.
std::vector<int> xz_indices;
std::vector<Eigen::Triplet<double>> M_triplets;
// This is used when adding linear constraints to the Gurobi model to indicate
// that we are adding equality constraints.
std::vector<char> sense;
std::vector<int> qrow;
std::vector<int> qcol;
std::vector<double> qval;
for (int i = 0; i < ssize(prog.l2norm_costs()); ++i) {
const Eigen::SparseMatrix<double>& C =
prog.l2norm_costs()[i].evaluator()->get_sparse_A();
const auto& d = prog.l2norm_costs()[i].evaluator()->b();
const int num_x = C.cols();
const int num_z = C.rows() + 1;
// Add the constraint z[1:]-C*x=d
xz_indices.clear();
xz_indices.reserve(num_x + num_z - 1);
for (int j = 0; j < num_x; ++j) {
xz_indices.push_back(prog.FindDecisionVariableIndex(
prog.l2norm_costs()[i].variables()(j)));
}
for (int j = 1; j < num_z; ++j) {
xz_indices.push_back(l2norm_costs_lorentz_cone_variable_indices[i][j]);
}
// z[1:]-Cx will be written as M * [x;z[1:]], where M=[-C I].
ConvertSecondOrderConeLinearConstraint(C, xz_indices, &M_triplets);
// Gurobi expects the matrix in the sparse row format.
Eigen::SparseMatrix<double, Eigen::RowMajor> M(num_z - 1, num_gurobi_vars);
M.setFromTriplets(M_triplets.begin(), M_triplets.end());
sense.clear();
sense.reserve(num_z - 1);
for (int j = 0; j < num_z - 1; ++j) {
sense.push_back(GRB_EQUAL);
}
error = GRBaddconstrs(model, num_z - 1, M.nonZeros(), M.outerIndexPtr(),
M.innerIndexPtr(), M.valuePtr(), sense.data(),
const_cast<double*>(d.data()), nullptr);
DRAKE_ASSERT(!error);
*num_gurobi_linear_constraints += num_z - 1;
CalcSecondOrderConeQ(false /*is_rotated_cone=false*/,
l2norm_costs_lorentz_cone_variable_indices[i], &qrow,
&qcol, &qval);
const size_t num_Q_nonzero = qrow.size();
error =
GRBaddqconstr(model, 0, nullptr, nullptr, num_Q_nonzero, qrow.data(),
qcol.data(), qval.data(), GRB_LESS_EQUAL, 0.0, NULL);
if (error) {
return error;
}
// Add the cost min z[0]
error = GRBsetdblattrelement(
model, "Obj", l2norm_costs_lorentz_cone_variable_indices[i][0], 1.0);
if (error) {
return error;
}
}
return 0;
}
// Explicit instantiation.
template int AddSecondOrderConeConstraints<LorentzConeConstraint>(
const MathematicalProgram& prog,
const std::vector<Binding<LorentzConeConstraint>>&
second_order_cone_constraints,
const std::vector<std::vector<int>>& second_order_cone_new_variable_indices,
GRBmodel* model, int* num_gurobi_linear_constraints);
template int AddSecondOrderConeConstraints<RotatedLorentzConeConstraint>(
const MathematicalProgram& prog,
const std::vector<Binding<RotatedLorentzConeConstraint>>&
second_order_cone_constraints,
const std::vector<std::vector<int>>& second_order_cone_new_variable_indices,
GRBmodel* model, int* num_gurobi_linear_constraints);
template void AddSecondOrderConeVariables<LorentzConeConstraint>(
const std::vector<Binding<LorentzConeConstraint>>& second_order_cones,
std::vector<bool>* is_new_variable, int* num_gurobi_vars,
std::vector<std::vector<int>>* second_order_cone_variable_indices,
std::vector<char>* gurobi_var_type, std::vector<double>* xlow,
std::vector<double>* xupp);
template void AddSecondOrderConeVariables<RotatedLorentzConeConstraint>(
const std::vector<Binding<RotatedLorentzConeConstraint>>&
second_order_cones,
std::vector<bool>* is_new_variable, int* num_gurobi_vars,
std::vector<std::vector<int>>* second_order_cone_variable_indices,
std::vector<char>* gurobi_var_type, std::vector<double>* xlow,
std::vector<double>* xupp);
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/augmented_lagrangian.cc | #include "drake/solvers/augmented_lagrangian.h"
#include <fmt/format.h>
#include "drake/common/default_scalars.h"
#include "drake/solvers/aggregate_costs_constraints.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
namespace {
// This function psi is defined as equation 17.55 of Numerical Optimization by
// Jorge Nocedal and Stephen Wright, Edition 1, 1999. (Note this equation is not
// presented in Edition 2). Mathematically it equals psi(c, λ, μ) = -λc +
// μ/2*c² if c - λ/μ <= 0 otherwise psi(c, λ, μ) = -0.5*λ²/μ The meaning of this
// function psi(c, λ, μ) is psi(c,λ, μ)= −λ(c−s) + μ/2*(c−s)² where s = max(c
// − λ/μ, 0)
// Note that in equation 17.55 of Numerical Optimization, Edition 1, what they
// use for μ is actually 1/μ in our formulation.
template <typename T>
T psi(const T& c, double lambda_val, double mu) {
if (ExtractDoubleOrThrow(c - lambda_val / mu) < 0) {
return -lambda_val * c + mu / 2 * c * c;
} else {
return T(-0.5 * lambda_val * lambda_val / mu);
}
}
// Compute the augmented lagrangian for the equality constraint c(x) = 0
// The augmented Lagrangian is −λc+μ/2*c² where c is lhs.
template <typename T>
T al_for_equality(const T& lhs, double lambda_val, double mu) {
return -lambda_val * lhs + mu / 2 * lhs * lhs;
}
void ParseProgram(const MathematicalProgram* prog, bool include_x_bounds,
int* lagrangian_size, std::vector<bool>* is_equality,
Eigen::VectorXd* x_lo, Eigen::VectorXd* x_up) {
*lagrangian_size = 0;
for (const auto& constraint : prog->GetAllConstraints()) {
if (!dynamic_cast<BoundingBoxConstraint*>(constraint.evaluator().get())) {
const auto& lb = constraint.evaluator()->lower_bound();
const auto& ub = constraint.evaluator()->upper_bound();
for (int i = 0; i < constraint.evaluator()->num_constraints(); ++i) {
if (lb(i) == ub(i)) {
(*lagrangian_size)++;
} else {
if (!std::isinf(lb(i))) {
(*lagrangian_size)++;
}
if (!std::isinf(ub(i))) {
(*lagrangian_size)++;
}
}
}
}
}
AggregateBoundingBoxConstraints(*prog, x_lo, x_up);
if (include_x_bounds) {
for (int i = 0; i < prog->num_vars(); ++i) {
if ((*x_lo)(i) == (*x_up)(i)) {
(*lagrangian_size)++;
} else {
if (!std::isinf((*x_lo)(i))) {
(*lagrangian_size)++;
}
if (!std::isinf((*x_up)(i))) {
(*lagrangian_size)++;
}
}
}
}
is_equality->resize(*lagrangian_size);
// We loop through all the constraints again instead of combining this loop
// with the previous loop when we find lagrangian_size_. The reason is that we
// want to first find lagrangian_size_ and then allocate all the memory of
// is_equality_.
int constraint_row = 0;
for (const auto& constraint : prog->GetAllConstraints()) {
if (!dynamic_cast<BoundingBoxConstraint*>(constraint.evaluator().get())) {
const auto& lb = constraint.evaluator()->lower_bound();
const auto& ub = constraint.evaluator()->upper_bound();
for (int i = 0; i < constraint.evaluator()->num_constraints(); ++i) {
if (lb(i) == ub(i)) {
(*is_equality)[constraint_row] = true;
constraint_row++;
} else {
if (!std::isinf(lb(i))) {
(*is_equality)[constraint_row] = false;
constraint_row++;
}
if (!std::isinf(ub(i))) {
(*is_equality)[constraint_row] = false;
constraint_row++;
}
}
}
}
}
if (include_x_bounds) {
for (int i = 0; i < prog->num_vars(); ++i) {
if ((*x_lo)(i) == (*x_up)(i)) {
(*is_equality)[constraint_row] = true;
constraint_row++;
} else {
if (!std::isinf((*x_lo)(i))) {
(*is_equality)[constraint_row] = false;
constraint_row++;
}
if (!std::isinf((*x_up)(i))) {
(*is_equality)[constraint_row] = false;
constraint_row++;
}
}
}
}
}
} // namespace
AugmentedLagrangianNonsmooth::AugmentedLagrangianNonsmooth(
const MathematicalProgram* prog, bool include_x_bounds)
: prog_{prog}, include_x_bounds_{include_x_bounds} {
ParseProgram(prog_, include_x_bounds, &lagrangian_size_, &is_equality_,
&x_lo_, &x_up_);
}
namespace {
template <typename AL, typename T>
T EvalAugmentedLagrangian(const AL& al, const Eigen::Ref<const VectorX<T>>& x,
const Eigen::Ref<const VectorX<T>>& s,
const Eigen::VectorXd& lambda_val, double mu,
VectorX<T>* constraint_residue, T* cost) {
DRAKE_DEMAND(x.rows() == al.prog().num_vars());
if constexpr (std::is_same_v<AL, AugmentedLagrangianSmooth>) {
DRAKE_DEMAND(al.s_size() == s.rows());
}
DRAKE_DEMAND(lambda_val.rows() == al.lagrangian_size());
DRAKE_DEMAND(mu > 0);
DRAKE_DEMAND(constraint_residue != nullptr);
DRAKE_DEMAND(cost != nullptr);
*cost = T{0};
constraint_residue->resize(lambda_val.rows());
for (const auto& cost_binding : al.prog().GetAllCosts()) {
*cost += al.prog().EvalBinding(cost_binding, x)(0);
}
T al_val = *cost;
int lagrangian_count = 0;
int s_count = 0;
// First evaluate all generic nonlinear constraints
for (const auto& constraint : al.prog().GetAllConstraints()) {
if (!dynamic_cast<BoundingBoxConstraint*>(constraint.evaluator().get())) {
const VectorX<T> constraint_val = al.prog().EvalBinding(constraint, x);
// Now check if each row of the constraint is equality or inequality.
for (int i = 0; i < constraint.evaluator()->num_constraints(); ++i) {
const double& lb = constraint.evaluator()->lower_bound()(i);
const double& ub = constraint.evaluator()->upper_bound()(i);
if ((std::isinf(lb) && lb > 0) || (std::isinf(ub) && ub < 0)) {
throw std::invalid_argument(fmt::format(
"constraint lower bound is {}, upper bound is {}", lb, ub));
}
if (lb == ub) {
// We have one Lagrangian multiplier for the equality constraint. Add
// −λ*h(x) + μ/2*h(x)² to the augmented Lagrangian.
al_val += al_for_equality(constraint_val(i) - lb,
lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) = constraint_val(i) - lb;
lagrangian_count++;
} else {
if (!std::isinf(lb)) {
// The constraint is constraint_val - lb >= 0.
if constexpr (std::is_same_v<AL, AugmentedLagrangianNonsmooth>) {
al_val +=
psi(constraint_val(i) - lb, lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) = constraint_val(i) - lb;
} else {
al_val += al_for_equality(constraint_val(i) - s(s_count) - lb,
lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) =
constraint_val(i) - s(s_count) - lb;
s_count++;
}
lagrangian_count++;
}
if (!std::isinf(ub)) {
// The constraint is ub - constraint_val >= 0.
if constexpr (std::is_same_v<AL, AugmentedLagrangianNonsmooth>) {
al_val +=
psi(ub - constraint_val(i), lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) = ub - constraint_val(i);
} else {
al_val += al_for_equality(ub - constraint_val(i) - s(s_count),
lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) =
ub - constraint_val(i) - s(s_count);
s_count++;
}
lagrangian_count++;
}
}
}
}
}
if (al.include_x_bounds()) {
for (int i = 0; i < al.prog().num_vars(); ++i) {
if (al.x_lo()(i) == al.x_up()(i)) {
al_val += al_for_equality(x(i) - al.x_lo()(i),
lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) = x(i) - al.x_lo()(i);
lagrangian_count++;
} else {
if (!std::isinf(al.x_lo()(i))) {
if constexpr (std::is_same_v<AL, AugmentedLagrangianNonsmooth>) {
al_val +=
psi(x(i) - al.x_lo()(i), lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) = x(i) - al.x_lo()(i);
} else {
al_val += al_for_equality(x(i) - al.x_lo()(i) - s(s_count),
lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) =
x(i) - al.x_lo()(i) - s(s_count);
}
s_count++;
lagrangian_count++;
}
if (!std::isinf(al.x_up()(i))) {
if constexpr (std::is_same_v<AL, AugmentedLagrangianNonsmooth>) {
al_val +=
psi(al.x_up()(i) - x(i), lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) = al.x_up()(i) - x(i);
} else {
al_val += al_for_equality(al.x_up()(i) - x(i) - s(s_count),
lambda_val(lagrangian_count), mu);
(*constraint_residue)(lagrangian_count) =
al.x_up()(i) - x(i) - s(s_count);
s_count++;
}
lagrangian_count++;
}
}
}
}
return al_val;
}
} // namespace
template <typename T>
T AugmentedLagrangianNonsmooth::Eval(const Eigen::Ref<const VectorX<T>>& x,
const Eigen::VectorXd& lambda_val,
double mu, VectorX<T>* constraint_residue,
T* cost) const {
Eigen::Matrix<T, 0, 1> s_dummy;
return EvalAugmentedLagrangian<AugmentedLagrangianNonsmooth, T>(
*this, x, s_dummy, lambda_val, mu, constraint_residue, cost);
}
AugmentedLagrangianSmooth::AugmentedLagrangianSmooth(
const MathematicalProgram* prog, bool include_x_bounds)
: prog_{prog}, include_x_bounds_{include_x_bounds} {
ParseProgram(prog_, include_x_bounds, &lagrangian_size_, &is_equality_,
&x_lo_, &x_up_);
// For each inequality constraint, we need one slack variable s.
s_size_ = 0;
for (auto flag : is_equality_) {
if (!flag) {
s_size_++;
}
}
}
template <typename T>
T AugmentedLagrangianSmooth::Eval(const Eigen::Ref<const VectorX<T>>& x,
const Eigen::Ref<const VectorX<T>>& s,
const Eigen::VectorXd& lambda_val, double mu,
VectorX<T>* constraint_residue,
T* cost) const {
return EvalAugmentedLagrangian<AugmentedLagrangianSmooth, T>(
*this, x, s, lambda_val, mu, constraint_residue, cost);
}
// Explicit instantiation.
DRAKE_DEFINE_FUNCTION_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS(
(&AugmentedLagrangianNonsmooth::Eval<T>,
&AugmentedLagrangianSmooth::Eval<T>))
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mathematical_program_doxygen.h | /** @file
Doxygen-only documentation for @ref solvers. */
/** @addtogroup solvers
* @{
* Drake's MathematicalProgram class is used to solve the mathematical
* optimization problem in the following form
* <pre>
* minₓ f(x)
* s.t x ∈ S.
* </pre>
* Depending on the formulation of the objective function f, and the structure
* of the constraint set S, this optimization problem can be grouped into
* different categories (linear programming, quadratic programming, nonconvex
* nonlinear programming, etc). Drake will call suitable solvers for each
* category of optimization problem.
*
* Drake wraps a number of open source and commercial solvers
* (+ a few custom solvers) to provide a common interface for convex
* optimization, mixed-integer convex optimization, and other non-convex
* mathematical programs.
*
* The MathematicalProgram class handles the coordination of decision variables,
* objectives, and constraints. The @ref drake::solvers::Solve() "Solve()"
* method reflects on the accumulated objectives and constraints and will
* dispatch to the most appropriate solver. Alternatively, one can invoke
* specific solver by instantiating its @ref drake::solvers::SolverInterface
* "SolverInterface" and passing the MathematicalProgram directly to the @ref
* drake::solvers::SolverInterface::Solve() "SolverInterface::Solve()" method.
*
* Our solver coverage still has many gaps, but is under active development.
*
* <h2>Closed-form solutions</h2>
*
* When the mathematical problem is formulated as the following linear system
* <pre>
* find x
* s.t Ax = b,
* </pre>
* then @ref drake::solvers::LinearSystemSolver "LinearSystemSolver" provides
* efficient closed form solution.
*
* When the mathematical problem is formulated as the following (convex)
* quadratic program with only linear equality constraint
* <pre>
* min 0.5 xᵀHx + aᵀx + b
* s.t Ax = b,
* </pre>
* then @ref drake::solvers::EqualityConstrainedQPSolver
* "EqualityConstraintQPSolver" provides efficient closed form solution.
*
* <h2>Convex Optimization</h2>
*
* <table>
* <tr>
* <td>Solver</td>
* <td><a href="https://en.wikipedia.org/wiki/Linear_programming">LP</a></td>
* <td><a href="https://en.wikipedia.org/wiki/Quadratic_programming">
* QP</a></td>
* <td><a href="https://en.wikipedia.org/wiki/Second-order_cone_programming">
* SOCP</a></td>
* <td><a href="https://en.wikipedia.org/wiki/Semidefinite_programming">
* SDP</a></td>
* <td><a href="https://en.wikipedia.org/wiki/Sum-of-squares_optimization">
* SOS</a></td>
* </tr>
* <tr><td><a href="https://www.gurobi.com/products/gurobi-optimizer">
* Gurobi</a> †</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td></td>
* <td></td>
* </tr>
* <tr><td><a href="https://www.mosek.com/products/mosek">
* MOSEK™</a> †</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* </tr>
* <tr><td> <a href="https://github.com/coin-or/Clp">
* CLP</a></td>
* <td align="center">♦</td>
* <td></td>
* <td></td>
* <td></td>
* <td></td>
* </tr>
* <tr><td> <a href="https://github.com/coin-or/Csdp">
* CSDP</a></td>
* <td align="center">⟡</td>
* <td></td>
* <td align="center">⟡</td>
* <td align="center">⟡</td>
* <td align="center">⟡</td>
* </tr>
* <tr><td><a href="https://github.com/oxfordcontrol/Clarabel.rs">
* Clarabel</a></td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* </tr>
* <tr><td><a href="https://github.com/cvxgrp/scs">
* SCS</a></td>
* <td align="center">△</td>
* <td align="center">△</td>
* <td align="center">△</td>
* <td align="center">△</td>
* <td align="center">△</td>
* </tr>
* <tr><td><a href="https://github.com/oxfordcontrol/osqp">
* OSQP</a></td>
* <td></td>
* <td align="center">△</td>
* <td></td>
* <td></td>
* <td></td>
* </tr>
* <tr><td><a href="https://ccom.ucsd.edu/~optimizers/solvers/snopt/">
* SNOPT</a> † ‡</td>
* <td align="center">▢</td>
* <td align="center">▢</td>
* <td align="center">⬘</td>
* <td align="center">⬘</td>
* <td align="center">⬘</td>
* </tr>
* <tr><td><a href="https://projects.coin-or.org/Ipopt">Ipopt</a></td>
* <td align="center">▢</td>
* <td align="center">▢</td>
* <td align="center">⬘</td>
* <td align="center">⬘</td>
* <td align="center">⬘</td>
* </tr>
* <tr><td>
* <a href="http://ab-initio.mit.edu/wiki/index.php/NLopt">NLopt</a></td>
* <td align="center">▢</td>
* <td align="center">▢</td>
* <td align="center">⬘</td>
* <td align="center">⬘</td>
* <td align="center">⬘</td>
* </tr>
* </table>
*
* † This is a commercial solver which requires a license
* (note that some have free licenses for academics). See <a
* href="https://drake.mit.edu/bazel.html#proprietary-solvers"> the build system
* documentation</a> for details.
*
* ‡ <a href="https://drake.mit.edu/installation.html">Drake's pre-compiled
* binary releases</a> incorporate a private build of SNOPT that does not
* require a license when invoked via Drake's SnoptSolver wrapper class.
*
* ♦ A preferred solver for the given category.
*
* ⟡ The native CSDP solver cannot handle free variables (namely all variables
* have to be constrained within a cone). In Drake we apply special techniques
* to handle free variables (refer to RemoveFreeVariableMethod for more
* details). These heuristics can make the problem expensive to solve or
* poorly conditioned.
*
* △ These solvers are not accurate. They implement ADMM algorithm, which
* converges quickly to a low-accuracy solution, and requires many iterations to
* achieve high accuracy.
*
* ▢ These solvers can solve the convex problems, but are not good at it. They
* treat the convex problems as general nonlinear optimization problems.
*
* ⬘ These gradient-based solvers expect smooth gradients. These problems don't
* have smooth gradients everywhere, hence even though the problem is convex,
* these gradient-bases solvers might not converge to the globally optimal
* solution.
*
* <h2>Mixed-Integer Convex Optimization</h2>
*
* <table>
* <tr>
* <td>Solver</td>
* <td>MILP</a></td>
* <td>MIQP</a></td>
* <td>MISOCP</a></td>
* <td>MISDP</a></td>
* </tr>
* <tr><td><a href="https://www.gurobi.com/products/gurobi-optimizer">
* Gurobi</a> †</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td></td>
* </tr>
* <tr><td><a href="https://www.mosek.com/products/mosek">
* MOSEK™</a> †</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td align="center">♦</td>
* <td></td>
* </tr>
* <tr><td>
* @ref drake::solvers::MixedIntegerBranchAndBound "naive branch-and-bound"
* </td>
* <td align="center">◊</td>
* <td align="center">◊</td>
* <td align="center">◊</td>
* <td align="center">◊</td>
* </table>
*
* † This is a commercial solver which requires a license
* (note that some have free licenses for academics). See <a
* href="https://drake.mit.edu/bazel.html#proprietary-solvers"> the build system
* documentation</a> for details.
*
* ♦ A preferred solver for the given category.
*
* ◊ The naive solver's usefulness is likely restricted to small-sized problems
* with dozens of binary variables. We implement only the basic branch-and-bound
* algorithm, without cutting planes nor advanced branching heuristics.
*
* <h2>Nonconvex Programming</h2>
*
* <table>
* <tr>
* <td>Solver</td>
* <td><a href="https://en.wikipedia.org/wiki/Nonlinear_programming">
* Nonlinear Program</a></td>
* <td><a href="https://en.wikipedia.org/wiki/Linear_complementarity_problem">
* LCP</a></td>
* <td><a href="https://en.wikipedia.org/wiki/Satisfiability_modulo_theories">
* SMT</a></td>
* </tr>
* <tr><td><a href="https://ccom.ucsd.edu/~optimizers/solvers/snopt/">
* SNOPT</a> † ‡</td></tr>
* <td align="center">♦</td>
* <td>⟐</td>
* <td></td>
* <tr><td><a href="https://projects.coin-or.org/Ipopt">Ipopt</a></td></tr>
* <td align="center">♦</td>
* <td>⟐</td>
* <td></td>
* <tr><td><a href="http://ab-initio.mit.edu/wiki/index.php/NLopt">
* NLopt</a></td></tr>
* <td align="center">♦</td>
* <td>⟐</td>
* <td></td>
* <tr><td><a href="https://github.com/PositronicsLab/Moby">
* Moby LCP</a></td>
* <td></td>
* <td align="center">♦</td>
* <td></td>
* </tr>
* </table>
*
* † This is a commercial solver which requires a license
* (note that some have free licenses for academics). See <a
* href="https://drake.mit.edu/bazel.html#proprietary-solvers"> the build system
* documentation</a> for details.
*
* ‡ <a href="https://drake.mit.edu/installation.html">Drake's pre-compiled
* binary releases</a> incorporate a private build of SNOPT that does not
* require a license when invoked via Drake's SnoptSolver wrapper class.
*
* ♦ A preferred solver for the given category.
* ⟐ SNOPT/IPOPT/NLOPT might be able to solve LCP, but they are not the
* preferred solver.
*
* @}
*/
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/csdp_solver_internal.cc | #include "drake/solvers/csdp_solver_internal.h"
namespace drake {
namespace solvers {
namespace internal {
void ConvertSparseMatrixFormatToCsdpProblemData(
const std::vector<BlockInX>& X_blocks, const Eigen::SparseMatrix<double>& C,
const std::vector<Eigen::SparseMatrix<double>> A,
const Eigen::VectorXd& rhs, csdp::blockmatrix* C_csdp, double** rhs_csdp,
csdp::constraintmatrix** constraints) {
const int num_X_rows = C.rows();
DRAKE_ASSERT(C.cols() == C.rows());
DRAKE_ASSERT(static_cast<int>(A.size()) == rhs.rows());
// Maps the row index in X to the block index. Both the row index and the
// block index are 0-indexed.
std::vector<int> X_row_to_block_index(num_X_rows);
std::vector<int> block_start_rows(static_cast<int>(X_blocks.size()));
int row_count = 0;
for (int block_index = 0; block_index < static_cast<int>(X_blocks.size());
++block_index) {
block_start_rows[block_index] = row_count;
for (int row = row_count; row < row_count + X_blocks[block_index].num_rows;
++row) {
X_row_to_block_index[row] = block_index;
}
row_count += static_cast<int>(X_blocks[block_index].num_rows);
}
C_csdp->nblocks = static_cast<int>(X_blocks.size());
// We need to add 1 here because CSDP uses Fortran 1-indexed, so the
// 0'th block is wasted.
C_csdp->blocks = static_cast<struct csdp::blockrec*>(
malloc((C_csdp->nblocks + 1) * sizeof(struct csdp::blockrec)));
for (int block_index = 0; block_index < C_csdp->nblocks; ++block_index) {
const BlockInX& X_block = X_blocks[block_index];
// CSDP uses Fortran index, so we need to add 1.
csdp::blockrec& C_block = C_csdp->blocks[block_index + 1];
C_block.blockcategory =
X_block.block_type == BlockType::kMatrix ? csdp::MATRIX : csdp::DIAG;
C_block.blocksize = X_block.num_rows;
if (X_block.block_type == BlockType::kMatrix) {
C_block.data.mat = static_cast<double*>(
// CSDP's data.mat is an array of size num_rows x num_rows.
malloc(X_block.num_rows * X_block.num_rows * sizeof(double)));
for (int j = 0; j < X_block.num_rows; ++j) {
// First fill in this column with 0, and then we will go through the
// non-zero entries (stored inside C) to set the value of the
// corresponding entries in C_csdp.
for (int i = 0; i < X_block.num_rows; ++i) {
C_block.data.mat[CsdpMatrixIndex(i, j, X_block.num_rows)] = 0;
}
for (Eigen::SparseMatrix<double>::InnerIterator it(
C, block_start_rows[block_index] + j);
it; ++it) {
C_block.data.mat[CsdpMatrixIndex(
it.row() - block_start_rows[block_index], j, X_block.num_rows)] =
it.value();
}
}
} else if (X_block.block_type == BlockType::kDiagonal) {
// CSDP uses Fortran 1-index array, so the 0'th entry is wasted.
C_block.data.vec =
static_cast<double*>(malloc((X_block.num_rows + 1) * sizeof(double)));
for (int j = 0; j < X_block.num_rows; ++j) {
C_block.data.vec[j + 1] = 0.0;
for (Eigen::SparseMatrix<double>::InnerIterator it(
C, block_start_rows[block_index] + j);
it; ++it) {
DRAKE_ASSERT(it.row() == it.col());
C_block.data.vec[j + 1] = it.value();
}
}
} else {
throw std::runtime_error(
"ConvertSparseMatrixFormatToCsdpProblemData() only supports MATRIX "
"or DIAG blocks.");
}
}
// Copy rhs.
// CSDP stores the right-hand vector as an Fortran 1-indexed array, so we
// need to add 1 here.
*rhs_csdp = static_cast<double*>(malloc((rhs.rows() + 1) * sizeof(double)));
for (int i = 0; i < rhs.rows(); ++i) {
(*rhs_csdp)[i + 1] = rhs(i);
}
// Copy constraints.
*constraints = static_cast<struct csdp::constraintmatrix*>(
malloc((static_cast<int>(A.size()) + 1) *
sizeof(struct csdp::constraintmatrix)));
for (int constraint_index = 0; constraint_index < static_cast<int>(A.size());
++constraint_index) {
(*constraints)[constraint_index + 1].blocks = nullptr;
// Start from the last block in the block-diagonal matrix
// A[constraint_index], we add each block in the reverse order.
for (int block_index = static_cast<int>(X_blocks.size() - 1);
block_index >= 0; --block_index) {
std::vector<Eigen::Triplet<double>> A_block_triplets;
// CSDP only stores the non-zero entries in the upper-triangular part of
// each block. Also the row and column indices in A_block_triplets are
// the indices within THIS block, not the indices in the whole matrix
// A[constraint_index].
A_block_triplets.reserve((X_blocks[block_index].num_rows + 1) *
X_blocks[block_index].num_rows / 2);
for (int col_index = block_start_rows[block_index];
col_index <
block_start_rows[block_index] + X_blocks[block_index].num_rows;
++col_index) {
for (Eigen::SparseMatrix<double>::InnerIterator it(A[constraint_index],
col_index);
it; ++it) {
if (it.row() > it.col()) {
break;
}
A_block_triplets.emplace_back(
it.row() - block_start_rows[block_index] + 1,
it.col() - block_start_rows[block_index] + 1, it.value());
}
}
if (!A_block_triplets.empty()) {
struct csdp::sparseblock* blockptr =
static_cast<struct csdp::sparseblock*>(
malloc(sizeof(struct csdp::sparseblock)));
// CSDP uses Fortran 1-indexed array.
blockptr->blocknum = block_index + 1;
blockptr->blocksize = X_blocks[block_index].num_rows;
// CSDP uses Fortran 1-indexed array.
blockptr->constraintnum = constraint_index + 1;
blockptr->next = nullptr;
blockptr->nextbyblock = nullptr;
blockptr->entries = static_cast<double*>(malloc(
(static_cast<int>(A_block_triplets.size()) + 1) * sizeof(double)));
blockptr->iindices = static_cast<int*>(malloc(
(static_cast<int>(A_block_triplets.size()) + 1) * sizeof(int)));
blockptr->jindices = static_cast<int*>(malloc(
(1 + static_cast<int>(A_block_triplets.size())) * sizeof(int)));
blockptr->numentries = static_cast<int>(A_block_triplets.size());
for (int i = 0; i < blockptr->numentries; ++i) {
blockptr->iindices[i + 1] = A_block_triplets[i].row();
blockptr->jindices[i + 1] = A_block_triplets[i].col();
blockptr->entries[i + 1] = A_block_triplets[i].value();
}
// Insert this block into the linked list of
// constraints[constraint_index + 1] blocks.
blockptr->next = (*constraints)[constraint_index + 1].blocks;
(*constraints)[constraint_index + 1].blocks = blockptr;
}
}
}
}
void GenerateCsdpProblemDataWithoutFreeVariables(
const SdpaFreeFormat& sdpa_free_format, csdp::blockmatrix* C_csdp,
double** rhs_csdp, csdp::constraintmatrix** constraints) {
if (sdpa_free_format.num_free_variables() == 0) {
Eigen::SparseMatrix<double> C(sdpa_free_format.num_X_rows(),
sdpa_free_format.num_X_rows());
C.setFromTriplets(sdpa_free_format.C_triplets().begin(),
sdpa_free_format.C_triplets().end());
std::vector<Eigen::SparseMatrix<double>> A;
A.reserve(sdpa_free_format.A_triplets().size());
for (int i = 0; i < static_cast<int>(sdpa_free_format.A_triplets().size());
++i) {
A.emplace_back(sdpa_free_format.num_X_rows(),
sdpa_free_format.num_X_rows());
A.back().setFromTriplets(sdpa_free_format.A_triplets()[i].begin(),
sdpa_free_format.A_triplets()[i].end());
}
ConvertSparseMatrixFormatToCsdpProblemData(sdpa_free_format.X_blocks(), C,
A, sdpa_free_format.g(), C_csdp,
rhs_csdp, constraints);
} else {
throw std::runtime_error(
"GenerateCsdpProblemDataWithoutFreeVariables(): the formulation has "
"free variables, you shouldn't call this method.");
}
}
void ConvertCsdpBlockMatrixtoEigen(const csdp::blockmatrix& X_csdp,
Eigen::SparseMatrix<double>* X) {
int num_X_nonzero_entries = 0;
for (int i = 0; i < X_csdp.nblocks; ++i) {
if (X_csdp.blocks[i + 1].blockcategory == csdp::MATRIX) {
num_X_nonzero_entries +=
X_csdp.blocks[i + 1].blocksize * X_csdp.blocks[i + 1].blocksize;
} else if (X_csdp.blocks[i + 1].blockcategory == csdp::DIAG) {
num_X_nonzero_entries += X_csdp.blocks[i + 1].blocksize;
} else {
throw std::runtime_error(
"ConvertCsdpBlockMatrixtoEigen(): unknown block category.");
}
}
std::vector<Eigen::Triplet<double>> X_triplets;
X_triplets.reserve(num_X_nonzero_entries);
int X_row_count = 0;
for (int block_index = 0; block_index < X_csdp.nblocks; ++block_index) {
if (X_csdp.blocks[block_index + 1].blockcategory == csdp::MATRIX) {
for (int i = 0; i < X_csdp.blocks[block_index + 1].blocksize; ++i) {
for (int j = 0; j < X_csdp.blocks[block_index + 1].blocksize; ++j) {
X_triplets.emplace_back(
X_row_count + i, X_row_count + j,
X_csdp.blocks[block_index + 1].data.mat[CsdpMatrixIndex(
i, j, X_csdp.blocks[block_index + 1].blocksize)]);
}
}
} else if (X_csdp.blocks[block_index + 1].blockcategory == csdp::DIAG) {
for (int i = 0; i < X_csdp.blocks[block_index + 1].blocksize; ++i) {
X_triplets.emplace_back(X_row_count + i, X_row_count + i,
X_csdp.blocks[block_index + 1].data.vec[i + 1]);
}
} else {
throw std::runtime_error(
"ConvertCsdpBlockMatrixtoEigen(): unknown block matrix type.");
}
X_row_count += X_csdp.blocks[block_index + 1].blocksize;
}
X->resize(X_row_count, X_row_count);
X->setFromTriplets(X_triplets.begin(), X_triplets.end());
}
void FreeCsdpProblemData(int num_constraints, csdp::blockmatrix C_csdp,
double* rhs_csdp,
csdp::constraintmatrix* constraints) {
// This function is copied from the source code in csdp/lib/freeprob.c
free(rhs_csdp);
csdp::cpp_free_mat(C_csdp);
csdp::sparseblock* ptr;
csdp::sparseblock* oldptr;
if (constraints != nullptr) {
for (int i = 1; i <= num_constraints; ++i) {
ptr = constraints[i].blocks;
while (ptr != nullptr) {
free(ptr->entries);
free(ptr->iindices);
free(ptr->jindices);
oldptr = ptr;
ptr = ptr->next;
free(oldptr);
}
}
free(constraints);
}
}
int CsdpMatrixIndex(int row, int col, int num_rows) {
// Internally matrix uses 1-indexed Fortran array, so we need to add 1.
return ijtok(row + 1, col + 1, num_rows);
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/indeterminate.cc | #include "drake/solvers/indeterminate.h"
#include "drake/solvers/decision_variable.h"
namespace drake {
namespace solvers {
VectorXIndeterminate ConcatenateIndeterminatesRefList(
const IndeterminatesRefList& var_list) {
// TODO(fischergundlach): Consolidate DecisionVariable and Indeterminate in
// variable.{h,cc}.
return ConcatenateVariableRefList(var_list);
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solver_interface.h | #pragma once
#include <optional>
#include <string>
#include <Eigen/Core>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mathematical_program_result.h"
#include "drake/solvers/solution_result.h"
#include "drake/solvers/solver_id.h"
#include "drake/solvers/solver_options.h"
namespace drake {
namespace solvers {
/// Interface used by implementations of individual solvers.
class SolverInterface {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SolverInterface)
virtual ~SolverInterface();
/// Returns true iff support for this solver has been compiled into Drake.
/// When this method returns false, the Solve method will throw.
///
/// Most solver implementations will always return true, but certain solvers
/// may have been excluded at compile-time due to licensing restrictions, or
/// to narrow Drake's dependency footprint. In Drake's default build, only
/// commercially-licensed solvers might return false.
///
/// Contrast this with enabled(), which reflects whether a solver has been
/// configured for use at runtime (not compile-time).
///
/// For details on linking commercial solvers, refer to the solvers' class
/// overview documentation, e.g., SnoptSolver, MosekSolver, GurobiSolver.
virtual bool available() const = 0;
/// Returns true iff this solver is properly configured for use at runtime.
/// When this method returns false, the Solve method will throw.
///
/// Most solver implementation will always return true, but certain solvers
/// require additional configuration before they may be used, e.g., setting
/// an environment variable to specify a license file or license server.
/// In Drake's default build, only commercially-licensed solvers might return
/// false.
///
/// Contrast this with available(), which reflects whether a solver has been
/// incorporated into Drake at compile-time (and has nothing to do with the
/// runtime configuration). A solver where available() returns false may still
/// return true for enabled() if it is properly configured.
///
/// The mechanism to configure a particular solver implementation is specific
/// to the solver in question, but typically uses an environment variable.
/// For details on configuring commercial solvers, refer to the solvers' class
/// overview documentation, e.g., SnoptSolver, MosekSolver, GurobiSolver.
virtual bool enabled() const = 0;
/// Solves an optimization program with optional initial guess and solver
/// options. Note that these initial guess and solver options are not written
/// to @p prog.
/// If the @p prog has set an option for a solver, and @p solver_options
/// contains a different value for the same option on the same solver, then @p
/// solver_options takes priority.
/// Derived implementations of this interface may elect to throw
/// std::exception for badly formed programs.
virtual void Solve(const MathematicalProgram& prog,
const std::optional<Eigen::VectorXd>& initial_guess,
const std::optional<SolverOptions>& solver_options,
MathematicalProgramResult* result) const = 0;
/// Returns the identifier of this solver.
virtual SolverId solver_id() const = 0;
/// Returns true iff the program's attributes are compatible with this
/// solver's capabilities.
virtual bool AreProgramAttributesSatisfied(
const MathematicalProgram& prog) const = 0;
/// Describes the reasons (if any) why the program is incompatible with this
/// solver's capabilities. If AreProgramAttributesSatisfied would return true
/// for the program, then this function returns the empty string.
virtual std::string ExplainUnsatisfiedProgramAttributes(
const MathematicalProgram& prog) const = 0;
protected:
SolverInterface();
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/no_osqp.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/osqp_solver.h"
/* clang-format on */
#include <stdexcept>
namespace drake {
namespace solvers {
bool OsqpSolver::is_available() {
return false;
}
void OsqpSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&,
const SolverOptions&,
MathematicalProgramResult*) const {
throw std::runtime_error(
"The OSQP bindings were not compiled. You'll need to use a different "
"solver.");
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solver_base.h | #pragma once
#include <functional>
#include <optional>
#include <string>
#include <Eigen/Core>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/solution_result.h"
#include "drake/solvers/solver_id.h"
#include "drake/solvers/solver_interface.h"
#include "drake/solvers/solver_options.h"
namespace drake {
namespace solvers {
/** Abstract base class used by implementations of individual solvers. */
class SolverBase : public SolverInterface {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SolverBase)
~SolverBase() override;
/** Like SolverInterface::Solve(), but the result is a return value instead of
an output argument. */
MathematicalProgramResult Solve(
const MathematicalProgram& prog,
const std::optional<Eigen::VectorXd>& initial_guess = std::nullopt,
const std::optional<SolverOptions>& solver_options = std::nullopt) const;
// Implement the SolverInterface methods.
void Solve(const MathematicalProgram&, const std::optional<Eigen::VectorXd>&,
const std::optional<SolverOptions>&,
MathematicalProgramResult*) const override;
bool available() const override;
bool enabled() const override;
SolverId solver_id() const final {
return solver_id_;
}
bool AreProgramAttributesSatisfied(const MathematicalProgram&) const override;
std::string ExplainUnsatisfiedProgramAttributes(
const MathematicalProgram&) const override;
protected:
/** Constructs a SolverBase with the given default implementations of the
solver_id(), available(), enabled(), AreProgramAttributesSatisfied(), and
ExplainUnsatisfiedProgramAttributes() methods. Typically, the subclass will
simply pass the address of its static method, e.g., `&available`, for these
functors. Any of the functors can be nullptr, in which case the subclass must
override the matching virtual method instead, except for `explain_unsatisfied`
which already has a default implementation. */
SolverBase(const SolverId& id, std::function<bool()> available,
std::function<bool()> enabled,
std::function<bool(const MathematicalProgram&)> are_satisfied,
std::function<std::string(const MathematicalProgram&)>
explain_unsatisfied = nullptr);
/** Hook for subclasses to implement Solve. Prior to the SolverBase's call to
this method, the solver's availability and capabilities vs the program
attributes have already been checked, and the result's set_solver_id() and
set_decision_variable_index() have already been set. The options and initial
guess are already merged, i.e., the DoSolve implementation should ignore
prog's solver options and prog's initial guess. */
virtual void DoSolve(const MathematicalProgram& prog,
const Eigen::VectorXd& initial_guess,
const SolverOptions& merged_options,
MathematicalProgramResult* result) const = 0;
private:
SolverId solver_id_;
std::function<bool()> default_available_;
std::function<bool()> default_enabled_;
std::function<bool(const MathematicalProgram&)> default_are_satisfied_;
std::function<std::string(const MathematicalProgram&)>
default_explain_unsatisfied_;
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/semidefinite_relaxation_internal.h | #pragma once
#include "drake/math/matrix_util.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
namespace internal {
// Take the sparse Kronecker product of A and B.
Eigen::SparseMatrix<double> SparseKroneckerProduct(
const Eigen::SparseMatrix<double>& A, const Eigen::SparseMatrix<double>& B);
// Get the matrix representation for the map Y -> [tr(Y), y00 - ∑ᵢ₌₁ʳ⁻¹yᵢᵢ,
// 2y_{0i-1}] when applied to the lower triangular part of Y as a column. This
// map goes from symmetric matrices with r - 1 rows to a vector with r rows.
Eigen::SparseMatrix<double> GetWAdjForTril(const int r);
// Given a vector expressing an element of Sⁿ ⊗ Sᵐ, return the corresponding
// symmetric matrix of size Sⁿᵐ. Note that Sⁿ ⊗ Sᵐ is a
// subspace of Sⁿᵐ of dimension (n+1) choose 2 * (m+1) choose 2. Therefore, this
// method requires that tensor_vector.rows() be of size (n+1) choose 2 * (m+1)
// choose 2.
template <typename Derived>
drake::MatrixX<typename Derived::Scalar> ToSymmetricMatrixFromTensorVector(
const Eigen::MatrixBase<Derived>& tensor_vector, int n, int m) {
const int sym_elt_n = (n * (n + 1)) / 2;
const int sym_elt_m = (m * (m + 1)) / 2;
DRAKE_THROW_UNLESS(tensor_vector.rows() == sym_elt_n * sym_elt_m);
// TODO(Alexandre.Amice) Make this efficient.
drake::MatrixX<typename Derived::Scalar> symmetric_matrix(n * m, n * m);
for (int i = 0; i < sym_elt_n; ++i) {
Eigen::SparseVector<double> ei(sym_elt_n);
ei.insert(i) = 1;
Eigen::MatrixXd symmetric_matrix_i =
math::ToSymmetricMatrixFromLowerTriangularColumns(ei.toDense());
for (int j = 0; j < sym_elt_m; ++j) {
Eigen::SparseVector<double> ej(sym_elt_m);
ej.insert(j) = 1;
Eigen::MatrixXd symmetric_matrix_j =
math::ToSymmetricMatrixFromLowerTriangularColumns(ej.toDense());
Eigen::SparseMatrix<double> kron = SparseKroneckerProduct(
symmetric_matrix_i.sparseView(), symmetric_matrix_j.sparseView());
for (int k = 0; k < kron.outerSize(); ++k) {
for (Eigen::SparseMatrix<double>::InnerIterator it(kron, k); it; ++it) {
if (it.value() > 0) {
symmetric_matrix(it.row(), it.col()) =
tensor_vector(i * sym_elt_m + j);
}
}
}
}
}
return symmetric_matrix;
}
// TODO(Alexandre.Amice) Move these to mathematical_program.h
// Adds the constraint that the matrix X is Lorentz-positive-orthant separable
// i.e. a conic combination of tensors in ℒᵐ ⊗ R₊ⁿ, where ℒᵐ is the Lorentz cone
// of size m and R₊ⁿ is the positive orthant in n dimensions. Namely X = ∑ᵢ
// λᵢxᵢyᵢᵀ where λᵢ ≥ 0, xᵢ is in the Lorentz cone of size X.rows() and y ≥ 0
// componentwise and is of size X.cols(). This condition is equivalent to each
// column of X being in the Lorentz cone.
void AddMatrixIsLorentzByPositiveOrthantSeparableConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X,
MathematicalProgram* prog);
// Adds the constraint that the matrix of expressions X is
// Lorentz-positive-orthant separable i.e. a conic combination of tensors
// in ℒᵐ ⊗ R₊ⁿ, where ℒᵐ is the Lorentz cone of size m and R₊ⁿ is the positive
// orthant in n dimensions. Namely X = ∑ᵢ λᵢxᵢyᵢᵀ where λᵢ ≥ 0, xᵢ is in the
// Lorentz cone of size X.rows() and y ≥ 0 componentwise and is of size
// X.cols(). This condition is equivalent to each column of X being in the
// Lorentz cone.
void AddMatrixIsLorentzByPositiveOrthantSeparableConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X,
MathematicalProgram* prog);
// Adds the constraint that the matrix X is positive-orthant-Lorentz separable
// i.e. a conic combination of tensors in R₊ᵐ ⊗ ℒⁿ, where R₊ᵐ is the positive
// orthant in m dimensions and ℒⁿ is the Lorentz cone of size n. Namely X = ∑ᵢ
// λᵢxᵢyᵢᵀ where λᵢ ≥ 0, xᵢ ≥ 0 componentwise and of size X.rows() and yᵢ is in
// the Lorentz cone of size X.cols(). This condition is equivalent to each row
// of X being in the Lorentz cone.
void AddMatrixIsPositiveOrthantByLorentzSeparableConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X,
MathematicalProgram* prog);
// Adds the constraint that the matrix of expressions X is
// positive-orthant-Lorentz separable i.e. a conic combination of tensors
// in R₊ᵐ ⊗ ℒⁿ, where R₊ᵐ is the positive orthant in m dimensions and ℒⁿ is the
// Lorentz cone of size n. Namely X = ∑ᵢ λᵢxᵢyᵢᵀ where λᵢ ≥ 0, xᵢ ≥ 0
// componentwise and of size X.rows() and yᵢ is in the Lorentz cone of size
// X.cols(). This condition is equivalent to each row of X being in the
// Lorentz cone.
void AddMatrixIsPositiveOrthantByLorentzSeparableConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X,
MathematicalProgram* prog);
// Adds the constraint that the matrix X is Lorentz-Lorentz separable i.e. a
// conic combination of tensors in ℒᵐ ⊗ ℒⁿ, where ℒᵐ is the Lorentz cone of size
// m and ℒⁿ is the Lorentz cone of size n. Namely X = ∑ᵢ λᵢxᵢyᵢᵀ where λᵢ ≥ 0,
// xᵢ is in the Lorentz cone of size X.rows() and yᵢ is in the Lorentz cone of
// size X.cols().
void AddMatrixIsLorentzByLorentzSeparableConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X,
MathematicalProgram* prog);
// Adds the constraint that the matrix of expresssions X is Lorentz-Lorentz
// separable i.e. a conic combination of tensors in ℒᵐ ⊗ ℒⁿ, where ℒᵐ is the
// Lorentz cone of size m and ℒⁿ is the Lorentz cone of size n. Namely X = ∑ᵢ
// λᵢxᵢyᵢᵀ where λᵢ ≥ 0, xᵢ is in the Lorentz cone of size X.rows() and yᵢ is in
// the Lorentz cone of size X.cols().
void AddMatrixIsLorentzByLorentzSeparableConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X,
MathematicalProgram* prog);
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/clp_solver.h | #pragma once
#include <string>
#include <Eigen/Core>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/solver_base.h"
namespace drake {
namespace solvers {
/**
* The CLP solver details after calling Solve() function. The user can call
* MathematicalProgramResult::get_solver_details<ClpSolver>() to obtain the
* details.
*/
struct ClpSolverDetails {
/** The CLP_VERSION from the Clp build. */
std::string clp_version;
/** Refer to ClpModel::status() function for the meaning of the status code.
* - -1: unknown error.
* - 0: optimal.
* - 1: primal infeasible
* - 2: dual infeasible
* - 3: stopped on iterations or time.
* - 4: stopped due to errors
* - 5: stopped by event handler
*/
int status{-1};
};
/**
* A wrapper to call CLP using Drake's MathematicalProgram.
* @note Currently our ClpSolver has a memory issue when solving a QP. The user
* should be aware of this risk.
* @note The authors can adjust the problem scaling option by setting "scaling"
as mentioned in
https://github.com/coin-or/Clp/blob/43129ba1a7fd66ce70fe0761fcd696951917ed2e/src/ClpModel.hpp#L705-L706
* For example
* prog.SetSolverOption(ClpSolver::id(), "scaling", 0);
* will do "no scaling". The default is 1.
*/
class ClpSolver final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ClpSolver)
using Details = ClpSolverDetails;
ClpSolver();
~ClpSolver() 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&);
static std::string UnsatisfiedProgramAttributes(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/create_constraint.cc | #include "drake/solvers/create_constraint.h"
#include <algorithm>
#include <cmath>
#include <sstream>
#include <fmt/format.h>
#include "drake/common/symbolic/decompose.h"
#include "drake/math/quadratic_form.h"
#include "drake/solvers/decision_variable.h"
namespace drake {
namespace solvers {
namespace internal {
using std::find;
using std::isfinite;
using std::make_shared;
using std::numeric_limits;
using std::ostringstream;
using std::runtime_error;
using std::set;
using std::shared_ptr;
using std::unordered_map;
using std::vector;
using symbolic::Expression;
using symbolic::Formula;
using symbolic::Polynomial;
using symbolic::Variable;
using symbolic::Variables;
const double kInf = numeric_limits<double>::infinity();
Binding<Constraint> ParseConstraint(
const Eigen::Ref<const VectorX<Expression>>& v,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub) {
DRAKE_ASSERT(v.rows() == lb.rows() && v.rows() == ub.rows());
if (!IsAffine(v)) {
// Quadratic constraints.
if (v.size() == 1 && v[0].is_polynomial()) {
const symbolic::Polynomial poly{v[0]};
if (poly.TotalDegree() == 2) {
return ParseQuadraticConstraint(v[0], lb[0], ub[0]);
}
}
auto constraint = make_shared<ExpressionConstraint>(v, lb, ub);
return CreateBinding(constraint, constraint->vars());
} // else, continue on to linear-specific version below.
if ((ub - lb).isZero()) {
return ParseLinearEqualityConstraint(v, lb);
}
// Setup map_var_to_index and vars.
// such that map_var_to_index[vars(i)] = i
VectorXDecisionVariable vars;
unordered_map<Variable::Id, int> map_var_to_index;
std::tie(vars, map_var_to_index) =
symbolic::ExtractVariablesFromExpression(v);
// Construct A, new_lb, new_ub. map_var_to_index is used here.
Eigen::MatrixXd A{Eigen::MatrixXd::Zero(v.size(), vars.size())};
Eigen::VectorXd new_lb{v.size()};
Eigen::VectorXd new_ub{v.size()};
// We will determine if lb <= v <= ub is a bounding box constraint, namely
// x_lb <= x <= x_ub.
bool is_v_bounding_box = true;
Eigen::RowVectorXd Ai(A.cols());
for (int i = 0; i < v.size(); ++i) {
double constant_term = 0;
int num_vi_variables = symbolic::DecomposeAffineExpression(
v(i), map_var_to_index, &Ai, &constant_term);
A.row(i) = Ai;
if (num_vi_variables == 0 &&
!(lb(i) <= constant_term && constant_term <= ub(i))) {
// Unsatisfiable constraint with no variables, such as 1 <= 0 <= 2
throw std::runtime_error(
fmt::format("Constraint {} <= {} <= {} is unsatisfiable but called "
"with ParseConstraint.",
lb(i), v(i).to_string(), ub(i)));
} else {
new_lb(i) = lb(i) - constant_term;
new_ub(i) = ub(i) - constant_term;
DRAKE_DEMAND(!std::isnan(new_lb(i)));
DRAKE_DEMAND(!std::isnan(new_ub(i)));
if (num_vi_variables != 1) {
is_v_bounding_box = false;
}
}
}
if (is_v_bounding_box) {
// If every lb(i) <= v(i) <= ub(i) is a bounding box constraint, then
// formulate a bounding box constraint x_lb <= x <= x_ub
VectorXDecisionVariable bounding_box_x(v.size());
for (int i = 0; i < v.size(); ++i) {
// v(i) is in the form of c * x
double x_coeff = 0;
for (const auto& x : v(i).GetVariables()) {
const double coeff = A(i, map_var_to_index[x.get_id()]);
if (coeff != 0) {
x_coeff += coeff;
bounding_box_x(i) = x;
}
}
if (x_coeff > 0) {
new_lb(i) /= x_coeff;
new_ub(i) /= x_coeff;
} else {
const double lb_i = new_lb(i);
new_lb(i) = new_ub(i) / x_coeff;
new_ub(i) = lb_i / x_coeff;
}
DRAKE_DEMAND(!std::isnan(new_lb(i)));
DRAKE_DEMAND(!std::isnan(new_ub(i)));
}
return CreateBinding(make_shared<BoundingBoxConstraint>(new_lb, new_ub),
bounding_box_x);
}
return CreateBinding(make_shared<LinearConstraint>(A, new_lb, new_ub), vars);
}
std::unique_ptr<Binding<Constraint>> MaybeParseLinearConstraint(
const symbolic::Expression& e, double lb, double ub) {
if (!e.is_polynomial()) {
return std::unique_ptr<Binding<Constraint>>{nullptr};
}
const Polynomial p{e};
if (p.TotalDegree() > 1) {
return std::unique_ptr<Binding<Constraint>>{nullptr};
}
// If p only has one indeterminates, then we can always return a bounding box
// constraint.
if (p.indeterminates().size() == 1) {
// We decompose the polynomial `p` into `constant_term + coeff * var`.
double coeff = 0;
double constant_term = 0;
for (const auto& term : p.monomial_to_coefficient_map()) {
if (term.first.total_degree() == 0) {
constant_term += get_constant_value(term.second);
} else {
coeff += get_constant_value(term.second);
}
}
// coeff should not be 0. The symbolic polynomial should be able to detect
// when the coefficient is 0, and remove it from
// monomial_to_coefficient_map.
DRAKE_DEMAND(coeff != 0);
double var_lower{}, var_upper{};
if (coeff > 0) {
var_lower = (lb - constant_term) / coeff;
var_upper = (ub - constant_term) / coeff;
} else {
var_lower = (ub - constant_term) / coeff;
var_upper = (lb - constant_term) / coeff;
}
return std::make_unique<Binding<Constraint>>(
std::make_shared<BoundingBoxConstraint>(Vector1d(var_lower),
Vector1d(var_upper)),
Vector1<symbolic::Variable>(*(p.indeterminates().begin())));
}
VectorX<symbolic::Variable> bound_variables(p.indeterminates().size());
std::unordered_map<symbolic::Variable::Id, int> map_var_to_index;
int index = 0;
for (const auto& var : p.indeterminates()) {
bound_variables(index) = var;
map_var_to_index.emplace(var.get_id(), index++);
}
Eigen::RowVectorXd a(p.indeterminates().size());
a.setZero();
double lower = lb;
double upper = ub;
for (const auto& term : p.monomial_to_coefficient_map()) {
if (term.first.total_degree() == 0) {
const double coeff = get_constant_value(term.second);
lower -= coeff;
upper -= coeff;
} else {
const int var_index =
map_var_to_index.at(term.first.GetVariables().begin()->get_id());
a(var_index) = get_constant_value(term.second);
}
}
if (lower == upper) {
return std::make_unique<Binding<Constraint>>(
std::make_shared<LinearEqualityConstraint>(a, Vector1d(lower)),
bound_variables);
} else {
return std::make_unique<Binding<Constraint>>(
std::make_shared<LinearConstraint>(a, Vector1d(lower), Vector1d(upper)),
bound_variables);
}
}
namespace {
// Given two symbolic expressions, e1 and e2, finds an equi-satisfiable
// constraint `e <= c` for `e1 <= e2`. First, it decomposes e1 and e2 into `e1 =
// c1 + e1'` and `e2 = c2 + e2'`. Then it does the following case analysis.
//
// Case 1: If c1 or c2 are finite, we use the following derivations:
//
// e1 <= e2
// -> c1 + e1' <= c2 + e2'
// -> e1' - e2' <= c2 - c1.
//
// and set e := e1' - e2' and c := c2 - c1.
//
// Case 2: If both c1 and c2 are infinite. We use the following table
//
// c1 c2
// --------------------------
// +∞ <= +∞ Trivially holds.
// +∞ <= -∞ Infeasible.
// -∞ <= +∞ Trivially holds.
// -∞ <= -∞ Trivially holds.
//
// and throw an exception for all the cases.
//
// Note that c1 (resp. c2) can be infinite only if e1 (resp. e2) is zero.
// Otherwise, it throws an exception. To understand this side-condition,
// consider the following example:
//
// e1 = 0
// e2 = x + ∞
//
// e1 <= e2 := 0 <= x + ∞ -- (1)
//
// Without the side-condition, we might derive the following (wrong)
// equi-satisfiable constraint:
//
// -x <= ∞ -- (2)
//
// This is problematic because x ↦ -∞ is a satisfying constraint of
// (2) but it's not for (1) since we have:
//
// 0 <= -∞ + ∞
// 0 <= nan
// False.
//
void FindBound(const Expression& e1, const Expression& e2, Expression* const e,
double* const c) {
DRAKE_ASSERT(e != nullptr);
DRAKE_ASSERT(c != nullptr);
double c1 = 0;
double c2 = 0;
const Expression e1_expanded{e1.Expand()};
if (is_constant(e1_expanded)) {
c1 = get_constant_value(e1_expanded);
} else if (is_addition(e1_expanded)) {
c1 = get_constant_in_addition(e1_expanded);
if (!isfinite(c1)) {
ostringstream oss;
oss << "FindBound() cannot handle the constraint: " << e1 << " <= " << e2
<< " because " << e1
<< " has infinity in the constant term after expansion.";
throw runtime_error{oss.str()};
}
*e = Expression::Zero();
for (const auto& p : get_expr_to_coeff_map_in_addition(e1_expanded)) {
*e += p.first * p.second;
}
} else {
*e = e1_expanded;
}
const Expression e2_expanded{e2.Expand()};
if (is_constant(e2_expanded)) {
c2 = get_constant_value(e2_expanded);
} else if (is_addition(e2_expanded)) {
c2 = get_constant_in_addition(e2_expanded);
if (!isfinite(c2)) {
ostringstream oss;
oss << "FindBound() cannot handle the constraint: " << e1 << " <= " << e2
<< " because " << e2
<< " has infinity in the constant term after expansion.";
throw runtime_error{oss.str()};
}
for (const auto& p : get_expr_to_coeff_map_in_addition(e2_expanded)) {
*e -= p.first * p.second;
}
} else {
*e -= e2_expanded;
}
if (isfinite(c1) || isfinite(c2)) {
*c = c2 - c1;
return;
}
// Handle special cases where both of `c1` and `c2` are infinite.
// c1 c2
// --------------------------
// +∞ <= +∞ Trivially holds.
// +∞ <= -∞ Infeasible.
// -∞ <= +∞ Trivially holds.
// -∞ <= -∞ Trivially holds.
ostringstream oss;
if (c1 == numeric_limits<double>::infinity() &&
c2 == -numeric_limits<double>::infinity()) {
oss << "FindBound() detects an infeasible constraint: " << e1
<< " <= " << e2 << ".";
throw runtime_error{oss.str()};
} else {
oss << "FindBound() detects a trivial constraint: " << e1 << " <= " << e2
<< ".";
throw runtime_error{oss.str()};
}
}
} // namespace
Binding<Constraint> ParseConstraint(
const Eigen::Ref<const MatrixX<symbolic::Formula>>& formulas) {
const int n = formulas.rows() * formulas.cols();
// Decomposes 2D-array of formulas into 1D-vector of expression, `v`, and two
// 1D-vector of double `lb` and `ub`.
VectorX<Expression> v{n};
Eigen::VectorXd lb{n};
Eigen::VectorXd ub{n};
int k{0}; // index variable for 1D components.
for (int j{0}; j < formulas.cols(); ++j) {
for (int i{0}; i < formulas.rows(); ++i) {
const symbolic::Formula& f{formulas(i, j)};
if (symbolic::is_false(f)) {
throw std::runtime_error(
fmt::format("ParseConstraint is called with formulas({}, {}) being "
"always false",
i, j));
} else if (symbolic::is_true(f)) {
continue;
} else if (is_equal_to(f)) {
// f(i) := (lhs == rhs)
// (lhs - rhs == 0)
v(k) = get_lhs_expression(f) - get_rhs_expression(f);
lb(k) = 0.0;
ub(k) = 0.0;
} else if (is_less_than_or_equal_to(f)) {
// f(i) := (lhs <= rhs)
const Expression& lhs = get_lhs_expression(f);
const Expression& rhs = get_rhs_expression(f);
if (is_constant(lhs, kInf)) {
throw std::runtime_error(
fmt::format("ParseConstraint is called with a formula ({}) with "
"a lower bound of +inf.", f));
}
if (is_constant(rhs, -kInf)) {
throw std::runtime_error(
fmt::format("ParseConstraint is called with a formula ({}) with "
"an upper bound of -inf.", f));
}
if (is_constant(lhs, -kInf)) {
// The constraint is trivial, but valid.
v(k) = rhs;
lb(k) = -kInf;
ub(k) = kInf;
} else if (is_constant(rhs, kInf)) {
// The constraint is trivial, but valid.
v(k) = lhs;
lb(k) = -kInf;
ub(k) = kInf;
} else {
// -∞ <= lhs - rhs <= 0
v(k) = lhs - rhs;
lb(k) = -kInf;
ub(k) = 0.0;
}
} else if (is_greater_than_or_equal_to(f)) {
// f(i) := (lhs >= rhs)
const Expression& lhs = get_lhs_expression(f);
const Expression& rhs = get_rhs_expression(f);
if (is_constant(rhs, kInf)) {
throw std::runtime_error(
fmt::format("ParseConstraint is called with a formula ({}) with "
"a lower bound of +inf.", f));
}
if (is_constant(lhs, -kInf)) {
throw std::runtime_error(
fmt::format("ParseConstraint is called with a formula ({}) with "
"an upper bound of -inf.", f));
}
if (is_constant(rhs, -kInf)) {
// The constraint is trivial, but valid.
v(k) = lhs;
lb(k) = -kInf;
ub(k) = kInf;
} else if (is_constant(lhs, kInf)) {
// The constraint is trivial, but valid.
v(k) = rhs;
lb(k) = -kInf;
ub(k) = kInf;
} else {
// 0 <= lhs - rhs <= ∞
v(k) = lhs - rhs;
lb(k) = 0.0;
ub(k) = kInf;
}
} else {
std::ostringstream oss;
oss << "ParseConstraint is called with an "
"array of formulas which includes a formula "
<< f
<< " which is not a relational formula using one of {==, <=, >=} "
"operators.";
throw std::runtime_error(oss.str());
}
++k;
}
}
if (k == 0) {
// All formulas are always True, return an empty bounding box constraint.
return internal::CreateBinding(std::make_shared<BoundingBoxConstraint>(
Eigen::VectorXd(0), Eigen::VectorXd(0)),
VectorXDecisionVariable(0));
}
return ParseConstraint(v.head(k), lb.head(k), ub.head(k));
}
Binding<Constraint> ParseConstraint(const Formula& f) {
if (symbolic::is_false(f)) {
throw std::runtime_error(
"ParseConstraint is called with a formula being always false.");
} else if (symbolic::is_true(f)) {
return internal::CreateBinding(std::make_shared<BoundingBoxConstraint>(
Eigen::VectorXd(0), Eigen::VectorXd(0)),
VectorXDecisionVariable(0));
} else if (is_equal_to(f)) {
// e1 == e2
const Expression& e1{get_lhs_expression(f)};
const Expression& e2{get_rhs_expression(f)};
return ParseConstraint(e1 - e2, 0.0, 0.0);
} else if (is_greater_than_or_equal_to(f)) {
// e1 >= e2
const Expression& e1{get_lhs_expression(f)};
const Expression& e2{get_rhs_expression(f)};
Expression e;
double ub = 0.0;
FindBound(e2, e1, &e, &ub);
return ParseConstraint(e, -numeric_limits<double>::infinity(), ub);
} else if (is_less_than_or_equal_to(f)) {
// e1 <= e2
const Expression& e1{get_lhs_expression(f)};
const Expression& e2{get_rhs_expression(f)};
Expression e;
double ub = 0.0;
FindBound(e1, e2, &e, &ub);
return ParseConstraint(e, -numeric_limits<double>::infinity(), ub);
} else if (is_conjunction(f)) {
const std::set<Formula>& operands = get_operands(f);
// TODO(jwnimmer-tri) We should use an absl::InlinedVector here.
const std::vector<Formula> vec_operands(operands.begin(), operands.end());
const Eigen::Map<const VectorX<Formula>> map_operands(vec_operands.data(),
vec_operands.size());
return ParseConstraint(map_operands);
}
ostringstream oss;
oss << "ParseConstraint is called with a formula " << f
<< " which is neither a relational formula using one of {==, <=, >=} "
"operators nor a conjunction of those relational formulas.";
throw runtime_error(oss.str());
}
Binding<LinearEqualityConstraint> ParseLinearEqualityConstraint(
const set<Formula>& formulas) {
const auto n = formulas.size();
// Decomposes a set of formulas, `{e₁₁ == e₁₂, ..., eₙ₁ == eₙ₂}`
// into a 1D-vector of expressions, `v = [e₁₁ - e₁₂, ..., eₙ₁ - eₙ₂]`.
VectorX<symbolic::Expression> v{n};
int i{0}; // index variable used in the loop
for (const symbolic::Formula& f : formulas) {
if (symbolic::is_false(f)) {
throw std::runtime_error(
"ParseLinearEqualityConstraint is called with one of formulas being "
"always false.");
} else if (symbolic::is_true(f)) {
continue;
} else if (is_equal_to(f)) {
// f := (lhs == rhs)
// (lhs - rhs == 0)
v(i) = get_lhs_expression(f) - get_rhs_expression(f);
} else {
ostringstream oss;
oss << "ParseLinearEqualityConstraint(const "
<< "set<Formula>& formulas) is called while its argument 'formulas' "
<< "includes a non-equality formula " << f << ".";
throw runtime_error(oss.str());
}
++i;
}
if (i == 0) {
// All formulas are always true, return an empty linear equality constraint.
return internal::CreateBinding(
std::make_shared<LinearEqualityConstraint>(
Eigen::Matrix<double, 0, 0>(), Eigen::Matrix<double, 0, 1>()),
Eigen::Matrix<symbolic::Variable, 0, 1>());
}
return ParseLinearEqualityConstraint(v.head(i), Eigen::VectorXd::Zero(i));
}
Binding<LinearEqualityConstraint> ParseLinearEqualityConstraint(
const Formula& f) {
if (symbolic::is_false(f)) {
throw std::runtime_error(
"ParseLinearEqualityConstraint is called with a formula being always "
"false.");
}
if (symbolic::is_true(f)) {
// The formula is always true, return an empty linear equality constraint.
return internal::CreateBinding(
std::make_shared<LinearEqualityConstraint>(
Eigen::Matrix<double, 0, 0>(), Eigen::Matrix<double, 0, 1>()),
Eigen::Matrix<symbolic::Variable, 0, 1>());
} else if (is_equal_to(f)) {
// e1 == e2
const Expression& e1{get_lhs_expression(f)};
const Expression& e2{get_rhs_expression(f)};
return ParseLinearEqualityConstraint(e1 - e2, 0.0);
}
if (is_conjunction(f)) {
return ParseLinearEqualityConstraint(get_operands(f));
}
ostringstream oss;
oss << "ParseLinearConstraint is called with a formula " << f
<< " which is neither an equality formula nor a conjunction of equality "
"formulas.";
throw runtime_error(oss.str());
}
Binding<LinearEqualityConstraint> DoParseLinearEqualityConstraint(
const Eigen::Ref<const VectorX<Expression>>& v,
const Eigen::Ref<const Eigen::VectorXd>& b) {
DRAKE_DEMAND(v.rows() == b.rows());
VectorX<symbolic::Variable> vars;
unordered_map<Variable::Id, int> map_var_to_index;
std::tie(vars, map_var_to_index) =
symbolic::ExtractVariablesFromExpression(v);
// TODO(hongkai.dai): use sparse matrix.
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(v.rows(), vars.rows());
Eigen::VectorXd beq = Eigen::VectorXd::Zero(v.rows());
Eigen::RowVectorXd Ai(A.cols());
for (int i = 0; i < v.rows(); ++i) {
double constant_term(0);
symbolic::DecomposeAffineExpression(v(i), map_var_to_index, &Ai,
&constant_term);
A.row(i) = Ai;
beq(i) = b(i) - constant_term;
}
return CreateBinding(make_shared<LinearEqualityConstraint>(A, beq), vars);
}
Binding<QuadraticConstraint> ParseQuadraticConstraint(
const symbolic::Expression& e, double lower_bound, double upper_bound,
std::optional<QuadraticConstraint::HessianType> hessian_type) {
// First build an Eigen vector that contains all the bound variables.
auto p = symbolic::ExtractVariablesFromExpression(e);
const auto& vars_vec = p.first;
const auto& map_var_to_index = p.second;
// Now decompose the expression into coefficients and monomials.
const symbolic::Polynomial poly{e};
Eigen::MatrixXd Q(vars_vec.size(), vars_vec.size());
Eigen::VectorXd b(vars_vec.size());
double constant_term;
// Decompose the polynomial as 0.5xᵀQx + bᵀx + k.
symbolic::DecomposeQuadraticPolynomial(poly, map_var_to_index, &Q, &b,
&constant_term);
// The constraint to be imposed is
// lb - k ≤ 0.5 xᵀQx + bᵀx ≤ ub - k
return CreateBinding(make_shared<QuadraticConstraint>(
Q, b, lower_bound - constant_term,
upper_bound - constant_term, hessian_type),
vars_vec);
}
shared_ptr<Constraint> MakePolynomialConstraint(
const VectorXPoly& polynomials,
const vector<Polynomiald::VarType>& poly_vars, const Eigen::VectorXd& lb,
const Eigen::VectorXd& ub) {
// Polynomials that are actually affine (a sum of linear terms + a
// constant) can be special-cased. Other polynomials are treated as
// generic for now.
// TODO(ggould-tri) There may be other such special easy cases.
bool all_affine = true;
for (int i = 0; i < polynomials.rows(); i++) {
if (!polynomials[i].IsAffine()) {
all_affine = false;
break;
}
}
if (all_affine) {
Eigen::MatrixXd linear_constraint_matrix =
Eigen::MatrixXd::Zero(polynomials.rows(), poly_vars.size());
Eigen::VectorXd linear_constraint_lb = lb;
Eigen::VectorXd linear_constraint_ub = ub;
for (int poly_num = 0; poly_num < polynomials.rows(); poly_num++) {
for (const auto& monomial : polynomials[poly_num].GetMonomials()) {
if (monomial.terms.size() == 0) {
linear_constraint_lb[poly_num] -= monomial.coefficient;
linear_constraint_ub[poly_num] -= monomial.coefficient;
} else {
DRAKE_DEMAND(monomial.terms.size() == 1); // Because isAffine().
const Polynomiald::VarType term_var = monomial.terms[0].var;
int var_num = (find(poly_vars.begin(), poly_vars.end(), term_var) -
poly_vars.begin());
DRAKE_ASSERT(var_num < static_cast<int>(poly_vars.size()));
linear_constraint_matrix(poly_num, var_num) = monomial.coefficient;
}
}
}
if (ub == lb) {
return make_shared<LinearEqualityConstraint>(linear_constraint_matrix,
linear_constraint_ub);
} else {
return make_shared<LinearConstraint>(
linear_constraint_matrix, linear_constraint_lb, linear_constraint_ub);
}
} else {
return make_shared<PolynomialConstraint>(polynomials, poly_vars, lb, ub);
}
}
Binding<LorentzConeConstraint> ParseLorentzConeConstraint(
const Eigen::Ref<const VectorX<Expression>>& v,
LorentzConeConstraint::EvalType eval_type) {
DRAKE_DEMAND(v.rows() >= 2);
Eigen::MatrixXd A{};
Eigen::VectorXd b(v.size());
VectorXDecisionVariable vars{};
symbolic::DecomposeAffineExpressions(v, &A, &b, &vars);
DRAKE_DEMAND(vars.rows() >= 1);
return CreateBinding(make_shared<LorentzConeConstraint>(A, b, eval_type),
vars);
}
Binding<LorentzConeConstraint> ParseLorentzConeConstraint(
const Expression& linear_expr, const Expression& quadratic_expr, double tol,
LorentzConeConstraint::EvalType eval_type) {
const auto& quadratic_p =
symbolic::ExtractVariablesFromExpression(quadratic_expr);
const auto& quadratic_vars = quadratic_p.first;
const auto& quadratic_var_to_index_map = quadratic_p.second;
const symbolic::Polynomial poly{quadratic_expr};
Eigen::MatrixXd Q(quadratic_vars.size(), quadratic_vars.size());
Eigen::VectorXd b(quadratic_vars.size());
double a;
symbolic::DecomposeQuadraticPolynomial(poly, quadratic_var_to_index_map, &Q,
&b, &a);
// The constraint that the linear expression v1 satisfying
// v1 >= sqrt(0.5 * x' * Q * x + b' * x + a), is equivalent to the vector
// [z; y] being within a Lorentz cone, where
// z = v1
// y = C * x + d
// such that yᵀy = 0.5xᵀQx + bᵀx + a
VectorX<Expression> expr{};
Eigen::MatrixXd C;
Eigen::VectorXd d;
std::tie(C, d) = math::DecomposePositiveQuadraticForm(0.5 * Q, b, a, tol);
expr.resize(1 + C.rows());
// expr(0) is z
expr(0) = linear_expr;
// expr.segment(1, C.rows()) = y
expr.segment(1, C.rows()) = C * quadratic_vars + d;
return ParseLorentzConeConstraint(expr, eval_type);
}
Binding<RotatedLorentzConeConstraint> ParseRotatedLorentzConeConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v) {
DRAKE_DEMAND(v.rows() >= 3);
Eigen::MatrixXd A{};
Eigen::VectorXd b(v.size());
VectorXDecisionVariable vars{};
symbolic::DecomposeAffineExpressions(v, &A, &b, &vars);
DRAKE_DEMAND(vars.rows() >= 1);
return CreateBinding(std::make_shared<RotatedLorentzConeConstraint>(A, b),
vars);
}
Binding<RotatedLorentzConeConstraint> ParseRotatedLorentzConeConstraint(
const symbolic::Expression& linear_expr1,
const symbolic::Expression& linear_expr2,
const symbolic::Expression& quadratic_expr, double tol) {
const auto& quadratic_p =
symbolic::ExtractVariablesFromExpression(quadratic_expr);
const auto& quadratic_vars = quadratic_p.first;
const auto& quadratic_var_to_index_map = quadratic_p.second;
const symbolic::Polynomial poly{quadratic_expr};
Eigen::MatrixXd Q(quadratic_vars.size(), quadratic_vars.size());
Eigen::VectorXd b(quadratic_vars.size());
double a;
symbolic::DecomposeQuadraticPolynomial(poly, quadratic_var_to_index_map, &Q,
&b, &a);
Eigen::MatrixXd C;
Eigen::VectorXd d;
std::tie(C, d) = math::DecomposePositiveQuadraticForm(0.5 * Q, b, a, tol);
VectorX<symbolic::Expression> expr(2 + C.rows());
expr(0) = linear_expr1;
expr(1) = linear_expr2;
expr.tail(C.rows()) = C * quadratic_vars + d;
return ParseRotatedLorentzConeConstraint(expr);
}
std::shared_ptr<RotatedLorentzConeConstraint>
ParseQuadraticAsRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double c, double zero_tol) {
// [-bᵀx-c, 1, Fx] is in the rotated Lorentz cone, where FᵀF = 0.5 * Q
const Eigen::MatrixXd F = math::DecomposePSDmatrixIntoXtransposeTimesX(
(Q + Q.transpose()) / 4, zero_tol);
// A_lorentz * x + b_lorentz = [-bᵀx-c, 1, Fx]
Eigen::MatrixXd A_lorentz = Eigen::MatrixXd::Zero(2 + F.rows(), F.cols());
Eigen::VectorXd b_lorentz = Eigen::VectorXd::Zero(2 + F.rows());
A_lorentz.row(0) = -b.transpose();
b_lorentz(0) = -c;
b_lorentz(1) = 1;
A_lorentz.bottomRows(F.rows()) = F;
return std::make_shared<RotatedLorentzConeConstraint>(A_lorentz, b_lorentz);
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/branch_and_bound.cc | #include "drake/solvers/branch_and_bound.h"
#include <algorithm>
#include <limits>
#include <vector>
#include <fmt/format.h>
#include "drake/common/unused.h"
#include "drake/solvers/choose_best_solver.h"
#include "drake/solvers/gurobi_solver.h"
#include "drake/solvers/scs_solver.h"
namespace drake {
namespace solvers {
/** Determines if the mathematical program has binary variables.
*/
bool MathProgHasBinaryVariables(const MathematicalProgram& prog) {
for (int i = 0; i < prog.num_vars(); ++i) {
if (prog.decision_variable(i).get_type() ==
symbolic::Variable::Type::BINARY) {
return true;
}
}
return false;
}
MixedIntegerBranchAndBoundNode::MixedIntegerBranchAndBoundNode(
const MathematicalProgram& prog,
const std::list<symbolic::Variable>& binary_variables,
const SolverId& solver_id)
: prog_{prog.Clone()},
prog_result_{std::make_unique<MathematicalProgramResult>()},
left_child_{nullptr},
right_child_{nullptr},
parent_{nullptr},
fixed_binary_variable_{},
fixed_binary_value_{-1},
remaining_binary_variables_{binary_variables},
solution_result_{SolutionResult::kSolverSpecificError},
optimal_solution_is_integral_{OptimalSolutionIsIntegral::kUnknown},
solver_id_{solver_id} {
// Check if there are still binary variables.
DRAKE_ASSERT(!MathProgHasBinaryVariables(*prog_));
// Set Gurobi DualReductions to 0, to differentiate infeasible from unbounded.
prog_->SetSolverOption(GurobiSolver::id(), "DualReductions", 0);
}
bool MixedIntegerBranchAndBoundNode::IsRoot() const {
return parent_ == nullptr;
}
namespace {
// Replaces the variables bound with the constraint or cost with new variables.
template <typename Constraint>
Binding<Constraint> ReplaceBoundVariables(
const Binding<Constraint>& binding,
const std::unordered_map<symbolic::Variable::Id, symbolic::Variable>&
map_old_vars_to_new_vars) {
const auto& old_bound_vars = binding.variables();
VectorXDecisionVariable new_bound_vars(old_bound_vars.rows());
for (int i = 0; i < new_bound_vars.rows(); ++i) {
new_bound_vars(i) = map_old_vars_to_new_vars.at(old_bound_vars(i).get_id());
}
return Binding<Constraint>(binding.evaluator(), new_bound_vars);
}
// Adds a vector of costs to a mathematical program.
template <typename Cost>
void AddVectorOfCostsToProgram(
const std::vector<Binding<Cost>>& costs,
const std::unordered_map<symbolic::Variable::Id, symbolic::Variable>&
map_old_vars_to_new_vars,
MathematicalProgram* prog) {
for (const auto& cost : costs) {
prog->AddCost(ReplaceBoundVariables(cost, map_old_vars_to_new_vars));
}
}
// Adds a vector of constraints to a mathematical program.
template <typename Constraint>
void AddVectorOfConstraintsToProgram(
const std::vector<Binding<Constraint>>& constraints,
const std::unordered_map<symbolic::Variable::Id, symbolic::Variable>&
map_old_vars_to_new_vars,
MathematicalProgram* prog) {
for (const auto& constraint : constraints) {
prog->AddConstraint(
ReplaceBoundVariables(constraint, map_old_vars_to_new_vars));
}
}
SolutionResult SolveProgramWithSolver(const MathematicalProgram& prog,
const SolverId& solver_id,
MathematicalProgramResult* result) {
std::unique_ptr<SolverInterface> solver = MakeSolver(solver_id);
DRAKE_ASSERT(solver != nullptr);
solver->Solve(prog, {}, {}, result);
return result->get_solution_result();
}
} // namespace
std::pair<std::unique_ptr<MixedIntegerBranchAndBoundNode>,
std::unordered_map<symbolic::Variable::Id, symbolic::Variable>>
MixedIntegerBranchAndBoundNode::ConstructRootNode(
const MathematicalProgram& prog, const SolverId& solver_id) {
// Construct a new optimization program, same as prog, but relaxing the binary
// constraint to 0 ≤ y ≤ 1.
MathematicalProgram new_prog;
// First check the decision variables of prog. Construct a new set of decision
// variables with the same names as those in prog, but with different IDs.
const auto& prog_vars = prog.decision_variables();
VectorXDecisionVariable new_vars(prog_vars.rows());
std::unordered_map<symbolic::Variable::Id, symbolic::Variable>
map_old_vars_to_new_vars;
std::vector<int> binary_variable_indices{};
for (int i = 0; i < prog_vars.rows(); ++i) {
switch (prog_vars(i).get_type()) {
case symbolic::Variable::Type::CONTINUOUS: {
// If the prog_vars(i) is of type CONTINUOUS, then new_vars(i) is also
// CONTINUOUS.
new_vars(i) = symbolic::Variable(prog_vars(i).get_name(),
symbolic::Variable::Type::CONTINUOUS);
map_old_vars_to_new_vars.emplace_hint(
map_old_vars_to_new_vars.end(), prog_vars(i).get_id(), new_vars(i));
break;
}
case symbolic::Variable::Type::BINARY: {
// If program_vars(i) is of type BINARY, then new_vars(i) is CONTINUOUS
// instead. We will later add the constraint 0 ≤ new_vars(i) ≤ 1
new_vars(i) = symbolic::Variable(prog_vars(i).get_name(),
symbolic::Variable::Type::CONTINUOUS);
map_old_vars_to_new_vars.emplace_hint(
map_old_vars_to_new_vars.end(), prog_vars(i).get_id(), new_vars(i));
binary_variable_indices.push_back(i);
break;
}
default: {
throw std::runtime_error(
"This variable type is not supported in branch and bound.");
}
}
}
new_prog.AddDecisionVariables(new_vars);
if (binary_variable_indices.empty()) {
throw std::runtime_error(
"No binary variable found in the optimization program.\n");
}
const int num_binary_variables = binary_variable_indices.size();
VectorXDecisionVariable binary_variables(num_binary_variables);
for (int i = 0; i < num_binary_variables; ++i) {
binary_variables(i) = new_vars(binary_variable_indices[i]);
}
new_prog.AddBoundingBoxConstraint(Eigen::VectorXd::Zero(num_binary_variables),
Eigen::VectorXd::Ones(num_binary_variables),
binary_variables);
// Add the indeterminates
new_prog.AddIndeterminates(prog.indeterminates());
// Now add all the costs in prog to new_prog.
AddVectorOfCostsToProgram(prog.generic_costs(), map_old_vars_to_new_vars,
&new_prog);
AddVectorOfCostsToProgram(prog.linear_costs(), map_old_vars_to_new_vars,
&new_prog);
AddVectorOfCostsToProgram(prog.quadratic_costs(), map_old_vars_to_new_vars,
&new_prog);
// Now add all the constraints in prog to new_prog.
// TODO(hongkai.dai): Make sure that all constraints stored in
// MathematicalProgram are added. In the future, if we add more constraint
// types to MathematicalProgram, we need to add these constraints to new_prog
// here as well. One solution is to add a method in MathematicalProgram, to
// get all costs and constraints.
AddVectorOfConstraintsToProgram(prog.generic_constraints(),
map_old_vars_to_new_vars, &new_prog);
AddVectorOfConstraintsToProgram(prog.linear_constraints(),
map_old_vars_to_new_vars, &new_prog);
AddVectorOfConstraintsToProgram(prog.linear_equality_constraints(),
map_old_vars_to_new_vars, &new_prog);
AddVectorOfConstraintsToProgram(prog.bounding_box_constraints(),
map_old_vars_to_new_vars, &new_prog);
AddVectorOfConstraintsToProgram(prog.lorentz_cone_constraints(),
map_old_vars_to_new_vars, &new_prog);
AddVectorOfConstraintsToProgram(prog.rotated_lorentz_cone_constraints(),
map_old_vars_to_new_vars, &new_prog);
AddVectorOfConstraintsToProgram(prog.positive_semidefinite_constraints(),
map_old_vars_to_new_vars, &new_prog);
AddVectorOfConstraintsToProgram(prog.linear_matrix_inequality_constraints(),
map_old_vars_to_new_vars, &new_prog);
AddVectorOfConstraintsToProgram(prog.linear_complementarity_constraints(),
map_old_vars_to_new_vars, &new_prog);
// Set the initial guess.
new_prog.SetInitialGuessForAllVariables(prog.initial_guess());
// TODO(hongkai.dai) Set the solver options as well.
std::list<symbolic::Variable> binary_variables_list;
for (int i = 0; i < binary_variables.rows(); ++i) {
binary_variables_list.push_back(binary_variables(i));
}
MixedIntegerBranchAndBoundNode* node = new MixedIntegerBranchAndBoundNode(
new_prog, binary_variables_list, solver_id);
node->solution_result_ =
SolveProgramWithSolver(*node->prog_, solver_id, node->prog_result_.get());
if (node->solution_result_ == SolutionResult::kSolutionFound) {
node->CheckOptimalSolutionIsIntegral();
}
return std::make_pair(std::unique_ptr<MixedIntegerBranchAndBoundNode>(node),
map_old_vars_to_new_vars);
}
void MixedIntegerBranchAndBoundNode::CheckOptimalSolutionIsIntegral() {
// Check if the solution to the remaining binary variables are all either
// 0 or 1.
if (solution_result_ != SolutionResult::kSolutionFound) {
throw std::runtime_error("The program does not have an optimal solution.");
}
for (const auto& var : remaining_binary_variables_) {
const double binary_var_val{prog_result_->GetSolution(var)};
if (std::isnan(binary_var_val)) {
throw std::runtime_error(
"The solution contains NAN, either the problem is not solved "
"yet, or the problem is infeasible, unbounded, or encountered"
"numerical errors during solve.");
}
if (binary_var_val > integral_tol_ && binary_var_val < 1 - integral_tol_) {
optimal_solution_is_integral_ = OptimalSolutionIsIntegral::kFalse;
return;
}
}
optimal_solution_is_integral_ = OptimalSolutionIsIntegral::kTrue;
}
bool MixedIntegerBranchAndBoundNode::optimal_solution_is_integral() const {
if (solution_result_ != SolutionResult::kSolutionFound) {
throw std::runtime_error("The optimal solution is not found.");
}
switch (optimal_solution_is_integral_) {
case OptimalSolutionIsIntegral::kTrue: {
return true;
}
case OptimalSolutionIsIntegral::kFalse: {
return false;
}
case OptimalSolutionIsIntegral::kUnknown: {
throw std::runtime_error(
"Call CheckOptimalSolutionIsIntegral() before calling this "
"function.");
}
}
DRAKE_UNREACHABLE();
}
bool MixedIntegerBranchAndBoundNode::is_explored() const {
return prog_result_.get() != nullptr;
}
int MixedIntegerBranchAndBoundNode::NumExploredNodesInSubtree() const {
// First count this node as the root of the subtree.
int ret = is_explored();
if (left_child_.get() != nullptr) {
ret += left_child_->NumExploredNodesInSubtree();
}
if (right_child_.get() != nullptr) {
ret += right_child_->NumExploredNodesInSubtree();
}
return ret;
}
bool IsVariableInList(const std::list<symbolic::Variable>& variable_list,
const symbolic::Variable& variable) {
for (const auto& var : variable_list) {
if (var.equal_to(variable)) {
return true;
}
}
return false;
}
void MixedIntegerBranchAndBoundNode::FixBinaryVariable(
const symbolic::Variable& binary_variable, bool binary_value) {
// Add constraint y == 0 or y == 1.
prog_->AddBoundingBoxConstraint(static_cast<double>(binary_value),
static_cast<double>(binary_value),
binary_variable);
// Remove binary_variable from remaining_binary_variables_
bool found_binary_variable = false;
for (auto it = remaining_binary_variables_.begin();
it != remaining_binary_variables_.end(); ++it) {
if (it->equal_to(binary_variable)) {
found_binary_variable = true;
remaining_binary_variables_.erase(it);
break;
}
}
if (!found_binary_variable) {
std::ostringstream oss;
oss << binary_variable
<< " is not a remaining binary variable in this node.\n";
throw std::runtime_error(oss.str());
}
// Set fixed_binary_variable_ and fixed_binary_value_.
fixed_binary_variable_ = binary_variable;
fixed_binary_value_ = binary_value;
}
void MixedIntegerBranchAndBoundNode::Branch(
const symbolic::Variable& binary_variable) {
left_child_.reset(new MixedIntegerBranchAndBoundNode(
*prog_, remaining_binary_variables_, solver_id_));
right_child_.reset(new MixedIntegerBranchAndBoundNode(
*prog_, remaining_binary_variables_, solver_id_));
left_child_->FixBinaryVariable(binary_variable, 0);
right_child_->FixBinaryVariable(binary_variable, 1);
left_child_->parent_ = this;
right_child_->parent_ = this;
left_child_->solution_result_ =
SolveProgramWithSolver(*left_child_->prog_, left_child_->solver_id_,
left_child_->prog_result_.get());
right_child_->solution_result_ =
SolveProgramWithSolver(*right_child_->prog_, right_child_->solver_id_,
right_child_->prog_result_.get());
if (left_child_->solution_result_ == SolutionResult::kSolutionFound) {
left_child_->CheckOptimalSolutionIsIntegral();
}
if (right_child_->solution_result_ == SolutionResult::kSolutionFound) {
right_child_->CheckOptimalSolutionIsIntegral();
}
}
MixedIntegerBranchAndBound::MixedIntegerBranchAndBound(
const MathematicalProgram& prog, const SolverId& solver_id,
MixedIntegerBranchAndBound::Options options)
: root_{nullptr},
options_{std::move(options)},
map_old_vars_to_new_vars_{},
best_upper_bound_{std::numeric_limits<double>::infinity()},
best_lower_bound_{-std::numeric_limits<double>::infinity()},
solutions_{} {
std::tie(root_, map_old_vars_to_new_vars_) =
MixedIntegerBranchAndBoundNode::ConstructRootNode(prog, solver_id);
if (root_->solution_result() == SolutionResult::kSolutionFound) {
best_lower_bound_ = root_->prog_result()->get_optimal_cost();
// If an integral solution is found, then update the best solutions,
// together with the best upper bound.
if (root_->optimal_solution_is_integral()) {
UpdateIntegralSolution(root_->prog_result()->GetSolution(
root_->prog()->decision_variables()),
root_->prog_result()->get_optimal_cost());
}
}
}
SolutionResult MixedIntegerBranchAndBound::Solve() {
// Call back on the root node.
NodeCallback(*root_);
// First check the status of the root node. If the root node is infeasible,
// then the MIP is infeasible.
if (root_->solution_result() == SolutionResult::kInfeasibleConstraints) {
return SolutionResult::kInfeasibleConstraints;
}
if (search_integral_solution_by_rounding_) {
SearchIntegralSolutionByRounding(*root_);
}
if (HasConverged()) {
return SolutionResult::kSolutionFound;
}
// If the optimal solution to the root node is not integral, do some
// post-processing on the non-integral solution, and try to find an integral
// solution of the MIP (but not necessarily optimal).
// This is done here (rather than when the root node is solved in the
// constructor), because the strategy to search for the integral
// solution can be specified after the constructor call.
if (root_->solution_result() == SolutionResult::kSolutionFound &&
!root_->optimal_solution_is_integral()) {
SearchIntegralSolutionByRounding(*root_);
}
MixedIntegerBranchAndBoundNode* branching_node = PickBranchingNode();
while (branching_node) {
// Each branch will create two new nodes. So if the current number of nodes
// + 2 is larger than options_.max_explored_nodes, we don't branch
// any more.
if (options_.max_explored_nodes >= 1 &&
root_->NumExploredNodesInSubtree() + 2 > options_.max_explored_nodes) {
return SolutionResult::kIterationLimit;
} else {
// Found a branching node, branch on this node. If no branching node is
// found, then every leaf node is fathomed, the branch-and-bound process
// should terminate.
// TODO(hongkai.dai) We might need to have a function that picks the
// branching node together with the branching variable simultaneously.
const symbolic::Variable* branching_variable =
PickBranchingVariable(*branching_node);
BranchAndUpdate(branching_node, *branching_variable);
if (HasConverged()) {
return SolutionResult::kSolutionFound;
}
branching_node = PickBranchingNode();
}
}
// No node to branch.
if (best_lower_bound_ == -std::numeric_limits<double>::infinity()) {
return SolutionResult::kUnbounded;
}
if (best_lower_bound_ == std::numeric_limits<double>::infinity()) {
return SolutionResult::kInfeasibleConstraints;
}
throw std::runtime_error(
"Unknown result. The problem is not optimal, infeasible, nor unbounded.");
}
void MixedIntegerBranchAndBound::NodeCallback(
const MixedIntegerBranchAndBoundNode& node) {
if (node_callback_userfun_ != nullptr) {
node_callback_userfun_(node, this);
}
}
double MixedIntegerBranchAndBound::GetOptimalCost() const {
if (solutions_.empty()) {
throw std::runtime_error(
"The branch-and-bound process did not find an optimal solution.");
}
return solutions_.begin()->first;
}
double MixedIntegerBranchAndBound::GetSubOptimalCost(
int nth_suboptimal_cost) const {
if (nth_suboptimal_cost < 0 ||
nth_suboptimal_cost >= static_cast<int>(solutions().size()) - 1) {
throw std::runtime_error(
fmt::format("Cannot access {}'th sub-optimal cost. The branch-and-"
"bound process only found {} solution(s).",
nth_suboptimal_cost, solutions().size()));
}
auto it = solutions().begin();
++it;
for (int suboptimal_cost_count = 0;
suboptimal_cost_count < nth_suboptimal_cost; ++suboptimal_cost_count) {
++it;
}
return it->first;
}
double MixedIntegerBranchAndBound::GetSolution(
const symbolic::Variable& mip_var, int nth_best_solution) const {
if (nth_best_solution < 0 ||
nth_best_solution >= static_cast<int>(solutions().size())) {
throw std::runtime_error(
fmt::format("Cannot access {}'th integral solution. The "
"branch-and-bound process only found {} solution(s).",
nth_best_solution, solutions().size()));
}
const int variable_index =
root_->prog()->FindDecisionVariableIndex(GetNewVariable(mip_var));
auto it = solutions().begin();
for (int best_solution_count = 0; best_solution_count < nth_best_solution;
++best_solution_count) {
++it;
}
return it->second(variable_index);
}
const symbolic::Variable& MixedIntegerBranchAndBound::GetNewVariable(
const symbolic::Variable& old_variable) const {
const auto it = map_old_vars_to_new_vars_.find(old_variable.get_id());
if (it == map_old_vars_to_new_vars_.end()) {
std::ostringstream oss;
oss << old_variable
<< " is not a variable in the original mixed-integer problem.\n";
throw std::runtime_error(oss.str());
}
return it->second;
}
MixedIntegerBranchAndBoundNode* MixedIntegerBranchAndBound::PickBranchingNode()
const {
switch (node_selection_method_) {
case NodeSelectionMethod::kMinLowerBound: {
return PickMinLowerBoundNode();
}
case NodeSelectionMethod::kDepthFirst: {
return PickDepthFirstNode();
}
case NodeSelectionMethod::kUserDefined: {
if (node_selection_userfun_ != nullptr) {
auto node = node_selection_userfun_(*this);
if (!node->IsLeaf() || IsLeafNodeFathomed(*node)) {
throw std::runtime_error(
"The user should pick an un-fathomed leaf node for branching.");
}
return node_selection_userfun_(*this);
} else {
throw std::runtime_error(
"The user defined function should not be null, call "
"SetUserDefinedVariableSelectionFunction to provide a user defined "
"function for selecting the branching node.");
}
}
}
DRAKE_UNREACHABLE();
}
namespace {
// Pick the non-fathomed leaf node in the tree with the smallest optimal cost.
MixedIntegerBranchAndBoundNode* PickMinLowerBoundNodeInSubTree(
const MixedIntegerBranchAndBound& bnb,
const MixedIntegerBranchAndBoundNode& sub_tree_root) {
if (sub_tree_root.IsLeaf()) {
if (bnb.IsLeafNodeFathomed(sub_tree_root)) {
return nullptr;
}
return const_cast<MixedIntegerBranchAndBoundNode*>(&sub_tree_root);
} else {
MixedIntegerBranchAndBoundNode* left_min_lower_bound_node =
PickMinLowerBoundNodeInSubTree(bnb, *(sub_tree_root.left_child()));
MixedIntegerBranchAndBoundNode* right_min_lower_bound_node =
PickMinLowerBoundNodeInSubTree(bnb, *(sub_tree_root.right_child()));
if (left_min_lower_bound_node && right_min_lower_bound_node) {
return (left_min_lower_bound_node->prog_result()->get_optimal_cost() <
right_min_lower_bound_node->prog_result()->get_optimal_cost())
? left_min_lower_bound_node
: right_min_lower_bound_node;
} else if (left_min_lower_bound_node) {
return left_min_lower_bound_node;
} else if (right_min_lower_bound_node) {
return right_min_lower_bound_node;
}
return nullptr;
}
}
MixedIntegerBranchAndBoundNode* PickDepthFirstNodeInSubTree(
const MixedIntegerBranchAndBound& bnb,
const MixedIntegerBranchAndBoundNode& sub_tree_root) {
if (sub_tree_root.IsLeaf()) {
if (bnb.IsLeafNodeFathomed(sub_tree_root)) {
return nullptr;
}
return const_cast<MixedIntegerBranchAndBoundNode*>(&sub_tree_root);
} else {
MixedIntegerBranchAndBoundNode* left_deepest_node =
PickDepthFirstNodeInSubTree(bnb, *(sub_tree_root.left_child()));
MixedIntegerBranchAndBoundNode* right_deepest_node =
PickDepthFirstNodeInSubTree(bnb, *(sub_tree_root.right_child()));
if (left_deepest_node && right_deepest_node) {
return left_deepest_node->remaining_binary_variables().size() >
right_deepest_node->remaining_binary_variables().size()
? right_deepest_node
: left_deepest_node;
} else if (left_deepest_node) {
return left_deepest_node;
} else if (right_deepest_node) {
return right_deepest_node;
}
return nullptr;
}
}
double BestLowerBoundInSubTree(
const MixedIntegerBranchAndBound& bnb,
const MixedIntegerBranchAndBoundNode& sub_tree_root) {
if (sub_tree_root.IsLeaf()) {
if (bnb.IsLeafNodeFathomed(sub_tree_root)) {
switch (sub_tree_root.solution_result()) {
case SolutionResult::kSolutionFound:
return sub_tree_root.prog_result()->get_optimal_cost();
case SolutionResult::kUnbounded:
return -std::numeric_limits<double>::infinity();
case SolutionResult::kInfeasibleConstraints:
return std::numeric_limits<double>::infinity();
default:
throw std::runtime_error(
"Cannot obtain the best lower bound for this fathomed leaf "
"node.");
}
}
return sub_tree_root.prog_result()->get_optimal_cost();
} else {
const double left_best_lower_bound =
BestLowerBoundInSubTree(bnb, *(sub_tree_root.left_child()));
const double right_best_lower_bound =
BestLowerBoundInSubTree(bnb, *(sub_tree_root.right_child()));
return left_best_lower_bound < right_best_lower_bound
? left_best_lower_bound
: right_best_lower_bound;
}
}
const symbolic::Variable* PickMostOrLeastAmbivalentAsBranchingVariable(
const MixedIntegerBranchAndBoundNode& node,
MixedIntegerBranchAndBound::VariableSelectionMethod
variable_selection_method) {
DRAKE_ASSERT(variable_selection_method ==
MixedIntegerBranchAndBound::VariableSelectionMethod::
kMostAmbivalent ||
variable_selection_method ==
MixedIntegerBranchAndBound::VariableSelectionMethod::
kLeastAmbivalent);
if (node.solution_result() == SolutionResult::kSolutionFound) {
const double sign = variable_selection_method ==
MixedIntegerBranchAndBound::
VariableSelectionMethod::kMostAmbivalent
? 1
: -1;
double value = sign * std::numeric_limits<double>::infinity();
const symbolic::Variable* return_var{nullptr};
for (const auto& var : node.remaining_binary_variables()) {
const double var_value = node.prog_result()->GetSolution(var);
const double var_value_to_half = std::abs(var_value - 0.5);
if (sign * var_value_to_half < sign * value) {
value = var_value_to_half;
return_var = &var;
}
}
return return_var;
} else if (node.solution_result() == SolutionResult::kUnbounded) {
return &(node.remaining_binary_variables().front());
}
throw std::runtime_error(
"The problem is neither optimal nor unbounded. Cannot pick a branching "
"variable.");
}
} // namespace
MixedIntegerBranchAndBoundNode*
MixedIntegerBranchAndBound::PickMinLowerBoundNode() const {
return PickMinLowerBoundNodeInSubTree(*this, *root_);
}
MixedIntegerBranchAndBoundNode* MixedIntegerBranchAndBound::PickDepthFirstNode()
const {
// The deepest node has the largest number of fixed binary variables.
return PickDepthFirstNodeInSubTree(*this, *root_);
}
const symbolic::Variable* MixedIntegerBranchAndBound::PickBranchingVariable(
const MixedIntegerBranchAndBoundNode& node) const {
switch (variable_selection_method_) {
case VariableSelectionMethod::kMostAmbivalent:
case VariableSelectionMethod::kLeastAmbivalent:
return PickMostOrLeastAmbivalentAsBranchingVariable(
node, variable_selection_method_);
case VariableSelectionMethod::kUserDefined:
if (variable_selection_userfun_) {
return variable_selection_userfun_(node);
}
throw std::runtime_error(
"The user defined function cannot be null. Call "
"SetUserDefinedVariableSelectionFunction to provide the user-defined "
"function for selecting the branching variable.");
}
DRAKE_UNREACHABLE();
}
bool MixedIntegerBranchAndBound::IsLeafNodeFathomed(
const MixedIntegerBranchAndBoundNode& leaf_node) const {
if (!leaf_node.IsLeaf()) {
throw std::runtime_error("Not a leaf node.");
}
if (leaf_node.solution_result() == SolutionResult::kInfeasibleConstraints) {
return true;
}
if (leaf_node.prog_result()->get_optimal_cost() > best_upper_bound_) {
return true;
}
if (leaf_node.solution_result() == SolutionResult::kSolutionFound &&
leaf_node.optimal_solution_is_integral()) {
return true;
}
if (leaf_node.remaining_binary_variables().empty()) {
return true;
}
return false;
}
void MixedIntegerBranchAndBound::BranchAndUpdate(
MixedIntegerBranchAndBoundNode* node,
const symbolic::Variable& branching_variable) {
node->Branch(branching_variable);
// Update the best lower and upper bounds.
// The best lower bound is the minimal among all the optimal costs of the
// non-fathomed leaf nodes.
best_lower_bound_ = BestLowerBoundInSubTree(*this, *root_);
// If either the left or the right children finds integral solution, then
// we can potentially update the best upper bound, and insert the solutions
// to the list solutions_;
for (auto& child : {node->left_child(), node->right_child()}) {
if (child->solution_result() == SolutionResult::kSolutionFound &&
child->optimal_solution_is_integral()) {
const double child_node_optimal_cost =
child->prog_result()->get_optimal_cost();
const Eigen::VectorXd x_sol = child->prog_result()->GetSolution(
child->prog()->decision_variables());
UpdateIntegralSolution(x_sol, child_node_optimal_cost);
}
if (search_integral_solution_by_rounding_) {
SearchIntegralSolutionByRounding(*child);
}
NodeCallback(*child);
}
}
void MixedIntegerBranchAndBound::UpdateIntegralSolution(
const Eigen::Ref<const Eigen::VectorXd>& solution, double cost) {
// First make sure that this solution has not been found before. The solution
// could be found already when we search the integral solution in each node
// by rounding the un-fixed binary variables, or by some user callback
// procedure.
bool found_match = false;
const double tol{1E-6};
for (const auto& cost_solution : solutions_) {
// The same solution should have the same cost, up to some numerical
// tolerance.
found_match = std::abs(cost_solution.first - cost) < tol &&
(cost_solution.second - solution).cwiseAbs().maxCoeff() < tol;
if (found_match) {
break;
}
}
if (!found_match) {
solutions_.emplace(cost, solution);
if (static_cast<int>(solutions_.size()) > max_num_solutions_) {
auto it = solutions_.end();
--it;
solutions_.erase(it);
}
best_upper_bound_ = std::min(best_upper_bound_, solutions_.begin()->first);
}
}
bool MixedIntegerBranchAndBound::HasConverged() const {
if (best_upper_bound_ - best_lower_bound_ <= absolute_gap_tol_) {
return true;
}
if ((best_upper_bound_ - best_lower_bound_) / std::abs(best_lower_bound_) <=
relative_gap_tol_) {
return true;
}
return false;
}
void MixedIntegerBranchAndBound::SearchIntegralSolutionByRounding(
const MixedIntegerBranchAndBoundNode& node) {
// Only searches integral solution by rounding, if the optimization program
// in this node has an optimal solution, and that solution is non-integral.
if (node.solution_result() == SolutionResult::kSolutionFound &&
!node.optimal_solution_is_integral()) {
// Create a new program that fix the remaining binary variables to either 0
// or 1, and solve for the continuous variables. If this optimization
// problem is feasible, then the optimal solution is a feasible
// solution to the MIP, and we get an upper bound on the MIP optimal cost.
auto new_prog = node.prog()->Clone();
// Go through each remaining binary variables, and constrain them to either
// 0 or 1 by rounding the solution to the integer.
for (const auto& remaining_binary_variable :
node.remaining_binary_variables()) {
// Notice that roundoff_integer_val is of type double here. This is
// because AddBoundingBoxConstraint(...) requires bounds of type double.
const double roundoff_integer_val = std::round(
node.prog_result()->GetSolution(remaining_binary_variable));
new_prog->AddBoundingBoxConstraint(roundoff_integer_val,
roundoff_integer_val,
remaining_binary_variable);
}
MathematicalProgramResult result;
SolveProgramWithSolver(*new_prog, node.solver_id(), &result);
if (result.is_success()) {
// Found integral solution.
UpdateIntegralSolution(result.GetSolution(new_prog->decision_variables()),
result.get_optimal_cost());
}
}
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/no_ipopt.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/ipopt_solver.h"
/* clang-format on */
#include <stdexcept>
namespace drake {
namespace solvers {
const char* IpoptSolverDetails::ConvertStatusToString() const {
throw std::runtime_error(
"The IPOPT bindings were not compiled. You'll need to use a different "
"solver.");
}
bool IpoptSolver::is_available() {
return false;
}
void IpoptSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&,
const SolverOptions&,
MathematicalProgramResult*) const {
throw std::runtime_error(
"The IPOPT bindings were not compiled. You'll need to use a different "
"solver.");
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/indeterminate.h | #pragma once
#include <list>
#include <Eigen/Core>
#include "drake/common/symbolic/expression.h"
namespace drake {
namespace solvers {
/** MatrixIndeterminate<int, int> is used as an alias for
* Eigen::Matrix<symbolic::Variable, int, int>. After resolving aliases, a
* compiler does not distinguish between these two. All indeterminates are a
* variable of type symbolic::Variable::Type::CONTINUOUS (by default).
* @tparam rows The number of rows in the new matrix containing indeterminates.
* @tparam cols The number of columns in the new matrix containing
* indeterminates.
*/
template <int rows, int cols>
using MatrixIndeterminate = Eigen::Matrix<symbolic::Variable, rows, cols>;
/** VectorIndeterminate<int> is used as an alias for
* Eigen::Matrix<symbolic::Variable, int, 1>.
* @tparam rows The number of rows in the new matrix containing indeterminates.
* @see MatrixIndeterminate<int, int>
*/
template <int rows>
using VectorIndeterminate = MatrixIndeterminate<rows, 1>;
/** MatrixXIndeterminate is used as an alias for
* Eigen::Matrix<symbolic::Variable, Eigen::Dynamic, Eigen::Dynamic>.
* @see MatrixIndeterminate<int, int>
*/
using MatrixXIndeterminate =
MatrixIndeterminate<Eigen::Dynamic, Eigen::Dynamic>;
/** VectorXIndeterminate is used as an alias for
* Eigen::Matrix<symbolic::Variable, Eigen::Dynamic, 1>.
* @see MatrixIndeterminate<int, int>
*/
using VectorXIndeterminate = VectorIndeterminate<Eigen::Dynamic>;
using IndeterminatesRefList = std::list<Eigen::Ref<const VectorXIndeterminate>>;
/**
* Concatenates each element in \p var_list into a single Eigen vector of
* indeterminates, returns this concatenated vector.
*/
[[nodiscard]] VectorXIndeterminate ConcatenateIndeterminatesRefList(
const IndeterminatesRefList& var_list);
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solver_options.cc | #include "drake/solvers/solver_options.h"
#include <map>
#include <sstream>
#include <utility>
#include <fmt/format.h>
#include "drake/common/never_destroyed.h"
namespace drake {
namespace solvers {
// A shorthand for our member field type, for options typed as T's, as in
// MapMap[SolverId][string] => T.
template <typename T>
using MapMap = std::unordered_map<SolverId, std::unordered_map<std::string, T>>;
// A shorthand for our member field type.
using CommonMap =
std::unordered_map<CommonSolverOption, SolverOptions::OptionValue>;
void SolverOptions::SetOption(const SolverId& solver_id,
const std::string& solver_option,
double option_value) {
solver_options_double_[solver_id][solver_option] = option_value;
}
void SolverOptions::SetOption(const SolverId& solver_id,
const std::string& solver_option,
int option_value) {
solver_options_int_[solver_id][solver_option] = option_value;
}
void SolverOptions::SetOption(const SolverId& solver_id,
const std::string& solver_option,
const std::string& option_value) {
solver_options_str_[solver_id][solver_option] = option_value;
}
void SolverOptions::SetOption(CommonSolverOption key, OptionValue value) {
switch (key) {
case CommonSolverOption::kPrintToConsole: {
if (!std::holds_alternative<int>(value)) {
throw std::runtime_error(fmt::format(
"SolverOptions::SetOption support {} only with int value.", key));
}
const int int_value = std::get<int>(value);
if (int_value != 0 && int_value != 1) {
throw std::runtime_error(
fmt::format("{} expects value either 0 or 1", key));
}
common_solver_options_[key] = std::move(value);
return;
}
case CommonSolverOption::kPrintFileName: {
if (!std::holds_alternative<std::string>(value)) {
throw std::runtime_error(fmt::format(
"SolverOptions::SetOption support {} only with std::string value.",
key));
}
common_solver_options_[key] = std::move(value);
return;
}
}
DRAKE_UNREACHABLE();
}
namespace {
// If options has an entry for the given solver_id, returns a reference to the
// mapped value. Otherwise, returns a long-lived reference to an empty value.
template <typename T>
const std::unordered_map<std::string, T>& GetOptionsHelper(
const SolverId& solver_id, const MapMap<T>& options) {
static never_destroyed<std::unordered_map<std::string, T>> empty;
const auto iter = options.find(solver_id);
return (iter != options.end()) ? iter->second : empty.access();
}
} // namespace
const std::unordered_map<std::string, double>& SolverOptions::GetOptionsDouble(
const SolverId& solver_id) const {
return GetOptionsHelper(solver_id, solver_options_double_);
}
const std::unordered_map<std::string, int>& SolverOptions::GetOptionsInt(
const SolverId& solver_id) const {
return GetOptionsHelper(solver_id, solver_options_int_);
}
const std::unordered_map<std::string, std::string>&
SolverOptions::GetOptionsStr(const SolverId& solver_id) const {
return GetOptionsHelper(solver_id, solver_options_str_);
}
std::string SolverOptions::get_print_file_name() const {
// N.B. SetOption sanity checks the value; we don't need to re-check here.
std::string result;
auto iter = common_solver_options_.find(CommonSolverOption::kPrintFileName);
if (iter != common_solver_options_.end()) {
result = std::get<std::string>(iter->second);
}
return result;
}
bool SolverOptions::get_print_to_console() const {
// N.B. SetOption sanity checks the value; we don't need to re-check here.
bool result = false;
auto iter = common_solver_options_.find(CommonSolverOption::kPrintToConsole);
if (iter != common_solver_options_.end()) {
const int value = std::get<int>(iter->second);
result = static_cast<bool>(value);
}
return result;
}
std::unordered_set<SolverId> SolverOptions::GetSolverIds() const {
std::unordered_set<SolverId> result;
for (const auto& pair : solver_options_double_) {
result.insert(pair.first);
}
for (const auto& pair : solver_options_int_) {
result.insert(pair.first);
}
for (const auto& pair : solver_options_str_) {
result.insert(pair.first);
}
return result;
}
namespace {
template <typename T>
void MergeHelper(const MapMap<T>& other, MapMap<T>* self) {
for (const auto& other_id_keyvals : other) {
const SolverId& id = other_id_keyvals.first;
std::unordered_map<std::string, T>& self_keyvals = (*self)[id];
for (const auto& other_keyval : other_id_keyvals.second) {
// This is a no-op when the key already exists.
self_keyvals.insert(other_keyval);
}
}
}
void MergeHelper(const CommonMap& other, CommonMap* self) {
for (const auto& other_keyval : other) {
// This is a no-op when the key already exists.
self->insert(other_keyval);
}
}
} // namespace
void SolverOptions::Merge(const SolverOptions& other) {
MergeHelper(other.solver_options_double_, &solver_options_double_);
MergeHelper(other.solver_options_int_, &solver_options_int_);
MergeHelper(other.solver_options_str_, &solver_options_str_);
MergeHelper(other.common_solver_options_, &common_solver_options_);
}
bool SolverOptions::operator==(const SolverOptions& other) const {
return solver_options_double_ == other.solver_options_double_ &&
solver_options_int_ == other.solver_options_int_ &&
solver_options_str_ == other.solver_options_str_ &&
common_solver_options_ == other.common_solver_options_;
}
bool SolverOptions::operator!=(const SolverOptions& other) const {
return !(*this == other);
}
namespace {
template <typename T>
void Summarize(const SolverId& id,
const std::unordered_map<std::string, T>& keyvals,
std::map<std::string, std::string>* pairs) {
for (const auto& keyval : keyvals) {
(*pairs)[fmt::format("{}:{}", id.name(), keyval.first)] =
fmt::format("{}", keyval.second);
}
}
} // namespace
std::ostream& operator<<(std::ostream& os, const SolverOptions& x) {
os << "{SolverOptions";
const auto& ids = x.GetSolverIds();
if (ids.empty()) {
os << " empty";
} else {
// Map keyed on "solver_name:option_key" so our output is deterministic.
std::map<std::string, std::string> pairs;
for (const auto& id : ids) {
Summarize(id, x.GetOptionsDouble(id), &pairs);
Summarize(id, x.GetOptionsInt(id), &pairs);
Summarize(id, x.GetOptionsStr(id), &pairs);
}
for (const auto& keyval : x.common_solver_options()) {
const CommonSolverOption& key = keyval.first;
const auto& val = keyval.second;
std::visit(
[key, &pairs](auto& val_x) {
pairs[fmt::format("CommonSolverOption::{}", key)] =
fmt::format("{}", val_x);
},
val);
}
for (const auto& pair : pairs) {
os << ", " << pair.first << "=" << pair.second;
}
}
os << "}";
return os;
}
std::string to_string(const SolverOptions& x) {
std::ostringstream result;
result << x;
return result.str();
}
namespace {
// Check if all the keys in key_value pair key_vals is a subset of
// allowable_keys, and throw an invalid argument if not.
template <typename T>
void CheckOptionKeysForSolverHelper(
const std::unordered_map<std::string, T>& key_vals,
const std::unordered_set<std::string>& allowable_keys,
const std::string& solver_name) {
for (const auto& key_val : key_vals) {
if (!allowable_keys.contains(key_val.first)) {
throw std::invalid_argument(key_val.first +
" is not allowed in the SolverOptions for " +
solver_name + ".");
}
}
}
} // namespace
void SolverOptions::CheckOptionKeysForSolver(
const SolverId& solver_id,
const std::unordered_set<std::string>& double_keys,
const std::unordered_set<std::string>& int_keys,
const std::unordered_set<std::string>& str_keys) const {
CheckOptionKeysForSolverHelper(GetOptionsDouble(solver_id), double_keys,
solver_id.name());
CheckOptionKeysForSolverHelper(GetOptionsInt(solver_id), int_keys,
solver_id.name());
CheckOptionKeysForSolverHelper(GetOptionsStr(solver_id), str_keys,
solver_id.name());
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/constraint.cc | #include "drake/solvers/constraint.h"
#include <cmath>
#include <limits>
#include <set>
#include <stdexcept>
#include <unordered_map>
#include <fmt/format.h>
#include "drake/common/symbolic/decompose.h"
#include "drake/common/symbolic/latex.h"
#include "drake/common/text_logging.h"
#include "drake/math/autodiff_gradient.h"
#include "drake/math/matrix_util.h"
using std::abs;
namespace drake {
namespace solvers {
using symbolic::ToLatex;
const double kInf = std::numeric_limits<double>::infinity();
namespace {
// Returns `True` if lb is -∞. Otherwise returns a symbolic formula `lb <= e`.
symbolic::Formula MakeLowerBound(const double lb,
const symbolic::Expression& e) {
if (lb == -std::numeric_limits<double>::infinity()) {
return symbolic::Formula::True();
} else {
return lb <= e;
}
}
// Returns `True` if ub is ∞. Otherwise returns a symbolic formula `e <= ub`.
symbolic::Formula MakeUpperBound(const symbolic::Expression& e,
const double ub) {
if (ub == std::numeric_limits<double>::infinity()) {
return symbolic::Formula::True();
} else {
return e <= ub;
}
}
std::ostream& DisplayConstraint(const Constraint& constraint, std::ostream& os,
const std::string& name,
const VectorX<symbolic::Variable>& vars,
bool equality) {
os << name;
VectorX<symbolic::Expression> e(constraint.num_constraints());
constraint.Eval(vars, &e);
// Append the description (when provided).
const std::string& description = constraint.get_description();
if (!description.empty()) {
os << " described as '" << description << "'";
}
os << "\n";
for (int i = 0; i < constraint.num_constraints(); ++i) {
if (equality) {
os << e(i) << " == " << constraint.upper_bound()(i) << "\n";
} else {
os << constraint.lower_bound()(i) << " <= " << e(i)
<< " <= " << constraint.upper_bound()(i) << "\n";
}
}
return os;
}
std::string ToLatexLowerBound(const Constraint& constraint, int precision) {
const auto& lb = constraint.lower_bound();
if (lb.array().isInf().all()) {
return "";
}
if (lb == constraint.upper_bound()) {
// We'll write this as == instead of <=.
return "";
}
if (lb.size() == 1) {
return ToLatex(lb[0], precision) + " \\le ";
}
return ToLatex(lb) + " \\le ";
}
std::string ToLatexUpperBound(const Constraint& constraint, int precision) {
const auto& ub = constraint.upper_bound();
if (ub.array().isInf().all()) {
return "";
}
std::string comparator = (ub == constraint.lower_bound()) ? " = " : " \\le ";
if (ub.size() == 1) {
return comparator + ToLatex(ub[0], precision);
}
return comparator + ToLatex(ub);
}
std::string ToLatexConstraint(const Constraint& constraint,
const VectorX<symbolic::Variable>& vars,
int precision) {
VectorX<symbolic::Expression> y(constraint.num_constraints());
constraint.Eval(vars, &y);
return fmt::format("{}{}{}", ToLatexLowerBound(constraint, precision),
constraint.num_constraints() == 1
? symbolic::ToLatex(y[0], precision)
: symbolic::ToLatex(y, precision),
ToLatexUpperBound(constraint, precision));
}
} // namespace
void Constraint::check(int num_constraints) const {
if (lower_bound_.size() != num_constraints ||
upper_bound_.size() != num_constraints) {
throw std::invalid_argument(
fmt::format("Constraint {} expects lower and upper bounds of size {}, "
"got lower bound of size {} and upper bound of size {}.",
this->get_description(), num_constraints,
lower_bound_.size(), upper_bound_.size()));
}
}
symbolic::Formula Constraint::DoCheckSatisfied(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x) const {
VectorX<symbolic::Expression> y(num_constraints());
DoEval(x, &y);
symbolic::Formula f{symbolic::Formula::True()};
for (int i = 0; i < num_constraints(); ++i) {
if (lower_bound_[i] == upper_bound_[i]) {
// Add 'lbᵢ = yᵢ' to f.
f = f && lower_bound_[i] == y[i];
} else {
// Add 'lbᵢ ≤ yᵢ ≤ ubᵢ' to f.
f = f && MakeLowerBound(lower_bound_[i], y[i]) &&
MakeUpperBound(y[i], upper_bound_[i]);
}
}
return f;
}
bool QuadraticConstraint::is_convex() const {
switch (hessian_type_) {
case HessianType::kPositiveSemidefinite: {
// lower_bound is -inf
return std::isinf(lower_bound()(0)) && lower_bound()(0) < 0;
}
case HessianType::kNegativeSemidefinite: {
// upper bound is inf
return std::isinf(upper_bound()(0)) && upper_bound()(0) > 0;
}
case HessianType::kIndefinite: {
return false;
}
}
DRAKE_UNREACHABLE();
}
void QuadraticConstraint::UpdateHessianType(
std::optional<HessianType> hessian_type) {
if (hessian_type.has_value()) {
hessian_type_ = hessian_type.value();
return;
}
Eigen::LDLT<Eigen::MatrixXd> ldlt_solver;
ldlt_solver.compute(Q_);
if (ldlt_solver.info() != Eigen::Success) {
// Fall back to an indefinite Hessian type if we cannot determine the
// Hessian type.
drake::log()->warn(
"UpdateHessianType(): Unable to determine Hessian type of the "
"Quadratic Constraint. Falling "
"back to indefinite Hessian type.");
hessian_type_ = HessianType::kIndefinite;
} else {
if (ldlt_solver.isPositive()) {
hessian_type_ = HessianType::kPositiveSemidefinite;
} else if (ldlt_solver.isNegative()) {
hessian_type_ = HessianType::kNegativeSemidefinite;
} else {
hessian_type_ = HessianType::kIndefinite;
}
}
}
template <typename DerivedX, typename ScalarY>
void QuadraticConstraint::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<ScalarY>* y) const {
y->resize(num_constraints());
*y = .5 * x.transpose() * Q_ * x + b_.transpose() * x;
}
void QuadraticConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void QuadraticConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void QuadraticConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& QuadraticConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "QuadraticConstraint", vars, false);
}
std::string QuadraticConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
// TODO(russt): Handle Q_ = c*I as a special case.
std::string b_term;
if (!b_.isZero()) {
b_term = " + " + symbolic::ToLatex(b_.dot(vars), precision);
}
return fmt::format(
"{}{}^T {} {}{}{}", ToLatexLowerBound(*this, precision),
symbolic::ToLatex(vars), symbolic::ToLatex((0.5 * Q_).eval(), precision),
symbolic::ToLatex(vars), b_term, ToLatexUpperBound(*this, precision));
}
namespace {
int get_lorentz_cone_constraint_size(
LorentzConeConstraint::EvalType eval_type) {
return eval_type == LorentzConeConstraint::EvalType::kNonconvex ? 2 : 1;
}
} // namespace
LorentzConeConstraint::LorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b, EvalType eval_type)
: Constraint(
get_lorentz_cone_constraint_size(eval_type), A.cols(),
Eigen::VectorXd::Zero(get_lorentz_cone_constraint_size(eval_type)),
Eigen::VectorXd::Constant(get_lorentz_cone_constraint_size(eval_type),
kInf)),
A_(A.sparseView()),
A_dense_(A),
b_(b),
eval_type_{eval_type} {
DRAKE_DEMAND(A_.rows() >= 2);
DRAKE_ASSERT(A_.rows() == b_.rows());
}
void LorentzConeConstraint::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != num_vars()) {
throw std::invalid_argument(
fmt::format("LorentzConeConstraint::UpdateCoefficients uses new_A with "
"{} columns to update a constraint with {} variables.",
new_A.cols(), num_vars()));
}
A_ = new_A.sparseView();
A_dense_ = new_A;
b_ = new_b;
DRAKE_DEMAND(A_.rows() >= 2);
DRAKE_DEMAND(A_.rows() == b_.rows());
// Note that we don't need to update the lower and upper bounds as the
// constraints lower/upper bounds are fixed (independent of A and b). The
// bounds only depend on EvalType. When EvalType=kNonconvex, the lower/upper
// bound is [0, 0]/[inf, inf] respectively; otherwise, the lower/upper bound
// is 0/inf respectively.
}
namespace {
template <typename DerivedX>
void LorentzConeConstraintEvalConvex2Autodiff(
const Eigen::MatrixXd& A_dense, const Eigen::VectorXd& b,
const Eigen::MatrixBase<DerivedX>& x, VectorX<AutoDiffXd>* y) {
const Eigen::VectorXd x_val = math::ExtractValue(x);
const Eigen::VectorXd z_val = A_dense * x_val + b;
const double z_tail_squared_norm = z_val.tail(z_val.rows() - 1).squaredNorm();
Vector1d y_val(z_val(0) - std::sqrt(z_tail_squared_norm));
Eigen::RowVectorXd dy_dz(z_val.rows());
dy_dz(0) = 1;
// We use a small value epsilon to approximate the gradient of sqrt(z) as
// ∂sqrt(zᵀz) / ∂z ≈ z(i) / sqrt(zᵀz + eps)
const double eps = 1E-12;
dy_dz.tail(z_val.rows() - 1) =
-z_val.tail(z_val.rows() - 1) / std::sqrt(z_tail_squared_norm + eps);
Eigen::RowVectorXd dy = dy_dz * A_dense * math::ExtractGradient(x);
(*y) = math::InitializeAutoDiff(y_val, dy);
}
} // namespace
template <typename DerivedX, typename ScalarY>
void LorentzConeConstraint::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<ScalarY>* y) const {
using std::pow;
const VectorX<ScalarY> z = A_dense_ * x.template cast<ScalarY>() + b_;
y->resize(num_constraints());
switch (eval_type_) {
case EvalType::kConvex: {
(*y)(0) = z(0) - z.tail(z.rows() - 1).norm();
break;
}
case EvalType::kConvexSmooth: {
if constexpr (std::is_same_v<ScalarY, AutoDiffXd>) {
LorentzConeConstraintEvalConvex2Autodiff(A_dense_, b_, x, y);
} else {
(*y)(0) = z(0) - z.tail(z.rows() - 1).norm();
}
break;
}
case EvalType::kNonconvex: {
(*y)(0) = z(0);
(*y)(1) = pow(z(0), 2) - z.tail(z.size() - 1).squaredNorm();
break;
}
}
}
void LorentzConeConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void LorentzConeConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void LorentzConeConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& LorentzConeConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "LorentzConeConstraint", vars, false);
}
std::string LorentzConeConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
VectorX<symbolic::Expression> z = A_ * vars + b_;
return fmt::format("\\left|{}\\right|_2 \\le {}",
symbolic::ToLatex(z.tail(z.size() - 1).eval(), precision),
symbolic::ToLatex(z(0), precision));
}
void RotatedLorentzConeConstraint::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != num_vars()) {
throw std::invalid_argument(fmt::format(
"RotatedLorentzConeConstraint::UpdateCoefficients uses new_A with "
"{} columns to update a constraint with {} variables.",
new_A.cols(), num_vars()));
}
A_ = new_A.sparseView();
A_dense_ = new_A;
b_ = new_b;
DRAKE_DEMAND(A_.rows() >= 3);
DRAKE_DEMAND(A_.rows() == b_.rows());
// Note that we don't need to update the lower and upper bounds as the
// constraints lower/upper bounds are fixed (independent of A and b).
}
template <typename DerivedX, typename ScalarY>
void RotatedLorentzConeConstraint::DoEvalGeneric(
const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const {
const VectorX<ScalarY> z = A_dense_ * x.template cast<ScalarY>() + b_;
y->resize(num_constraints());
(*y)(0) = z(0);
(*y)(1) = z(1);
(*y)(2) = z(0) * z(1) - z.tail(z.size() - 2).squaredNorm();
}
void RotatedLorentzConeConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void RotatedLorentzConeConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void RotatedLorentzConeConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& RotatedLorentzConeConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "RotatedLorentzConeConstraint", vars,
false);
}
std::string RotatedLorentzConeConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
VectorX<symbolic::Expression> z = A_ * vars + b_;
return fmt::format(
"0 \\le {},\\\\ 0 \\le {},\\\\ \\left|{}\\right|_2^2 \\le {}",
symbolic::ToLatex(z(0), precision), symbolic::ToLatex(z(1), precision),
symbolic::ToLatex(z.tail(z.size() - 2).eval(), precision),
symbolic::ToLatex(z(0) * z(1), precision));
}
LinearConstraint::LinearConstraint(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub)
: Constraint(A.rows(), A.cols(), lb, ub), A_(A) {
DRAKE_THROW_UNLESS(A.rows() == lb.rows());
DRAKE_THROW_UNLESS(A.array().allFinite());
}
LinearConstraint::LinearConstraint(const Eigen::SparseMatrix<double>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub)
: Constraint(A.rows(), A.cols(), lb, ub), A_(A) {
DRAKE_THROW_UNLESS(A.rows() == lb.rows());
DRAKE_THROW_UNLESS(A_.IsFinite());
}
const Eigen::MatrixXd& LinearConstraint::GetDenseA() const {
return A_.GetAsDense();
}
void LinearConstraint::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_lb,
const Eigen::Ref<const Eigen::VectorXd>& new_ub) {
if (new_A.rows() != new_lb.rows() || new_lb.rows() != new_ub.rows()) {
throw std::runtime_error("New constraints have invalid dimensions");
}
if (new_A.cols() != A_.get_as_sparse().cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
A_ = new_A;
DRAKE_THROW_UNLESS(A_.IsFinite());
set_num_outputs(A_.get_as_sparse().rows());
set_bounds(new_lb, new_ub);
}
void LinearConstraint::UpdateCoefficients(
const Eigen::SparseMatrix<double>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_lb,
const Eigen::Ref<const Eigen::VectorXd>& new_ub) {
if (new_A.rows() != new_lb.rows() || new_lb.rows() != new_ub.rows()) {
throw std::runtime_error("New constraints have invalid dimensions");
}
if (new_A.cols() != A_.get_as_sparse().cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
A_ = new_A;
DRAKE_THROW_UNLESS(A_.IsFinite());
set_num_outputs(A_.get_as_sparse().rows());
set_bounds(new_lb, new_ub);
}
void LinearConstraint::RemoveTinyCoefficient(double tol) {
if (tol < 0) {
throw std::invalid_argument(
"RemoveTinyCoefficient: tol should be non-negative");
}
std::vector<Eigen::Triplet<double>> new_A_triplets;
const auto& A_sparse = A_.get_as_sparse();
new_A_triplets.reserve(A_sparse.nonZeros());
for (int i = 0; i < A_sparse.outerSize(); ++i) {
for (Eigen::SparseMatrix<double>::InnerIterator it(A_sparse, i); it; ++it) {
if (std::abs(it.value()) > tol) {
new_A_triplets.emplace_back(it.row(), it.col(), it.value());
}
}
}
Eigen::SparseMatrix<double> new_A(A_sparse.rows(), A_sparse.cols());
new_A.setFromTriplets(new_A_triplets.begin(), new_A_triplets.end());
UpdateCoefficients(new_A, lower_bound(), upper_bound());
}
bool LinearConstraint::is_dense_A_constructed() const {
return A_.is_dense_constructed();
}
template <typename DerivedX, typename ScalarY>
void LinearConstraint::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<ScalarY>* y) const {
y->resize(num_constraints());
(*y) = A_.get_as_sparse() * x.template cast<ScalarY>();
}
void LinearConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void LinearConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void LinearConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& LinearConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "LinearConstraint", vars, false);
}
std::string LinearConstraint::DoToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const {
if (num_constraints() == 1) {
return fmt::format(
"{}{}{}", ToLatexLowerBound(*this, precision),
symbolic::ToLatex((A_.get_as_sparse() * vars)[0], precision),
ToLatexUpperBound(*this, precision));
}
return fmt::format("{}{} {}{}", ToLatexLowerBound(*this, precision),
symbolic::ToLatex(GetDenseA(), precision),
symbolic::ToLatex(vars),
ToLatexUpperBound(*this, precision));
}
std::ostream& LinearEqualityConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "LinearEqualityConstraint", vars, true);
}
namespace internal {
Eigen::SparseMatrix<double> ConstructSparseIdentity(int rows) {
Eigen::SparseMatrix<double> mat(rows, rows);
mat.setIdentity();
return mat;
}
} // namespace internal
BoundingBoxConstraint::BoundingBoxConstraint(
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub)
: LinearConstraint(internal::ConstructSparseIdentity(lb.rows()), lb, ub) {}
template <typename DerivedX, typename ScalarY>
void BoundingBoxConstraint::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<ScalarY>* y) const {
y->resize(num_constraints());
(*y) = x.template cast<ScalarY>();
}
void BoundingBoxConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void BoundingBoxConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void BoundingBoxConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& BoundingBoxConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "BoundingBoxConstraint", vars, false);
}
std::string BoundingBoxConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
return fmt::format("{}{}{}", ToLatexLowerBound(*this, precision),
num_constraints() == 1 ? symbolic::ToLatex(vars[0])
: symbolic::ToLatex(vars),
ToLatexUpperBound(*this, precision));
}
template <typename DerivedX, typename ScalarY>
void LinearComplementarityConstraint::DoEvalGeneric(
const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const {
y->resize(num_constraints());
(*y) = (M_ * x.template cast<ScalarY>()) + q_;
}
void LinearComplementarityConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void LinearComplementarityConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void LinearComplementarityConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
bool LinearComplementarityConstraint::DoCheckSatisfied(
const Eigen::Ref<const Eigen::VectorXd>& x, const double tol) const {
// Check: x >= 0 && Mx + q >= 0 && x'(Mx + q) == 0
Eigen::VectorXd y(num_constraints());
DoEval(x, &y);
return (x.array() > -tol).all() && (y.array() > -tol).all() &&
(abs(x.dot(y)) < tol);
}
bool LinearComplementarityConstraint::DoCheckSatisfied(
const Eigen::Ref<const AutoDiffVecXd>& x, const double tol) const {
AutoDiffVecXd y(num_constraints());
DoEval(x, &y);
return (x.array() > -tol).all() && (y.array() > -tol).all() &&
(abs(x.dot(y)) < tol);
}
symbolic::Formula LinearComplementarityConstraint::DoCheckSatisfied(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x) const {
VectorX<symbolic::Expression> y(num_constraints());
DoEval(x, &y);
symbolic::Formula f{symbolic::Formula::True()};
// 1. Mx + q >= 0
for (VectorX<symbolic::Expression>::Index i = 0; i < y.size(); ++i) {
f = f && (y(i) >= 0);
}
// 2. x >= 0
for (VectorX<symbolic::Expression>::Index i = 0; i < x.size(); ++i) {
f = f && (x(i) >= 0);
}
// 3. x'(Mx + q) == 0
f = f && (x.dot(y) == 0);
return f;
}
std::string LinearComplementarityConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
return fmt::format("0 \\le {} \\perp {} \\ge 0",
symbolic::ToLatex(vars, precision),
symbolic::ToLatex((M_ * vars + q_).eval(), precision));
}
void PositiveSemidefiniteConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DRAKE_ASSERT(x.rows() == num_constraints() * num_constraints());
Eigen::MatrixXd S(num_constraints(), num_constraints());
for (int i = 0; i < num_constraints(); ++i) {
S.col(i) = x.segment(i * num_constraints(), num_constraints());
}
DRAKE_ASSERT(S.rows() == num_constraints());
// This uses the lower diagonal part of S to compute the eigen values.
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen_solver(S);
*y = eigen_solver.eigenvalues();
}
void PositiveSemidefiniteConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>&, AutoDiffVecXd*) const {
throw std::logic_error(
"The Eval function for positive semidefinite constraint is not defined, "
"since the eigen solver does not work for AutoDiffXd.");
}
void PositiveSemidefiniteConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const {
throw std::logic_error(
"The Eval function for positive semidefinite constraint is not defined, "
"since the eigen solver does not work for symbolic::Expression.");
}
std::string PositiveSemidefiniteConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
Eigen::Map<const MatrixX<symbolic::Variable>> S(vars.data(), matrix_rows(),
matrix_rows());
return fmt::format("{} \\succeq 0", symbolic::ToLatex(S.eval(), precision));
}
void LinearMatrixInequalityConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DRAKE_ASSERT(x.rows() == static_cast<int>(F_.size()) - 1);
Eigen::MatrixXd S = F_[0];
for (int i = 1; i < static_cast<int>(F_.size()); ++i) {
S += x(i - 1) * F_[i];
}
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen_solver(S);
*y = eigen_solver.eigenvalues();
}
void LinearMatrixInequalityConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>&, AutoDiffVecXd*) const {
throw std::logic_error(
"The Eval function for positive semidefinite constraint is not defined, "
"since the eigen solver does not work for AutoDiffXd.");
}
void LinearMatrixInequalityConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const {
throw std::logic_error(
"The Eval function for positive semidefinite constraint is not defined, "
"since the eigen solver does not work for symbolic::Expression.");
}
LinearMatrixInequalityConstraint::LinearMatrixInequalityConstraint(
std::vector<Eigen::MatrixXd> F, double symmetry_tolerance)
: Constraint(F.empty() ? 0 : F.front().rows(),
F.empty() ? 0 : F.size() - 1),
F_{std::move(F)},
matrix_rows_(F_.empty() ? 0 : F_.front().rows()) {
DRAKE_DEMAND(!F_.empty());
set_bounds(Eigen::VectorXd::Zero(matrix_rows_),
Eigen::VectorXd::Constant(
matrix_rows_, std::numeric_limits<double>::infinity()));
for (const auto& Fi : F_) {
DRAKE_ASSERT(Fi.rows() == matrix_rows_);
DRAKE_ASSERT(math::IsSymmetric(Fi, symmetry_tolerance));
}
}
std::string LinearMatrixInequalityConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
MatrixX<symbolic::Expression> S = F_[0];
for (int i = 1; i < static_cast<int>(F_.size()); ++i) {
S += vars(i - 1) * F_[i];
}
return fmt::format("{} \\succeq 0", symbolic::ToLatex(S, precision));
}
ExpressionConstraint::ExpressionConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub)
: Constraint(v.rows(), GetDistinctVariables(v).size(), lb, ub),
expressions_(v) {
// Setup map_var_to_index_ and vars_ so that
// map_var_to_index_[vars_(i).get_id()] = i.
std::tie(vars_, map_var_to_index_) =
symbolic::ExtractVariablesFromExpression(expressions_);
derivatives_ = symbolic::Jacobian(expressions_, vars_);
// Setup the environment.
for (int i = 0; i < vars_.size(); i++) {
environment_.insert(vars_[i], 0.0);
}
}
void ExpressionConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DRAKE_DEMAND(x.rows() == vars_.rows());
// Set environment with current x values.
for (int i = 0; i < vars_.size(); i++) {
environment_[vars_[i]] = x(map_var_to_index_.at(vars_[i].get_id()));
}
// Evaluate into the output, y.
y->resize(num_constraints());
for (int i = 0; i < num_constraints(); i++) {
(*y)[i] = expressions_[i].Evaluate(environment_);
}
}
void ExpressionConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DRAKE_DEMAND(x.rows() == vars_.rows());
// Set environment with current x values.
for (int i = 0; i < vars_.size(); i++) {
environment_[vars_[i]] = x(map_var_to_index_.at(vars_[i].get_id())).value();
}
// Evaluate value and derivatives into the output, y.
// Using ∂yᵢ/∂zⱼ = ∑ₖ ∂fᵢ/∂xₖ ∂xₖ/∂zⱼ.
y->resize(num_constraints());
Eigen::VectorXd dyidx(x.size());
for (int i = 0; i < num_constraints(); i++) {
(*y)[i].value() = expressions_[i].Evaluate(environment_);
for (int k = 0; k < x.size(); k++) {
dyidx[k] = derivatives_(i, k).Evaluate(environment_);
}
(*y)[i].derivatives().resize(x(0).derivatives().size());
for (int j = 0; j < x(0).derivatives().size(); j++) {
(*y)[i].derivatives()[j] = 0.0;
for (int k = 0; k < x.size(); k++) {
(*y)[i].derivatives()[j] += dyidx[k] * x(k).derivatives()[j];
}
}
}
}
void ExpressionConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DRAKE_DEMAND(x.rows() == vars_.rows());
symbolic::Substitution subst;
for (int i = 0; i < vars_.size(); ++i) {
if (!vars_[i].equal_to(x[i])) {
subst.emplace(vars_[i], x[i]);
}
}
y->resize(num_constraints());
if (subst.empty()) {
*y = expressions_;
} else {
for (int i = 0; i < num_constraints(); ++i) {
(*y)[i] = expressions_[i].Substitute(subst);
}
}
}
std::ostream& ExpressionConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "ExpressionConstraint", vars, false);
}
std::string ExpressionConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
return ToLatexConstraint(*this, vars, precision);
}
ExponentialConeConstraint::ExponentialConeConstraint(
const Eigen::Ref<const Eigen::SparseMatrix<double>>& A,
const Eigen::Ref<const Eigen::Vector3d>& b)
: Constraint(
2, A.cols(), Eigen::Vector2d::Zero(),
Eigen::Vector2d::Constant(std::numeric_limits<double>::infinity())),
A_{A},
b_{b} {
DRAKE_DEMAND(A.rows() == 3);
}
template <typename DerivedX, typename ScalarY>
void ExponentialConeConstraint::DoEvalGeneric(
const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const {
y->resize(num_constraints());
const Vector3<ScalarY> z = A_ * x.template cast<ScalarY>() + b_;
using std::exp;
(*y)(0) = z(0) - z(1) * exp(z(2) / z(1));
(*y)(1) = z(1);
}
void ExponentialConeConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void ExponentialConeConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void ExponentialConeConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::string ExponentialConeConstraint::DoToLatex(
const VectorX<symbolic::Variable>& vars, int precision) const {
const Vector3<symbolic::Expression> z = A_ * vars + b_;
return fmt::format("0 \\le {},\\\\ {} \\le {}",
symbolic::ToLatex(z(1), precision),
symbolic::ToLatex(z(0), precision),
symbolic::ToLatex(z(1) * exp(z(2) / z(1)), precision));
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mathematical_program.cc | #include "drake/solvers/mathematical_program.h"
#include <algorithm>
#include <cstddef>
#include <limits>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include "drake/common/eigen_types.h"
#include "drake/common/fmt_eigen.h"
#include "drake/common/ssize.h"
#include "drake/common/symbolic/decompose.h"
#include "drake/common/symbolic/latex.h"
#include "drake/common/symbolic/monomial_util.h"
#include "drake/math/matrix_util.h"
#include "drake/solvers/binding.h"
#include "drake/solvers/decision_variable.h"
#include "drake/solvers/sos_basis_generator.h"
namespace drake {
namespace solvers {
using std::enable_if;
using std::endl;
using std::find;
using std::is_same;
using std::make_pair;
using std::make_shared;
using std::map;
using std::numeric_limits;
using std::ostringstream;
using std::pair;
using std::runtime_error;
using std::shared_ptr;
using std::string;
using std::unordered_map;
using std::vector;
using symbolic::Expression;
using symbolic::Formula;
using symbolic::Variable;
using symbolic::Variables;
using internal::CreateBinding;
const double kInf = std::numeric_limits<double>::infinity();
MathematicalProgram::MathematicalProgram() = default;
MathematicalProgram::MathematicalProgram(const MathematicalProgram&) = default;
MathematicalProgram::~MathematicalProgram() = default;
std::unique_ptr<MathematicalProgram> MathematicalProgram::Clone() const {
return std::unique_ptr<MathematicalProgram>(new MathematicalProgram(*this));
}
string MathematicalProgram::to_string() const {
std::ostringstream os;
os << *this;
return os.str();
}
std::string MathematicalProgram::ToLatex(int precision) {
if (num_vars() == 0) {
return "\\text{This MathematicalProgram has no decision variables.}";
}
std::stringstream ss;
ss << "\\begin{align*}\n";
if (GetAllCosts().empty()) {
ss << "\\text{find}_{";
} else {
ss << "\\min_{";
}
// TODO(russt): summarize vectors and matrices here by name, instead of every
// element.
bool first = true;
for (int i = 0; i < num_vars(); ++i) {
if (!first) {
ss << ", ";
}
first = false;
ss << symbolic::ToLatex(
decision_variables()[i]); // precision is not needed.
}
ss << "} \\quad & ";
first = true;
for (const auto& b : GetAllCosts()) {
if (!first) ss << "\\\\\n & + ";
first = false;
ss << b.ToLatex(precision);
}
std::vector<Binding<Constraint>> constraints = GetAllConstraints();
for (int i = 0; i < ssize(constraints); ++i) {
if (i == 0) {
ss << "\\\\\n \\text{subject to}\\quad";
}
ss << " & " << constraints[i].ToLatex(precision);
if (i == ssize(constraints) - 1) {
ss << ".";
} else {
ss << ",";
}
ss << "\\\\\n";
}
ss << "\\end{align*}\n";
return ss.str();
}
MatrixXDecisionVariable MathematicalProgram::NewVariables(
VarType type, int rows, int cols, bool is_symmetric,
const vector<string>& names) {
MatrixXDecisionVariable decision_variable_matrix(rows, cols);
NewVariables_impl(type, names, is_symmetric, decision_variable_matrix);
return decision_variable_matrix;
}
MatrixXDecisionVariable MathematicalProgram::NewSymmetricContinuousVariables(
int rows, const string& name) {
vector<string> names(rows * (rows + 1) / 2);
int count = 0;
for (int j = 0; j < static_cast<int>(rows); ++j) {
for (int i = j; i < static_cast<int>(rows); ++i) {
names[count] =
name + "(" + std::to_string(i) + "," + std::to_string(j) + ")";
++count;
}
}
return NewVariables(VarType::CONTINUOUS, rows, rows, true, names);
}
namespace {
template <typename T>
VectorX<T> Flatten(const Eigen::Ref<const MatrixX<T>>& mat) {
if (mat.cols() == 1) {
return mat;
} else {
// Cannot use Eigen::Map to flatten the matrix since mat.outerStride() might
// not equal to mat.rows(), namely the data in mat is not in contiguous
// space on memory.
// TODO(hongkai.dai): figure out a better way that avoids copy and dynamic
// memory allocation.
VectorX<T> vec(mat.size());
for (int j = 0; j < mat.cols(); ++j) {
vec.segment(j * mat.rows(), mat.rows()) = mat.col(j);
}
return vec;
}
}
} // namespace
void MathematicalProgram::AddDecisionVariables(
const Eigen::Ref<const MatrixXDecisionVariable>& decision_variables) {
int new_var_count = 0;
for (int i = 0; i < decision_variables.rows(); ++i) {
for (int j = 0; j < decision_variables.cols(); ++j) {
const auto& var = decision_variables(i, j);
if (decision_variable_index_.find(var.get_id()) !=
decision_variable_index_.end()) {
continue;
}
if (indeterminates_index_.find(var.get_id()) !=
indeterminates_index_.end()) {
throw std::runtime_error(
fmt::format("{} is already an indeterminate.", var));
}
CheckVariableType(var.get_type());
decision_variables_.push_back(var);
const int var_index = decision_variables_.size() - 1;
decision_variable_index_.insert(std::make_pair(var.get_id(), var_index));
++new_var_count;
}
}
AppendNanToEnd(new_var_count, &x_initial_guess_);
}
symbolic::Polynomial MathematicalProgram::NewFreePolynomialImpl(
const Variables& indeterminates, const int degree, const string& coeff_name,
symbolic::internal::DegreeType degree_type) {
const drake::VectorX<symbolic::Monomial> m =
symbolic::internal::ComputeMonomialBasis<Eigen::Dynamic>(
indeterminates, degree, degree_type);
const VectorXDecisionVariable coeffs{
this->NewContinuousVariables(m.size(), coeff_name)};
symbolic::Polynomial::MapType p_map;
// Since each entry in m is unique, we construct the polynomial using a map
// with m(i) being the map key.
for (int i = 0; i < coeffs.rows(); ++i) {
p_map.emplace(m(i), coeffs(i));
}
return symbolic::Polynomial(std::move(p_map));
}
symbolic::Polynomial MathematicalProgram::NewFreePolynomial(
const Variables& indeterminates, const int degree,
const string& coeff_name) {
return NewFreePolynomialImpl(indeterminates, degree, coeff_name,
symbolic::internal::DegreeType::kAny);
}
symbolic::Polynomial MathematicalProgram::NewEvenDegreeFreePolynomial(
const symbolic::Variables& indeterminates, int degree,
const std::string& coeff_name) {
return NewFreePolynomialImpl(indeterminates, degree, coeff_name,
symbolic::internal::DegreeType::kEven);
}
symbolic::Polynomial MathematicalProgram::NewOddDegreeFreePolynomial(
const symbolic::Variables& indeterminates, int degree,
const std::string& coeff_name) {
return NewFreePolynomialImpl(indeterminates, degree, coeff_name,
symbolic::internal::DegreeType::kOdd);
}
// This is the utility function for creating new nonnegative polynomials
// (sos-polynomial, sdsos-polynomial, dsos-polynomial). It creates a
// symmetric matrix Q as decision variables, and return m' * Q * m as the new
// polynomial, where m is the monomial basis.
pair<symbolic::Polynomial, MatrixXDecisionVariable>
MathematicalProgram::NewSosPolynomial(
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
NonnegativePolynomial type, const std::string& gram_name) {
const MatrixXDecisionVariable Q =
NewSymmetricContinuousVariables(monomial_basis.size(), gram_name);
const symbolic::Polynomial p = NewSosPolynomial(Q, monomial_basis, type);
return std::make_pair(p, Q);
}
namespace {
symbolic::Polynomial ComputePolynomialFromMonomialBasisAndGramMatrix(
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
const Eigen::Ref<const MatrixX<symbolic::Variable>>& gram) {
// TODO(hongkai.dai & soonho.kong): ideally we should compute p in one line as
// monomial_basis.dot(gramian * monomial_basis). But as explained in #10200,
// this one line version is too slow, so we use this double for loop to
// compute the matrix product by hand. I will revert to the one line version
// when it is fast.
symbolic::Polynomial p{};
for (int i = 0; i < gram.rows(); ++i) {
p.AddProduct(gram(i, i), pow(monomial_basis(i), 2));
for (int j = i + 1; j < gram.cols(); ++j) {
p.AddProduct(2 * gram(i, j), monomial_basis(i) * monomial_basis(j));
}
}
return p;
}
} // namespace
symbolic::Polynomial MathematicalProgram::NewSosPolynomial(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& gramian,
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
NonnegativePolynomial type) {
DRAKE_ASSERT(gramian.rows() == gramian.cols());
DRAKE_ASSERT(gramian.rows() == monomial_basis.rows());
const symbolic::Polynomial p =
ComputePolynomialFromMonomialBasisAndGramMatrix(monomial_basis, gramian);
switch (type) {
case MathematicalProgram::NonnegativePolynomial::kSos: {
AddPositiveSemidefiniteConstraint(gramian);
return p;
}
case MathematicalProgram::NonnegativePolynomial::kSdsos: {
AddScaledDiagonallyDominantMatrixConstraint(gramian);
return p;
}
case MathematicalProgram::NonnegativePolynomial::kDsos: {
AddPositiveDiagonallyDominantMatrixConstraint(
gramian.cast<symbolic::Expression>());
return p;
}
}
throw std::runtime_error(
"NewSosPolynomial() was passed an invalid NonnegativePolynomial type");
}
pair<symbolic::Polynomial, MatrixXDecisionVariable>
MathematicalProgram::NewSosPolynomial(const symbolic::Variables& indeterminates,
int degree, NonnegativePolynomial type,
const std::string& gram_name) {
DRAKE_DEMAND(degree >= 0 && degree % 2 == 0);
if (degree == 0) {
// The polynomial only has a non-negative constant term.
const symbolic::Variable poly_constant =
NewContinuousVariables<1>(gram_name)(0);
AddBoundingBoxConstraint(0, kInf, poly_constant);
MatrixXDecisionVariable gram(1, 1);
gram(0, 0) = poly_constant;
return std::make_pair(
symbolic::Polynomial({{symbolic::Monomial(), poly_constant}}), gram);
} else {
const drake::VectorX<symbolic::Monomial> x{
MonomialBasis(indeterminates, degree / 2)};
return NewSosPolynomial(x, type, gram_name);
}
}
std::tuple<symbolic::Polynomial, MatrixXDecisionVariable,
MatrixXDecisionVariable>
MathematicalProgram::NewEvenDegreeNonnegativePolynomial(
const symbolic::Variables& indeterminates, int degree,
MathematicalProgram::NonnegativePolynomial type) {
DRAKE_DEMAND(degree % 2 == 0);
const VectorX<symbolic::Monomial> m_e =
EvenDegreeMonomialBasis(indeterminates, degree / 2);
const VectorX<symbolic::Monomial> m_o =
OddDegreeMonomialBasis(indeterminates, degree / 2);
symbolic::Polynomial p1, p2;
MatrixXDecisionVariable Q_ee, Q_oo;
std::tie(p1, Q_ee) = NewSosPolynomial(m_e, type);
std::tie(p2, Q_oo) = NewSosPolynomial(m_o, type);
const symbolic::Polynomial p = p1 + p2;
return std::make_tuple(p, Q_oo, Q_ee);
}
std::tuple<symbolic::Polynomial, MatrixXDecisionVariable,
MatrixXDecisionVariable>
MathematicalProgram::NewEvenDegreeSosPolynomial(
const symbolic::Variables& indeterminates, int degree) {
return NewEvenDegreeNonnegativePolynomial(
indeterminates, degree, MathematicalProgram::NonnegativePolynomial::kSos);
}
std::tuple<symbolic::Polynomial, MatrixXDecisionVariable,
MatrixXDecisionVariable>
MathematicalProgram::NewEvenDegreeSdsosPolynomial(
const symbolic::Variables& indeterminates, int degree) {
return NewEvenDegreeNonnegativePolynomial(
indeterminates, degree,
MathematicalProgram::NonnegativePolynomial::kSdsos);
}
std::tuple<symbolic::Polynomial, MatrixXDecisionVariable,
MatrixXDecisionVariable>
MathematicalProgram::NewEvenDegreeDsosPolynomial(
const symbolic::Variables& indeterminates, int degree) {
return NewEvenDegreeNonnegativePolynomial(
indeterminates, degree,
MathematicalProgram::NonnegativePolynomial::kDsos);
}
symbolic::Polynomial MathematicalProgram::MakePolynomial(
const symbolic::Expression& e) const {
return symbolic::Polynomial{e, symbolic::Variables{indeterminates()}};
}
void MathematicalProgram::Reparse(symbolic::Polynomial* const p) const {
p->SetIndeterminates(symbolic::Variables{indeterminates()});
}
MatrixXIndeterminate MathematicalProgram::NewIndeterminates(
int rows, int cols, const vector<string>& names) {
MatrixXIndeterminate indeterminates_matrix(rows, cols);
NewIndeterminates_impl(names, indeterminates_matrix);
return indeterminates_matrix;
}
VectorXIndeterminate MathematicalProgram::NewIndeterminates(
int rows, const std::vector<std::string>& names) {
return NewIndeterminates(rows, 1, names);
}
VectorXIndeterminate MathematicalProgram::NewIndeterminates(
int rows, const string& name) {
vector<string> names(rows);
for (int i = 0; i < static_cast<int>(rows); ++i) {
names[i] = name + "(" + std::to_string(i) + ")";
}
return NewIndeterminates(rows, names);
}
MatrixXIndeterminate MathematicalProgram::NewIndeterminates(
int rows, int cols, const string& name) {
vector<string> names(rows * cols);
int count = 0;
for (int j = 0; j < static_cast<int>(cols); ++j) {
for (int i = 0; i < static_cast<int>(rows); ++i) {
names[count] =
name + "(" + std::to_string(i) + "," + std::to_string(j) + ")";
++count;
}
}
return NewIndeterminates(rows, cols, names);
}
int MathematicalProgram::AddIndeterminate(
const symbolic::Variable& new_indeterminate) {
if (decision_variable_index_.find(new_indeterminate.get_id()) !=
decision_variable_index_.end()) {
throw std::runtime_error(
fmt::format("{} is a decision variable in the optimization program.",
new_indeterminate));
}
if (new_indeterminate.get_type() != symbolic::Variable::Type::CONTINUOUS) {
throw std::runtime_error(
fmt::format("{} should be of type CONTINUOUS.", new_indeterminate));
}
auto it = indeterminates_index_.find(new_indeterminate.get_id());
if (it == indeterminates_index_.end()) {
const int var_index = indeterminates_.size();
indeterminates_index_.insert(
std::make_pair(new_indeterminate.get_id(), var_index));
indeterminates_.push_back(new_indeterminate);
indeterminates_index_.emplace(new_indeterminate.get_id(), var_index);
return var_index;
} else {
return it->second;
}
}
void MathematicalProgram::AddIndeterminates(
const Eigen::Ref<const MatrixXDecisionVariable>& new_indeterminates) {
for (int i = 0; i < new_indeterminates.rows(); ++i) {
for (int j = 0; j < new_indeterminates.cols(); ++j) {
const auto& var = new_indeterminates(i, j);
this->AddIndeterminate(var);
}
}
}
void MathematicalProgram::AddIndeterminates(
const symbolic::Variables& new_indeterminates) {
for (const auto& var : new_indeterminates) {
this->AddIndeterminate(var);
}
}
Binding<VisualizationCallback> MathematicalProgram::AddVisualizationCallback(
const VisualizationCallback::CallbackFunction& callback,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
visualization_callbacks_.push_back(
internal::CreateBinding<VisualizationCallback>(
make_shared<VisualizationCallback>(vars.size(), callback), vars));
required_capabilities_.insert(ProgramAttribute::kCallback);
return visualization_callbacks_.back();
}
Binding<Cost> MathematicalProgram::AddCost(const Binding<Cost>& binding) {
// See AddConstraint(const Binding<Constraint>&) for explanation
Cost* cost = binding.evaluator().get();
if (dynamic_cast<QuadraticCost*>(cost)) {
return AddCost(internal::BindingDynamicCast<QuadraticCost>(binding));
} else if (dynamic_cast<LinearCost*>(cost)) {
return AddCost(internal::BindingDynamicCast<LinearCost>(binding));
} else if (dynamic_cast<L2NormCost*>(cost)) {
return AddCost(internal::BindingDynamicCast<L2NormCost>(binding));
} else {
DRAKE_DEMAND(CheckBinding(binding));
required_capabilities_.insert(ProgramAttribute::kGenericCost);
generic_costs_.push_back(binding);
return generic_costs_.back();
}
}
Binding<LinearCost> MathematicalProgram::AddCost(
const Binding<LinearCost>& binding) {
DRAKE_DEMAND(CheckBinding(binding));
required_capabilities_.insert(ProgramAttribute::kLinearCost);
linear_costs_.push_back(binding);
return linear_costs_.back();
}
Binding<LinearCost> MathematicalProgram::AddLinearCost(const Expression& e) {
return AddCost(internal::ParseLinearCost(e));
}
Binding<LinearCost> MathematicalProgram::AddLinearCost(
const Eigen::Ref<const Eigen::VectorXd>& a, double b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddCost(make_shared<LinearCost>(a, b), vars);
}
Binding<QuadraticCost> MathematicalProgram::AddCost(
const Binding<QuadraticCost>& binding) {
DRAKE_DEMAND(CheckBinding(binding));
required_capabilities_.insert(ProgramAttribute::kQuadraticCost);
DRAKE_ASSERT(binding.evaluator()->Q().rows() ==
static_cast<int>(binding.GetNumElements()) &&
binding.evaluator()->b().rows() ==
static_cast<int>(binding.GetNumElements()));
quadratic_costs_.push_back(binding);
return quadratic_costs_.back();
}
Binding<QuadraticCost> MathematicalProgram::AddQuadraticCost(
const Expression& e, std::optional<bool> is_convex) {
return AddCost(internal::ParseQuadraticCost(e, is_convex));
}
Binding<QuadraticCost> MathematicalProgram::AddQuadraticErrorCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& x_desired,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddCost(MakeQuadraticErrorCost(Q, x_desired), vars);
}
Binding<QuadraticCost> MathematicalProgram::AddQuadraticCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double c,
const Eigen::Ref<const VectorXDecisionVariable>& vars,
std::optional<bool> is_convex) {
return AddCost(make_shared<QuadraticCost>(Q, b, c, is_convex), vars);
}
Binding<QuadraticCost> MathematicalProgram::AddQuadraticCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars,
std::optional<bool> is_convex) {
return AddQuadraticCost(Q, b, 0., vars, is_convex);
}
Binding<L2NormCost> MathematicalProgram::AddCost(
const Binding<L2NormCost>& binding) {
DRAKE_DEMAND(CheckBinding(binding));
required_capabilities_.insert(ProgramAttribute::kL2NormCost);
l2norm_costs_.push_back(binding);
return l2norm_costs_.back();
}
Binding<L2NormCost> MathematicalProgram::AddL2NormCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddCost(std::make_shared<L2NormCost>(A, b), vars);
}
Binding<L2NormCost> MathematicalProgram::AddL2NormCost(
const symbolic::Expression& e, double psd_tol, double coefficient_tol) {
return AddCost(internal::ParseL2NormCost(e, psd_tol, coefficient_tol));
}
std::tuple<symbolic::Variable, Binding<LinearCost>,
Binding<LorentzConeConstraint>>
MathematicalProgram::AddL2NormCostUsingConicConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
auto s = this->NewContinuousVariables<1>("slack")(0);
auto linear_cost =
this->AddLinearCost(Vector1d(1), 0, Vector1<symbolic::Variable>(s));
// A_full = [1 0]
// [0 A]
// b_full = [0 b]
// A_full * [s ; vars] + b_full = [s, A*vars+b]
Eigen::MatrixXd A_full(A.rows() + 1, A.cols() + 1);
A_full.setZero();
A_full(0, 0) = 1;
A_full.bottomRightCorner(A.rows(), A.cols()) = A;
Eigen::VectorXd b_full(b.rows() + 1);
b_full(0) = 0;
b_full.bottomRows(b.rows()) = b;
auto lorentz_cone_constraint = this->AddLorentzConeConstraint(
A_full, b_full, {Vector1<symbolic::Variable>(s), vars});
return std::make_tuple(s, linear_cost, lorentz_cone_constraint);
}
Binding<PolynomialCost> MathematicalProgram::AddPolynomialCost(
const Expression& e) {
auto binding = AddCost(internal::ParsePolynomialCost(e));
return internal::BindingDynamicCast<PolynomialCost>(binding);
}
Binding<Cost> MathematicalProgram::AddCost(const Expression& e) {
return AddCost(internal::ParseCost(e));
}
namespace {
void CreateLogDetermiant(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X,
VectorX<symbolic::Variable>* t, MatrixX<symbolic::Expression>* Z) {
DRAKE_DEMAND(X.rows() == X.cols());
const int X_rows = X.rows();
auto Z_lower = prog->NewContinuousVariables(X_rows * (X_rows + 1) / 2);
Z->resize(X_rows, X_rows);
Z->setZero();
// diag_Z is the diagonal matrix that only contains the diagonal entries of Z.
MatrixX<symbolic::Expression> diag_Z(X_rows, X_rows);
diag_Z.setZero();
int Z_lower_index = 0;
for (int j = 0; j < X_rows; ++j) {
for (int i = j; i < X_rows; ++i) {
(*Z)(i, j) = Z_lower(Z_lower_index++);
}
diag_Z(j, j) = (*Z)(j, j);
}
MatrixX<symbolic::Expression> psd_mat(2 * X_rows, 2 * X_rows);
// clang-format off
psd_mat << X, *Z,
Z->transpose(), diag_Z;
// clang-format on
prog->AddPositiveSemidefiniteConstraint(psd_mat);
// Now introduce the slack variable t.
*t = prog->NewContinuousVariables(X_rows);
// Introduce the constraint log(Z(i, i)) >= t(i).
for (int i = 0; i < X_rows; ++i) {
prog->AddExponentialConeConstraint(
Vector3<symbolic::Expression>((*Z)(i, i), 1, (*t)(i)));
}
}
} // namespace
std::tuple<Binding<LinearCost>, VectorX<symbolic::Variable>,
MatrixX<symbolic::Expression>>
MathematicalProgram::AddMaximizeLogDeterminantCost(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X) {
VectorX<symbolic::Variable> t;
MatrixX<symbolic::Expression> Z;
CreateLogDetermiant(this, X, &t, &Z);
const auto cost = AddLinearCost(-Eigen::VectorXd::Ones(t.rows()), t);
return std::make_tuple(cost, std::move(t), std::move(Z));
}
std::tuple<Binding<LinearConstraint>, VectorX<symbolic::Variable>,
MatrixX<symbolic::Expression>>
MathematicalProgram::AddLogDeterminantLowerBoundConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X, double lower) {
VectorX<symbolic::Variable> t;
MatrixX<symbolic::Expression> Z;
CreateLogDetermiant(this, X, &t, &Z);
const auto constraint =
AddLinearConstraint(Eigen::RowVectorXd::Ones(t.rows()), lower, kInf, t);
return std::make_tuple(constraint, std::move(t), std::move(Z));
}
Binding<LinearCost> MathematicalProgram::AddMaximizeGeometricMeanCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorX<symbolic::Variable>>& x) {
if (A.rows() != b.rows() || A.cols() != x.rows()) {
throw std::invalid_argument(
"MathematicalProgram::AddMaximizeGeometricMeanCost: the argument A, b "
"and x don't have consistent size.");
}
if (A.rows() <= 1) {
throw std::runtime_error(
"MathematicalProgram::AddMaximizeGeometricMeanCost: the size of A*x+b "
"should be at least 2.");
}
// We will impose the constraint w(i)² ≤ (A.row(2i) * x + b(2i)) *
// (A.row(2i+1) * x + b(2i+1)). This could be reformulated as the vector
// C * [x;w(i)] + d is in the rotated Lorentz cone, where
// C = [A.row(2i) 0]
// [A.row(2i+1) 0]
// [0, 0, ...,0 1]
// d = [b(2i) ]
// [b(2i+1)]
// [0 ]
// The special case is that if A.rows() is an odd number, then for the last
// entry of w, we will impose (w((A.rows() - 1)/2)² ≤ A.row(A.rows() - 1) * x
// + b(b.rows() - 1)
auto w = NewContinuousVariables((A.rows() + 1) / 2);
DRAKE_ASSERT(w.rows() >= 1);
VectorX<symbolic::Variable> xw(x.rows() + 1);
xw.head(x.rows()) = x;
Eigen::Matrix3Xd C(3, x.rows() + 1);
for (int i = 0; i < w.size(); ++i) {
C.setZero();
C.row(0) << A.row(2 * i), 0;
Eigen::Vector3d d;
d(0) = b(2 * i);
if (2 * i + 1 == A.rows()) {
// The special case, C.row(1) * x + d(1) = 1.
C.row(1).setZero();
d(1) = 1;
} else {
// The normal case, C.row(1) * x + d(1) = A.row(2i+1) * x + b(2i+1)
C.row(1) << A.row(2 * i + 1), 0;
d(1) = b(2 * i + 1);
}
C.row(2).setZero();
C(2, C.cols() - 1) = 1;
d(2) = 0;
xw(x.rows()) = w(i);
AddRotatedLorentzConeConstraint(C, d, xw);
}
if (w.rows() == 1) {
return AddLinearCost(-w(0));
}
return AddMaximizeGeometricMeanCost(w, 1);
}
Binding<LinearCost> MathematicalProgram::AddMaximizeGeometricMeanCost(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x, double c) {
if (c <= 0) {
throw std::invalid_argument(
"MathematicalProgram::AddMaximizeGeometricMeanCost(): c should be "
"positive.");
}
// We maximize the geometric mean through a recursive procedure. If we assume
// that the size of x is 2ᵏ, then in each iteration, we introduce new slack
// variables w of size 2ᵏ⁻¹, with the constraint
// w(i)² ≤ x(2i) * x(2i+1)
// we then call AddMaximizeGeometricMeanCost(w). This recursion ends until
// w.size() == 2. We then add the constraint z(0)² ≤ w(0) * w(1), and maximize
// the cost z(0).
if (x.rows() <= 1) {
throw std::invalid_argument(
"MathematicalProgram::AddMaximizeGeometricMeanCost(): x should have "
"more than one entry.");
}
// We will impose the constraint w(i)² ≤ x(2i) * x(2i+1). Namely the vector
// [x(2i); x(2i+1); w(i)] is in the rotated Lorentz cone.
// The special case is when x.rows() = 2n+1, then for the last
// entry of w, we impose the constraint w(n)² ≤ x(2n), namely the vector
// [x(2n); 1; w(n)] is in the rotated Lorentz cone.
auto w = NewContinuousVariables((x.rows() + 1) / 2);
DRAKE_ASSERT(w.rows() >= 1);
for (int i = 0; i < w.rows() - 1; ++i) {
AddRotatedLorentzConeConstraint(
Vector3<symbolic::Variable>(x(2 * i), x(2 * i + 1), w(i)));
}
if (2 * w.rows() == x.rows()) {
// x has even number of rows.
AddRotatedLorentzConeConstraint(Vector3<symbolic::Variable>(
x(x.rows() - 2), x(x.rows() - 1), w(w.rows() - 1)));
} else {
// x has odd number of rows.
// C * xw + d = [x(2n); 1; w(n)], where xw = [x(2n); w(n)].
Eigen::Matrix<double, 3, 2> C;
C << 1, 0, 0, 0, 0, 1;
const Eigen::Vector3d d(0, 1, 0);
AddRotatedLorentzConeConstraint(
C, d, Vector2<symbolic::Variable>(x(x.rows() - 1), w(w.rows() - 1)));
}
if (x.rows() == 2) {
return AddLinearCost(-c * w(0));
}
return AddMaximizeGeometricMeanCost(w);
}
Binding<Constraint> MathematicalProgram::AddConstraint(
const Binding<Constraint>& binding) {
// TODO(eric.cousineau): Use alternative to RTTI.
// Move kGenericConstraint, etc. to Constraint. Dispatch based on this
// information. As it is, this causes extra work when we explicitly want a
// generic constraint.
// If we get here, then this was possibly a dynamically-simplified
// constraint. Determine correct container. As last resort, add to generic
// constraints.
Constraint* constraint = binding.evaluator().get();
// Check constraints types in reverse order, such that classes that inherit
// from other classes will not be prematurely added to less specific (or
// incorrect) container.
if (dynamic_cast<LinearMatrixInequalityConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearMatrixInequalityConstraint>(
binding));
} else if (dynamic_cast<PositiveSemidefiniteConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<PositiveSemidefiniteConstraint>(binding));
} else if (dynamic_cast<RotatedLorentzConeConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<RotatedLorentzConeConstraint>(binding));
} else if (dynamic_cast<LorentzConeConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LorentzConeConstraint>(binding));
} else if (dynamic_cast<QuadraticConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<QuadraticConstraint>(binding));
} else if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
if (!CheckBinding(binding)) {
return binding;
}
required_capabilities_.insert(ProgramAttribute::kGenericConstraint);
generic_constraints_.push_back(binding);
return generic_constraints_.back();
}
}
Binding<Constraint> MathematicalProgram::AddConstraint(const Expression& e,
const double lb,
const double ub) {
return AddConstraint(internal::ParseConstraint(e, lb, ub));
}
Binding<Constraint> MathematicalProgram::AddConstraint(
const Eigen::Ref<const MatrixX<Expression>>& v,
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub) {
DRAKE_DEMAND(v.rows() == lb.rows());
DRAKE_DEMAND(v.rows() == ub.rows());
DRAKE_DEMAND(v.cols() == lb.cols());
DRAKE_DEMAND(v.cols() == ub.cols());
return AddConstraint(
internal::ParseConstraint(Flatten(v), Flatten(lb), Flatten(ub)));
}
Binding<Constraint> MathematicalProgram::AddConstraint(const Formula& f) {
return AddConstraint(internal::ParseConstraint(f));
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Expression& e, const double lb, const double ub) {
Binding<Constraint> binding = internal::ParseConstraint(e, lb, ub);
Constraint* constraint = binding.evaluator().get();
if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
std::stringstream oss;
oss << "Expression " << e << " is non-linear.";
throw std::runtime_error(oss.str());
}
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Eigen::Ref<const MatrixX<Expression>>& v,
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub) {
DRAKE_DEMAND(v.rows() == lb.rows());
DRAKE_DEMAND(v.rows() == ub.rows());
DRAKE_DEMAND(v.cols() == lb.cols());
DRAKE_DEMAND(v.cols() == ub.cols());
Binding<Constraint> binding =
internal::ParseConstraint(Flatten(v), Flatten(lb), Flatten(ub));
Constraint* constraint = binding.evaluator().get();
if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
throw std::runtime_error(
fmt::format("Expression {} is non-linear.", fmt_eigen(v)));
}
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Formula& f) {
Binding<Constraint> binding = internal::ParseConstraint(f);
Constraint* constraint = binding.evaluator().get();
if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
std::stringstream oss;
oss << "Formula " << f << " is non-linear.";
throw std::runtime_error(oss.str());
}
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Eigen::Ref<const Eigen::Array<symbolic::Formula, Eigen::Dynamic,
Eigen::Dynamic>>& formulas) {
Binding<Constraint> binding = internal::ParseConstraint(formulas);
Constraint* constraint = binding.evaluator().get();
if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
std::stringstream oss;
oss << "Formulas are non-linear.";
throw std::runtime_error(
"AddLinearConstraint called but formulas are non-linear");
}
}
Binding<LinearConstraint> MathematicalProgram::AddConstraint(
const Binding<LinearConstraint>& binding) {
// Because the ParseConstraint methods can return instances of
// LinearEqualityConstraint or BoundingBoxConstraint, do a dynamic check
// here.
LinearConstraint* constraint = binding.evaluator().get();
if (dynamic_cast<BoundingBoxConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<BoundingBoxConstraint>(binding));
} else if (dynamic_cast<LinearEqualityConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearEqualityConstraint>(binding));
} else {
// TODO(eric.cousineau): This is a good assertion... But seems out of place,
// possibly redundant w.r.t. the binding infrastructure.
DRAKE_ASSERT(binding.evaluator()->get_sparse_A().cols() ==
static_cast<int>(binding.GetNumElements()));
if (!CheckBinding(binding)) {
return binding;
}
required_capabilities_.insert(ProgramAttribute::kLinearConstraint);
linear_constraints_.push_back(binding);
return linear_constraints_.back();
}
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddConstraint(make_shared<LinearConstraint>(A, lb, ub), vars);
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Eigen::SparseMatrix<double>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddConstraint(make_shared<LinearConstraint>(A, lb, ub), vars);
}
Binding<LinearEqualityConstraint> MathematicalProgram::AddConstraint(
const Binding<LinearEqualityConstraint>& binding) {
DRAKE_ASSERT(binding.evaluator()->get_sparse_A().cols() ==
static_cast<int>(binding.GetNumElements()));
if (!CheckBinding(binding)) {
return binding;
}
required_capabilities_.insert(ProgramAttribute::kLinearEqualityConstraint);
linear_equality_constraints_.push_back(binding);
return linear_equality_constraints_.back();
}
Binding<LinearEqualityConstraint>
MathematicalProgram::AddLinearEqualityConstraint(const Expression& e,
double b) {
return AddConstraint(internal::ParseLinearEqualityConstraint(e, b));
}
Binding<LinearEqualityConstraint>
MathematicalProgram::AddLinearEqualityConstraint(const Formula& f) {
return AddConstraint(internal::ParseLinearEqualityConstraint(f));
}
Binding<LinearEqualityConstraint>
MathematicalProgram::AddLinearEqualityConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Aeq,
const Eigen::Ref<const Eigen::VectorXd>& beq,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddConstraint(make_shared<LinearEqualityConstraint>(Aeq, beq), vars);
}
Binding<LinearEqualityConstraint>
MathematicalProgram::AddLinearEqualityConstraint(
const Eigen::SparseMatrix<double>& Aeq,
const Eigen::Ref<const Eigen::VectorXd>& beq,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddConstraint(make_shared<LinearEqualityConstraint>(Aeq, beq), vars);
}
Binding<BoundingBoxConstraint> MathematicalProgram::AddConstraint(
const Binding<BoundingBoxConstraint>& binding) {
if (!CheckBinding(binding)) {
return binding;
}
DRAKE_ASSERT(binding.evaluator()->num_outputs() ==
static_cast<int>(binding.GetNumElements()));
required_capabilities_.insert(ProgramAttribute::kLinearConstraint);
bbox_constraints_.push_back(binding);
return bbox_constraints_.back();
}
Binding<LorentzConeConstraint> MathematicalProgram::AddConstraint(
const Binding<LorentzConeConstraint>& binding) {
DRAKE_DEMAND(CheckBinding(binding));
required_capabilities_.insert(ProgramAttribute::kLorentzConeConstraint);
lorentz_cone_constraint_.push_back(binding);
return lorentz_cone_constraint_.back();
}
Binding<LorentzConeConstraint> MathematicalProgram::AddLorentzConeConstraint(
const Eigen::Ref<const VectorX<Expression>>& v,
LorentzConeConstraint::EvalType eval_type) {
return AddConstraint(internal::ParseLorentzConeConstraint(v, eval_type));
}
Binding<LorentzConeConstraint> MathematicalProgram::AddLorentzConeConstraint(
const Expression& linear_expression, const Expression& quadratic_expression,
double tol, LorentzConeConstraint::EvalType eval_type) {
return AddConstraint(internal::ParseLorentzConeConstraint(
linear_expression, quadratic_expression, tol, eval_type));
}
Binding<LorentzConeConstraint> MathematicalProgram::AddLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars,
LorentzConeConstraint::EvalType eval_type) {
shared_ptr<LorentzConeConstraint> constraint =
make_shared<LorentzConeConstraint>(A, b, eval_type);
return AddConstraint(Binding<LorentzConeConstraint>(constraint, vars));
}
Binding<RotatedLorentzConeConstraint> MathematicalProgram::AddConstraint(
const Binding<RotatedLorentzConeConstraint>& binding) {
DRAKE_DEMAND(CheckBinding(binding));
required_capabilities_.insert(
ProgramAttribute::kRotatedLorentzConeConstraint);
rotated_lorentz_cone_constraint_.push_back(binding);
return rotated_lorentz_cone_constraint_.back();
}
Binding<RotatedLorentzConeConstraint>
MathematicalProgram::AddRotatedLorentzConeConstraint(
const symbolic::Expression& linear_expression1,
const symbolic::Expression& linear_expression2,
const symbolic::Expression& quadratic_expression, double tol) {
auto binding = internal::ParseRotatedLorentzConeConstraint(
linear_expression1, linear_expression2, quadratic_expression, tol);
AddConstraint(binding);
return binding;
}
Binding<RotatedLorentzConeConstraint>
MathematicalProgram::AddRotatedLorentzConeConstraint(
const Eigen::Ref<const VectorX<Expression>>& v) {
auto binding = internal::ParseRotatedLorentzConeConstraint(v);
AddConstraint(binding);
return binding;
}
Binding<RotatedLorentzConeConstraint>
MathematicalProgram::AddRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
shared_ptr<RotatedLorentzConeConstraint> constraint =
make_shared<RotatedLorentzConeConstraint>(A, b);
return AddConstraint(constraint, vars);
}
Binding<RotatedLorentzConeConstraint>
MathematicalProgram::AddQuadraticAsRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double c,
const Eigen::Ref<const VectorXDecisionVariable>& vars, double psd_tol) {
auto constraint =
internal::ParseQuadraticAsRotatedLorentzConeConstraint(Q, b, c, psd_tol);
return AddConstraint(constraint, vars);
}
Binding<BoundingBoxConstraint> MathematicalProgram::AddBoundingBoxConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub,
const Eigen::Ref<const MatrixXDecisionVariable>& vars) {
DRAKE_DEMAND(lb.rows() == ub.rows());
DRAKE_DEMAND(lb.rows() == vars.rows());
DRAKE_DEMAND(lb.cols() == ub.cols());
DRAKE_DEMAND(lb.cols() == vars.cols());
shared_ptr<BoundingBoxConstraint> constraint =
make_shared<BoundingBoxConstraint>(Flatten(lb), Flatten(ub));
return AddConstraint(
Binding<BoundingBoxConstraint>(constraint, Flatten(vars)));
}
Binding<QuadraticConstraint> MathematicalProgram::AddConstraint(
const Binding<QuadraticConstraint>& binding) {
DRAKE_DEMAND(CheckBinding(binding));
required_capabilities_.insert(ProgramAttribute::kQuadraticConstraint);
quadratic_constraints_.push_back(binding);
return quadratic_constraints_.back();
}
Binding<QuadraticConstraint> MathematicalProgram::AddQuadraticConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double lb, double ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars,
std::optional<QuadraticConstraint::HessianType> hessian_type) {
auto constraint =
std::make_shared<QuadraticConstraint>(Q, b, lb, ub, hessian_type);
return AddConstraint(Binding<QuadraticConstraint>(constraint, vars));
}
Binding<QuadraticConstraint> MathematicalProgram::AddQuadraticConstraint(
const symbolic::Expression& e, double lb, double ub,
std::optional<QuadraticConstraint::HessianType> hessian_type) {
return AddConstraint(
internal::ParseQuadraticConstraint(e, lb, ub, hessian_type));
}
Binding<LinearComplementarityConstraint> MathematicalProgram::AddConstraint(
const Binding<LinearComplementarityConstraint>& binding) {
if (!CheckBinding(binding)) {
return binding;
}
required_capabilities_.insert(
ProgramAttribute::kLinearComplementarityConstraint);
linear_complementarity_constraints_.push_back(binding);
return linear_complementarity_constraints_.back();
}
Binding<LinearComplementarityConstraint>
MathematicalProgram::AddLinearComplementarityConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& M,
const Eigen::Ref<const Eigen::VectorXd>& q,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
shared_ptr<LinearComplementarityConstraint> constraint =
make_shared<LinearComplementarityConstraint>(M, q);
return AddConstraint(constraint, vars);
}
Binding<Constraint> MathematicalProgram::AddPolynomialConstraint(
const Eigen::Ref<const MatrixX<Polynomiald>>& polynomials,
const vector<Polynomiald::VarType>& poly_vars,
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
DRAKE_DEMAND(polynomials.rows() == lb.rows());
DRAKE_DEMAND(polynomials.rows() == ub.rows());
DRAKE_DEMAND(polynomials.cols() == lb.cols());
DRAKE_DEMAND(polynomials.cols() == ub.cols());
auto constraint = internal::MakePolynomialConstraint(
Flatten(polynomials), poly_vars, Flatten(lb), Flatten(ub));
return AddConstraint(constraint, vars);
}
Binding<PositiveSemidefiniteConstraint> MathematicalProgram::AddConstraint(
const Binding<PositiveSemidefiniteConstraint>& binding) {
if (!CheckBinding(binding)) {
return binding;
}
DRAKE_ASSERT(math::IsSymmetric(Eigen::Map<const MatrixXDecisionVariable>(
binding.variables().data(), binding.evaluator()->matrix_rows(),
binding.evaluator()->matrix_rows())));
required_capabilities_.insert(
ProgramAttribute::kPositiveSemidefiniteConstraint);
positive_semidefinite_constraint_.push_back(binding);
return positive_semidefinite_constraint_.back();
}
Binding<PositiveSemidefiniteConstraint> MathematicalProgram::AddConstraint(
shared_ptr<PositiveSemidefiniteConstraint> con,
const Eigen::Ref<const MatrixXDecisionVariable>& symmetric_matrix_var) {
DRAKE_ASSERT(math::IsSymmetric(symmetric_matrix_var));
return AddConstraint(CreateBinding(con, Flatten(symmetric_matrix_var)));
}
Binding<PositiveSemidefiniteConstraint>
MathematicalProgram::AddPositiveSemidefiniteConstraint(
const Eigen::Ref<const MatrixXDecisionVariable>& symmetric_matrix_var) {
auto constraint =
make_shared<PositiveSemidefiniteConstraint>(symmetric_matrix_var.rows());
return AddConstraint(constraint, symmetric_matrix_var);
}
Binding<PositiveSemidefiniteConstraint>
MathematicalProgram::AddPrincipalSubmatrixIsPsdConstraint(
const Eigen::Ref<const MatrixXDecisionVariable>& symmetric_matrix_var,
const std::set<int>& minor_indices) {
// This function relies on AddPositiveSemidefiniteConstraint to validate the
// documented symmetry prerequisite.
return AddPositiveSemidefiniteConstraint(
math::ExtractPrincipalSubmatrix(symmetric_matrix_var, minor_indices));
}
Binding<PositiveSemidefiniteConstraint>
MathematicalProgram::AddPrincipalSubmatrixIsPsdConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& e,
const std::set<int>& minor_indices) {
// This function relies on AddPositiveSemidefiniteConstraint to validate the
// documented symmetry prerequisite.
return AddPositiveSemidefiniteConstraint(
math::ExtractPrincipalSubmatrix(e, minor_indices));
}
Binding<LinearMatrixInequalityConstraint> MathematicalProgram::AddConstraint(
const Binding<LinearMatrixInequalityConstraint>& binding) {
if (!CheckBinding(binding)) {
return binding;
}
DRAKE_ASSERT(static_cast<int>(binding.evaluator()->F().size()) ==
static_cast<int>(binding.GetNumElements()) + 1);
required_capabilities_.insert(
ProgramAttribute::kPositiveSemidefiniteConstraint);
linear_matrix_inequality_constraint_.push_back(binding);
return linear_matrix_inequality_constraint_.back();
}
Binding<LinearMatrixInequalityConstraint>
MathematicalProgram::AddLinearMatrixInequalityConstraint(
vector<Eigen::MatrixXd> F,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
auto constraint = make_shared<LinearMatrixInequalityConstraint>(std::move(F));
return AddConstraint(constraint, vars);
}
MatrixX<symbolic::Expression>
MathematicalProgram::AddPositiveDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X) {
// First create the slack variables Y with the same size as X, Y being the
// symmetric matrix representing the absolute value of X.
const int num_X_rows = X.rows();
DRAKE_DEMAND(X.cols() == num_X_rows);
auto Y_upper = NewContinuousVariables((num_X_rows - 1) * num_X_rows / 2,
"diagonally_dominant_slack");
MatrixX<symbolic::Expression> Y(num_X_rows, num_X_rows);
int Y_upper_count = 0;
// Fill in the upper triangle of Y.
for (int j = 0; j < num_X_rows; ++j) {
for (int i = 0; i < j; ++i) {
Y(i, j) = Y_upper(Y_upper_count);
Y(j, i) = Y(i, j);
++Y_upper_count;
}
// The diagonal entries of Y.
Y(j, j) = X(j, j);
}
// Add the constraint that Y(i, j) >= |X(i, j) + X(j, i) / 2|
for (int i = 0; i < num_X_rows; ++i) {
for (int j = i + 1; j < num_X_rows; ++j) {
AddLinearConstraint(Y(i, j) >= (X(i, j) + X(j, i)) / 2);
AddLinearConstraint(Y(i, j) >= -(X(i, j) + X(j, i)) / 2);
}
}
// Add the constraint X(i, i) >= sum_j Y(i, j), j ≠ i
for (int i = 0; i < num_X_rows; ++i) {
symbolic::Expression y_sum = 0;
for (int j = 0; j < num_X_rows; ++j) {
if (j == i) {
continue;
}
y_sum += Y(i, j);
}
AddLinearConstraint(X(i, i) >= y_sum);
}
return Y;
}
MatrixX<symbolic::Expression> MathematicalProgram::TightenPsdConstraintToDd(
const Binding<PositiveSemidefiniteConstraint>& constraint) {
RemoveConstraint(constraint);
// Variables are flattened by the Flatten method, which flattens in
// column-major order. This is the same convention as Eigen, so we can use the
// map methods.
const int n = constraint.evaluator()->matrix_rows();
const MatrixXDecisionVariable mat_vars =
Eigen::Map<const MatrixXDecisionVariable>(constraint.variables().data(),
n, n);
return AddPositiveDiagonallyDominantMatrixConstraint(
mat_vars.cast<Expression>());
}
namespace {
// Constructs the matrices A, lb, ub for the linear constraint lb <= A * X <= ub
// encoding that X is in DD* for a matrix of size n. Returns the tuple
// (A, lb, ub).
std::tuple<Eigen::SparseMatrix<double>, Eigen::VectorXd, Eigen::VectorXd>
ConstructPositiveDiagonallyDominantDualConeConstraintMatricesForN(const int n) {
// Return the index of Xᵢⱼ in the vector created by stacking the column of X
// into a vector.
auto compute_flat_index = [&n](int i, int j) {
return i + n * j;
};
// The DD dual cone constraint is a sparse linear constraint. We instantiate
// the A matrix using this triplet list.
std::vector<Eigen::Triplet<double>> A_triplet_list;
// 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.
A_triplet_list.reserve(4 * n * n - 3 * n);
const Eigen::VectorXd lb = Eigen::VectorXd::Zero(n * n);
const Eigen::VectorXd ub = kInf * Eigen::VectorXd::Ones(n * n);
// vᵢᵀXvᵢ ≥ 0 is equivalent to Xᵢᵢ ≥ 0 when vᵢ is a vector with exactly one
// entry equal to 1.
for (int i = 0; i < n; ++i) {
// Variable Xᵢᵢ is in position i*(n+1)
A_triplet_list.emplace_back(i, compute_flat_index(i, i), 1);
}
// When vᵢ is a vector with two non-zero at entries k and j, we can choose
// without loss of generality that the jth entry to be 1, and the kth entry be
// either +1 or -1. This enumerates over all the parities of vᵢ. Under this
// choice vᵢᵀXvᵢ = Xₖₖ + sign(vᵢ(k))* (Xₖⱼ+ Xⱼₖ) + Xⱼⱼ
int row_ctr = n;
for (int j = 0; j < n; ++j) {
for (int k = j + 1; k < n; ++k) {
// X(k, k) + X(k, j) + X(j, k) + X(j, j)
A_triplet_list.emplace_back(row_ctr, compute_flat_index(k, k), 1);
A_triplet_list.emplace_back(row_ctr, compute_flat_index(j, j), 1);
A_triplet_list.emplace_back(row_ctr, compute_flat_index(j, k), 1);
A_triplet_list.emplace_back(row_ctr, compute_flat_index(k, j), 1);
++row_ctr;
// X(k, k) - X(k, j) - X(j, k) + X(j, j)
A_triplet_list.emplace_back(row_ctr, compute_flat_index(k, k), 1);
A_triplet_list.emplace_back(row_ctr, compute_flat_index(j, j), 1);
A_triplet_list.emplace_back(row_ctr, compute_flat_index(j, k), -1);
A_triplet_list.emplace_back(row_ctr, compute_flat_index(k, j), -1);
++row_ctr;
}
}
DRAKE_ASSERT(row_ctr == n * n);
DRAKE_ASSERT(ssize(A_triplet_list) == 4 * n * n - 3 * n);
Eigen::SparseMatrix<double> A(row_ctr, n * n);
A.setFromTriplets(A_triplet_list.begin(), A_triplet_list.end());
return std::make_tuple(std::move(A), std::move(lb), std::move(ub));
}
} // namespace
Binding<LinearConstraint>
MathematicalProgram::AddPositiveDiagonallyDominantDualConeMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X) {
const int n = X.rows();
DRAKE_DEMAND(X.cols() == n);
Eigen::MatrixXd A_expr;
Eigen::VectorXd b_expr;
VectorX<Variable> variables;
symbolic::DecomposeAffineExpressions(
Eigen::Map<const VectorX<symbolic::Expression>>(X.data(), X.size()),
&A_expr, &b_expr, &variables);
const std::tuple<Eigen::SparseMatrix<double>, Eigen::VectorXd,
Eigen::VectorXd>
constraint_mats{
ConstructPositiveDiagonallyDominantDualConeConstraintMatricesForN(n)};
return AddLinearConstraint(
(std::get<0>(constraint_mats) * A_expr).sparseView(), // A * A_expr
std::get<1>(constraint_mats) -
std::get<0>(constraint_mats) * b_expr, // lb - A * b_expr
std::get<2>(constraint_mats), // ub - A * b_expr, but since ub is kInf no
// need to do the operations
variables);
}
Binding<LinearConstraint>
MathematicalProgram::AddPositiveDiagonallyDominantDualConeMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X) {
const int n = X.rows();
DRAKE_DEMAND(X.cols() == n);
const std::tuple<Eigen::SparseMatrix<double>, Eigen::VectorXd,
Eigen::VectorXd>
constraint_mats{
ConstructPositiveDiagonallyDominantDualConeConstraintMatricesForN(n)};
return AddLinearConstraint(
std::get<0>(constraint_mats), std::get<1>(constraint_mats),
std::get<2>(constraint_mats),
Eigen::Map<const VectorXDecisionVariable>(X.data(), X.size()));
}
Binding<LinearConstraint> MathematicalProgram::RelaxPsdConstraintToDdDualCone(
const Binding<PositiveSemidefiniteConstraint>& constraint) {
RemoveConstraint(constraint);
// Variables are flattened by the Flatten method, which flattens in
// column-major order. This is the same convention as Eigen, so we can use the
// map methods.
const int n = constraint.evaluator()->matrix_rows();
const MatrixXDecisionVariable mat_vars =
Eigen::Map<const MatrixXDecisionVariable>(constraint.variables().data(),
n, n);
return AddPositiveDiagonallyDominantDualConeMatrixConstraint(mat_vars);
}
namespace {
// Add the slack variable for scaled diagonally dominant matrix constraint. In
// AddScaledDiagonallyDominantMatrixConstraint, we should add the constraint
// that the diagonal terms in the sdd matrix should match the summation of
// the diagonally terms in the slack variable, and the upper diagonal corner
// in M[i][j] should satisfy the rotated Lorentz cone constraint.
template <typename T>
void AddSlackVariableForScaledDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<T>>& X, MathematicalProgram* prog,
Eigen::Matrix<symbolic::Variable, 2, Eigen::Dynamic>* M_ij_diagonal,
std::vector<std::vector<Matrix2<T>>>* M) {
const int n = X.rows();
DRAKE_DEMAND(X.cols() == n);
// The diagonal terms of M[i][j] are new variables.
// M[i][j](0, 0) = M_ij_diagonal(0, k)
// M[i][j](1, 1) = M_ij_diagonal(1, k)
// where k = (2n - 1) * i / 2 + j - i - 1, namely k is the index of X(i, j)
// in the vector X_upper_diagonal, where X_upper_diagonal is obtained by
// stacking each row of the upper diagonal part (not including the diagonal
// entries) in X to a row vector.
*M_ij_diagonal = prog->NewContinuousVariables<2, Eigen::Dynamic>(
2, (n - 1) * n / 2, "sdd_slack_M");
int k = 0;
M->resize(n);
for (int i = 0; i < n; ++i) {
(*M)[i].resize(n);
for (int j = i + 1; j < n; ++j) {
(*M)[i][j](0, 0) = (*M_ij_diagonal)(0, k);
(*M)[i][j](1, 1) = (*M_ij_diagonal)(1, k);
(*M)[i][j](0, 1) = X(i, j);
(*M)[i][j](1, 0) = X(j, i);
++k;
}
}
}
} // namespace
std::vector<std::vector<Matrix2<symbolic::Expression>>>
MathematicalProgram::AddScaledDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X) {
const int n = X.rows();
std::vector<std::vector<Matrix2<symbolic::Expression>>> M(n);
Matrix2X<symbolic::Variable> M_ij_diagonal;
AddSlackVariableForScaledDiagonallyDominantMatrixConstraint<
symbolic::Expression>(X, this, &M_ij_diagonal, &M);
for (int i = 0; i < n; ++i) {
symbolic::Expression diagonal_sum = 0;
for (int j = 0; j < i; ++j) {
diagonal_sum += M[j][i](1, 1);
}
for (int j = i + 1; j < n; ++j) {
diagonal_sum += M[i][j](0, 0);
AddRotatedLorentzConeConstraint(Vector3<symbolic::Expression>(
M[i][j](0, 0), M[i][j](1, 1), M[i][j](0, 1)));
}
AddLinearEqualityConstraint(X(i, i) - diagonal_sum, 0);
}
return M;
}
std::vector<std::vector<Matrix2<symbolic::Variable>>>
MathematicalProgram::AddScaledDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X) {
const int n = X.rows();
std::vector<std::vector<Matrix2<symbolic::Variable>>> M(n);
Matrix2X<symbolic::Variable> M_ij_diagonal;
AddSlackVariableForScaledDiagonallyDominantMatrixConstraint<
symbolic::Variable>(X, this, &M_ij_diagonal, &M);
// k is the index of X(i, j) in the vector X_upper_diagonal, where
// X_upper_diagonal is obtained by stacking each row of the upper diagonal
// part in X to a row vector.
auto ij_to_k = [&n](int i, int j) {
return (2 * n - 1 - i) * i / 2 + j - i - 1;
};
// diagonal_sum_var = [M_ij_diagonal(:); X(0, 0); X(1, 1); ...; X(n-1, n-1)]
const int n_square = n * n;
VectorXDecisionVariable diagonal_sum_var(n_square);
for (int i = 0; i < (n_square - n) / 2; ++i) {
diagonal_sum_var.segment<2>(2 * i) = M_ij_diagonal.col(i);
}
for (int i = 0; i < n; ++i) {
diagonal_sum_var(n_square - n + i) = X(i, i);
}
// Create a RotatedLorentzConeConstraint
auto rotated_lorentz_cone_constraint =
std::make_shared<RotatedLorentzConeConstraint>(
Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero());
// A_diagonal_sum.row(i) * diagonal_sum_var = M[0][i](1, 1) + M[1][i](1, 1) +
// ... + M[i-1][i](1, 1) - X(i, i) + M[i][i+1](0, 0) + M[i][i+2](0, 0) + ... +
// M[i][n-1](0, 0);
Eigen::MatrixXd A_diagonal_sum(n, n_square);
A_diagonal_sum.setZero();
for (int i = 0; i < n; ++i) {
// The coefficient for X(i, i)
A_diagonal_sum(i, n_square - n + i) = -1;
for (int j = 0; j < i; ++j) {
// The coefficient for M[j][i](1, 1)
A_diagonal_sum(i, 2 * ij_to_k(j, i) + 1) = 1;
}
for (int j = i + 1; j < n; ++j) {
// The coefficient for M[i][j](0, 0)
A_diagonal_sum(i, 2 * ij_to_k(i, j)) = 1;
// Bind the rotated Lorentz cone constraint to (M[i][j](0, 0); M[i][j](1,
// 1); M[i][j](0, 1))
AddConstraint(rotated_lorentz_cone_constraint,
Vector3<symbolic::Variable>(M[i][j](0, 0), M[i][j](1, 1),
M[i][j](0, 1)));
}
}
AddLinearEqualityConstraint(A_diagonal_sum, Eigen::VectorXd::Zero(n),
diagonal_sum_var);
return M;
}
std::vector<std::vector<Matrix2<symbolic::Variable>>>
MathematicalProgram::TightenPsdConstraintToSdd(
const Binding<PositiveSemidefiniteConstraint>& constraint) {
RemoveConstraint(constraint);
// Variables are flattened by the Flatten method, which flattens in
// column-major order. This is the same convention as Eigen, so we can use the
// map methods.
const int n = constraint.evaluator()->matrix_rows();
const MatrixXDecisionVariable mat_vars =
Eigen::Map<const MatrixXDecisionVariable>(constraint.variables().data(),
n, n);
return AddScaledDiagonallyDominantMatrixConstraint(mat_vars);
}
std::vector<Binding<RotatedLorentzConeConstraint>>
MathematicalProgram::AddScaledDiagonallyDominantDualConeMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X) {
const int n = X.rows();
DRAKE_DEMAND(X.cols() == n);
std::vector<Binding<RotatedLorentzConeConstraint>> ret;
ret.reserve(n);
// if i ≥ j
for (int i = 0; i < n; ++i) {
// VᵢⱼᵀXVᵢⱼ = [[Xᵢᵢ, Xᵢⱼ],[Xᵢⱼ,Xⱼⱼ]] and this matrix is PSD if an only if
// Xᵢᵢ ≥ 0, Xⱼⱼ ≥ 0, and XᵢᵢXⱼⱼ - XᵢⱼXᵢⱼ >= 0. Notice that if i == j, this
// is simply that Xᵢᵢ ≥ 0 and so we don't need to include the Xᵢᵢ ≥ 0 as it
// is already added when i ≠ j.
for (int j = i + 1; j < n; ++j) {
// VᵢⱼᵀXVᵢⱼ = [[Xᵢᵢ, Xᵢⱼ],[Xᵢⱼ,Xⱼⱼ]]. Since we already imposed that Xᵢᵢ ≥
// 0 and Xⱼⱼ ≥ 0, we only have to impose that XᵢᵢXⱼⱼ - XᵢⱼXᵢⱼ >= 0 which
// can be
ret.push_back(
AddRotatedLorentzConeConstraint(Vector3<symbolic::Expression>(
X(i, i), X(j, j), 0.5 * (X(i, j) + X(j, i)))));
}
}
return ret;
}
std::vector<Binding<RotatedLorentzConeConstraint>>
MathematicalProgram::AddScaledDiagonallyDominantDualConeMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X) {
return AddScaledDiagonallyDominantDualConeMatrixConstraint(
X.cast<Expression>());
}
std::vector<Binding<RotatedLorentzConeConstraint>>
MathematicalProgram::RelaxPsdConstraintToSddDualCone(
const Binding<PositiveSemidefiniteConstraint>& constraint) {
RemoveConstraint(constraint);
// Variables are flattened by the Flatten method, which flattens in
// column-major order. This is the same convention as Eigen, so we can use the
// map methods.
const int n = constraint.evaluator()->matrix_rows();
const MatrixXDecisionVariable mat_vars =
Eigen::Map<const MatrixXDecisionVariable>(constraint.variables().data(),
n, n);
return AddScaledDiagonallyDominantDualConeMatrixConstraint(mat_vars);
}
Binding<ExponentialConeConstraint> MathematicalProgram::AddConstraint(
const Binding<ExponentialConeConstraint>& binding) {
DRAKE_DEMAND(CheckBinding(binding));
required_capabilities_.insert(ProgramAttribute::kExponentialConeConstraint);
exponential_cone_constraints_.push_back(binding);
return exponential_cone_constraints_.back();
}
Binding<ExponentialConeConstraint>
MathematicalProgram::AddExponentialConeConstraint(
const Eigen::Ref<const Eigen::SparseMatrix<double>>& A,
const Eigen::Ref<const Eigen::Vector3d>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
auto constraint = std::make_shared<ExponentialConeConstraint>(A, b);
return AddConstraint(constraint, vars);
}
Binding<ExponentialConeConstraint>
MathematicalProgram::AddExponentialConeConstraint(
const Eigen::Ref<const Vector3<symbolic::Expression>>& z) {
Eigen::MatrixXd A{};
Eigen::VectorXd b(3);
VectorXDecisionVariable vars{};
symbolic::DecomposeAffineExpressions(z, &A, &b, &vars);
return AddExponentialConeConstraint(A.sparseView(), Eigen::Vector3d(b), vars);
}
std::vector<Binding<Cost>> MathematicalProgram::GetAllCosts() const {
auto costlist = generic_costs_;
costlist.insert(costlist.end(), linear_costs_.begin(), linear_costs_.end());
costlist.insert(costlist.end(), quadratic_costs_.begin(),
quadratic_costs_.end());
costlist.insert(costlist.end(), l2norm_costs_.begin(), l2norm_costs_.end());
return costlist;
}
std::vector<Binding<LinearConstraint>>
MathematicalProgram::GetAllLinearConstraints() const {
std::vector<Binding<LinearConstraint>> conlist = linear_constraints_;
conlist.insert(conlist.end(), linear_equality_constraints_.begin(),
linear_equality_constraints_.end());
return conlist;
}
std::vector<Binding<Constraint>> MathematicalProgram::GetAllConstraints()
const {
std::vector<Binding<Constraint>> conlist = generic_constraints_;
auto extend = [&conlist](auto container) {
conlist.insert(conlist.end(), container.begin(), container.end());
};
extend(quadratic_constraints_);
extend(linear_constraints_);
extend(linear_equality_constraints_);
extend(bbox_constraints_);
extend(lorentz_cone_constraint_);
extend(rotated_lorentz_cone_constraint_);
extend(linear_matrix_inequality_constraint_);
extend(positive_semidefinite_constraint_);
extend(linear_complementarity_constraints_);
extend(exponential_cone_constraints_);
return conlist;
}
int MathematicalProgram::FindDecisionVariableIndex(const Variable& var) const {
auto it = decision_variable_index_.find(var.get_id());
if (it == decision_variable_index_.end()) {
ostringstream oss;
oss << var
<< " is not a decision variable in the mathematical program, "
"when calling FindDecisionVariableIndex.\n";
throw runtime_error(oss.str());
}
return it->second;
}
std::vector<int> MathematicalProgram::FindDecisionVariableIndices(
const Eigen::Ref<const VectorXDecisionVariable>& vars) const {
std::vector<int> x_indices(vars.rows());
for (int i = 0; i < vars.rows(); ++i) {
x_indices[i] = FindDecisionVariableIndex(vars(i));
}
return x_indices;
}
size_t MathematicalProgram::FindIndeterminateIndex(const Variable& var) const {
auto it = indeterminates_index_.find(var.get_id());
if (it == indeterminates_index_.end()) {
ostringstream oss;
oss << var
<< " is not an indeterminate in the mathematical program, "
"when calling GetSolution.\n";
throw runtime_error(oss.str());
}
return it->second;
}
bool MathematicalProgram::CheckSatisfied(
const Binding<Constraint>& binding,
const Eigen::Ref<const Eigen::VectorXd>& prog_var_vals, double tol) const {
const Eigen::VectorXd vals = GetBindingVariableValues(binding, prog_var_vals);
return binding.evaluator()->CheckSatisfied(vals, tol);
}
bool MathematicalProgram::CheckSatisfied(
const std::vector<Binding<Constraint>>& bindings,
const Eigen::Ref<const Eigen::VectorXd>& prog_var_vals, double tol) const {
for (const auto& b : bindings) {
if (!CheckSatisfied(b, prog_var_vals, tol)) {
return false;
}
}
return true;
}
bool MathematicalProgram::CheckSatisfiedAtInitialGuess(
const Binding<Constraint>& binding, double tol) const {
return CheckSatisfied(binding, x_initial_guess_, tol);
}
bool MathematicalProgram::CheckSatisfiedAtInitialGuess(
const std::vector<Binding<Constraint>>& bindings, double tol) const {
return CheckSatisfied(bindings, x_initial_guess_, tol);
}
namespace {
// Body of MathematicalProgram::AddSosConstraint(const symbolic::Polynomial&,
// const Eigen::Ref<const VectorX<symbolic::Monomial>>&).
MatrixXDecisionVariable DoAddSosConstraint(
MathematicalProgram* const prog, const symbolic::Polynomial& p,
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
MathematicalProgram::NonnegativePolynomial type,
const std::string& gram_name) {
const auto pair = prog->NewSosPolynomial(monomial_basis, type, gram_name);
const symbolic::Polynomial& sos_poly{pair.first};
const MatrixXDecisionVariable& Q{pair.second};
const symbolic::Polynomial poly_diff = sos_poly - p;
for (const auto& term : poly_diff.monomial_to_coefficient_map()) {
prog->AddLinearEqualityConstraint(term.second, 0);
}
return Q;
}
// Body of MathematicalProgram::AddSosConstraint(const symbolic::Polynomial&).
pair<MatrixXDecisionVariable, VectorX<symbolic::Monomial>> DoAddSosConstraint(
MathematicalProgram* const prog, const symbolic::Polynomial& p,
MathematicalProgram::NonnegativePolynomial type,
const std::string& gram_name) {
const symbolic::Polynomial p_expanded = p.Expand();
const VectorX<symbolic::Monomial> m = ConstructMonomialBasis(p_expanded);
const MatrixXDecisionVariable Q =
prog->AddSosConstraint(p_expanded, m, type, gram_name);
return std::make_pair(Q, m);
}
} // namespace
MatrixXDecisionVariable MathematicalProgram::AddSosConstraint(
const symbolic::Polynomial& p,
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
MathematicalProgram::NonnegativePolynomial type,
const std::string& gram_name) {
const Variables indeterminates_vars{indeterminates()};
if (Variables(p.indeterminates()).IsSubsetOf(indeterminates_vars) &&
intersect(indeterminates_vars, Variables(p.decision_variables()))
.empty()) {
return DoAddSosConstraint(this, p, monomial_basis, type, gram_name);
} else {
// Need to reparse p, we first make a copy of p and reparse that.
symbolic::Polynomial p_reparsed{p};
Reparse(&p_reparsed);
return DoAddSosConstraint(this, p_reparsed, monomial_basis, type,
gram_name);
}
}
pair<MatrixXDecisionVariable, VectorX<symbolic::Monomial>>
MathematicalProgram::AddSosConstraint(
const symbolic::Polynomial& p,
MathematicalProgram::NonnegativePolynomial type,
const std::string& gram_name) {
const Variables indeterminates_vars{indeterminates()};
if (Variables(p.indeterminates()).IsSubsetOf(indeterminates_vars) &&
intersect(indeterminates_vars, Variables(p.decision_variables()))
.empty()) {
return DoAddSosConstraint(this, p, type, gram_name);
} else {
// Need to reparse p, we first make a copy of p and reparse that.
symbolic::Polynomial p_reparsed{p};
Reparse(&p_reparsed);
return DoAddSosConstraint(this, p_reparsed, type, gram_name);
}
}
MatrixXDecisionVariable MathematicalProgram::AddSosConstraint(
const symbolic::Expression& e,
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
MathematicalProgram::NonnegativePolynomial type,
const std::string& gram_name) {
return AddSosConstraint(
symbolic::Polynomial{e, symbolic::Variables{this->indeterminates()}},
monomial_basis, type, gram_name);
}
pair<MatrixXDecisionVariable, VectorX<symbolic::Monomial>>
MathematicalProgram::AddSosConstraint(
const symbolic::Expression& e,
MathematicalProgram::NonnegativePolynomial type,
const std::string& gram_name) {
return AddSosConstraint(
symbolic::Polynomial{e, symbolic::Variables{this->indeterminates()}},
type, gram_name);
}
std::vector<Binding<LinearEqualityConstraint>>
MathematicalProgram::AddEqualityConstraintBetweenPolynomials(
const symbolic::Polynomial& p1, const symbolic::Polynomial& p2) {
symbolic::Polynomial poly_diff = p1 - p2;
Reparse(&poly_diff);
std::vector<Binding<LinearEqualityConstraint>> ret;
for (const auto& item : poly_diff.monomial_to_coefficient_map()) {
ret.push_back(AddLinearEqualityConstraint(item.second, 0));
}
return ret;
}
double MathematicalProgram::GetInitialGuess(
const symbolic::Variable& decision_variable) const {
return x_initial_guess_[FindDecisionVariableIndex(decision_variable)];
}
void MathematicalProgram::SetInitialGuess(
const symbolic::Variable& decision_variable, double variable_guess_value) {
x_initial_guess_(FindDecisionVariableIndex(decision_variable)) =
variable_guess_value;
}
void MathematicalProgram::SetDecisionVariableValueInVector(
const symbolic::Variable& decision_variable,
double decision_variable_new_value,
EigenPtr<Eigen::VectorXd> values) const {
DRAKE_THROW_UNLESS(values != nullptr);
DRAKE_THROW_UNLESS(values->size() == num_vars());
const int index = FindDecisionVariableIndex(decision_variable);
(*values)(index) = decision_variable_new_value;
}
void MathematicalProgram::SetDecisionVariableValueInVector(
const Eigen::Ref<const MatrixXDecisionVariable>& decision_variables,
const Eigen::Ref<const Eigen::MatrixXd>& decision_variables_new_values,
EigenPtr<Eigen::VectorXd> values) const {
DRAKE_THROW_UNLESS(values != nullptr);
DRAKE_THROW_UNLESS(values->size() == num_vars());
DRAKE_THROW_UNLESS(decision_variables.rows() ==
decision_variables_new_values.rows());
DRAKE_THROW_UNLESS(decision_variables.cols() ==
decision_variables_new_values.cols());
for (int i = 0; i < decision_variables.rows(); ++i) {
for (int j = 0; j < decision_variables.cols(); ++j) {
const int index = FindDecisionVariableIndex(decision_variables(i, j));
(*values)(index) = decision_variables_new_values(i, j);
}
}
}
void MathematicalProgram::AppendNanToEnd(int new_var_size, Eigen::VectorXd* v) {
v->conservativeResize(v->rows() + new_var_size);
v->tail(new_var_size).fill(std::numeric_limits<double>::quiet_NaN());
}
void MathematicalProgram::EvalVisualizationCallbacks(
const Eigen::Ref<const Eigen::VectorXd>& prog_var_vals) const {
if (prog_var_vals.rows() != num_vars()) {
std::ostringstream oss;
oss << "The input binding variable is not in the right size. Expects "
<< num_vars() << " rows, but it actually has " << prog_var_vals.rows()
<< " rows.\n";
throw std::logic_error(oss.str());
}
Eigen::VectorXd this_x;
for (auto const& binding : visualization_callbacks_) {
auto const& obj = binding.evaluator();
const int num_v_variables = binding.GetNumElements();
this_x.resize(num_v_variables);
for (int j = 0; j < num_v_variables; ++j) {
this_x(j) =
prog_var_vals(FindDecisionVariableIndex(binding.variables()(j)));
}
obj->EvalCallback(this_x);
}
}
void MathematicalProgram::SetVariableScaling(const symbolic::Variable& var,
double s) {
DRAKE_DEMAND(0 < s);
int idx = FindDecisionVariableIndex(var);
if (var_scaling_map_.find(idx) != var_scaling_map_.end()) {
// Update the scaling factor
var_scaling_map_[idx] = s;
} else {
// Add a new scaling factor
var_scaling_map_.insert(std::pair<int, double>(idx, s));
}
}
namespace {
template <typename C>
[[nodiscard]] bool IsVariableBound(const symbolic::Variable& var,
const std::vector<Binding<C>>& bindings,
std::string* binding_description) {
for (const auto& binding : bindings) {
if (binding.ContainsVariable(var)) {
*binding_description = binding.to_string();
return true;
}
}
return false;
}
// Return true if the variable is bound with a cost or constraint (except for a
// bounding box constraint); false otherwise.
[[nodiscard]] bool IsVariableBound(const symbolic::Variable& var,
const MathematicalProgram& prog,
std::string* binding_description) {
if (IsVariableBound(var, prog.GetAllCosts(), binding_description)) {
return true;
}
if (IsVariableBound(var, prog.GetAllConstraints(), binding_description)) {
return true;
}
if (IsVariableBound(var, prog.visualization_callbacks(),
binding_description)) {
return true;
}
return false;
}
} // namespace
int MathematicalProgram::RemoveDecisionVariable(const symbolic::Variable& var) {
if (decision_variable_index_.count(var.get_id()) == 0) {
throw std::invalid_argument(
fmt::format("RemoveDecisionVariable: {} is not a decision variable of "
"this MathematicalProgram.",
var.get_name()));
}
std::string binding_description;
if (IsVariableBound(var, *this, &binding_description)) {
throw std::invalid_argument(
fmt::format("RemoveDecisionVariable: {} is associated with a {}.",
var.get_name(), binding_description));
}
const auto var_it = decision_variable_index_.find(var.get_id());
const int var_index = var_it->second;
// Update decision_variable_index_.
decision_variable_index_.erase(var_it);
for (auto& [variable_id, variable_index] : decision_variable_index_) {
// Decrement the index of the variable after `var`.
if (variable_index > var_index) {
--variable_index;
}
}
// Remove the variable from decision_variables_.
decision_variables_.erase(decision_variables_.begin() + var_index);
// Remove from var_scaling_map_.
std::unordered_map<int, double> new_var_scaling_map;
for (const auto& [variable_index, scale] : var_scaling_map_) {
if (variable_index < var_index) {
new_var_scaling_map.emplace(variable_index, scale);
} else if (variable_index > var_index) {
new_var_scaling_map.emplace(variable_index - 1, scale);
}
}
var_scaling_map_ = std::move(new_var_scaling_map);
// Update x_initial_guess_;
for (int i = var_index; i < x_initial_guess_.rows() - 1; ++i) {
x_initial_guess_(i) = x_initial_guess_(i + 1);
}
x_initial_guess_.conservativeResize(x_initial_guess_.rows() - 1);
return var_index;
}
template <typename C>
int MathematicalProgram::RemoveCostOrConstraintImpl(
const Binding<C>& removal, ProgramAttribute affected_capability,
std::vector<Binding<C>>* existings) {
const int num_existing = static_cast<int>(existings->size());
existings->erase(std::remove(existings->begin(), existings->end(), removal),
existings->end());
UpdateRequiredCapability(affected_capability);
const int num_removed = num_existing - static_cast<int>(existings->size());
return num_removed;
}
namespace {
// Update @p program_capabilities. If @p binding is empty, then remove @p
// capability from @p program_capabilities; otherwise add @p capability to @p
// program_capabilities.
template <typename C>
void UpdateRequiredCapabilityImpl(ProgramAttribute capability,
const std::vector<C>& bindings,
ProgramAttributes* program_capabilities) {
if (bindings.empty()) {
// erasing a non-existent key doesn't cause an error.
program_capabilities->erase(capability);
} else {
program_capabilities->emplace(capability);
}
}
} // namespace
void MathematicalProgram::UpdateRequiredCapability(
ProgramAttribute query_capability) {
switch (query_capability) {
case ProgramAttribute::kLinearCost: {
UpdateRequiredCapabilityImpl(query_capability, this->linear_costs(),
&required_capabilities_);
break;
}
case ProgramAttribute::kQuadraticCost: {
UpdateRequiredCapabilityImpl(query_capability, this->quadratic_costs(),
&required_capabilities_);
break;
}
case ProgramAttribute::kGenericCost: {
UpdateRequiredCapabilityImpl(query_capability, this->generic_costs(),
&required_capabilities_);
break;
}
case ProgramAttribute::kGenericConstraint: {
UpdateRequiredCapabilityImpl(query_capability,
this->generic_constraints(),
&required_capabilities_);
break;
}
case ProgramAttribute::kLinearConstraint: {
if (this->linear_constraints().empty() &&
this->bounding_box_constraints().empty()) {
required_capabilities_.erase(ProgramAttribute::kLinearConstraint);
} else {
required_capabilities_.emplace(ProgramAttribute::kLinearConstraint);
}
break;
}
case ProgramAttribute::kLinearEqualityConstraint: {
UpdateRequiredCapabilityImpl(query_capability,
this->linear_equality_constraints(),
&required_capabilities_);
break;
}
case ProgramAttribute::kLinearComplementarityConstraint: {
UpdateRequiredCapabilityImpl(query_capability,
this->linear_complementarity_constraints(),
&required_capabilities_);
break;
}
case ProgramAttribute::kLorentzConeConstraint: {
UpdateRequiredCapabilityImpl(query_capability,
this->lorentz_cone_constraints(),
&required_capabilities_);
break;
}
case ProgramAttribute::kRotatedLorentzConeConstraint: {
UpdateRequiredCapabilityImpl(query_capability,
this->rotated_lorentz_cone_constraints(),
&required_capabilities_);
break;
}
case ProgramAttribute::kPositiveSemidefiniteConstraint: {
if (positive_semidefinite_constraint_.empty() &&
linear_matrix_inequality_constraint_.empty()) {
required_capabilities_.erase(
ProgramAttribute::kPositiveSemidefiniteConstraint);
} else {
required_capabilities_.emplace(
ProgramAttribute::kPositiveSemidefiniteConstraint);
}
break;
}
case ProgramAttribute::kExponentialConeConstraint: {
UpdateRequiredCapabilityImpl(query_capability,
this->exponential_cone_constraints(),
&required_capabilities_);
break;
}
case ProgramAttribute::kQuadraticConstraint: {
UpdateRequiredCapabilityImpl(query_capability,
this->quadratic_constraints(),
&required_capabilities_);
break;
}
case ProgramAttribute::kL2NormCost: {
UpdateRequiredCapabilityImpl(query_capability, this->l2norm_costs(),
&required_capabilities_);
break;
}
case ProgramAttribute::kBinaryVariable: {
bool has_binary_var = false;
for (int i = 0; i < num_vars(); ++i) {
if (decision_variables_[i].get_type() ==
symbolic::Variable::Type::BINARY) {
has_binary_var = true;
break;
}
}
if (has_binary_var) {
required_capabilities_.emplace(ProgramAttribute::kBinaryVariable);
} else {
required_capabilities_.erase(ProgramAttribute::kBinaryVariable);
}
break;
}
case ProgramAttribute::kCallback: {
UpdateRequiredCapabilityImpl(query_capability, visualization_callbacks_,
&required_capabilities_);
break;
}
}
}
int MathematicalProgram::RemoveCost(const Binding<Cost>& cost) {
Cost* cost_evaluator = cost.evaluator().get();
// TODO(hongkai.dai): Remove the dynamic cast as part of #8349.
if (dynamic_cast<QuadraticCost*>(cost_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<QuadraticCost>(cost),
ProgramAttribute::kQuadraticCost, &(this->quadratic_costs_));
} else if (dynamic_cast<LinearCost*>(cost_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<LinearCost>(cost),
ProgramAttribute::kLinearCost, &(this->linear_costs_));
} else if (dynamic_cast<L2NormCost*>(cost_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<L2NormCost>(cost),
ProgramAttribute::kL2NormCost, &(this->l2norm_costs_));
} else {
return RemoveCostOrConstraintImpl(cost, ProgramAttribute::kGenericCost,
&(this->generic_costs_));
}
DRAKE_UNREACHABLE();
}
int MathematicalProgram::RemoveConstraint(
const Binding<Constraint>& constraint) {
Constraint* constraint_evaluator = constraint.evaluator().get();
// TODO(hongkai.dai): Remove the dynamic cast as part of #8349.
// Check constraints types in reverse order, such that classes that inherit
// from other classes will not be prematurely added to less specific (or
// incorrect) container.
if (dynamic_cast<ExponentialConeConstraint*>(constraint_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<ExponentialConeConstraint>(constraint),
ProgramAttribute::kExponentialConeConstraint,
&exponential_cone_constraints_);
} else if (dynamic_cast<LinearMatrixInequalityConstraint*>(
constraint_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<LinearMatrixInequalityConstraint>(
constraint),
ProgramAttribute::kPositiveSemidefiniteConstraint,
&linear_matrix_inequality_constraint_);
} else if (dynamic_cast<PositiveSemidefiniteConstraint*>(
constraint_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<PositiveSemidefiniteConstraint>(
constraint),
ProgramAttribute::kPositiveSemidefiniteConstraint,
&positive_semidefinite_constraint_);
} else if (dynamic_cast<QuadraticConstraint*>(constraint_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<QuadraticConstraint>(constraint),
ProgramAttribute::kQuadraticConstraint, &quadratic_constraints_);
} else if (dynamic_cast<RotatedLorentzConeConstraint*>(
constraint_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<RotatedLorentzConeConstraint>(constraint),
ProgramAttribute::kRotatedLorentzConeConstraint,
&rotated_lorentz_cone_constraint_);
} else if (dynamic_cast<LorentzConeConstraint*>(constraint_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<LorentzConeConstraint>(constraint),
ProgramAttribute::kLorentzConeConstraint, &lorentz_cone_constraint_);
} else if (dynamic_cast<LinearComplementarityConstraint*>(
constraint_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<LinearComplementarityConstraint>(
constraint),
ProgramAttribute::kLinearComplementarityConstraint,
&linear_complementarity_constraints_);
} else if (dynamic_cast<LinearEqualityConstraint*>(constraint_evaluator)) {
// LinearEqualityConstraint is derived from LinearConstraint. Put this
// branch before the LinearConstraint branch.
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<LinearEqualityConstraint>(constraint),
ProgramAttribute::kLinearEqualityConstraint,
&linear_equality_constraints_);
} else if (dynamic_cast<BoundingBoxConstraint*>(constraint_evaluator)) {
// BoundingBoxConstraint is derived from LinearConstraint. Put this branch
// before the LinearConstraint branch.
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<BoundingBoxConstraint>(constraint),
ProgramAttribute::kLinearConstraint, &bbox_constraints_);
} else if (dynamic_cast<LinearConstraint*>(constraint_evaluator)) {
return RemoveCostOrConstraintImpl(
internal::BindingDynamicCast<LinearConstraint>(constraint),
ProgramAttribute::kLinearConstraint, &linear_constraints_);
} else {
// All constraints are derived from Constraint class. Put this branch last.
return RemoveCostOrConstraintImpl(constraint,
ProgramAttribute::kGenericConstraint,
&generic_constraints_);
}
DRAKE_UNREACHABLE();
}
int MathematicalProgram::RemoveVisualizationCallback(
const Binding<VisualizationCallback>& callback) {
return RemoveCostOrConstraintImpl(callback, ProgramAttribute::kCallback,
&visualization_callbacks_);
}
void MathematicalProgram::CheckVariableType(VarType var_type) {
switch (var_type) {
case VarType::CONTINUOUS:
break;
case VarType::BINARY:
required_capabilities_.insert(ProgramAttribute::kBinaryVariable);
break;
case VarType::INTEGER:
throw std::runtime_error(
"MathematicalProgram does not support integer variables yet.");
case VarType::BOOLEAN:
throw std::runtime_error(
"MathematicalProgram does not support Boolean variables.");
case VarType::RANDOM_UNIFORM:
throw std::runtime_error(
"MathematicalProgram does not support random uniform variables.");
case VarType::RANDOM_GAUSSIAN:
throw std::runtime_error(
"MathematicalProgram does not support random Gaussian variables.");
case VarType::RANDOM_EXPONENTIAL:
throw std::runtime_error(
"MathematicalProgram does not support random exponential "
"variables.");
}
}
void MathematicalProgram::CheckIsDecisionVariable(
const VectorXDecisionVariable& vars) const {
for (int i = 0; i < vars.rows(); ++i) {
for (int j = 0; j < vars.cols(); ++j) {
if (!decision_variable_index_.contains(vars(i, j).get_id())) {
throw std::logic_error(fmt::format(
"{} is not a decision variable of the mathematical program.",
vars(i, j)));
}
}
}
}
template <typename C>
bool MathematicalProgram::CheckBinding(const Binding<C>& binding) const {
// TODO(eric.cousineau): In addition to identifiers, hash bindings by
// their constraints and their variables, to prevent duplicates.
// TODO(eric.cousineau): Once bindings have identifiers (perhaps
// retrofitting `description`), ensure that they have unique names.
CheckIsDecisionVariable(binding.variables());
return (binding.evaluator()->num_outputs() > 0);
}
std::ostream& operator<<(std::ostream& os, const MathematicalProgram& prog) {
if (prog.num_vars() > 0) {
os << fmt::format("Decision variables: {}\n\n",
fmt_eigen(prog.decision_variables().transpose()));
} else {
os << "No decision variables.\n";
}
if (prog.num_indeterminates() > 0) {
os << fmt::format("Indeterminates: {}\n\n",
fmt_eigen(prog.indeterminates().transpose()));
}
for (const auto& b : prog.GetAllCosts()) {
os << b << "\n";
}
for (const auto& b : prog.GetAllConstraints()) {
os << b;
}
return os;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/snopt_solver_common.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/snopt_solver.h"
/* clang-format on */
#include "drake/common/never_destroyed.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
SnoptSolver::SnoptSolver()
: SolverBase(id(), &is_available, &is_enabled,
&ProgramAttributesSatisfied) {}
SnoptSolver::~SnoptSolver() = default;
SolverId SnoptSolver::id() {
static const never_destroyed<SolverId> singleton{"SNOPT"};
return singleton.access();
}
bool SnoptSolver::is_enabled() {
const char* snopt_solver_enabled = std::getenv("DRAKE_SNOPT_SOLVER_ENABLED");
if (snopt_solver_enabled == nullptr) {
return true;
}
return (std::string(snopt_solver_enabled) != "0");
}
bool SnoptSolver::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::kLinearComplementarityConstraint,
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 | /home/johnshepherd/drake/solvers/no_nlopt.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/nlopt_solver.h"
/* clang-format on */
#include <stdexcept>
namespace drake {
namespace solvers {
bool NloptSolver::is_available() {
return false;
}
void NloptSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&,
const SolverOptions&,
MathematicalProgramResult*) const {
throw std::runtime_error(
"The Nlopt bindings were not compiled. You'll need to use a different "
"solver.");
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/csdp_cpp_wrapper.cc | #include "drake/solvers/csdp_cpp_wrapper.h"
#include <stdexcept>
#include "drake/solvers/csdp_solver_error_handling.h"
// We must call this macro immediately prior to *any* call into CSDP.
#define DRAKE_CSDP_SETJMP() \
do { \
std::jmp_buf& env = get_per_thread_csdp_jmp_buf(); \
if (setjmp(env) > 0) { \
throw std::runtime_error( \
"CsdpSolver: the CSDP library exited via a fatal exception"); \
} \
} while (0)
namespace drake {
namespace solvers {
namespace internal {
namespace csdp {
extern "C" {
#include <csdp/declarations.h>
} // extern C
int cpp_easy_sdp(const char* params_pathname, int n, int k,
struct blockmatrix C, double* a,
struct constraintmatrix* constraints, double constant_offset,
struct blockmatrix* pX, double** py, struct blockmatrix* pZ,
double* ppobj, double* pdobj) {
DRAKE_CSDP_SETJMP();
return easy_sdp(params_pathname, n, k, C, a, constraints, constant_offset, pX,
py, pZ, ppobj, pdobj);
}
void cpp_free_mat(struct blockmatrix A) {
DRAKE_CSDP_SETJMP();
free_mat(A);
}
void cpp_free_prob(int n, int k, struct blockmatrix C, double* a,
struct constraintmatrix* constraints, struct blockmatrix X,
double* y, struct blockmatrix Z) {
DRAKE_CSDP_SETJMP();
free_prob(n, k, C, a, constraints, X, y, Z);
}
void cpp_initsoln(int n, int k, struct blockmatrix C, double* a,
struct constraintmatrix* constraints, struct blockmatrix* pX0,
double** py0, struct blockmatrix* pZ0) {
DRAKE_CSDP_SETJMP();
initsoln(n, k, C, a, constraints, pX0, py0, pZ0);
}
} // namespace csdp
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/nlopt_solver.cc | #include "drake/solvers/nlopt_solver.h"
#include <algorithm>
#include <limits>
#include <list>
#include <set>
#include <stdexcept>
#include <unordered_map>
#include <vector>
#include <nlopt.hpp>
#include "drake/common/autodiff.h"
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
#include "drake/common/unused.h"
#include "drake/math/autodiff.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
namespace {
Eigen::VectorXd MakeEigenVector(const std::vector<double>& x) {
Eigen::VectorXd xvec(x.size());
for (size_t i = 0; i < x.size(); i++) {
xvec[i] = x[i];
}
return xvec;
}
AutoDiffVecXd MakeInputAutoDiffVec(const MathematicalProgram& prog,
const Eigen::VectorXd& xvec,
const VectorXDecisionVariable& vars) {
const int num_vars = vars.rows();
auto tx = math::InitializeAutoDiff(xvec);
AutoDiffVecXd this_x(num_vars);
for (int i = 0; i < num_vars; ++i) {
this_x(i) = tx(prog.FindDecisionVariableIndex(vars(i)));
}
return this_x;
}
// This function meets the signature requirements for nlopt::vfunc as
// described in
// http://ab-initio.mit.edu/wiki/index.php/NLopt_C-plus-plus_Reference#Objective_function
// Note : NLopt uses the term "Objective" which corresponds to the Drake usage
// of "Cost".
// TODO(#2274) Fix NOLINTNEXTLINE(runtime/references).
double EvaluateCosts(const std::vector<double>& x, std::vector<double>& grad,
void* f_data) {
const MathematicalProgram* prog =
reinterpret_cast<const MathematicalProgram*>(f_data);
double cost = 0;
Eigen::VectorXd xvec = MakeEigenVector(x);
prog->EvalVisualizationCallbacks(xvec);
auto tx = math::InitializeAutoDiff(xvec);
AutoDiffVecXd ty(1);
AutoDiffVecXd this_x;
if (!grad.empty()) {
grad.assign(grad.size(), 0);
}
for (auto const& binding : prog->GetAllCosts()) {
int num_vars = binding.GetNumElements();
this_x.resize(num_vars);
for (int i = 0; i < num_vars; ++i) {
this_x(i) = tx(prog->FindDecisionVariableIndex(binding.variables()(i)));
}
binding.evaluator()->Eval(this_x, &ty);
cost += ty(0).value();
if (!grad.empty()) {
if (ty(0).derivatives().size() > 0) {
for (int j = 0; j < num_vars; ++j) {
const size_t vj_index =
prog->FindDecisionVariableIndex(binding.variables()(j));
grad[vj_index] += ty(0).derivatives()(vj_index);
}
}
}
}
return cost;
}
/// Structure to marshall data into the NLopt callback functions,
/// which take only a single pointer argument.
struct WrappedConstraint {
WrappedConstraint(const Constraint* constraint_in,
const VectorXDecisionVariable* vars_in,
const MathematicalProgram* prog_in)
: constraint(constraint_in),
vars(vars_in),
prog(prog_in),
force_bounds(false),
force_upper(false) {}
const Constraint* constraint;
const VectorXDecisionVariable* vars;
const MathematicalProgram* prog;
bool force_bounds; ///< force usage of only upper or lower bounds
bool force_upper; ///< Only used if force_bounds is set. Selects
///< which bounds are being tested (lower bound
///< vs. upper bound).
// TODO(sam.creasey) It might be desirable to have a cache for the
// result of evaluating the constraints if NLopt were being used in
// a situation where constraints were frequently being wrapped in
// such a way as to result in multiple evaluations. As this is a
// speculative case, and since NLopt's roundoff issues with
// duplicate constraints preclude it from being used in some
// scenarios, I'm not implementing such a cache at this time.
std::set<size_t> active_constraints;
};
double ApplyConstraintBounds(double result, double lb, double ub) {
// Our (Drake's) constraints are expressed in the form lb <= f(x) <=
// ub. NLopt always wants the value of a constraint expressed as
// f(x) <= 0.
//
// For upper bounds rewrite as: f(x) - ub <= 0
// For lower bounds rewrite as: -f(x) + lb <= 0
//
// If both upper and lower bounds are set, default to evaluating the
// upper bound, and switch to the lower bound only if it's being
// exceeded.
//
// See
// http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Nonlinear_constraints
// for more detail on how NLopt interprets return values.
if ((ub != std::numeric_limits<double>::infinity()) &&
((result >= lb) || (lb == ub))) {
result -= ub;
} else {
if (lb == -std::numeric_limits<double>::infinity()) {
throw std::runtime_error("Unable to handle constraint with no bounds.");
}
result *= -1;
result += lb;
}
return result;
}
// This function meets the signature of nlopt_mfunc as described in
// http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Vector-valued_constraints
void EvaluateVectorConstraint(unsigned m, double* result, unsigned n,
const double* x, double* grad, void* f_data) {
const WrappedConstraint* wrapped =
reinterpret_cast<WrappedConstraint*>(f_data);
Eigen::VectorXd xvec(n);
for (size_t i = 0; i < n; i++) {
xvec[i] = x[i];
}
// http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Vector-valued_constraints
// explicitly tells us that it's allocated m * n array elements
// before invoking this function. It does not seem to have been
// zeroed, and not all constraints will store gradients for all
// decision variables (so don't leave junk in the other array
// elements).
if (grad) {
memset(grad, 0, sizeof(double) * m * n);
}
const Constraint* c = wrapped->constraint;
const int num_constraints = c->num_constraints();
DRAKE_ASSERT(num_constraints >= static_cast<int>(m));
DRAKE_ASSERT(wrapped->active_constraints.size() == m);
AutoDiffVecXd ty(num_constraints);
AutoDiffVecXd this_x =
MakeInputAutoDiffVec(*(wrapped->prog), xvec, *(wrapped->vars));
c->Eval(this_x, &ty);
const Eigen::VectorXd& lower_bound = c->lower_bound();
const Eigen::VectorXd& upper_bound = c->upper_bound();
size_t result_idx = 0;
for (int i = 0; i < num_constraints; i++) {
if (!wrapped->active_constraints.contains(i)) {
continue;
}
if (wrapped->force_bounds && wrapped->force_upper &&
(upper_bound(i) != std::numeric_limits<double>::infinity())) {
result[result_idx] = ApplyConstraintBounds(
ty(i).value(), -std::numeric_limits<double>::infinity(),
upper_bound(i));
} else if (wrapped->force_bounds && !wrapped->force_upper &&
(lower_bound(i) != -std::numeric_limits<double>::infinity())) {
result[result_idx] =
ApplyConstraintBounds(ty(i).value(), lower_bound(i),
std::numeric_limits<double>::infinity());
} else {
result[result_idx] =
ApplyConstraintBounds(ty(i).value(), lower_bound(i), upper_bound(i));
}
result_idx++;
DRAKE_ASSERT(result_idx <= m);
}
if (grad) {
result_idx = 0;
const int num_v_variable = wrapped->vars->rows();
std::vector<size_t> v_index(num_v_variable);
for (int i = 0; i < num_v_variable; ++i) {
v_index[i] =
wrapped->prog->FindDecisionVariableIndex((*wrapped->vars)(i));
}
for (int i = 0; i < num_constraints; i++) {
if (!wrapped->active_constraints.contains(i)) {
continue;
}
double grad_sign = 1;
if (c->upper_bound()(i) == std::numeric_limits<double>::infinity()) {
grad_sign = -1;
} else if (wrapped->force_bounds && !wrapped->force_upper) {
grad_sign = -1;
}
DRAKE_ASSERT(wrapped->vars->cols() == 1);
if (ty(i).derivatives().size() > 0) {
for (int j = 0; j < wrapped->vars->rows(); ++j) {
grad[(result_idx * n) + v_index[j]] =
ty(i).derivatives()(v_index[j]) * grad_sign;
}
}
result_idx++;
DRAKE_ASSERT(result_idx <= m);
}
DRAKE_ASSERT(result_idx == m);
}
}
template <typename C>
void WrapConstraint(const MathematicalProgram& prog, const Binding<C>& binding,
double constraint_tol, nlopt::opt* opt,
std::list<WrappedConstraint>* wrapped_list) {
// Version of the wrapped constraint which refers only to equality
// constraints (if any), and will be used with
// add_equality_mconstraint.
WrappedConstraint wrapped_eq(binding.evaluator().get(), &binding.variables(),
&prog);
// Version of the wrapped constraint which refers only to inequality
// constraints (if any), and will be used with
// add_equality_mconstraint.
WrappedConstraint wrapped_in(binding.evaluator().get(), &binding.variables(),
&prog);
bool is_pure_inequality = true;
const Eigen::VectorXd& lower_bound = binding.evaluator()->lower_bound();
const Eigen::VectorXd& upper_bound = binding.evaluator()->upper_bound();
DRAKE_ASSERT(lower_bound.size() == upper_bound.size());
for (size_t i = 0; i < static_cast<size_t>(lower_bound.size()); i++) {
if (lower_bound(i) == upper_bound(i)) {
wrapped_eq.active_constraints.insert(i);
} else {
if ((lower_bound(i) != -std::numeric_limits<double>::infinity()) &&
(upper_bound(i) != std::numeric_limits<double>::infinity())) {
is_pure_inequality = false;
}
wrapped_in.active_constraints.insert(i);
}
}
if (wrapped_eq.active_constraints.size()) {
wrapped_list->push_back(wrapped_eq);
std::vector<double> tol(wrapped_eq.active_constraints.size(),
constraint_tol);
opt->add_equality_mconstraint(EvaluateVectorConstraint,
&wrapped_list->back(), tol);
}
if (wrapped_in.active_constraints.size()) {
std::vector<double> tol(wrapped_in.active_constraints.size(),
constraint_tol);
wrapped_list->push_back(wrapped_in);
if (is_pure_inequality) {
opt->add_inequality_mconstraint(EvaluateVectorConstraint,
&wrapped_list->back(), tol);
} else {
wrapped_list->back().force_bounds = true;
wrapped_list->back().force_upper = true;
opt->add_inequality_mconstraint(EvaluateVectorConstraint,
&wrapped_list->back(), tol);
wrapped_list->push_back(wrapped_in);
wrapped_list->back().force_bounds = true;
wrapped_list->back().force_upper = false;
opt->add_inequality_mconstraint(EvaluateVectorConstraint,
&wrapped_list->back(), tol);
}
}
}
template <typename Binding>
bool IsVectorOfConstraintsSatisfiedAtSolution(
const MathematicalProgram& prog, const std::vector<Binding>& bindings,
const Eigen::Ref<const Eigen::VectorXd>& decision_variable_values,
double tol) {
for (const auto& binding : bindings) {
const Eigen::VectorXd constraint_val =
prog.EvalBinding(binding, decision_variable_values);
const int num_constraint = constraint_val.rows();
if (((constraint_val - binding.evaluator()->lower_bound()).array() <
-Eigen::ArrayXd::Constant(num_constraint, tol))
.any() ||
((constraint_val - binding.evaluator()->upper_bound()).array() >
Eigen::ArrayXd::Constant(num_constraint, tol))
.any()) {
return false;
}
}
return true;
}
template <typename T>
T GetOptionValueWithDefault(const std::unordered_map<std::string, T>& options,
const std::string& key, const T& default_value) {
auto it = options.find(key);
if (it == options.end()) {
return default_value;
}
return it->second;
}
nlopt::algorithm GetNloptAlgorithm(const SolverOptions& merged_options) {
const auto& options_str = merged_options.GetOptionsStr(NloptSolver::id());
auto it = options_str.find(NloptSolver::AlgorithmName());
if (it == options_str.end()) {
// Use SLSQP for default;
return nlopt::algorithm::LD_SLSQP;
} else {
const std::string& requested_algorithm = it->second;
for (int i = 0; i < nlopt::algorithm::NUM_ALGORITHMS; ++i) {
if (requested_algorithm ==
nlopt_algorithm_to_string(static_cast<nlopt_algorithm>(i))) {
return static_cast<nlopt::algorithm>(i);
}
}
throw std::runtime_error(fmt::format(
"Unknown NLopt algorithm {}, please check "
"nlopt_algorithm_to_string() function "
"github.com/stevengj/nlopt/blob/master/src/api/general.c for "
"all supported algorithm names",
it->second));
}
}
} // namespace
bool NloptSolver::is_available() {
return true;
}
void NloptSolver::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(
"NloptSolver doesn't support the feature of variable scaling.");
}
const int nx = prog.num_vars();
// Load the algo to use and the size.
const nlopt::algorithm algorithm = GetNloptAlgorithm(merged_options);
nlopt::opt opt(algorithm, nx);
std::vector<double> x(initial_guess.size());
for (size_t i = 0; i < x.size(); i++) {
if (!std::isnan(initial_guess[i])) {
x[i] = initial_guess[i];
} else {
x[i] = 0.0;
}
}
std::vector<double> xlow(nx, -std::numeric_limits<double>::infinity());
std::vector<double> xupp(nx, std::numeric_limits<double>::infinity());
for (auto const& binding : prog.bounding_box_constraints()) {
const auto& c = binding.evaluator();
const auto& lower_bound = c->lower_bound();
const auto& upper_bound = c->upper_bound();
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
const size_t idx = prog.FindDecisionVariableIndex(binding.variables()(k));
xlow[idx] = std::max(lower_bound(k), xlow[idx]);
xupp[idx] = std::min(upper_bound(k), xupp[idx]);
if (x[idx] < xlow[idx]) {
x[idx] = xlow[idx];
}
if (x[idx] > xupp[idx]) {
x[idx] = xupp[idx];
}
}
}
opt.set_lower_bounds(xlow);
opt.set_upper_bounds(xupp);
opt.set_min_objective(EvaluateCosts, const_cast<MathematicalProgram*>(&prog));
const auto& nlopt_options_double = merged_options.GetOptionsDouble(id());
const auto& nlopt_options_int = merged_options.GetOptionsInt(id());
const double constraint_tol = GetOptionValueWithDefault(
nlopt_options_double, ConstraintToleranceName(), 1e-6);
const double xtol_rel = GetOptionValueWithDefault(
nlopt_options_double, XRelativeToleranceName(), 1e-6);
const double xtol_abs = GetOptionValueWithDefault(
nlopt_options_double, XAbsoluteToleranceName(), 1e-6);
const int max_eval =
GetOptionValueWithDefault(nlopt_options_int, MaxEvalName(), 1000);
std::list<WrappedConstraint> wrapped_vector;
// TODO(sam.creasey): Missing test coverage for generic constraints
// with >1 output.
for (const auto& c : prog.generic_constraints()) {
WrapConstraint(prog, c, constraint_tol, &opt, &wrapped_vector);
}
for (const auto& c : prog.quadratic_constraints()) {
WrapConstraint(prog, c, constraint_tol, &opt, &wrapped_vector);
}
for (const auto& c : prog.lorentz_cone_constraints()) {
WrapConstraint(prog, c, constraint_tol, &opt, &wrapped_vector);
}
for (const auto& c : prog.rotated_lorentz_cone_constraints()) {
WrapConstraint(prog, c, constraint_tol, &opt, &wrapped_vector);
}
for (const auto& c : prog.linear_equality_constraints()) {
WrapConstraint(prog, c, constraint_tol, &opt, &wrapped_vector);
}
// TODO(sam.creasey): Missing test coverage for linear constraints
// with >1 output.
for (const auto& c : prog.linear_constraints()) {
WrapConstraint(prog, c, constraint_tol, &opt, &wrapped_vector);
}
opt.set_xtol_rel(xtol_rel);
opt.set_xtol_abs(xtol_abs);
opt.set_maxeval(max_eval);
result->set_solution_result(SolutionResult::kSolutionFound);
NloptSolverDetails& solver_details =
result->SetSolverDetailsType<NloptSolverDetails>();
double minf = 0;
const double kUnboundedTol = -1E30;
try {
const nlopt::result nlopt_result = opt.optimize(x, minf);
solver_details.status = nlopt_result;
if (nlopt_result == nlopt::SUCCESS ||
nlopt_result == nlopt::STOPVAL_REACHED ||
nlopt_result == nlopt::XTOL_REACHED ||
nlopt_result == nlopt::FTOL_REACHED ||
nlopt_result == nlopt::MAXEVAL_REACHED ||
nlopt_result == nlopt::MAXTIME_REACHED) {
result->set_x_val(Eigen::Map<Eigen::VectorXd>(x.data(), nx));
}
switch (nlopt_result) {
case nlopt::SUCCESS:
case nlopt::STOPVAL_REACHED: {
result->set_solution_result(SolutionResult::kSolutionFound);
break;
}
case nlopt::FTOL_REACHED:
case nlopt::XTOL_REACHED: {
// Now check if the constraints are violated.
bool all_constraints_satisfied = true;
auto constraint_test = [&prog, constraint_tol,
&all_constraints_satisfied,
result](auto constraints) {
all_constraints_satisfied &= IsVectorOfConstraintsSatisfiedAtSolution(
prog, constraints, result->get_x_val(), constraint_tol);
};
constraint_test(prog.generic_constraints());
constraint_test(prog.bounding_box_constraints());
constraint_test(prog.linear_constraints());
constraint_test(prog.linear_equality_constraints());
constraint_test(prog.quadratic_constraints());
constraint_test(prog.lorentz_cone_constraints());
constraint_test(prog.rotated_lorentz_cone_constraints());
if (!all_constraints_satisfied) {
result->set_solution_result(SolutionResult::kInfeasibleConstraints);
}
break;
}
case nlopt::MAXTIME_REACHED:
case nlopt::MAXEVAL_REACHED: {
result->set_solution_result(SolutionResult::kIterationLimit);
break;
}
case nlopt::INVALID_ARGS: {
result->set_solution_result(SolutionResult::kInvalidInput);
break;
}
case nlopt::ROUNDOFF_LIMITED: {
if (minf < kUnboundedTol) {
result->set_solution_result(SolutionResult::kUnbounded);
minf = -std::numeric_limits<double>::infinity();
} else {
result->set_solution_result(SolutionResult::kSolverSpecificError);
}
break;
}
default: {
result->set_solution_result(SolutionResult::kSolverSpecificError);
}
}
} catch (std::invalid_argument&) {
result->set_solution_result(SolutionResult::kInvalidInput);
} catch (std::bad_alloc&) {
result->set_solution_result(SolutionResult::kSolverSpecificError);
} catch (nlopt::roundoff_limited&) {
if (minf < kUnboundedTol) {
result->set_solution_result(SolutionResult::kUnbounded);
minf = MathematicalProgram::kUnboundedCost;
} else {
result->set_solution_result(SolutionResult::kSolverSpecificError);
}
} catch (nlopt::forced_stop&) {
result->set_solution_result(SolutionResult::kSolverSpecificError);
} catch (std::runtime_error&) {
result->set_solution_result(SolutionResult::kSolverSpecificError);
}
result->set_optimal_cost(minf);
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/csdp_cpp_wrapper.h | #pragma once
namespace drake {
namespace solvers {
namespace internal {
namespace csdp {
// Add CSDP's types into this namespace.
extern "C" {
#include <csdp/blockmat.h>
#include <csdp/index.h>
#include <csdp/parameters.h>
} // extern C
// Wrap CSDP's C functions with our own C++ functions, for error handling.
int cpp_easy_sdp(const char* params_pathname, int n, int k,
struct blockmatrix C, double* a,
struct constraintmatrix* constraints, double constant_offset,
struct blockmatrix* pX, double** py, struct blockmatrix* pZ,
double* ppobj, double* pdobj);
void cpp_free_mat(struct blockmatrix A);
void cpp_free_prob(int n, int k, struct blockmatrix C, double* a,
struct constraintmatrix* constraints, struct blockmatrix X,
double* y, struct blockmatrix Z);
void cpp_initsoln(int n, int k, struct blockmatrix C, double* a,
struct constraintmatrix* constraints, struct blockmatrix* pX0,
double** py0, struct blockmatrix* pZ0);
} // namespace csdp
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/binding.h | #pragma once
#include <cstdint>
#include <memory>
#include <ostream>
#include <sstream>
#include <string>
#include <utility>
#include "drake/common/drake_copyable.h"
#include "drake/common/fmt_ostream.h"
#include "drake/common/hash.h"
#include "drake/solvers/decision_variable.h"
#include "drake/solvers/evaluator_base.h"
namespace drake {
namespace solvers {
/**
* A binding on constraint type C is a mapping of the decision
* variables onto the inputs of C. This allows the constraint to operate
* on a vector made up of different elements of the decision variables.
*/
template <typename C>
class Binding {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Binding)
Binding(const std::shared_ptr<C>& c,
const Eigen::Ref<const VectorXDecisionVariable>& v)
: evaluator_(c), vars_(v) {
DRAKE_DEMAND(c->num_vars() == v.rows() || c->num_vars() == Eigen::Dynamic);
}
/**
* Concatenates each VectorDecisionVariable object in @p v into a single
* column vector, binds this column vector of decision variables with
* the constraint @p c.
*/
Binding(const std::shared_ptr<C>& c, const VariableRefList& v)
: evaluator_(c) {
vars_ = ConcatenateVariableRefList(v);
DRAKE_DEMAND(c->num_vars() == vars_.rows() ||
c->num_vars() == Eigen::Dynamic);
}
template <typename U>
Binding(const Binding<U>& b,
typename std::enable_if_t<
std::is_convertible_v<std::shared_ptr<U>, std::shared_ptr<C>>>* =
nullptr)
: Binding(b.evaluator(), b.variables()) {}
[[nodiscard]] const std::shared_ptr<C>& evaluator() const {
return evaluator_;
}
[[nodiscard]] const VectorXDecisionVariable& variables() const {
return vars_;
}
/**
* Returns true iff the given @p var is included in this Binding. */
[[nodiscard]] bool ContainsVariable(const symbolic::Variable& var) const {
for (int i = 0; i < vars_.rows(); ++i) {
if (vars_(i).equal_to(var)) {
return true;
}
}
return false;
}
/**
* Returns the number of variables associated with this evaluator.
*/
[[nodiscard]] size_t GetNumElements() const {
// TODO(ggould-tri) assumes that no index appears more than once in the
// view, which is nowhere asserted (but seems assumed elsewhere).
return vars_.size();
}
/**
* Returns string representation of Binding.
*/
[[nodiscard]] std::string to_string() const {
std::ostringstream os;
os << *this;
return os.str();
}
/** Returns a LaTeX description of this Binding. Does not include any
* characters to enter/exit math mode; you might want, e.g. "$$" +
* evaluator.ToLatex() + "$$". */
std::string ToLatex(int precision = 3) const {
return evaluator()->ToLatex(variables(), precision);
}
/**
* Compare two bindings based on their evaluator pointers and the bound
* variables.
*/
[[nodiscard]] bool operator==(const Binding<C>& other) const {
if (this->evaluator().get() != other.evaluator().get()) {
return false;
}
if (vars_.rows() != other.vars_.rows()) {
return false;
}
for (int i = 0; i < vars_.rows(); ++i) {
if (!vars_(i).equal_to(other.vars_(i))) {
return false;
}
}
return true;
}
[[nodiscard]] bool operator!=(const Binding<C>& other) const {
return !((*this) == (other));
}
/** Implements the @ref hash_append concept. */
template <class HashAlgorithm>
friend void hash_append(HashAlgorithm& hasher,
const Binding<C>& item) noexcept {
using drake::hash_append;
const EvaluatorBase* const base = item.evaluator().get();
hash_append(hasher, reinterpret_cast<std::uintptr_t>(base));
// We follow the pattern in
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3980.html#hash_append_vector
// to append the hash for a std::vector, first to append all its elements,
// and then append the vector size.
for (int i = 0; i < item.variables().rows(); ++i) {
hash_append(hasher, item.variables()(i));
}
hash_append(hasher, item.variables().rows());
}
private:
std::shared_ptr<C> evaluator_;
VectorXDecisionVariable vars_;
};
/**
* Print out the Binding.
*/
template <typename C>
std::ostream& operator<<(std::ostream& os, const Binding<C>& binding) {
return binding.evaluator()->Display(os, binding.variables());
}
namespace internal {
/*
* Create binding, inferring the type from the provided pointer.
* @tparam C Cost or Constraint type to be bound.
* @note Since this forwards arguments, this will not be usable with
* `std::intializer_list`.
*/
template <typename C, typename... Args>
[[nodiscard]] Binding<C> CreateBinding(const std::shared_ptr<C>& c,
Args&&... args) {
return Binding<C>(c, std::forward<Args>(args)...);
}
template <typename To, typename From>
[[nodiscard]] Binding<To> BindingDynamicCast(const Binding<From>& binding) {
auto constraint = std::dynamic_pointer_cast<To>(binding.evaluator());
DRAKE_DEMAND(constraint != nullptr);
return Binding<To>(constraint, binding.variables());
}
} // namespace internal
} // namespace solvers
} // namespace drake
namespace std {
template <typename C>
struct hash<drake::solvers::Binding<C>> : public drake::DefaultHash {};
} // namespace std
// TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<.
namespace fmt {
template <typename C>
struct formatter<drake::solvers::Binding<C>> : drake::ostream_formatter {};
} // namespace fmt
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/decision_variable.h | #pragma once
#include <list>
#include <Eigen/Core>
#include "drake/common/symbolic/expression.h"
namespace drake {
namespace solvers {
using DecisionVariable = symbolic::Variable;
template <int rows, int cols>
using MatrixDecisionVariable = Eigen::Matrix<symbolic::Variable, rows, cols>;
template <int rows>
using VectorDecisionVariable = MatrixDecisionVariable<rows, 1>;
using MatrixXDecisionVariable =
MatrixDecisionVariable<Eigen::Dynamic, Eigen::Dynamic>;
using VectorXDecisionVariable = VectorDecisionVariable<Eigen::Dynamic>;
using VariableRefList = std::list<Eigen::Ref<const VectorXDecisionVariable>>;
/**
* Concatenates each element in \p var_list into a single Eigen vector of
* decision variables, returns this concatenated vector.
*/
[[nodiscard]] VectorXDecisionVariable ConcatenateVariableRefList(
const VariableRefList& var_list);
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/equality_constrained_qp_solver.cc | #include "drake/solvers/equality_constrained_qp_solver.h"
#include <cstring>
#include <initializer_list>
#include <limits>
#include <memory>
#include <optional>
#include <unordered_map>
#include <vector>
#include "drake/common/autodiff.h"
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
namespace {
// Solves the un-constrained QP problem
// min 0.5 * xᵀ * G * x + cᵀ * x
SolutionResult SolveUnconstrainedQP(const Eigen::Ref<const Eigen::MatrixXd>& G,
const Eigen::Ref<const Eigen::VectorXd>& c,
double feasibility_tol,
Eigen::VectorXd* x) {
// If the Hessian G is positive definite, then the problem has a unique
// optimal solution.
// If the Hessian G has one or more negative eigen values, then the problem is
// unbounded.
// If the Hessian G is positive semidefinite, but with some eigen values
// being 0, then we check the first order derivative G * x + c. If there
// exists solution x* such that the first order derivative at x* is 0, then
// the problem has optimal cost (but infinitely many optimal x* will exist).
// Check for positive definite Hessian matrix.
Eigen::LLT<Eigen::MatrixXd> llt(G);
if (llt.info() == Eigen::Success) {
// G is positive definite.
*x = llt.solve(-c);
return SolutionResult::kSolutionFound;
} else {
// G is not strictly positive definite.
// There are two possible cases
// 1. If there exists x, s.t G * x = -c, and G is positive semidefinite
// then there are infinitely many optimal solutions, and we will return
// one of the optimal solutions.
// 2. Otherwise, if G * x = -c does not have a solution, or G is not
// positive semidefinite, then the problem is unbounded.
// We check if G is positive semidefinite.
bool is_G_psd = false;
// We first use LDLT (which is fast) decomposition. But we found that LDLT
// sometimes fails, so we then fall back to Eigen value decomposition.
Eigen::LDLT<Eigen::MatrixXd> ldlt(G);
bool use_ldlt = false;
if (ldlt.info() == Eigen::Success && ldlt.isPositive()) {
is_G_psd = true;
use_ldlt = true;
} else {
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(G);
if (es.info() == Eigen::Success &&
(es.eigenvalues().array() >= -feasibility_tol).all()) {
is_G_psd = true;
use_ldlt = false;
}
}
if (is_G_psd) {
// G is positive semidefinite.
if (use_ldlt) {
*x = ldlt.solve(-c);
} else {
Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr(G);
*x = qr.solve(-c);
}
if ((G * (*x)).isApprox(-c, feasibility_tol)) {
return SolutionResult::kSolutionFound;
}
}
*x = Eigen::VectorXd::Constant(c.rows(), NAN);
return SolutionResult::kUnbounded;
}
}
struct EqualityConstrainedQPSolverOptions {
// The default tolerance is Eigen's dummy precision.
double feasibility_tol{Eigen::NumTraits<double>::dummy_precision()};
};
void GetEqualityConstrainedQPSolverOptions(
const SolverOptions& solver_options,
EqualityConstrainedQPSolverOptions* equality_qp_solver_options) {
DRAKE_ASSERT_VOID(solver_options.CheckOptionKeysForSolver(
EqualityConstrainedQPSolver::id(),
{EqualityConstrainedQPSolver::FeasibilityTolOptionName()}, {}, {}));
const auto& options_double =
solver_options.GetOptionsDouble(EqualityConstrainedQPSolver::id());
auto it = options_double.find(
EqualityConstrainedQPSolver::FeasibilityTolOptionName());
if (it != options_double.end()) {
if (it->second >= 0) {
equality_qp_solver_options->feasibility_tol = it->second;
} else {
throw std::invalid_argument(
"FeasibilityTol should be a non-negative number.");
}
}
}
void SetDualSolutions(const MathematicalProgram& prog,
const Eigen::VectorXd& dual_solutions,
MathematicalProgramResult* result) {
int num_constraints = 0;
for (const auto& binding : prog.linear_equality_constraints()) {
result->set_dual_solution(
binding, dual_solutions.segment(
num_constraints, binding.evaluator()->num_constraints()));
num_constraints += binding.evaluator()->num_constraints();
}
}
} // namespace
EqualityConstrainedQPSolver::EqualityConstrainedQPSolver()
: SolverBase(id(), &is_available, &is_enabled,
&ProgramAttributesSatisfied) {}
EqualityConstrainedQPSolver::~EqualityConstrainedQPSolver() = default;
void EqualityConstrainedQPSolver::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(
"EqualityConstrainedQPSolver doesn't support the feature of variable "
"scaling.");
}
// An equality constrained QP problem has analytical solution. It doesn't
// depend on the initial guess.
unused(initial_guess);
// There are three ways to solve the KKT subproblem for convex QPs.
// Formally, we want to solve:
// | G A' | | x | = | -c |
// | A 0 | | y | = | b |
// for problem variables x and Lagrange multiplier variables y. This
// corresponds to the QP:
// minimize 1/2 x'*G*x + c'*x + constant_term
// s.t.: A*x = b
// Approach 1: Solve the full linear system above.
// Approach 2: Use the Schur complement ("range space" approach).
// Approach 3: Use the nullspace of A ("null space" approach).
// The QP approach attempts Approach (2), if G is strictly positive definite,
// and falls back to Approach (3) otherwise. For the null-space approach, we
// compute kernel(A) = N, and convert the equality constrained QP to an
// un-constrained QP, as
// minimize 0.5 y'*(N'*G*N)*y + (c'*N + N'*G*x0)* y
// where x0 is one solution to A * x = b.
//
// This implementation was conducted using [Nocedal 1999], Ch. 16 (Quadratic
// Programming). It is recommended that programmers desiring to modify this
// code have a solid understanding of equality constrained quadratic
// programming before proceeding.
// - J. Nocedal and S. Wright. Numerical Optimization. Springer, 1999.
EqualityConstrainedQPSolverOptions solver_options_struct{};
GetEqualityConstrainedQPSolverOptions(merged_options, &solver_options_struct);
size_t num_constraints = 0;
for (auto const& binding : prog.linear_equality_constraints()) {
num_constraints += binding.evaluator()->get_sparse_A().rows();
}
// Setup the quadratic cost matrix and linear cost vector.
Eigen::MatrixXd G = Eigen::MatrixXd::Zero(prog.num_vars(), prog.num_vars());
Eigen::VectorXd c = Eigen::VectorXd::Zero(prog.num_vars());
double constant_term{0};
for (auto const& binding : prog.quadratic_costs()) {
const auto& Q = binding.evaluator()->Q();
const auto& b = binding.evaluator()->b();
constant_term += binding.evaluator()->c();
int num_v_variables = binding.variables().rows();
std::vector<size_t> v_index(num_v_variables);
for (int i = 0; i < num_v_variables; ++i) {
v_index[i] = prog.FindDecisionVariableIndex(binding.variables()(i));
}
for (int i = 0; i < num_v_variables; ++i) {
for (int j = 0; j < num_v_variables; ++j) {
G(v_index[i], v_index[j]) += Q(i, j);
}
c(v_index[i]) += b(i);
}
}
for (const auto& binding : prog.linear_costs()) {
const auto& a = binding.evaluator()->a();
constant_term += binding.evaluator()->b();
int num_v_variables = binding.variables().rows();
for (int i = 0; i < num_v_variables; ++i) {
auto v_index_i = prog.FindDecisionVariableIndex(binding.variables()(i));
c(v_index_i) += a(i);
}
}
Eigen::VectorXd x{};
SolutionResult solution_result{SolutionResult::kSolverSpecificError};
// lambda stores the dual variable solutions.
Eigen::VectorXd lambda(num_constraints);
if (num_constraints > 0) {
// Setup the linear constraints.
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(num_constraints, prog.num_vars());
Eigen::VectorXd b = Eigen::VectorXd::Zero(num_constraints);
int constraint_index = 0;
for (auto const& binding : prog.linear_equality_constraints()) {
auto const& bc = binding.evaluator();
size_t n = bc->get_sparse_A().rows();
int num_v_variables = binding.variables().rows();
for (int i = 0; i < num_v_variables; ++i) {
const int variable_index =
prog.FindDecisionVariableIndex(binding.variables()(i));
for (Eigen::SparseMatrix<double>::InnerIterator it(bc->get_sparse_A(),
i);
it; ++it) {
A(constraint_index + it.row(), variable_index) = it.value();
}
}
b.segment(constraint_index, n) =
bc->lower_bound().segment(0, n); // = c->upper_bound() since it's
// an equality constraint
constraint_index += n;
}
// Check for positive definite Hessian matrix.
Eigen::LLT<Eigen::MatrixXd> llt(G);
if (llt.info() == Eigen::Success) {
// Matrix is positive definite. (inv(G)*A')' = A*inv(G) because G is
// symmetric.
Eigen::MatrixXd AiG_T = llt.solve(A.transpose());
// Compute a full pivoting, QR factorization.
const Eigen::MatrixXd A_iG_A_T = A * AiG_T;
Eigen::FullPivHouseholderQR<Eigen::MatrixXd> qr(A_iG_A_T);
// Solve using least-squares A*inv(G)*A'y = A*inv(G)*c + b for `y`.
const Eigen::VectorXd rhs = AiG_T.transpose() * c + b;
lambda = qr.solve(rhs);
solution_result =
rhs.isApprox(A_iG_A_T * lambda, solver_options_struct.feasibility_tol)
? SolutionResult::kSolutionFound
: SolutionResult::kInfeasibleConstraints;
// Solve G*x = A'y - c
x = llt.solve(A.transpose() * lambda - c);
} else {
// The following code assumes that the Hessian is not positive definite.
// We first compute the null space of A. Denote kernel(A) = N.
// If A * x = b is feasible, then x = x₀ + N * y, where A * x₀ = b.
// The QP can be re-formulated as an un-constrained QP problem
// min 0.5 * (x₀ + N * y)ᵀ * G * (x₀ + N * y) + cᵀ * (x₀ + N * y)
// which has the same optimal solution as
// min 0.5 * yᵀ * Nᵀ*G*N * y + (x₀ᵀ*G*N + cᵀ*N) * y
Eigen::JacobiSVD<Eigen::MatrixXd> svd_A_thin(
A, Eigen::ComputeThinU | Eigen::ComputeThinV);
const Eigen::VectorXd x0 = svd_A_thin.solve(b);
if (!b.isApprox(A * x0, solver_options_struct.feasibility_tol)) {
solution_result = SolutionResult::kInfeasibleConstraints;
x = x0;
Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr_A(A.transpose());
lambda = qr_A.solve(G * x + c);
} else {
if (svd_A_thin.rank() == A.cols()) {
// The kernel is empty, the solution is unique.
solution_result = SolutionResult::kSolutionFound;
x = x0;
Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr_A(A.transpose());
lambda = qr_A.solve(G * x + c);
} else {
// N is the null space of A
// Using QR decomposition
// Aᵀ * P = [Q1 Q2] * [R] = Q1 * R
// [0]
// where P is a permutation matrix.
// So A = P * R1ᵀ * Q1ᵀ, and A * Q2 = P * R1ᵀ * Q1ᵀ * Q2 = 0 since
// Q1 and Q2 are orthogonal to each other.
// Thus kernel(A) = Q2.
// Notice that we do not call svd here because svd only gives
// us a "thin" V; thus the V matrix does not contain the basis vectors
// for the null space.
Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr_A(A.transpose());
const Eigen::MatrixXd Q =
qr_A.householderQ().setLength(qr_A.nonzeroPivots());
const Eigen::MatrixXd N = Q.rightCols(A.cols() - qr_A.rank());
Eigen::VectorXd y(N.cols());
solution_result = SolveUnconstrainedQP(
N.transpose() * G * N, x0.transpose() * G * N + c.transpose() * N,
solver_options_struct.feasibility_tol, &y);
x = x0 + N * y;
lambda = qr_A.solve(G * x + c);
}
}
}
} else {
// num_constraints = 0
solution_result =
SolveUnconstrainedQP(G, c, solver_options_struct.feasibility_tol, &x);
}
result->set_x_val(x);
result->set_solution_result(solution_result);
SetDualSolutions(prog, lambda, result);
double optimal_cost{};
switch (solution_result) {
case SolutionResult::kSolutionFound: {
optimal_cost = 0.5 * x.dot(G * x) + c.dot(x) + constant_term;
break;
}
case SolutionResult::kUnbounded: {
optimal_cost = MathematicalProgram::kUnboundedCost;
break;
}
case SolutionResult::kInfeasibleConstraints: {
optimal_cost = MathematicalProgram::kGlobalInfeasibleCost;
break;
}
default: {
optimal_cost = NAN;
}
}
result->set_optimal_cost(optimal_cost);
}
std::string EqualityConstrainedQPSolver::FeasibilityTolOptionName() {
return "FeasibilityTol";
}
SolverId EqualityConstrainedQPSolver::id() {
static const never_destroyed<SolverId> singleton{"EqConstrainedQP"};
return singleton.access();
}
bool EqualityConstrainedQPSolver::is_available() {
return true;
}
bool EqualityConstrainedQPSolver::is_enabled() {
return true;
}
bool EqualityConstrainedQPSolver::ProgramAttributesSatisfied(
const MathematicalProgram& prog) {
static const never_destroyed<ProgramAttributes> solver_capabilities(
std::initializer_list<ProgramAttribute>{
ProgramAttribute::kQuadraticCost, ProgramAttribute::kLinearCost,
ProgramAttribute::kLinearEqualityConstraint});
// TODO(hongkai.dai) also make sure that there exists at least a quadratic
// cost.
return AreRequiredAttributesSupported(prog.required_capabilities(),
solver_capabilities.access());
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mixed_integer_rotation_constraint.cc | #include "drake/solvers/mixed_integer_rotation_constraint.h"
#include <cmath>
#include <limits>
#include "drake/common/symbolic/replace_bilinear_terms.h"
#include "drake/math/gray_code.h"
#include "drake/solvers/integer_optimization_util.h"
#include "drake/solvers/mixed_integer_rotation_constraint_internal.h"
using drake::symbolic::Expression;
namespace drake {
namespace solvers {
namespace {
// Returns true if n is positive and n is a power of 2.
bool IsPowerOfTwo(int n) {
DRAKE_ASSERT(n > 0);
return (n & (n - 1)) == 0;
}
// Relax the unit length constraint x₀² + x₁² + x₂² = 1, to a set of linear
// constraints. The relaxation is achieved by assuming the intervals of xᵢ has
// been cut into smaller intervals in the form [φ(i) φ(i+1)], and xᵢ is
// constrained to be within one of the intervals. Namely we assume that
// xᵢ = φᵀ * λᵢ, where λ is the auxiliary variables, satisfying the SOS2
// constraint already.
// We know that due to the convexity of the curve w = x², we get
// x² ≥ 2φⱼ*x-φⱼ²
// where the right hand-side of the inequality is the tangent of the curve
// w = x² at φⱼ. Thus we have 1 ≥ sum_j sum_i 2φⱼ*xᵢ-φⱼ²
// Moreover, also due to the convexity of the curve w = x², we know
// xᵢ² ≤ sum_j φ(j)² * λᵢ(j)
// So we have the constraint
// 1 ≤ sum_i sum_j φ(j)² * λᵢ(j)
void AddUnitLengthConstraintWithSos2Lambda(
MathematicalProgram* prog, const Eigen::Ref<const Eigen::VectorXd>& phi,
const Eigen::Ref<const VectorXDecisionVariable>& lambda0,
const Eigen::Ref<const VectorXDecisionVariable>& lambda1,
const Eigen::Ref<const VectorXDecisionVariable>& lambda2) {
const int num_phi = phi.rows();
DRAKE_ASSERT(num_phi == lambda0.rows());
DRAKE_ASSERT(num_phi == lambda1.rows());
DRAKE_ASSERT(num_phi == lambda2.rows());
const symbolic::Expression x0{phi.dot(lambda0.cast<symbolic::Expression>())};
const symbolic::Expression x1{phi.dot(lambda1.cast<symbolic::Expression>())};
const symbolic::Expression x2{phi.dot(lambda2.cast<symbolic::Expression>())};
for (int phi0_idx = 0; phi0_idx < num_phi; phi0_idx++) {
const symbolic::Expression x0_square_lb{2 * phi(phi0_idx) * x0 -
std::pow(phi(phi0_idx), 2)};
for (int phi1_idx = 0; phi1_idx < num_phi; phi1_idx++) {
const symbolic::Expression x1_square_lb{2 * phi(phi1_idx) * x1 -
std::pow(phi(phi1_idx), 2)};
for (int phi2_idx = 0; phi2_idx < num_phi; phi2_idx++) {
const symbolic::Expression x2_square_lb{2 * phi(phi2_idx) * x2 -
std::pow(phi(phi2_idx), 2)};
symbolic::Expression x_sum_of_squares_lb{x0_square_lb + x1_square_lb +
x2_square_lb};
if (!is_constant(x_sum_of_squares_lb)) {
prog->AddLinearConstraint(x_sum_of_squares_lb <= 1);
}
}
}
}
symbolic::Expression x_square_ub{0};
for (int i = 0; i < num_phi; ++i) {
x_square_ub += phi(i) * phi(i) * (lambda0(i) + lambda1(i) + lambda2(i));
}
prog->AddLinearConstraint(x_square_ub >= 1);
}
std::pair<int, int> Index2Subscripts(int index, int num_rows, int num_cols) {
DRAKE_ASSERT(index >= 0 && index < num_rows * num_cols);
int column_index = index / num_rows;
int row_index = index - column_index * num_rows;
return std::make_pair(row_index, column_index);
}
// Relax the orthogonal constraint
// R.col(i)ᵀ * R.col(j) = 0
// R.row(i)ᵀ * R.row(j) = 0.
// and the cross product constraint
// R.col(i) x R.col(j) = R.col(k)
// R.row(i) x R.row(j) = R.row(k)
// To handle this non-convex bilinear product, we relax any bilinear product
// in the form x * y, we relax (x, y, w) to be in the convex hull of the
// curve w = x * y, and replace all the bilinear term x * y with w. For more
// details, @see AddBilinearProductMcCormickEnvelopeSos2.
void AddOrthogonalAndCrossProductConstraintRelaxationReplacingBilinearProduct(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
const Eigen::Ref<const Eigen::VectorXd>& phi,
const std::array<std::array<VectorXDecisionVariable, 3>, 3>& B,
IntervalBinning interval_binning) {
VectorDecisionVariable<9> R_flat;
R_flat << R.col(0), R.col(1), R.col(2);
MatrixDecisionVariable<9, 9> W;
// We cannot call W.cast<symbolic::Expression>() directly, since the diagonal
// entries in W is un-assigned, namely they are dummy variables. Converting a
// dummy variable to a symbolic expression is illegal. So we create this new
// W_expr, containing W(i, j) on the off-diagonal entries.
Eigen::Matrix<symbolic::Expression, 9, 9> W_expr;
W_expr.setZero();
for (int i = 0; i < 9; ++i) {
int Ri_row, Ri_col;
std::tie(Ri_row, Ri_col) = Index2Subscripts(i, 3, 3);
for (int j = i + 1; j < 9; ++j) {
int Rj_row, Rj_col;
std::tie(Rj_row, Rj_col) = Index2Subscripts(j, 3, 3);
std::string W_ij_name =
"R(" + std::to_string(Ri_row) + "," + std::to_string(Ri_col) +
")*R(" + std::to_string(Rj_row) + "," + std::to_string(Rj_col) + ")";
W(i, j) = prog->NewContinuousVariables<1>(W_ij_name)(0);
W_expr(i, j) = symbolic::Expression(W(i, j));
auto lambda_bilinear = AddBilinearProductMcCormickEnvelopeSos2(
prog, R(Ri_row, Ri_col), R(Rj_row, Rj_col), W(i, j), phi, phi,
B[Ri_row][Ri_col].template cast<symbolic::Expression>(),
B[Rj_row][Rj_col].template cast<symbolic::Expression>(),
interval_binning);
// Both sum_n lambda_bilinear(m, n) and sum_m lambda_bilinear(m, n)
// satisfy the SOS2 constraint, and
// R(Ri_row, Ri_col) = φᵀ * (sum_n lambda_bilinear(m, n))
// R(Rj_row, Rj_col) = φᵀ * (sum_m lambda_bilinear(m, n).transpose())
// Since we also know that both lambda[Ri_row][Ri_col] and
// lambda[Rj_row][Rj_col] satisfy the SOS2 constraint, and
// R[Ri_row][Ri_col] = φᵀ * lambda[Ri_row][Ri_col]
// R[Rj_row][Rj_col] = φᵀ * lambda[Rj_row][Rj_col]
// So sum_n lambda_bilinear(m, n) = lambda[Ri_row][Ri_col] (1)
// sum_m lambda_bilinear(m, n).transpose() = lambda[Rj_row][Rj_col] (2)
// TODO(hongkai.dai): I found the computation could be faster if we do not
// add constraint (1) and (2). Should investigate the reason.
W(j, i) = W(i, j);
W_expr(j, i) = W_expr(i, j);
}
}
for (int i = 0; i < 3; ++i) {
for (int j = i + 1; j < 3; ++j) {
// Orthogonal constraint between R.col(i), R.col(j).
prog->AddLinearConstraint(
symbolic::ReplaceBilinearTerms(
R.col(i).dot(R.col(j).cast<symbolic::Expression>()), R_flat,
R_flat, W_expr) == 0);
// Orthogonal constraint between R.row(i), R.row(j)
prog->AddLinearConstraint(
symbolic::ReplaceBilinearTerms(
R.row(i).transpose().dot(
R.row(j).cast<symbolic::Expression>().transpose()),
R_flat, R_flat, W_expr) == 0);
}
}
for (int i = 0; i < 3; ++i) {
int j = (i + 1) % 3;
int k = (i + 2) % 3;
Vector3<symbolic::Expression> cross_product1 =
R.col(i).cross(R.col(j).cast<symbolic::Expression>());
Vector3<symbolic::Expression> cross_product2 = R.row(i).transpose().cross(
R.row(j).transpose().cast<symbolic::Expression>());
for (int row = 0; row < 3; ++row) {
// R.col(i) x R.col(j) = R.col(k).
prog->AddLinearConstraint(
symbolic::ReplaceBilinearTerms(cross_product1(row), R_flat, R_flat,
W_expr) == R(row, k));
// R.row(i) x R.row(j) = R.row(k).
prog->AddLinearConstraint(
symbolic::ReplaceBilinearTerms(cross_product2(row), R_flat, R_flat,
W_expr) == R(k, row));
}
}
}
/**
* Add the constraint that vector R.col(i) and R.col(j) are not in the
* same or opposite orthants. This constraint should be satisfied since
* R.col(i) should be perpendicular to R.col(j). For example, if both
* R.col(i) and R.col(j) are in the first orthant (+++), their inner product
* has to be non-negative. If the inner product of two first orthant vectors
* is exactly zero, then both vectors has to be on the boundaries of the first
* orthant. But we can then assign the vector to a different orthant. The same
* proof applies to the opposite orthant case.
* To impose the constraint that R.col(0) and R.col(1) are not both in the first
* orthant, we consider the constraint
* Bpos0.col(0).sum() + Bpos0.col(1).sum() <= 5.
* Namely, not all 6 entries in Bpos0.col(0) and Bpos0.col(1) can be 1 at the
* same time, which is another way of saying R.col(0) and R.col(1) cannot be
* both in the first orthant.
* Similarly we can impose the constraint on the other orthant.
* @param prog Add the constraint to this mathematical program.
* @param Bpos0 Defined in AddRotationMatrixMcCormickEnvelopeMilpConstraints(),
* Bpos0(i,j) = 1 => R(i, j) >= 0. Bpos0(i, j) = 0 => R(i, j) <= 0.
*/
void AddNotInSameOrOppositeOrthantConstraint(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& Bpos0) {
const std::array<std::pair<int, int>, 3> column_idx = {
{{0, 1}, {0, 2}, {1, 2}}};
for (const auto& column_pair : column_idx) {
const int col_idx0 = column_pair.first;
const int col_idx1 = column_pair.second;
for (int o = 0; o < 8; ++o) {
// To enforce that R.col(i) and R.col(j) are not simultaneously in the
// o'th orthant, we will impose the constraint
// vars_same_orthant.sum() < = 5. The variables in vars_same_orthant
// depend on the orthant number o.
// To enforce that R.col(i) and R.col(j) are not in the opposite
// orthants, we will impose the constraint
// vars_oppo_orthant.sum() <= 5. The variables in vars_oppo_orthant
// depnd on the orthant number o.
Vector6<symbolic::Expression> vars_same_orthant;
Vector6<symbolic::Expression> vars_oppo_orthant;
for (int axis = 0; axis < 3; ++axis) {
// axis chooses x, y, or z axis.
if (o & (1 << axis)) {
// If the orthant has positive value along the `axis`, then
// `vars_same_orthant` choose the positive component Bpos0.
vars_same_orthant(2 * axis) = Bpos0(axis, col_idx0);
vars_same_orthant(2 * axis + 1) = Bpos0(axis, col_idx1);
vars_oppo_orthant(2 * axis) = Bpos0(axis, col_idx0);
vars_oppo_orthant(2 * axis + 1) = 1 - Bpos0(axis, col_idx1);
} else {
// If the orthant has negative value along the `axis`, then
// `vars_same_orthant` choose the negative component 1 - Bpos0.
vars_same_orthant(2 * axis) = 1 - Bpos0(axis, col_idx0);
vars_same_orthant(2 * axis + 1) = 1 - Bpos0(axis, col_idx1);
vars_oppo_orthant(2 * axis) = 1 - Bpos0(axis, col_idx0);
vars_oppo_orthant(2 * axis + 1) = Bpos0(axis, col_idx1);
}
}
prog->AddLinearConstraint(vars_same_orthant.sum() <= 5);
prog->AddLinearConstraint(vars_oppo_orthant.sum() <= 5);
}
}
}
// For the cross product c = a x b, based on the sign of a and b, we can imply
// the sign of c for some cases. For example, c0 = a1 * b2 - a2 * b1, so if
// (a1, a2, b1, b2) has sign (+, -, +, +), then c0 has to have sign +.
// @param Bpos0. Bpos0(i, j) = 1 => R(i, j) ≥ 0, Bpos0(i, j) = 0 => R(i, j) ≤ 0
void AddCrossProductImpliedOrthantConstraint(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& Bpos0) {
// The vertices of the polytope {x | A * x <= b} correspond to valid sign
// assignment for (a1, b2, a2, b1, c0) in the example above.
// Since R.col(k) = R.col(i) x R.col(j), we then know that
// A * [Bpos0(1, i); Bpos0(2, j); Bpos0(1, j); Bpos0(2, i); Bpos0(0, k)] <= b.
// The matrix A and b is found, by considering the polytope, whose vertices
// are {0, 1}⁵, excluding the 8 points
// (a1, b2, a2, b1, c0)
// ( 0, 0, 1, 0, 0)
// ( 0, 0, 0, 1, 0)
// ( 1, 1, 1, 0, 0)
// ( 1, 1, 0, 1, 0)
// ( 1, 0, 0, 0, 1)
// ( 1, 0, 1, 1, 1)
// ( 0, 1, 0, 0, 1)
// ( 0, 1, 1, 1, 1)
// So this polytope has 2⁵ - 8 = 24 vertices in total.
// The matrix A and b are obtained by converting this polytope from its
// vertices (V-representation), to its facets (H-representation). We did
// this conversion through Multi-parametric toolbox. Here is the MATLAB code
// P = Polyhedron(V);
// P.computeHRep();
// A = P.A;
// b = P.b;
constexpr int A_rows = 18;
constexpr int A_cols = 5;
Eigen::Matrix<double, A_rows, A_cols> A;
Eigen::Matrix<double, A_rows, 1> b;
A << 0, 0, 0, 0, -1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 0, 0, -1, 0, 0, -1, 0,
0, 0, 0, -1, -1, -1, 1, -1, -1, -1, 1, -1, -1, 0, -1, 0, 0, 0, 1, -1, -1,
-1, 1, -1, 1, -1, -1, 1, 0, 0, 0, -1, 0, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1,
0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0;
b << 0, 2, 2, 0, 0, 0, 0, 0, 1, 1, 0, 3, 3, 1, 1, 1, 1, 1;
for (int col0 = 0; col0 < 3; ++col0) {
int col1 = (col0 + 1) % 3;
int col2 = (col1 + 1) % 3;
// R(k, col2) = R(i, col0) * R(j, col1) - R(j, col0) * R(i, col1)
// where (i, j, k) = (0, 1, 2), (1, 2, 0) or (2, 0, 1)
VectorDecisionVariable<A_cols> var;
for (int i = 0; i < 3; ++i) {
int j = (i + 1) % 3;
int k = (j + 1) % 3;
var << Bpos0(i, col0), Bpos0(j, col1), Bpos0(j, col0), Bpos0(i, col1),
Bpos0(k, col2);
prog->AddLinearConstraint(A,
Eigen::Matrix<double, A_rows, 1>::Constant(
-std::numeric_limits<double>::infinity()),
b, var);
}
}
}
void AddConstraintInferredFromTheSign(
MathematicalProgram* prog,
const std::array<std::array<VectorXDecisionVariable, 3>, 3>& B,
int num_intervals_per_half_axis, IntervalBinning interval_binning) {
// Bpos(i, j) = 1 => R(i, j) >= 0
// Bpos(i, j) = 0 => R(i, j) <= 0
MatrixDecisionVariable<3, 3> Bpos;
switch (interval_binning) {
case IntervalBinning::kLogarithmic: {
// If num_intervals_per_half_axis is a power of 2, then B[i][j](0)
// indicates the sign of R(i, j).
if (IsPowerOfTwo(num_intervals_per_half_axis)) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
Bpos(i, j) = B[i][j](0);
}
}
AddNotInSameOrOppositeOrthantConstraint(prog, Bpos);
AddNotInSameOrOppositeOrthantConstraint(prog, Bpos.transpose());
AddCrossProductImpliedOrthantConstraint(prog, Bpos);
AddCrossProductImpliedOrthantConstraint(prog, Bpos.transpose());
// If num_intervals_per_half_axis is a power of 2, and it's >= 2, then
// B[i][j](1) = 1 => -0.5 <= R(i, j) <= 0.5. Furthermore, we know for
// each row/column of R, it cannot have all three entries in the
// interval [-0.5, 0.5], since that would imply the norm of the
// row/column being less than sqrt(3)/2. Thus, we have
// sum_i B[i][j](1) <= 2 and sum_j B[i][j](1) <= 2
if (num_intervals_per_half_axis >= 2) {
for (int i = 0; i < 3; ++i) {
symbolic::Expression row_sum{0};
symbolic::Expression col_sum{0};
for (int j = 0; j < 3; ++j) {
row_sum += B[i][j](1);
col_sum += B[j][i](1);
}
prog->AddLinearConstraint(row_sum <= 2);
prog->AddLinearConstraint(col_sum <= 2);
}
}
}
break;
}
case IntervalBinning::kLinear: {
// Bpos(i, j) = B[i][j](N) ∨ B[i][j](N+1) ∨ ... ∨ B[i][j](2*N-1)
// where N = num_intervals_per_half_axis_;
// This "logical or" constraint can be written as
// Bpos(i, j) ≥ B[i][j](N + k) ∀ k = 0, ..., N-1
// Bpos(i, j) ≤ ∑ₖ B[i][j](N+k)
// 0 ≤ Bpos(i, j) ≤ 1
Bpos = prog->NewContinuousVariables<3, 3>("Bpos");
prog->AddBoundingBoxConstraint(0, 1, Bpos);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
// clang-format off
prog->AddLinearConstraint(Bpos(i, j) <=
B[i][j].tail(num_intervals_per_half_axis)
.cast<symbolic::Expression>().sum());
// clang-format on
for (int k = 0; k < num_intervals_per_half_axis; ++k) {
prog->AddLinearConstraint(Bpos(i, j) >=
B[i][j](num_intervals_per_half_axis + k));
}
}
}
AddNotInSameOrOppositeOrthantConstraint(prog, Bpos);
AddNotInSameOrOppositeOrthantConstraint(prog, Bpos.transpose());
AddCrossProductImpliedOrthantConstraint(prog, Bpos);
AddCrossProductImpliedOrthantConstraint(prog, Bpos.transpose());
break;
}
}
}
void AddRotationMatrixBilinearMcCormickConstraints(
MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
const std::array<std::array<VectorXDecisionVariable, 3>, 3>& B,
const std::array<std::array<VectorXDecisionVariable, 3>, 3>& lambda,
const Eigen::Ref<const Eigen::VectorXd>& phi,
IntervalBinning interval_binning) {
for (int row = 0; row < 3; ++row) {
AddUnitLengthConstraintWithSos2Lambda(prog, phi, lambda[row][0],
lambda[row][1], lambda[row][2]);
}
for (int col = 0; col < 3; ++col) {
AddUnitLengthConstraintWithSos2Lambda(prog, phi, lambda[0][col],
lambda[1][col], lambda[2][col]);
}
AddOrthogonalAndCrossProductConstraintRelaxationReplacingBilinearProduct(
prog, R, phi, B, interval_binning);
}
// Given (an integer enumeration of) the orthant, takes a vector in the
// positive orthant into that orthant by flipping the signs of the individual
// elements.
Eigen::Vector3d FlipVector(const Eigen::Ref<const Eigen::Vector3d>& vpos,
int orthant) {
DRAKE_ASSERT(vpos(0) >= 0 && vpos(1) >= 0 && vpos(2) >= 0);
DRAKE_DEMAND(orthant >= 0 && orthant <= 7);
Eigen::Vector3d v = vpos;
if (orthant & (1 << 2)) v(0) = -v(0);
if (orthant & (1 << 1)) v(1) = -v(1);
if (orthant & 1) v(2) = -v(2);
return v;
}
// Given (an integer enumeration of) the orthant, return a vector c with
// c(i) = a(i) if element i is positive in the indicated orthant, otherwise
// c(i) = b(i).
template <typename Derived>
Eigen::Matrix<Derived, 3, 1> PickPermutation(
const Eigen::Matrix<Derived, 3, 1>& a,
const Eigen::Matrix<Derived, 3, 1>& b, int orthant) {
DRAKE_DEMAND(orthant >= 0 && orthant <= 7);
Eigen::Matrix<Derived, 3, 1> c = a;
if (orthant & (1 << 2)) c(0) = b(0);
if (orthant & (1 << 1)) c(1) = b(1);
if (orthant & 1) c(2) = b(2);
return c;
}
void AddBoxSphereIntersectionConstraints(
MathematicalProgram* prog, const VectorDecisionVariable<3>& v,
const std::vector<Vector3<Expression>>& cpos,
const std::vector<Vector3<Expression>>& cneg,
const VectorDecisionVariable<3>& v1, const VectorDecisionVariable<3>& v2,
const std::vector<std::vector<std::vector<std::vector<Eigen::Vector3d>>>>&
box_sphere_intersection_vertices,
const std::vector<
std::vector<std::vector<std::pair<Eigen::Vector3d, double>>>>&
box_sphere_intersection_halfspace) {
const int N = cpos.size(); // number of discretization points.
// Iterate through regions.
for (int xi = 0; xi < N; xi++) {
for (int yi = 0; yi < N; yi++) {
for (int zi = 0; zi < N; zi++) {
Vector3<Expression> this_cpos, this_cneg;
this_cpos << cpos[xi](0), cpos[yi](1), cpos[zi](2);
this_cneg << cneg[xi](0), cneg[yi](1), cneg[zi](2);
// If the box and the sphere surface has intersection
if (box_sphere_intersection_vertices[xi][yi][zi].size() > 0) {
// The box intersects with the surface of the unit sphere.
// Two possible cases
// 1. If the box bmin <= x <= bmax intersects with the surface of the
// unit sphere at a unique point (either bmin or bmax),
// 2. Otherwise, there is a region of intersection.
if (box_sphere_intersection_vertices[xi][yi][zi].size() == 1) {
// If box_min or box_max is on the sphere, then denote the point on
// the sphere as u, we have the following condition
// if c[xi](0) = 1 and c[yi](1) == 1 and c[zi](2) == 1, then
// v = u
// vᵀ * v1 = 0
// vᵀ * v2 = 0
// v.cross(v1) = v2
// Translate this to constraint, we have
// 2 * (c[xi](0) + c[yi](1) + c[zi](2)) - 6
// <= v - u <= -2 * (c[xi](0) + c[yi](1) + c[zi](2)) + 6
//
// c[xi](0) + c[yi](1) + c[zi](2) - 3
// <= vᵀ * v1 <= 3 - (c[xi](0) + c[yi](1) + c[zi](2))
//
// c[xi](0) + c[yi](1) + c[zi](2) - 3
// <= vᵀ * v2 <= 3 - (c[xi](0) + c[yi](1) + c[zi](2))
//
// 2 * c[xi](0) + c[yi](1) + c[zi](2) - 6
// <= v.cross(v1) - v2 <= 6 - 2 * (c[xi](0) + c[yi](1) +
// c[zi](2))
// `u` in the documentation above.
const Eigen::Vector3d unique_intersection =
box_sphere_intersection_vertices[xi][yi][zi][0];
Eigen::Vector3d orthant_u;
Vector3<Expression> orthant_c;
for (int o = 0; o < 8; o++) { // iterate over orthants
orthant_u = FlipVector(unique_intersection, o);
orthant_c = PickPermutation(this_cpos, this_cneg, o);
// TODO(hongkai.dai): remove this for loop when we can handle
// Eigen::Array of symbolic formulae.
Expression orthant_c_sum = orthant_c.cast<Expression>().sum();
for (int i = 0; i < 3; ++i) {
prog->AddLinearConstraint(v(i) - orthant_u(i) <=
6 - 2 * orthant_c_sum);
prog->AddLinearConstraint(v(i) - orthant_u(i) >=
2 * orthant_c_sum - 6);
}
const Expression v_dot_v1 = orthant_u.dot(v1);
const Expression v_dot_v2 = orthant_u.dot(v2);
prog->AddLinearConstraint(v_dot_v1 <= 3 - orthant_c_sum);
prog->AddLinearConstraint(orthant_c_sum - 3 <= v_dot_v1);
prog->AddLinearConstraint(v_dot_v2 <= 3 - orthant_c_sum);
prog->AddLinearConstraint(orthant_c_sum - 3 <= v_dot_v2);
const Vector3<Expression> v_cross_v1 = orthant_u.cross(v1);
for (int i = 0; i < 3; ++i) {
prog->AddLinearConstraint(v_cross_v1(i) - v2(i) <=
6 - 2 * orthant_c_sum);
prog->AddLinearConstraint(v_cross_v1(i) - v2(i) >=
2 * orthant_c_sum - 6);
}
}
} else {
// Find the intercepts of the unit sphere with the box, then find
// the tightest linear constraint of the form:
// d <= n'*v
// that puts v inside (but as close as possible to) the unit circle.
const double d =
box_sphere_intersection_halfspace[xi][yi][zi].second;
const Eigen::Vector3d& normal =
box_sphere_intersection_halfspace[xi][yi][zi].first;
Eigen::VectorXd b(0);
Eigen::Matrix<double, Eigen::Dynamic, 3> A(0, 3);
internal::ComputeInnerFacetsForBoxSphereIntersection(
box_sphere_intersection_vertices[xi][yi][zi], &A, &b);
// theta is the maximal angle between v and normal, where v is an
// intersecting point between the box and the sphere.
double cos_theta = d;
const double theta = std::acos(cos_theta);
Eigen::Matrix<double, 1, 6> a;
Eigen::Matrix<double, 3, 9> A_cross;
Eigen::Vector3d orthant_normal;
Vector3<Expression> orthant_c;
for (int o = 0; o < 8; o++) { // iterate over orthants
orthant_normal = FlipVector(normal, o);
orthant_c = PickPermutation(this_cpos, this_cneg, o);
for (int i = 0; i < A.rows(); ++i) {
// Add the constraint that A * v <= b, representing the inner
// facets f the convex hull, obtained from the vertices of the
// intersection region.
// This constraint is only active if the box is active.
// We impose the constraint
// A.row(i) * v - b(i) <= 3 - 3 * b(i) + (b(i) - 1) * (c[xi](0)
// + c[yi](1) + c[zi](2))
// Or in words
// If c[xi](0) = 1 and c[yi](1) = 1 and c[zi](1) = 1
// A.row(i) * v <= b(i)
// Otherwise
// A.row(i) * v -b(i) is not constrained
Eigen::Vector3d orthant_a =
-FlipVector(-A.row(i).transpose(), o);
prog->AddLinearConstraint(
orthant_a.dot(v) - b(i) <=
3 - 3 * b(i) +
(b(i) - 1) *
orthant_c.cast<symbolic::Expression>().sum());
}
// Max vector norm constraint: -1 <= normal'*x <= 1.
// No need to restrict to this orthant, but also no need to apply
// the same constraint twice (would be the same for opposite
// orthants), so skip all of the -x orthants.
if (o % 2 == 0)
prog->AddLinearConstraint(orthant_normal.transpose(), -1, 1, v);
const symbolic::Expression orthant_c_sum{orthant_c.sum()};
// Dot-product constraint: ideally v.dot(v1) = v.dot(v2) = 0.
// The cone of (unit) vectors within theta of the normal vector
// defines a band of admissible vectors v1 and v2 which are
// orthogonal to v. They must satisfy the constraint:
// -sin(theta) <= normal.dot(vi) <= sin(theta)
// Proof sketch:
// v is within theta of normal.
// => vi must be within theta of a vector orthogonal to
// the normal.
// => vi must be pi/2 +/- theta from the normal.
// => |normal||vi| cos(pi/2 + theta) <= normal.dot(vi) <=
// |normal||vi| cos(pi/2 - theta).
// Since normal and vi are both unit length,
// -sin(theta) <= normal.dot(vi) <= sin(theta).
// Note: (An alternative tighter, but SOCP constraint)
// v, v1, v2 forms an orthornormal basis. So n'*v is the
// projection of n in the v direction, same for n'*v1, n'*v2.
// Thus
// (n'*v)² + (n'*v1)² + (n'*v2)² = n'*n
// which translates to "The norm of a vector is equal to the
// sum of squares of the vector projected onto each axes of an
// orthornormal basis".
// This equation is the same as
// (nᵀ*v1)² + (nᵀ*v2)² <= sin(theta)²
// we can impose a tighter Lorentz cone constraint
// [|sin(theta)|, nᵀ*v1, nᵀ*v2] is in the Lorentz cone.
// We relax this Lorentz cone constraint by linear constraints
// -sinθ <= nᵀ * v1 <= sinθ
// -sinθ <= nᵀ * v2 <= sinθ
// To activate this constraint, we define
// c_sum = c[xi](0) + c[yi](1) + c[zi](2), and impose the
// following constraint using big-M approach.
// nᵀ * v1 - sinθ <= (1 - sinθ)*(3 - c_sum)
// nᵀ * v2 - sinθ <= (1 - sinθ)*(3 - c_sum)
// nᵀ * v1 + sinθ >= (-1 + sinθ)*(3 - c_sum)
// nᵀ * v2 + sinθ >= (-1 + sinθ)*(3 - c_sum)
const double sin_theta{sin(theta)};
prog->AddLinearConstraint(orthant_normal.dot(v1) + sin_theta >=
(-1 + sin_theta) * (3 - orthant_c_sum));
prog->AddLinearConstraint(orthant_normal.dot(v2) + sin_theta >=
(-1 + sin_theta) * (3 - orthant_c_sum));
prog->AddLinearConstraint(orthant_normal.dot(v1) - sin_theta <=
(1 - sin_theta) * (3 - orthant_c_sum));
prog->AddLinearConstraint(orthant_normal.dot(v2) - sin_theta <=
(1 - sin_theta) * (3 - orthant_c_sum));
// Cross-product constraint: ideally v2 = v.cross(v1).
// Since v is within theta of normal, we will prove that
// |v2 - normal.cross(v1)| <= 2 * sin(θ / 2)
// Notice that (v2 - normal.cross(v1))ᵀ * (v2 - normal.cross(v1))
// = v2ᵀ * v2 + |normal.cross(v1))|² -
// 2 * v2ᵀ * (normal.cross(v1))
// = 1 + |normal.cross(v1))|² - 2 * normalᵀ*(v1.cross(v2))
// = 1 + |normal.cross(v1))|² - 2 * normalᵀ*v
// <= 1 + 1 - 2 * cos(θ)
// = (2 * sin(θ / 2))²
// Thus we get |v2 - normal.cross(v1)| <= 2 * sin(θ / 2)
// Here we consider to use an elementwise linear constraint
// -2*sin(theta / 2) <= v2 - normal.cross(v1) <= 2*sin(θ / 2)
// Since 0<=θ<=pi/2, this should be enough to rule out the
// det(R)=-1 case (the shortest projection of a line across the
// circle onto a single axis has length 2sqrt(3)/3 > 1.15), and
// can be significantly tighter.
// To activate this only when the box is active, the complete
// constraints are
// -2*sin(θ/2)-(2 - 2sin(θ/2))*(3-(cxi+cyi+czi))
// <= v2-normal.cross(v1)
// <= 2*sin(θ/2)+(2 - 2sin(θ/2))*(3-(cxi+cyi+czi))
// Note: Again this constraint could be tighter as a Lorenz cone
// constraint of the form:
// |v2 - normal.cross(v1)| <= 2*sin(θ/2).
const double sin_theta2 = sin(theta / 2);
const Vector3<symbolic::Expression> v2_minus_n_cross_v1{
v2 - orthant_normal.cross(v1)};
prog->AddLinearConstraint(
v2_minus_n_cross_v1 <=
Vector3<symbolic::Expression>::Constant(
2 * sin_theta2 +
(2 - 2 * sin_theta2) * (3 - orthant_c_sum)));
prog->AddLinearConstraint(
v2_minus_n_cross_v1 >=
Vector3<symbolic::Expression>::Constant(
-2 * sin_theta2 +
(-2 + 2 * sin_theta2) * (3 - orthant_c_sum)));
}
}
} else {
// This box does not intersect with the surface of the sphere.
for (int o = 0; o < 8; ++o) { // iterate over orthants
prog->AddLinearConstraint(PickPermutation(this_cpos, this_cneg, o)
.cast<Expression>()
.sum(),
0.0, 2.0);
}
}
}
}
}
}
// This function just calls AddBoxSphereIntersectionConstraints for each
// row/column of R.
void AddBoxSphereIntersectionConstraintsForR(
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
const std::vector<Matrix3<symbolic::Expression>>& CRpos,
const std::vector<Matrix3<symbolic::Expression>>& CRneg,
int num_intervals_per_half_axis,
const std::vector<std::vector<std::vector<std::vector<Eigen::Vector3d>>>>&
box_sphere_intersection_vertices,
const std::vector<
std::vector<std::vector<std::pair<Eigen::Vector3d, double>>>>&
box_sphere_intersection_halfspace,
MathematicalProgram* prog) {
// Add constraints to the column and row vectors.
std::vector<Vector3<Expression>> cpos(num_intervals_per_half_axis),
cneg(num_intervals_per_half_axis);
for (int i = 0; i < 3; i++) {
// Make lists of the decision variables in terms of column vectors and row
// vectors to facilitate the calls below.
// TODO(russt): Consider reorganizing the original CRpos/CRneg variables to
// avoid this (albeit minor) cost?
for (int k = 0; k < num_intervals_per_half_axis; k++) {
cpos[k] = CRpos[k].col(i);
cneg[k] = CRneg[k].col(i);
}
AddBoxSphereIntersectionConstraints(
prog, R.col(i), cpos, cneg, R.col((i + 1) % 3), R.col((i + 2) % 3),
box_sphere_intersection_vertices, box_sphere_intersection_halfspace);
for (int k = 0; k < num_intervals_per_half_axis; k++) {
cpos[k] = CRpos[k].row(i).transpose();
cneg[k] = CRneg[k].row(i).transpose();
}
AddBoxSphereIntersectionConstraints(
prog, R.row(i).transpose(), cpos, cneg, R.row((i + 1) % 3).transpose(),
R.row((i + 2) % 3).transpose(), box_sphere_intersection_vertices,
box_sphere_intersection_halfspace);
}
}
// B[i][j] contains a vector of binary variables, such that if B[i][j] is the
// reflected gray code representation of integer k, then R(i, j) is in the k'th
// interval. We will write CRpos and CRneg as expressions of B, such that
// CRpos[k](i, j) = 1 <=> phi(k) <= R(i, j) <= phi(k + 1) => B[i][j] represents
// num_interval_per_half_axis + k in reflected gray code.
// CRneg[k](i, j) = 1 <=> -phi(k + 1) <= R(i, j) <= -phi(k) => B[i][j]
// represents num_interval_per_half_axis - k - 1 in reflected gray code.
template <typename T>
void GetCRposAndCRnegForLogarithmicBinning(
const std::array<std::array<T, 3>, 3>& B, int num_intervals_per_half_axis,
MathematicalProgram* prog, std::vector<Matrix3<Expression>>* CRpos,
std::vector<Matrix3<Expression>>* CRneg) {
if (num_intervals_per_half_axis > 1) {
const auto gray_codes = math::CalculateReflectedGrayCodes(
CeilLog2(num_intervals_per_half_axis) + 1);
CRpos->clear();
CRneg->clear();
CRpos->reserve(num_intervals_per_half_axis);
CRneg->reserve(num_intervals_per_half_axis);
for (int k = 0; k < num_intervals_per_half_axis; ++k) {
CRpos->push_back(prog->NewContinuousVariables<3, 3>(
"CRpos[" + std::to_string(k) + "]"));
CRneg->push_back(prog->NewContinuousVariables<3, 3>(
"CRneg[" + std::to_string(k) + "]"));
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
prog->AddConstraint(CreateBinaryCodeMatchConstraint(
B[i][j],
gray_codes.row(num_intervals_per_half_axis + k).transpose(),
(*CRpos)[k](i, j)));
prog->AddConstraint(CreateBinaryCodeMatchConstraint(
B[i][j],
gray_codes.row(num_intervals_per_half_axis - k - 1).transpose(),
(*CRneg)[k](i, j)));
}
}
}
} else {
// num_interval_per_half_axis = 1 is the special case, B[i][j](0) = 0 if
// -1 <= R(i, j) <= 0, and B[i][j](0) = 1 if 0 <= R(i, j) <= 1
CRpos->resize(1);
CRneg->resize(1);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
(*CRpos)[0](i, j) = B[i][j](0);
(*CRneg)[0](i, j) = 1 - B[i][j](0);
}
}
}
}
/**
* Compute the vertices of the intersection region between the boxes and the
* sphere surface. Also compute the tightest halfspace that contains the
* intersection region.
*/
void ComputeBoxSphereIntersectionAndHalfSpace(
int num_intervals_per_half_axis,
const Eigen::Ref<const Eigen::VectorXd>& phi_nonnegative,
std::vector<std::vector<std::vector<std::vector<Eigen::Vector3d>>>>*
box_sphere_intersection_vertices,
std::vector<std::vector<std::vector<std::pair<Eigen::Vector3d, double>>>>*
box_sphere_intersection_halfspace) {
const double kEpsilon = std::numeric_limits<double>::epsilon();
box_sphere_intersection_vertices->resize(num_intervals_per_half_axis);
box_sphere_intersection_halfspace->resize(num_intervals_per_half_axis);
for (int xi = 0; xi < num_intervals_per_half_axis; ++xi) {
(*box_sphere_intersection_vertices)[xi].resize(num_intervals_per_half_axis);
(*box_sphere_intersection_halfspace)[xi].resize(
num_intervals_per_half_axis);
for (int yi = 0; yi < num_intervals_per_half_axis; ++yi) {
(*box_sphere_intersection_vertices)[xi][yi].resize(
num_intervals_per_half_axis);
(*box_sphere_intersection_halfspace)[xi][yi].resize(
num_intervals_per_half_axis);
for (int zi = 0; zi < num_intervals_per_half_axis; ++zi) {
const Eigen::Vector3d box_min(phi_nonnegative(xi), phi_nonnegative(yi),
phi_nonnegative(zi));
const Eigen::Vector3d box_max(phi_nonnegative(xi + 1),
phi_nonnegative(yi + 1),
phi_nonnegative(zi + 1));
const double box_min_norm = box_min.lpNorm<2>();
const double box_max_norm = box_max.lpNorm<2>();
if (box_min_norm <= 1.0 - kEpsilon && box_max_norm >= 1.0 + kEpsilon) {
// box_min is strictly inside the sphere, box_max is strictly
// outside of the sphere.
// We choose eps here, because if a vector x has unit length, and
// another vector y is different from x by eps (||x - y||∞ < eps),
// then max ||y||₂ - 1 is eps.
(*box_sphere_intersection_vertices)[xi][yi][zi] =
internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max);
DRAKE_DEMAND((*box_sphere_intersection_vertices)[xi][yi][zi].size() >=
3);
Eigen::Vector3d normal{};
internal::ComputeHalfSpaceRelaxationForBoxSphereIntersection(
(*box_sphere_intersection_vertices)[xi][yi][zi],
&((*box_sphere_intersection_halfspace)[xi][yi][zi].first),
&((*box_sphere_intersection_halfspace)[xi][yi][zi].second));
} else if (std::abs(box_min_norm - 1) < kEpsilon) {
// box_min is on the surface. This is the unique intersection point
// between the sphere surface and the box.
(*box_sphere_intersection_vertices)[xi][yi][zi].push_back(
box_min / box_min_norm);
} else if (std::abs(box_max_norm - 1) < kEpsilon) {
// box_max is on the surface. This is the unique intersection point
// between the sphere surface and the box.
(*box_sphere_intersection_vertices)[xi][yi][zi].push_back(
box_max / box_max_norm);
}
}
}
}
}
} // namespace
std::string to_string(MixedIntegerRotationConstraintGenerator::Approach type) {
switch (type) {
case MixedIntegerRotationConstraintGenerator::Approach::
kBoxSphereIntersection: {
return "box_sphere_intersection";
}
case MixedIntegerRotationConstraintGenerator::Approach::
kBilinearMcCormick: {
return "bilinear_mccormick";
}
case MixedIntegerRotationConstraintGenerator::Approach::kBoth: {
return "both";
}
}
// The following line should not be reached. We add it due to a compiler
// defect.
throw std::runtime_error("Should not reach this part of the code.\n");
}
std::ostream& operator<<(
std::ostream& os,
const MixedIntegerRotationConstraintGenerator::Approach& type) {
os << to_string(type);
return os;
}
MixedIntegerRotationConstraintGenerator::
MixedIntegerRotationConstraintGenerator(
MixedIntegerRotationConstraintGenerator::Approach approach,
int num_intervals_per_half_axis, IntervalBinning interval_binning)
: approach_{approach},
num_intervals_per_half_axis_{num_intervals_per_half_axis},
interval_binning_{interval_binning},
phi_nonnegative_{
Eigen::VectorXd::LinSpaced(num_intervals_per_half_axis_ + 1, 0, 1)} {
phi_.resize(2 * num_intervals_per_half_axis_ + 1);
phi_(num_intervals_per_half_axis_) = 0;
for (int i = 1; i <= num_intervals_per_half_axis_; ++i) {
phi_(num_intervals_per_half_axis_ - i) = -phi_nonnegative_(i);
phi_(num_intervals_per_half_axis_ + i) = phi_nonnegative_(i);
}
// If we consider the box-sphere intersection, then we need to compute the
// halfspace nᵀx≥ d, as the tightest halfspace for each intersection region.
if (approach_ == Approach::kBoxSphereIntersection ||
approach_ == Approach::kBoth) {
ComputeBoxSphereIntersectionAndHalfSpace(
num_intervals_per_half_axis_, phi_nonnegative_,
&box_sphere_intersection_vertices_,
&box_sphere_intersection_halfspace_);
}
}
MixedIntegerRotationConstraintGenerator::ReturnType
MixedIntegerRotationConstraintGenerator::AddToProgram(
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
MathematicalProgram* prog) const {
ReturnType ret;
// Add new variable λ[i][j] and B[i][j] for R(i, j).
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
const std::string lambda_name =
"lambda[" + std::to_string(i) + "][" + std::to_string(j) + "]";
ret.lambda_[i][j] = prog->NewContinuousVariables(
2 * num_intervals_per_half_axis_ + 1, lambda_name);
// R(i, j) = φᵀ * λ[i][j]
prog->AddLinearEqualityConstraint(
R(i, j) -
phi_.dot(ret.lambda_[i][j].template cast<symbolic::Expression>()),
0);
switch (interval_binning_) {
case IntervalBinning::kLogarithmic: {
ret.B_[i][j] = AddLogarithmicSos2Constraint(
prog, ret.lambda_[i][j].cast<symbolic::Expression>());
break;
}
case IntervalBinning::kLinear: {
ret.B_[i][j] = prog->NewBinaryVariables(
2 * num_intervals_per_half_axis_,
"B[" + std::to_string(i) + "][" + std::to_string(j) + "]");
AddSos2Constraint(prog,
ret.lambda_[i][j].cast<symbolic::Expression>(),
ret.B_[i][j].cast<symbolic::Expression>());
break;
}
}
}
}
// Add some cutting planes on the binary variables, by inferring the sign
// of R(i, j) from binary variables B[i][j].
AddConstraintInferredFromTheSign(prog, ret.B_, num_intervals_per_half_axis_,
interval_binning_);
// Add mixed-integer constraint by replacing the bilinear product with another
// term in the McCormick envelope of w = x * y
if (approach_ == Approach::kBilinearMcCormick ||
approach_ == Approach::kBoth) {
AddRotationMatrixBilinearMcCormickConstraints(prog, R, ret.B_, ret.lambda_,
phi_, interval_binning_);
}
// Add mixed-integer constraint by considering the intersection between the
// sphere surface and boxes.
if (approach_ == Approach::kBoxSphereIntersection ||
approach_ == Approach::kBoth) {
// CRpos[k](i, j) = 1 => φ₊(k) ≤ R(i, j) ≤ φ₊(k+1)
// CRneg[k](i, j) = 1 => -φ₊(k+1) ≤ R(i, j) ≤ -φ₊(k)
std::vector<Matrix3<Expression>> CRpos(num_intervals_per_half_axis_);
std::vector<Matrix3<Expression>> CRneg(num_intervals_per_half_axis_);
if (interval_binning_ == IntervalBinning::kLinear) {
// CRpos[k](i, j) = 1 => φ₊(k) ≤ R(i, j) ≤ φ₊(k+1) => B[i][j](N+k) = 1
// CRneg[k](i, j) = 1 => -φ₊(k+1) ≤ R(i, j) ≤ -φ₊(k) => B[i][j](N-k-1)=1
// where N = num_intervals_per_half_axis_.
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < num_intervals_per_half_axis_; ++k) {
CRpos[k](i, j) = +ret.B_[i][j](num_intervals_per_half_axis_ + k);
CRneg[k](i, j) =
+ret.B_[i][j](num_intervals_per_half_axis_ - k - 1);
}
}
}
} else if (interval_binning_ == IntervalBinning::kLogarithmic) {
GetCRposAndCRnegForLogarithmicBinning(
ret.B_, num_intervals_per_half_axis_, prog, &CRpos, &CRneg);
}
AddBoxSphereIntersectionConstraintsForR(
R, CRpos, CRneg, num_intervals_per_half_axis_,
box_sphere_intersection_vertices_, box_sphere_intersection_halfspace_,
prog);
}
return ret;
}
AddRotationMatrixBoxSphereIntersectionReturn
AddRotationMatrixBoxSphereIntersectionMilpConstraints(
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
int num_intervals_per_half_axis, MathematicalProgram* prog) {
DRAKE_DEMAND(num_intervals_per_half_axis >= 1);
AddRotationMatrixBoxSphereIntersectionReturn ret;
// Use a simple lambda to make the constraints more readable below.
// Note that
// forall k>=0, 0<=phi(k), and
// forall k<=num_intervals_per_half_axis, phi(k)<=1.
const Eigen::VectorXd phi_nonnegative =
Eigen::VectorXd::LinSpaced(num_intervals_per_half_axis + 1, 0, 1);
// Creates binary decision variables which discretize each axis.
// BRpos[k](i,j) = 1 => R(i,j) >= phi(k)
// BRneg[k](i,j) = 1 => R(i,j) <= -phi(k)
for (int k = 0; k < num_intervals_per_half_axis; k++) {
ret.BRpos.push_back(
prog->NewBinaryVariables<3, 3>("BRpos" + std::to_string(k)));
ret.BRneg.push_back(
prog->NewBinaryVariables<3, 3>("BRneg" + std::to_string(k)));
}
// For convenience, we also introduce additional expressions to
// represent the individual sections of the real line
// CRpos[k](i, j) = 1 => phi(k) <= R(i, j) <= phi(k + 1)
// CRpos[k](i,j) = BRpos[k](i,j) if k=N-1, otherwise
// CRpos[k](i,j) = BRpos[k](i,j) - BRpos[k+1](i,j)
// Similarly CRneg[k](i, j) = 1 => -phi(k + 1) <= R(i, j) <= -phi(k)
// CRneg[k](i, j) = CRneg[k](i, j) if k = N-1, otherwise
// CRneg[k](i, j) = CRneg[k](i, j) - CRneg[k+1](i, j)
ret.CRpos.reserve(num_intervals_per_half_axis);
ret.CRneg.reserve(num_intervals_per_half_axis);
for (int k = 0; k < num_intervals_per_half_axis - 1; k++) {
ret.CRpos.push_back(ret.BRpos[k] - ret.BRpos[k + 1]);
ret.CRneg.push_back(ret.BRneg[k] - ret.BRneg[k + 1]);
}
ret.CRpos.push_back(
ret.BRpos[num_intervals_per_half_axis - 1].cast<symbolic::Expression>());
ret.CRneg.push_back(
ret.BRneg[num_intervals_per_half_axis - 1].cast<symbolic::Expression>());
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < num_intervals_per_half_axis; k++) {
// R(i,j) > phi(k) => BRpos[k](i,j) = 1
// R(i,j) < phi(k) => BRpos[k](i,j) = 0
// R(i,j) = phi(k) => BRpos[k](i,j) = 0 or 1
// Since -s1 <= R(i, j) - phi(k) <= s2,
// where s1 = 1 + phi(k), s2 = 1 - phi(k). The point
// [R(i,j) - phi(k), BRpos[k](i,j)] has to lie within the convex hull,
// whose vertices are (-s1, 0), (0, 0), (s2, 1), (0, 1). By computing
// the edges of this convex hull, we get
// -s1 + s1*BRpos[k](i,j) <= R(i,j)-phi(k) <= s2 * BRpos[k](i,j)
double s1 = 1 + phi_nonnegative(k);
double s2 = 1 - phi_nonnegative(k);
prog->AddLinearConstraint(R(i, j) - phi_nonnegative(k) >=
-s1 + s1 * ret.BRpos[k](i, j));
prog->AddLinearConstraint(R(i, j) - phi_nonnegative(k) <=
s2 * ret.BRpos[k](i, j));
// -R(i,j) > phi(k) => BRneg[k](i,j) = 1
// -R(i,j) < phi(k) => BRneg[k](i,j) = 0
// -R(i,j) = phi(k) => BRneg[k](i,j) = 0 or 1
// Since -s2 <= R(i, j) + phi(k) <= s1,
// where s1 = 1 + phi(k), s2 = 1 - phi(k). The point
// [R(i,j) + phi(k), BRneg[k](i,j)] has to lie within the convex hull
// whose vertices are (-s2, 1), (0, 0), (s1, 0), (0, 1). By computing
// the edges of the convex hull, we get
// -s2 * BRneg[k](i,j) <= R(i,j)+phi(k) <= s1-s1*BRneg[k](i,j)
prog->AddLinearConstraint(R(i, j) + phi_nonnegative(k) <=
s1 - s1 * ret.BRneg[k](i, j));
prog->AddLinearConstraint(R(i, j) + phi_nonnegative(k) >=
-s2 * ret.BRneg[k](i, j));
}
// R(i,j) has to pick a side, either non-positive or non-negative.
prog->AddLinearConstraint(ret.BRpos[0](i, j) + ret.BRneg[0](i, j) == 1);
// for debugging: constrain to positive orthant.
// prog->AddBoundingBoxConstraint(1,1,{BRpos[0].block<1,1>(i,j)});
}
}
// Add constraint that no two rows (or two columns) can lie in the same
// orthant (or opposite orthant).
AddNotInSameOrOppositeOrthantConstraint(prog, ret.BRpos[0]);
AddNotInSameOrOppositeOrthantConstraint(prog, ret.BRpos[0].transpose());
std::vector<std::vector<std::vector<std::vector<Eigen::Vector3d>>>>
box_sphere_intersection_vertices;
std::vector<std::vector<std::vector<std::pair<Eigen::Vector3d, double>>>>
box_sphere_intersection_halfspace;
ComputeBoxSphereIntersectionAndHalfSpace(
num_intervals_per_half_axis, phi_nonnegative,
&box_sphere_intersection_vertices, &box_sphere_intersection_halfspace);
AddBoxSphereIntersectionConstraintsForR(
R, ret.CRpos, ret.CRneg, num_intervals_per_half_axis,
box_sphere_intersection_vertices, box_sphere_intersection_halfspace,
prog);
AddCrossProductImpliedOrthantConstraint(prog, ret.BRpos[0]);
AddCrossProductImpliedOrthantConstraint(prog, ret.BRpos[0].transpose());
return ret;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mosek_solver_common.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/mosek_solver.h"
/* clang-format on */
#include <cstdlib>
#include <cstring>
#include "drake/common/never_destroyed.h"
#include "drake/solvers/aggregate_costs_constraints.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
MosekSolver::MosekSolver()
: SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied,
&UnsatisfiedProgramAttributes) {}
MosekSolver::~MosekSolver() = default;
SolverId MosekSolver::id() {
static const never_destroyed<SolverId> singleton{"Mosek"};
return singleton.access();
}
bool MosekSolver::is_enabled() {
const char* moseklm_license_file = std::getenv("MOSEKLM_LICENSE_FILE");
return ((moseklm_license_file != nullptr) &&
(std::strlen(moseklm_license_file) > 0));
}
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::kQuadraticConstraint,
ProgramAttribute::kLorentzConeConstraint,
ProgramAttribute::kRotatedLorentzConeConstraint,
ProgramAttribute::kPositiveSemidefiniteConstraint,
ProgramAttribute::kExponentialConeConstraint,
ProgramAttribute::kLinearCost, ProgramAttribute::kQuadraticCost,
ProgramAttribute::kL2NormCost, ProgramAttribute::kBinaryVariable});
return internal::CheckConvexSolverAttributes(
prog, solver_capabilities.access(), "MosekSolver", explanation);
}
} // namespace
bool MosekSolver::ProgramAttributesSatisfied(const MathematicalProgram& prog) {
return CheckAttributes(prog, nullptr);
}
std::string MosekSolver::UnsatisfiedProgramAttributes(
const MathematicalProgram& prog) {
std::string explanation;
CheckAttributes(prog, &explanation);
return explanation;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/augmented_lagrangian.h | #pragma once
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
/**
* Compute the augmented Lagrangian (AL) of a given mathematical program
*
* min f(x)
* s.t h(x) = 0
* l <= g(x) <= u
* x_lo <= x <= x_up
*
* We first turn it into an equality constrained program with non-negative slack
* variable s as follows
*
* min f(x)
* s.t h(x) = 0
* c(x) - s = 0
* s >= 0
*
* Depending on the option include_x_bounds, the constraint h(x)=0, c(x)>=0 may
* or may not include the bounding box constraint x_lo <= x <= x_up.
*
* the (non-smooth) augmented Lagrangian is defined as
*
* L(x, λ, μ) = f(x) − λ₁ᵀh(x) + μ/2 h(x)ᵀh(x)
* - λ₂ᵀ(c(x)-s) + μ/2 (c(x)-s)ᵀ(c(x)-s)
*
* where s = max(c(x) - λ₂/μ, 0).
*
* For more details, refer to section 17.4 of Numerical Optimization by Jorge
* Nocedal and Stephen Wright, Edition 1, 1999 (This formulation isn't presented
* in Edition 2, but to stay consistent with Edition 2, we use μ/2 as the
* coefficient of the quadratic penalty term instead of 1/(2μ) in Edition 1).
* Note that the augmented Lagrangian L(x, λ, μ) is NOT a smooth function of x,
* since s = max(c(x) - λ₂/μ, 0) is non-smooth at c(x) - λ₂/μ = 0.
*/
class AugmentedLagrangianNonsmooth {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(AugmentedLagrangianNonsmooth)
/**
* @param prog The mathematical program we will evaluate.
* @param include_x_bounds. Whether the Lagrangian and the penalty for the
* bounds x_lo <= x <= x_up are included in the augmented Lagrangian L(x, λ,
* μ) or not.
*/
AugmentedLagrangianNonsmooth(const MathematicalProgram* prog,
bool include_x_bounds);
/**
* @param x The value of all the decision variables.
* @param lambda_val The estimated Lagrangian multipliers. The order of the
* Lagrangian multiplier is as this: We first call to evaluate all
* constraints. Then for each row of the constraint, if it is an equality
* constraint, we append one single Lagrangian multiplier. Otherwise we
* append the Lagrangian multiplier for the lower and upper bounds (where the
* lower comes before the upper), if the corresponding bound is not ±∞. The
* order of evaluating all the constraints is the same as
* prog.GetAllConstraints() except for prog.bounding_box_constraints(). If
* include_x_bounds=true, then we aggregate all the bounding_box_constraints()
* and evaluate them at the end of all constraints.
* @param mu μ in the documentation above. The constant for penalty term
* weight. This should be a strictly positive number.
* @param[out] constraint_residue The value of the all the constraints. For an
* equality constraint c(x)=0 or the inequality constraint c(x)>= 0, the
* residue is c(x). Depending on include_x_bounds, `constraint_residue` may or
* may not contain the residue for bounding box constraints x_lo <= x <= x_up
* at the end.
* @param[out] cost The value of the cost function f(x).
* @return The evaluated Augmented Lagrangian (AL) L(x, λ, μ).
*/
template <typename T>
T Eval(const Eigen::Ref<const VectorX<T>>& x,
const Eigen::VectorXd& lambda_val, double mu,
VectorX<T>* constraint_residue, T* cost) const;
/**
* @return The mathematical program for which the augmented Lagrangian is
* computed.
*/
[[nodiscard]] const MathematicalProgram& prog() const { return *prog_; }
/**
* @return Whether the bounding box constraint x_lo <= x <=
* x_up is included in the augmented Lagrangian L(x, λ, μ).
*/
[[nodiscard]] bool include_x_bounds() const { return include_x_bounds_; }
/**
* @return The size of the Lagrangian multiplier λ.
*/
[[nodiscard]] int lagrangian_size() const { return lagrangian_size_; }
/**
* @return Whether each constraint is equality or not. The order of the
* constraint is explained in the class documentation.
*/
[[nodiscard]] const std::vector<bool>& is_equality() const {
return is_equality_;
}
/** @return all the lower bounds of x. */
[[nodiscard]] const Eigen::VectorXd& x_lo() const { return x_lo_; }
/** @return all the upper bounds of x. */
[[nodiscard]] const Eigen::VectorXd& x_up() const { return x_up_; }
private:
const MathematicalProgram* prog_;
bool include_x_bounds_;
int lagrangian_size_;
std::vector<bool> is_equality_;
Eigen::VectorXd x_lo_;
Eigen::VectorXd x_up_;
};
/**
* Compute the augmented Lagrangian (AL) of a given mathematical program
*
* min f(x)
* s.t h(x) = 0
* l <= g(x) <= u
* x_lo <= x <= x_up
*
* We first turn it into an equality constrained program with non-negative slack
* variable s as follows
*
* min f(x)
* s.t h(x) = 0
* c(x) - s = 0
* s >= 0
*
* We regard this as an optimization problem on variable (x, s), with equality
* constraints h(x) = 0, c(x)-s = 0, and the bound constraint s >= 0.
*
* Depending on the option include_x_bounds, the constraint h(x)=0, c(x)>=0 may
* or may not include the bounding box constraint x_lo <= x <= x_up.
*
* The (smooth) augmented Lagrangian is defined as
*
* L(x, s, λ, μ) = f(x) − λ₁ᵀh(x) + μ/2 h(x)ᵀh(x)
* - λ₂ᵀ(c(x)-s) + μ/2 (c(x)-s)ᵀ(c(x)-s)
*
* For more details, refer to section 17.4 of Numerical Optimization by Jorge
* Nocedal and Stephen Wright, Edition 2, 2006.
* Note that the augmented Lagrangian L(x, s, λ, μ) is a smooth function of (x,
* s),
*
* This is the implementation used in LANCELOT. To solve the nonlinear
* optimization through this Augmented Lagrangian, the nonlinear solve should be
* able to handle bounding box constraints on the decision variables.
*/
class AugmentedLagrangianSmooth {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(AugmentedLagrangianSmooth)
/**
* @param prog The mathematical program we will evaluate.
* @param include_x_bounds. Whether the Lagrangian and the penalty for the
* bounds x_lo <= x <= x_up are included in the augmented Lagrangian L(x, s,
* λ, μ) or not.
*/
AugmentedLagrangianSmooth(const MathematicalProgram* prog,
bool include_x_bounds);
/**
* @param x The value of all the decision variables in prog().
* @param s The value of all slack variables s.
* @param lambda_val The estimated Lagrangian multipliers. The order of the
* Lagrangian multiplier is as follows: We first call to evaluate all
* constraints. Then for each row of the constraint, if it is an equality
* constraint, we append one single Lagrangian multiplier. Otherwise we
* append the Lagrangian multiplier for the lower and upper bounds (where the
* lower comes before the upper), if the corresponding bound is not ±∞. The
* order of evaluating all the constraints is the same as
* prog.GetAllConstraints() except for prog.bounding_box_constraints(). If
* include_x_bounds=true, then we aggregate all the bounding_box_constraints()
* and evaluate them at the end of all constraints.
* @param mu μ in the documentation above. The constant for penalty term
* weight. This should be a strictly positive number.
* @param[out] constraint_residue The value of the all the constraints. For an
* equality constraint c(x)=0, the residue is c(x); for an inequality
* constraint c(x)>=0, the residue is c(x)-s where s is the corresponding
* slack variable. Depending on include_x_bounds, `constraint_residue` may or
* may not contain the residue for bounding box constraints x_lo <= x <= x_up
* at the end.
* @param[out] cost The value of the cost function f(x).
* @return The evaluated Augmented Lagrangian (AL) L(x, s, λ, μ).
* @note This Eval function differs from AugmentedLagrangianNonsmooth::Eval()
* function as `s` is an input argument.
*/
template <typename T>
T Eval(const Eigen::Ref<const VectorX<T>>& x,
const Eigen::Ref<const VectorX<T>>& s,
const Eigen::VectorXd& lambda_val, double mu,
VectorX<T>* constraint_residue, T* cost) const;
/**
* @return The mathematical program for which the augmented Lagrangian is
* computed.
*/
[[nodiscard]] const MathematicalProgram& prog() const { return *prog_; }
/**
* @return Whether the bounding box constraint x_lo <= x <=
* x_up is included in the augmented Lagrangian L(x, λ, μ).
*/
[[nodiscard]] bool include_x_bounds() const { return include_x_bounds_; }
/**
* @return The size of the Lagrangian multiplier λ.
*/
[[nodiscard]] int lagrangian_size() const { return lagrangian_size_; }
/**
* @return The size of the slack variable s.
*/
[[nodiscard]] int s_size() const { return s_size_; }
/**
* @return Whether each constraint is equality or not. The order of the
* constraint is explained in the class documentation.
*/
[[nodiscard]] const std::vector<bool>& is_equality() const {
return is_equality_;
}
/** @return All the lower bounds of x. */
[[nodiscard]] const Eigen::VectorXd& x_lo() const { return x_lo_; }
/** @return All the upper bounds of x. */
[[nodiscard]] const Eigen::VectorXd& x_up() const { return x_up_; }
private:
const MathematicalProgram* prog_;
bool include_x_bounds_;
int lagrangian_size_;
int s_size_{0};
std::vector<bool> is_equality_;
Eigen::VectorXd x_lo_;
Eigen::VectorXd x_up_;
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solver_interface.cc | #include "drake/solvers/solver_interface.h"
namespace drake {
namespace solvers {
SolverInterface::SolverInterface() = default;
SolverInterface::~SolverInterface() = default;
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/function.h | #pragma once
#include <memory>
#include <Eigen/Dense>
#include "drake/common/eigen_types.h"
namespace drake {
namespace solvers {
namespace internal {
template <typename ScalarType>
using VecIn = Eigen::Ref<const VectorX<ScalarType>>;
template <typename ScalarType>
using VecOut = VectorX<ScalarType>;
/** FunctionTraits
* @brief Define interface to a function of the form y = f(x).
*/
template <typename F>
struct FunctionTraits {
// TODO(bradking): add in/out relation, possibly distinguish
// differentiable functions
static size_t numInputs(F const& f) { return f.numInputs(); }
static size_t numOutputs(F const& f) { return f.numOutputs(); }
template <typename ScalarType>
static void eval(F const& f, VecIn<ScalarType> const& x,
VecOut<ScalarType>* y) {
f.eval(x, y);
}
};
template <typename F>
struct FunctionTraits<std::reference_wrapper<F>> {
static size_t numInputs(std::reference_wrapper<F> const& f) {
return FunctionTraits<F>::numInputs(f.get());
}
static size_t numOutputs(std::reference_wrapper<F> const& f) {
return FunctionTraits<F>::numOutputs(f.get());
}
template <typename ScalarType>
static void eval(std::reference_wrapper<F> const& f,
VecIn<ScalarType> const& x, VecOut<ScalarType>* y) {
FunctionTraits<F>::eval(f.get(), x, y);
}
};
template <typename F>
struct FunctionTraits<std::shared_ptr<F>> {
static size_t numInputs(std::shared_ptr<F> const& f) {
return FunctionTraits<F>::numInputs(*f);
}
static size_t numOutputs(std::shared_ptr<F> const& f) {
return FunctionTraits<F>::numOutputs(*f);
}
template <typename ScalarType>
static void eval(std::shared_ptr<F> const& f, VecIn<ScalarType> const& x,
VecOut<ScalarType>* y) {
FunctionTraits<F>::eval(*f, x, y);
}
};
template <typename F>
struct FunctionTraits<std::unique_ptr<F>> {
static size_t numInputs(std::unique_ptr<F> const& f) {
return FunctionTraits<F>::numInputs(*f);
}
static size_t numOutputs(std::unique_ptr<F> const& f) {
return FunctionTraits<F>::numOutputs(*f);
}
template <typename ScalarType>
static void eval(std::unique_ptr<F> const& f, VecIn<ScalarType> const& x,
VecOut<ScalarType>* y) {
FunctionTraits<F>::eval(*f, x, y);
}
};
// idea: use templates to support multi-input, multi-output functions which
// implement, e.g.
// void eval(x1,..., xn, y1,..., ym), and
// InputOutputRelation getInputOutputRelation(input_index, output_index)
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/mathematical_program.h | #pragma once
#include <array>
#include <cstddef>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <optional>
#include <ostream>
#include <set>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include <Eigen/Core>
#include <Eigen/SparseCore>
#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/common/fmt.h"
#include "drake/common/polynomial.h"
#include "drake/common/symbolic/expression.h"
#include "drake/common/symbolic/monomial_util.h"
#include "drake/common/symbolic/polynomial.h"
#include "drake/solvers/binding.h"
#include "drake/solvers/constraint.h"
#include "drake/solvers/cost.h"
#include "drake/solvers/create_constraint.h"
#include "drake/solvers/create_cost.h"
#include "drake/solvers/decision_variable.h"
#include "drake/solvers/function.h"
#include "drake/solvers/indeterminate.h"
#include "drake/solvers/program_attribute.h"
#include "drake/solvers/solver_options.h"
namespace drake {
namespace solvers {
template <int...>
struct NewVariableNames {};
/**
* The type of the names for the newly added variables.
* @tparam Size If Size is a fixed non-negative integer, then the type of the
* name is std::array<std::string, Size>. Otherwise the type is
* std::vector<std::string>.
*/
template <int Size>
struct NewVariableNames<Size> {
typedef std::array<std::string, Size> type;
};
template <>
struct NewVariableNames<Eigen::Dynamic> {
typedef std::vector<std::string> type;
};
template <int Rows, int Cols>
struct NewVariableNames<Rows, Cols>
: public NewVariableNames<
Eigen::Matrix<double, Rows, Cols>::SizeAtCompileTime> {};
template <int Rows>
struct NewSymmetricVariableNames
: public NewVariableNames<Rows == Eigen::Dynamic ? Eigen::Dynamic
: Rows*(Rows + 1) / 2> {};
namespace internal {
/**
* Return un-initialized new variable names.
*/
template <int Size>
typename std::enable_if_t<Size >= 0, typename NewVariableNames<Size>::type>
CreateNewVariableNames(int) {
typename NewVariableNames<Size>::type names;
return names;
}
/**
* Return un-initialized new variable names.
*/
template <int Size>
typename std::enable_if_t<Size == Eigen::Dynamic,
typename NewVariableNames<Size>::type>
CreateNewVariableNames(int size) {
typename NewVariableNames<Eigen::Dynamic>::type names(size);
return names;
}
/**
* Set the names of the newly added variables.
* @param name The common name of all new variables.
* @param rows The number of rows in the new variables.
* @param cols The number of columns in the new variables.
* @pre The size of @p names is @p rows * @p cols.
*/
template <typename Derived>
void SetVariableNames(const std::string& name, int rows, int cols,
Derived* names) {
DRAKE_DEMAND(static_cast<int>(names->size()) == rows * cols);
if (cols == 1) {
for (int i = 0; i < rows; ++i) {
(*names)[i] = name + "(" + std::to_string(i) + ")";
}
} else {
for (int j = 0; j < cols; ++j) {
for (int i = 0; i < rows; ++i) {
(*names)[j * rows + i] =
name + "(" + std::to_string(i) + "," + std::to_string(j) + ")";
}
}
}
}
/**
* Template condition to only catch when Constraints are inadvertently passed
* as an argument. If the class is binding-compatible with a Constraint, then
* this will provide a static assertion to enable easier debugging of which
* type failed.
* @tparam F The type to be tested.
* @see http://stackoverflow.com/a/13366183/7829525
*/
template <typename F>
struct assert_if_is_constraint {
static constexpr bool value = is_binding_compatible<F, Constraint>::value;
// Use deferred evaluation
static_assert(
!value,
"You cannot pass a Constraint to create a Cost object from a function. "
"Please ensure you are passing a Cost.");
};
} // namespace internal
/**
* MathematicalProgram stores the decision variables, the constraints and costs
* of an optimization problem. The user can solve the problem by calling
* solvers::Solve() function, and obtain the results of the optimization.
*
* @ingroup solvers
*/
class MathematicalProgram {
public:
/** @name Does not allow copy, move, or assignment. */
/** @{ */
#ifdef DRAKE_DOXYGEN_CXX
// Copy constructor is private for use in implementing Clone().
MathematicalProgram(const MathematicalProgram&) = delete;
#endif
MathematicalProgram& operator=(const MathematicalProgram&) = delete;
MathematicalProgram(MathematicalProgram&&) = delete;
MathematicalProgram& operator=(MathematicalProgram&&) = delete;
/** @} */
using VarType = symbolic::Variable::Type;
/// The optimal cost is +∞ when the problem is globally infeasible.
static constexpr double kGlobalInfeasibleCost =
std::numeric_limits<double>::infinity();
/// The optimal cost is -∞ when the problem is unbounded.
static constexpr double kUnboundedCost =
-std::numeric_limits<double>::infinity();
MathematicalProgram();
virtual ~MathematicalProgram();
/** Clones an optimization program.
* The clone will be functionally equivalent to the source program with the
* same:
*
* - decision variables
* - constraints
* - costs
* - solver settings
* - initial guess
*
* Note that this is currently a *shallow* clone. The costs and constraints
* are not themselves cloned.
*
* @retval new_prog. The newly constructed mathematical program.
*/
[[nodiscard]] std::unique_ptr<MathematicalProgram> Clone() const;
/**
* Returns string representation of this program, listing the decision
* variables, costs, and constraints.
*
* Note that by default, we do not require variables to have unique names.
* Providing useful variable names and calling Evaluator::set_description() to
* describe the costs and constraints can dramatically improve the readability
* of the output. See the tutorial `debug_mathematical_program.ipynb`
* for more information.
*/
[[nodiscard]] std::string to_string() const;
/** Returns a string representation of this program in LaTeX.
*
* This can be particularly useful e.g. in a Jupyter (python) notebook:
* @code
* from IPython.display import Markdown, display
* display(Markdown(prog.ToLatex()))
* @endcode
*
* Note that by default, we do not require variables to have unique names.
* Providing useful variable names and calling Evaluator::set_description() to
* describe the costs and constraints can dramatically improve the readability
* of the output. See the tutorial `debug_mathematical_program.ipynb`
* for more information.
*/
std::string ToLatex(int precision = 3);
/**
* Adds continuous variables, appending them to an internal vector of any
* existing vars.
* The initial guess values for the new variables are set to NaN, to
* indicate that an initial guess has not been assigned.
* Callers are expected to add costs
* and/or constraints to have any effect during optimization.
* Callers can also set the initial guess of the decision variables through
* SetInitialGuess() or SetInitialGuessForAllVariables().
* @param rows The number of rows in the new variables.
* @param name The name of the newly added variables
* @return The VectorDecisionVariable of size rows x 1, containing the new
* vars (not all the vars stored).
*
* Example:
* @code{.cc}
* MathematicalProgram prog;
* auto x = prog.NewContinuousVariables(2, "x");
* @endcode
* This adds a 2 x 1 vector containing decision variables into the program.
* The names of the variables are "x(0)" and "x(1)".
*
* The name of the variable is only used for the user in order to ease
* readability.
*/
VectorXDecisionVariable NewContinuousVariables(
int rows, const std::string& name = "x") {
return NewContinuousVariables<Eigen::Dynamic, 1>(rows, 1, name);
}
/**
* Adds continuous variables, appending them to an internal vector of any
* existing vars.
* The initial guess values for the new variables are set to NaN, to
* indicate that an initial guess has not been assigned.
* Callers are expected to add costs
* and/or constraints to have any effect during optimization.
* Callers can also set the initial guess of the decision variables through
* SetInitialGuess() or SetInitialGuessForAllVariables().
* @tparam Rows The number of rows of the new variables, in the compile time.
* @tparam Cols The number of columns of the new variables, in the compile
* time.
* @param rows The number of rows in the new variables. When Rows is not
* Eigen::Dynamic, rows is ignored.
* @param cols The number of columns in the new variables. When Cols is not
* Eigen::Dynamic, cols is ignored.
* @param name All variables will share the same name, but different index.
* @return The MatrixDecisionVariable of size Rows x Cols, containing the new
* vars (not all the vars stored).
*
* Example:
* @code{.cc}
* MathematicalProgram prog;
* auto x = prog.NewContinuousVariables(2, 3, "X");
* auto y = prog.NewContinuousVariables<2, 3>(2, 3, "X");
* @endcode
* This adds a 2 x 3 matrix decision variables into the program.
*
* The name of the variable is only used for the user in order to ease
* readability.
*/
template <int Rows = Eigen::Dynamic, int Cols = Eigen::Dynamic>
MatrixDecisionVariable<Rows, Cols> NewContinuousVariables(
int rows, int cols, const std::string& name = "X") {
rows = Rows == Eigen::Dynamic ? rows : Rows;
cols = Cols == Eigen::Dynamic ? cols : Cols;
auto names = internal::CreateNewVariableNames<
Eigen::Matrix<double, Rows, Cols>::SizeAtCompileTime>(rows * cols);
internal::SetVariableNames(name, rows, cols, &names);
return NewVariables<Rows, Cols>(VarType::CONTINUOUS, names, rows, cols);
}
/**
* Adds continuous variables, appending them to an internal vector of any
* existing vars.
* The initial guess values for the new variables are set to NaN, to
* indicate that an initial guess has not been assigned.
* Callers are expected to add costs
* and/or constraints to have any effect during optimization.
* Callers can also set the initial guess of the decision variables through
* SetInitialGuess() or SetInitialGuessForAllVariables().
* @tparam Rows The number of rows in the new variables.
* @tparam Cols The number of columns in the new variables. The default is 1.
* @param name All variables will share the same name, but different index.
* @return The MatrixDecisionVariable of size rows x cols, containing the new
* vars (not all the vars stored).
*
* Example:
* @code{.cc}
* MathematicalProgram prog;
* auto x = prog.NewContinuousVariables<2, 3>("X");
* @endcode
* This adds a 2 x 3 matrix decision variables into the program.
*
* The name of the variable is only used for the user in order to ease
* readability.
*/
template <int Rows, int Cols = 1>
MatrixDecisionVariable<Rows, Cols> NewContinuousVariables(
const std::string& name = "X") {
return NewContinuousVariables<Rows, Cols>(Rows, Cols, name);
}
/**
* Adds binary variables, appending them to an internal vector of any
* existing vars.
* The initial guess values for the new variables are set to NaN, to
* indicate that an initial guess has not been assigned.
* Callers are expected to add costs
* and/or constraints to have any effect during optimization.
* Callers can also set the initial guess of the decision variables through
* SetInitialGuess() or SetInitialGuessForAllVariables().
* @tparam Rows The number of rows in the new variables.
* @tparam Cols The number of columns in the new variables.
* @param rows The number of rows in the new variables.
* @param cols The number of columns in the new variables.
* @param name The commonly shared name of the new variables.
* @return The MatrixDecisionVariable of size rows x cols, containing the new
* vars (not all the vars stored).
*
* Example:
* @code{.cc}
* MathematicalProgram prog;
* auto b = prog.NewBinaryVariables(2, 3, "b");
* @endcode
* This adds a 2 x 3 matrix decision variables into the program.
*
* The name of the variable is only used for the user in order to ease
* readability.
*/
template <int Rows = Eigen::Dynamic, int Cols = Eigen::Dynamic>
MatrixDecisionVariable<Rows, Cols> NewBinaryVariables(
int rows, int cols, const std::string& name) {
rows = Rows == Eigen::Dynamic ? rows : Rows;
cols = Cols == Eigen::Dynamic ? cols : Cols;
auto names = internal::CreateNewVariableNames<
Eigen::Matrix<double, Rows, Cols>::SizeAtCompileTime>(rows * cols);
internal::SetVariableNames(name, rows, cols, &names);
return NewVariables<Rows, Cols>(VarType::BINARY, names, rows, cols);
}
/**
* Adds a matrix of binary variables into the optimization program.
* @tparam Rows The number of rows in the newly added binary variables.
* @tparam Cols The number of columns in the new variables. The default is 1.
* @param name Each newly added binary variable will share the same name. The
* default name is "b".
* @return A matrix containing the newly added variables.
*/
template <int Rows, int Cols = 1>
MatrixDecisionVariable<Rows, Cols> NewBinaryVariables(
const std::string& name = "b") {
return NewBinaryVariables<Rows, Cols>(Rows, Cols, name);
}
/**
* Adds binary variables to this MathematicalProgram. The new variables are
* viewed as a column vector, with size @p rows x 1.
* @see NewBinaryVariables(int rows, int cols, const
* std::vector<std::string>& names);
*/
VectorXDecisionVariable NewBinaryVariables(int rows,
const std::string& name = "b") {
return NewBinaryVariables<Eigen::Dynamic, 1>(rows, 1, name);
}
/**
* Adds a runtime sized symmetric matrix as decision variables to
* this MathematicalProgram.
* The optimization will only use the stacked columns of the
* lower triangular part of the symmetric matrix as decision variables.
* @param rows The number of rows in the symmetric matrix.
* @param name The name of the matrix. It is only used the for user to
* understand the optimization program. The default name is "Symmetric", and
* each variable will be named as
* <pre>
* Symmetric(0, 0) Symmetric(1, 0) ... Symmetric(rows-1, 0)
* Symmetric(1, 0) Symmetric(1, 1) ... Symmetric(rows-1, 1)
* ...
* Symmetric(rows-1,0) Symmetric(rows-1,1) ... Symmetric(rows-1, rows-1)
* </pre>
* Notice that the (i,j)'th entry and (j,i)'th entry has the same name.
* @return The newly added decision variables.
*/
MatrixXDecisionVariable NewSymmetricContinuousVariables(
int rows, const std::string& name = "Symmetric");
/**
* Adds a static sized symmetric matrix as decision variables to
* this MathematicalProgram.
* The optimization will only use the stacked columns of the
* lower triangular part of the symmetric matrix as decision variables.
* @tparam rows The number of rows in the symmetric matrix.
* @param name The name of the matrix. It is only used the for user to
* understand the optimization program. The default name is "Symmetric", and
* each variable will be named as
* <pre>
* Symmetric(0, 0) Symmetric(1, 0) ... Symmetric(rows-1, 0)
* Symmetric(1, 0) Symmetric(1, 1) ... Symmetric(rows-1, 1)
* ...
* Symmetric(rows-1,0) Symmetric(rows-1,1) ... Symmetric(rows-1, rows-1)
* </pre>
* Notice that the (i,j)'th entry and (j,i)'th entry has the same name.
* @return The newly added decision variables.
*/
template <int rows>
MatrixDecisionVariable<rows, rows> NewSymmetricContinuousVariables(
const std::string& name = "Symmetric") {
typename NewSymmetricVariableNames<rows>::type names;
int var_count = 0;
for (int j = 0; j < static_cast<int>(rows); ++j) {
for (int i = j; i < static_cast<int>(rows); ++i) {
names[var_count] =
name + "(" + std::to_string(i) + "," + std::to_string(j) + ")";
++var_count;
}
}
return NewSymmetricVariables<rows>(VarType::CONTINUOUS, names);
}
/** Appends new variables to the end of the existing variables.
* @param decision_variables The newly added decision_variables.
* @pre `decision_variables` should not intersect with the existing
* indeterminates in the optimization program.
* @throws std::exception if the preconditions are not satisfied.
*/
void AddDecisionVariables(
const Eigen::Ref<const MatrixXDecisionVariable>& decision_variables);
/**
* Returns a free polynomial in a monomial basis over @p indeterminates of a
* given @p degree. It uses @p coeff_name to make new decision variables and
* use them as coefficients. For example, `NewFreePolynomial({x₀, x₁}, 2)`
* returns a₀x₁² + a₁x₀x₁ + a₂x₀² + a₃x₁ + a₄x₀ + a₅.
*/
symbolic::Polynomial NewFreePolynomial(
const symbolic::Variables& indeterminates, int degree,
const std::string& coeff_name = "a");
/**
* Returns a free polynomial that only contains even degree monomials. A
* monomial is even degree if its total degree (sum of all variables' degree)
* is even. For example, xy is an even degree monomial (degree 2) while x²y is
* not (degree 3).
* @param indeterminates The monomial basis is over these indeterminates.
* @param degree The highest degree of the polynomial.
* @param coeff_name The coefficients of the polynomial are decision variables
* with this name as a base. The variable name would be "a1", "a2", etc.
*/
symbolic::Polynomial NewEvenDegreeFreePolynomial(
const symbolic::Variables& indeterminates, int degree,
const std::string& coeff_name = "a");
/**
* Returns a free polynomial that only contains odd degree monomials. A
* monomial is odd degree if its total degree (sum of all variables' degree)
* is even. For example, xy is not an odd degree monomial (degree 2) while x²y
* is (degree 3).
* @param indeterminates The monomial basis is over these indeterminates.
* @param degree The highest degree of the polynomial.
* @param coeff_name The coefficients of the polynomial are decision variables
* with this name as a base. The variable name would be "a1", "a2", etc.
*/
symbolic::Polynomial NewOddDegreeFreePolynomial(
const symbolic::Variables& indeterminates, int degree,
const std::string& coeff_name = "a");
/**
* Types of non-negative polynomial that can be found through conic
* optimization. We currently support SOS, SDSOS and DSOS. For more
* information about these polynomial types, please refer to
* "DSOS and SDSOS Optimization: More Tractable
* Alternatives to Sum of Squares and Semidefinite Optimization" by Amir Ali
* Ahmadi and Anirudha Majumdar, with arXiv link
* https://arxiv.org/abs/1706.02586
*/
enum class NonnegativePolynomial {
// We reserve the 0 value as a tactic for identifying uninitialized enums.
kSos = 1, ///< A sum-of-squares polynomial.
kSdsos, ///< A scaled-diagonally dominant sum-of-squares polynomial.
kDsos, ///< A diagonally dominant sum-of-squares polynomial.
};
/** Returns a pair of a SOS polynomial p = mᵀQm and the Gramian matrix Q,
* where m is the @p monomial basis.
* For example, `NewSosPolynomial(Vector2<Monomial>{x,y})` returns a
* polynomial
* p = Q₍₀,₀₎x² + 2Q₍₁,₀₎xy + Q₍₁,₁₎y²
* and Q.
* Depending on the type of the polynomial, we will impose different
* constraint on the polynomial.
* - if type = kSos, we impose the polynomial being SOS.
* - if type = kSdsos, we impose the polynomial being SDSOS.
* - if type = kDsos, we impose the polynomial being DSOS.
* @param gram_name The name of the gram matrix for print out.
* @note Q is a symmetric monomial_basis.rows() x monomial_basis.rows()
* matrix.
*/
std::pair<symbolic::Polynomial, MatrixXDecisionVariable> NewSosPolynomial(
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
NonnegativePolynomial type = NonnegativePolynomial::kSos,
const std::string& gram_name = "S");
/**
* Overloads NewSosPolynomial, except the Gramian matrix Q is an
* input instead of an output.
*/
symbolic::Polynomial NewSosPolynomial(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& gramian,
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
NonnegativePolynomial type = NonnegativePolynomial::kSos);
/**
* Overloads NewSosPolynomial.
* Returns a pair of a SOS polynomial p = m(x)ᵀQm(x) of degree @p degree
* and the Gramian matrix Q that should be PSD, where m(x) is the
* result of calling `MonomialBasis(indeterminates, degree/2)`. For example,
* `NewSosPolynomial({x}, 4)` returns a pair of a polynomial
* p = Q₍₀,₀₎x⁴ + 2Q₍₁,₀₎ x³ + (2Q₍₂,₀₎ + Q₍₁,₁₎)x² + 2Q₍₂,₁₎x + Q₍₂,₂₎
* and Q.
* @param type Depending on the type of the polynomial, we will impose
* different constraint on the polynomial.
* - if type = kSos, we impose the polynomial being SOS.
* - if type = kSdsos, we impose the polynomial being SDSOS.
* - if type = kDsos, we impose the polynomial being DSOS.
* @param gram_name The name of the gram matrix for print out.
*
* @throws std::exception if @p degree is not a positive even integer.
* @see MonomialBasis.
*/
std::pair<symbolic::Polynomial, MatrixXDecisionVariable> NewSosPolynomial(
const symbolic::Variables& indeterminates, int degree,
NonnegativePolynomial type = NonnegativePolynomial::kSos,
const std::string& gram_name = "S");
/**
* @anchor even_degree_nonnegative_polynomial
* @name Creating even-degree nonnegative polynomials
* Creates a nonnegative polynomial p = m(x)ᵀQm(x) of a given degree, and p
* only contains even-degree monomials. If we partition the monomials m(x) to
* odd degree monomials m_o(x) and even degree monomials m_e(x), then we
* can write p(x) as
* <pre>
* ⌈m_o(x)⌉ᵀ * ⌈Q_oo Q_oeᵀ⌉ * ⌈m_o(x)⌉
* ⌊m_e(x)⌋ ⌊Q_oe Q_ee ⌋ ⌊m_e(x)⌋
* </pre>
* Since p(x) doesn't contain any odd degree monomials, and p(x) contains
* terms m_e(x)ᵀ*Q_oe * m_o(x) which has odd degree, we know that the
* off-diagonal block Q_oe has to be zero. So the constraint that Q is psd
* can be simplified as Q_oo and Q_ee has to be psd. Since both Q_oo and
* Q_ee have smaller size than Q, these PSD constraints are easier to solve
* than requiring Q to be PSD.
* One use case for even-degree polynomial, is for polynomials that are even
* functions, namely p(x) = p(-x).
* @param indeterminates The set of indeterminates x
* @param degree The total degree of the polynomial p. @pre This must be an
* even number.
* @return (p(x), Q_oo, Q_ee). p(x) is the newly added non-negative
* polynomial. p(x) = m_o(x)ᵀ*Q_oo*m_o(x) + m_e(x)ᵀ*Q_ee*m_e(x) where m_o(x)
* and m_e(x) contain all the even/odd monomials of x respectively.
* The returned non-negative polynomial can be of different types, including
* Sum-of-squares (SOS), diagonally-dominant-sum-of-squares (dsos), and
* scaled-diagonally-dominant-sum-of-squares (sdsos).
*/
//@{
/**
* See @ref even_degree_nonnegative_polynomial for more details.
* Variant that produces different non-negative polynomials depending on @p
* type.
* @param type The returned polynomial p(x) can be either SOS, SDSOS or DSOS,
* depending on @p type.
*/
std::tuple<symbolic::Polynomial, MatrixXDecisionVariable,
MatrixXDecisionVariable>
NewEvenDegreeNonnegativePolynomial(const symbolic::Variables& indeterminates,
int degree, NonnegativePolynomial type);
/**
* See @ref even_degree_nonnegative_polynomial for more details.
* Variant that produces a SOS polynomial.
*/
std::tuple<symbolic::Polynomial, MatrixXDecisionVariable,
MatrixXDecisionVariable>
NewEvenDegreeSosPolynomial(const symbolic::Variables& indeterminates,
int degree);
/**
* see @ref even_degree_nonnegative_polynomial for details.
* Variant that produces an SDSOS polynomial.
*/
std::tuple<symbolic::Polynomial, MatrixXDecisionVariable,
MatrixXDecisionVariable>
NewEvenDegreeSdsosPolynomial(const symbolic::Variables& indeterminates,
int degree);
/**
* see @ref even_degree_nonnegative_polynomial for details.
* Variant that produces a DSOS polynomial.
* Same as NewEvenDegreeSosPolynomial, except the returned polynomial is
* diagonally dominant sum of squares (dsos).
*/
std::tuple<symbolic::Polynomial, MatrixXDecisionVariable,
MatrixXDecisionVariable>
NewEvenDegreeDsosPolynomial(const symbolic::Variables& indeterminates,
int degree);
//@}
/**
* Creates a symbolic polynomial from the given expression `e`. It uses this
* MathematicalProgram's `indeterminates()` in constructing the polynomial.
*
* This method helps a user create a polynomial with the right set of
* indeterminates which are declared in this MathematicalProgram. We recommend
* users to use this method over an explicit call to Polynomial constructors
* to avoid a possible mismatch between this MathematicalProgram's
* indeterminates and the user-specified indeterminates (or unspecified, which
* then includes all symbolic variables in the expression `e`). Consider the
* following example.
*
* e = ax + bx + c
*
* MP.indeterminates() = {x}
* MP.decision_variables() = {a, b}
*
* - `MP.MakePolynomial(e)` create a polynomial, `(a + b)x + c`. Here only
* `x` is an indeterminate of this polynomial.
*
* - In contrast, `symbolic::Polynomial(e)` returns `ax + bx + c` where all
* variables `{a, b, x}` are indeterminates. Note that this is problematic
* as its indeterminates, `{a, b, x}` and the MathematicalProgram's decision
* variables, `{a, b}` overlap.
*
* @note This function does not require that the decision variables in `e` is
* a subset of the decision variables in MathematicalProgram.
*/
[[nodiscard]] symbolic::Polynomial MakePolynomial(
const symbolic::Expression& e) const;
/**
* Reparses the polynomial `p` using this MathematicalProgram's
* indeterminates.
*/
void Reparse(symbolic::Polynomial* p) const;
/**
* Adds indeterminates, appending them to an internal vector of any
* existing indeterminates.
* @tparam rows The number of rows in the new indeterminates.
* @tparam cols The number of columns in the new indeterminates.
* @param names A vector of strings containing the name for each variable.
* @return The MatrixIndeterminate of size rows x cols, containing the
* new vars (not all the vars stored).
*
* Example:
* @code{.cc}
* MathematicalProgram prog;
* std::array<std::string, 6> names = {"x1", "x2", "x3", "x4", "x5", "x6"};
* auto x = prog.NewIndeterminates<2, 3>(names);
* @endcode
* This adds a 2 x 3 matrix indeterminates into the program.
*
* The name of the indeterminates is only used for the user in order to ease
* readability.
*
* @exclude_from_pydrake_mkdoc{Overloads that require explicit template
* arguments (rows, cols) are not bound in pydrake.}
*/
template <int rows, int cols>
MatrixIndeterminate<rows, cols> NewIndeterminates(
const std::array<std::string, rows * cols>& names) {
MatrixIndeterminate<rows, cols> indeterminates_matrix;
NewIndeterminates_impl(names, indeterminates_matrix);
return indeterminates_matrix;
}
/**
* Adds indeterminates, appending them to an internal vector of any
* existing indeterminates.
* @tparam rows The number of rows in the new indeterminates.
* @tparam cols The number of columns in the new indeterminates.
* @param names A vector of strings containing the name for each variable.
* @return The MatrixIndeterminate of size rows x cols, containing the
* new vars (not all the vars stored).
*
* Example:
* @code{.cc}
* MathematicalProgram prog;
* std::array<std::string, 2> names = {"x1", "x2"};
* auto x = prog.NewIndeterminates<2>(names);
* @endcode
* This adds a 2 vector indeterminates into the program.
*
* The name of the indeterminates is only used for the user in order to ease
* readability.
*
* @exclude_from_pydrake_mkdoc{Overloads that require explicit template
* arguments (rows) are not bound in pydrake.}
*/
template <int rows>
VectorIndeterminate<rows> NewIndeterminates(
const std::array<std::string, rows>& names) {
return NewIndeterminates<rows, 1>(names);
}
/**
* Adds indeterminates, appending them to an internal vector of any
* existing indeterminates.
* @tparam rows The number of rows in the new indeterminates.
* @tparam cols The number of columns in the new indeterminates.
* @param names A vector of strings containing the name for each variable.
* @return The MatrixIndeterminate of size rows x cols, containing the
* new vars (not all the vars stored).
*
* Example:
* @code{.cc}
* MathematicalProgram prog;
* auto x = prog.NewIndeterminates<2, 3>("X");
* @endcode
* This adds a 2 x 3 matrix indeterminates into the program.
*
* The name of the indeterminates is only used for the user in order to ease
* readability.
*
* @exclude_from_pydrake_mkdoc{Overloads that require explicit template
* arguments (rows, cols) are not bound in pydrake.}
*/
template <int rows, int cols>
MatrixIndeterminate<rows, cols> NewIndeterminates(
const std::string& name = "X") {
std::array<std::string, rows * cols> names;
for (int j = 0; j < cols; ++j) {
for (int i = 0; i < rows; ++i) {
names[j * rows + i] =
name + "(" + std::to_string(i) + "," + std::to_string(j) + ")";
}
}
return NewIndeterminates<rows, cols>(names);
}
/**
* Adds indeterminates to the program.
* The name for all newly added indeterminates are set to @p name. The default
* name is "x"
* @see NewIndeterminates(const std::array<std::string, rows>& names)
*
* @exclude_from_pydrake_mkdoc{Overloads that require explicit template
* arguments (rows) are not bound in pydrake.}
*/
template <int rows>
VectorIndeterminate<rows> NewIndeterminates(const std::string& name = "x") {
std::array<std::string, rows> names;
int offset = (name.compare("x") == 0) ? num_vars() : 0;
for (int i = 0; i < rows; ++i) {
names[i] = name + "(" + std::to_string(offset + i) + ")";
}
return NewIndeterminates<rows>(names);
}
/**
* Adds indeterminates to this MathematicalProgram.
* @see NewIndeterminates(int rows, int cols, const
* std::vector<std::string>& names);
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
VectorXIndeterminate NewIndeterminates(int rows,
const std::vector<std::string>& names);
/**
* Adds indeterminates to this MathematicalProgram, with default name
* "x".
* @see NewIndeterminates(int rows, int cols, const
* std::vector<std::string>& names);
*/
VectorXIndeterminate NewIndeterminates(int rows,
const std::string& name = "x");
/**
* Adds indeterminates, appending them to an internal vector of any
* existing vars.
* @param rows The number of rows in the new indeterminates.
* @param cols The number of columns in the new indeterminates.
* @param names A vector of strings containing the name for each variable.
* @return The MatrixIndeterminate of size rows x cols, containing the
* new vars (not all the vars stored).
*
* Example:
* @code{.cc}
* MathematicalProgram prog;
* auto x = prog.NewIndeterminates(2, 3, {"x1", "x2", "x3", "x4",
* "x5", "x6"});
* @endcode
* This adds a 2 x 3 matrix indeterminates into the program.
*
* The name of the variable is only used for the user in order to ease
* readability.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
MatrixXIndeterminate NewIndeterminates(int rows, int cols,
const std::vector<std::string>& names);
/**
* Adds indeterminates to this MathematicalProgram, with default name
* "X". The new variables are returned and viewed as a matrix, with size
* @p rows x @p cols.
* @see NewIndeterminates(int rows, int cols, const
* std::vector<std::string>& names);
*/
MatrixXIndeterminate NewIndeterminates(int rows, int cols,
const std::string& name = "X");
/** Adds indeterminate.
* This method appends an indeterminate to the end of the program's old
* indeterminates, if `new_indeterminate` is not already in the program's old
* indeterminates.
* @param new_indeterminate The indeterminate to be appended to the
* program's old indeterminates.
* @return indeterminate_index The index of the added indeterminate in the
* program's indeterminates. i.e. prog.indeterminates()(indeterminate_index) =
* new_indeterminate.
* @pre `new_indeterminate` should not intersect with the program's
* decision variables.
* @pre new_indeterminate should be of CONTINUOUS type.
*/
int AddIndeterminate(const symbolic::Variable& new_indeterminate);
/** Adds indeterminates.
* This method appends some indeterminates to the end of the program's old
* indeterminates.
* @param new_indeterminates The indeterminates to be appended to the
* program's old indeterminates.
* @pre `new_indeterminates` should not intersect with the program's old
* decision variables.
* @pre Each entry in new_indeterminates should be of CONTINUOUS type.
*/
void AddIndeterminates(
const Eigen::Ref<const MatrixXIndeterminate>& new_indeterminates);
/** Adds indeterminates.
* This method appends some indeterminates to the end of the program's old
* indeterminates.
* @param new_indeterminates The indeterminates to be appended to the
* program's old indeterminates.
* @pre `new_indeterminates` should not intersect with the program's old
* decision variables.
* @pre Each entry in new_indeterminates should be of CONTINUOUS type.
*/
void AddIndeterminates(const symbolic::Variables& new_indeterminates);
/**
* Adds a callback method to visualize intermediate results of the
* optimization.
*
* @note Just like other costs/constraints, not all solvers support callbacks.
* Adding a callback here will force MathematicalProgram::Solve to select a
* solver that support callbacks. For instance, adding a visualization
* callback to a quadratic programming problem may result in using a nonlinear
* programming solver as the default solver.
*
* @param callback a std::function that accepts an Eigen::Vector of doubles
* representing the bound decision variables.
* @param vars the decision variables that should be passed to the callback.
*/
Binding<VisualizationCallback> AddVisualizationCallback(
const VisualizationCallback::CallbackFunction& callback,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds a callback method to visualize intermediate results of the
* optimization.
*
* @note Just like other costs/constraints, not all solvers support callbacks.
* Adding a callback here will force MathematicalProgram::Solve to select a
* solver that support callbacks. For instance, adding a visualization
* callback to a quadratic programming problem may result in using a nonlinear
* programming solver as the default solver.
*
* @param callback a std::function that accepts an Eigen::Vector of doubles
* representing the for the bound decision variables.
* @param vars the decision variables that should be passed to the callback.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<VisualizationCallback> AddVisualizationCallback(
const VisualizationCallback::CallbackFunction& callback,
const VariableRefList& vars) {
return AddVisualizationCallback(callback,
ConcatenateVariableRefList((vars)));
}
/**
* Adds a generic cost to the optimization program.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<Cost> AddCost(const Binding<Cost>& binding);
/**
* Adds a cost type to the optimization program.
* @param obj The added objective.
* @param vars The decision variables on which the cost depend.
*
* @pydrake_mkdoc_identifier{2args_obj_vars}
*/
template <typename C>
auto AddCost(const std::shared_ptr<C>& obj,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
// Redirect to the appropriate type
// Use auto to enable the overloading method to upcast if needed
return AddCost(internal::CreateBinding(obj, vars));
}
/**
* Adds a generic cost to the optimization program.
* @param obj The added objective.
* @param vars The decision variables on which the cost depend.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
template <typename C>
auto AddCost(const std::shared_ptr<C>& obj, const VariableRefList& vars) {
return AddCost(obj, ConcatenateVariableRefList(vars));
}
/**
* Convert an input of type @p F to a FunctionCost object.
* @tparam F This class should have functions numInputs(), numOutputs and
* eval(x, y).
*/
template <typename F>
static std::shared_ptr<Cost> MakeCost(F&& f) {
return MakeFunctionCost(f);
}
/**
* Adds a cost to the optimization program on a list of variables.
* @tparam F it should define functions numInputs, numOutputs and eval. Check
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
template <typename F>
typename std::enable_if_t<internal::is_cost_functor_candidate<F>::value,
Binding<Cost>>
AddCost(F&& f, const VariableRefList& vars) {
return AddCost(f, ConcatenateVariableRefList(vars));
}
/**
* Adds a cost to the optimization program on an Eigen::Vector containing
* decision variables.
* @tparam F Type that defines functions numInputs, numOutputs and eval.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
template <typename F>
typename std::enable_if_t<internal::is_cost_functor_candidate<F>::value,
Binding<Cost>>
AddCost(F&& f, const Eigen::Ref<const VectorXDecisionVariable>& vars) {
auto c = MakeFunctionCost(std::forward<F>(f));
return AddCost(c, vars);
}
/**
* Statically assert if a user inadvertently passes a
* binding-compatible Constraint.
* @tparam F The type to check.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
template <typename F, typename Vars>
typename std::enable_if_t<internal::assert_if_is_constraint<F>::value,
Binding<Cost>>
AddCost(F&&, Vars&&) {
throw std::runtime_error("This will assert at compile-time.");
}
/**
* Adds a cost term of the form c'*x.
* Applied to a subset of the variables and pushes onto
* the linear cost data structure.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearCost> AddCost(const Binding<LinearCost>& binding);
/**
* Adds a linear cost term of the form a'*x + b.
* @param e A linear symbolic expression.
* @pre e is a linear expression a'*x + b, where each entry of x is a decision
* variable in the mathematical program.
* @return The newly added linear constraint, together with the bound
* variables.
*/
Binding<LinearCost> AddLinearCost(const symbolic::Expression& e);
/**
* Adds a linear cost term of the form a'*x + b.
* Applied to a subset of the variables and pushes onto
* the linear cost data structure.
*/
Binding<LinearCost> AddLinearCost(const Eigen::Ref<const Eigen::VectorXd>& a,
double b, const VariableRefList& vars) {
return AddLinearCost(a, b, ConcatenateVariableRefList((vars)));
}
/**
* Adds a linear cost term of the form a'*x + b.
* Applied to a subset of the variables and pushes onto
* the linear cost data structure.
*/
Binding<LinearCost> AddLinearCost(
const Eigen::Ref<const Eigen::VectorXd>& a, double b,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds a linear cost term of the form a'*x.
* Applied to a subset of the variables and pushes onto
* the linear cost data structure.
*/
template <typename VarType>
Binding<LinearCost> AddLinearCost(const Eigen::Ref<const Eigen::VectorXd>& a,
const VarType& vars) {
const double b = 0.;
return AddLinearCost(a, b, vars);
}
/**
* Adds a cost term of the form 0.5*x'*Q*x + b'x.
* Applied to subset of the variables and pushes onto
* the quadratic cost data structure.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<QuadraticCost> AddCost(const Binding<QuadraticCost>& binding);
/**
* Add a quadratic cost term of the form 0.5*x'*Q*x + b'*x + c.
* @param e A quadratic symbolic expression.
* @param is_convex Whether the cost is already known to be convex. If
* is_convex=nullopt (the default), then Drake will determine if `e` is a
* convex quadratic cost or not. To improve the computation speed, the user
* can set is_convex if the user knows whether the cost is convex or not.
* @throws std::exception if the expression is not quadratic.
* @return The newly added cost together with the bound variables.
*/
Binding<QuadraticCost> AddQuadraticCost(
const symbolic::Expression& e,
std::optional<bool> is_convex = std::nullopt);
/**
* Adds a cost term of the form 0.5*x'*Q*x + b'x.
* Applied to subset of the variables.
* @param is_convex Whether the cost is already known to be convex. If
* is_convex=nullopt (the default), then Drake will determine if this is a
* convex quadratic cost or not (by checking if matrix Q is positive
* semidefinite or not). To improve the computation speed, the user can set
* is_convex if the user knows whether the cost is convex or not.
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<QuadraticCost> AddQuadraticCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, const VariableRefList& vars,
std::optional<bool> is_convex = std::nullopt) {
return AddQuadraticCost(Q, b, ConcatenateVariableRefList(vars), is_convex);
}
/**
* Adds a cost term of the form 0.5*x'*Q*x + b'x + c
* Applied to subset of the variables.
* @param is_convex Whether the cost is already known to be convex. If
* is_convex=nullopt (the default), then Drake will determine if this is a
* convex quadratic cost or not. To improve the computation speed, the user
* can set is_convex if the user knows whether the cost is convex or not.
*/
Binding<QuadraticCost> AddQuadraticCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double c,
const Eigen::Ref<const VectorXDecisionVariable>& vars,
std::optional<bool> is_convex = std::nullopt);
/**
* Adds a cost term of the form 0.5*x'*Q*x + b'x
* Applied to subset of the variables.
* @param is_convex Whether the cost is already known to be convex. If
* is_convex=nullopt (the default), then Drake will determine if this is a
* convex quadratic cost or not. To improve the computation speed, the user
* can set is_convex if the user knows whether the cost is convex or not.
*/
Binding<QuadraticCost> AddQuadraticCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars,
std::optional<bool> is_convex = std::nullopt);
/**
* Adds a cost term of the form (x-x_desired)'*Q*(x-x_desired).
*/
Binding<QuadraticCost> AddQuadraticErrorCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& x_desired,
const VariableRefList& vars) {
return AddQuadraticErrorCost(Q, x_desired,
ConcatenateVariableRefList(vars));
}
/**
* Adds a cost term of the form (x-x_desired)'*Q*(x-x_desired).
*/
Binding<QuadraticCost> AddQuadraticErrorCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& x_desired,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds a quadratic cost of the form |Ax-b|²=(Ax-b)ᵀ(Ax-b)
*/
Binding<QuadraticCost> Add2NormSquaredCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b, const VariableRefList& vars) {
return Add2NormSquaredCost(A, b, ConcatenateVariableRefList(vars));
}
/**
* Adds a quadratic cost of the form |Ax-b|²=(Ax-b)ᵀ(Ax-b)
*/
Binding<QuadraticCost> Add2NormSquaredCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddCost(Make2NormSquaredCost(A, b), vars);
}
/**
* Adds an L2 norm cost |Ax+b|₂ (notice this cost is not quadratic since we
* don't take the square of the L2 norm).
* Refer to AddL2NormCost for more details.
*/
Binding<L2NormCost> AddCost(const Binding<L2NormCost>& binding);
// TODO(hongkai.dai): support L2NormCost in each solver.
/**
* Adds an L2 norm cost |Ax+b|₂ (notice this cost is not quadratic since we
* don't take the square of the L2 norm).
* @note Currently kL2NormCost is supported by SnoptSolver, IpoptSolver,
* GurobiSolver, MosekSolver, ClarabelSolver, and SCSSolver.
* @pydrake_mkdoc_identifier{3args_A_b_vars}
*/
Binding<L2NormCost> AddL2NormCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds an L2 norm cost |Ax+b|₂ (notice this cost is not quadratic since we
* don't take the square of the L2 norm)
* @pydrake_mkdoc_identifier{3args_A_b_vars_list}
*/
Binding<L2NormCost> AddL2NormCost(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const VariableRefList& vars) {
return AddL2NormCost(A, b, ConcatenateVariableRefList(vars));
}
/**
* Adds an L2 norm cost |Ax+b|₂ from a symbolic expression which can be
* decomposed into sqrt((Ax+b)'(Ax+b)). See
* symbolic::DecomposeL2NormExpression for details on the tolerance
* parameters.
* @throws std::exception if @p e cannot be decomposed into an L2 norm.
* @pydrake_mkdoc_identifier{expression}
*/
Binding<L2NormCost> AddL2NormCost(const symbolic::Expression& e,
double psd_tol = 1e-8,
double coefficient_tol = 1e-8);
// TODO(hongkai.dai) Decide whether to deprecate this.
/**
* Adds an L2 norm cost min |Ax+b|₂ as a linear cost min s
* on the slack variable s, together with a Lorentz cone constraint
* s ≥ |Ax+b|₂
* Many conic optimization solvers (Gurobi, MOSEK™, SCS, etc) natively prefers
* this form of linear cost + conic constraints. So if you are going to use
* one of these conic solvers, then add the L2 norm cost using this function
* instead of AddL2NormCost().
* @return (s, linear_cost, lorentz_cone_constraint). `s` is the slack
* variable (with variable name string as "slack"), `linear_cost` is the cost
* on `s`, and `lorentz_cone_constraint` is the constraint s≥|Ax+b|₂
*/
std::tuple<symbolic::Variable, Binding<LinearCost>,
Binding<LorentzConeConstraint>>
AddL2NormCostUsingConicConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds a cost term in the polynomial form.
* @param e A symbolic expression in the polynomial form.
* @return The newly created cost and the bound variables.
*/
Binding<PolynomialCost> AddPolynomialCost(const symbolic::Expression& e);
/**
* Adds a cost in the symbolic form.
* @return The newly created cost, together with the bound variables.
*/
Binding<Cost> AddCost(const symbolic::Expression& e);
/**
* @anchor log_determinant
* @name Matrix log determinant
* Represents the log-determinant of `X` by introducing slack variables t, and
* a lower triangular matrix Z and imposing the constraints
*
* ⌈X Z⌉ is positive semidifinite.
* ⌊Zᵀ diag(Z)⌋
*
* log(Z(i, i)) >= t(i)
*
* Since log(det(X)) is a concave function of X, we can either lower bound
* it's value by imposing the constraint `∑ᵢt(i) >= lower` or maximize its
* value by adding the cost -∑ᵢt(i) using convex optimization.
* @note The constraint log(Z(i, i)) >= t(i) is imposed as an exponential cone
* constraint. Please make sure your have a solver that supports exponential
* cone constraint (currently SCS and Mosek do).
* @note The constraint that
*
* ⌈X Z⌉ is positive semidifinite.
* ⌊Zᵀ diag(Z)⌋
*
* already implies that X is positive semidefinite. The user DO NOT need to
* separately impose the constraint that X being psd.
*
* Refer to
* https://docs.mosek.com/modeling-cookbook/sdo.html#log-determinant for more
* details.
*/
//@{
/**
* Maximize the log determinant. See @ref log_determinant for more details.
* @param X A symmetric positive semidefinite matrix X, whose log(det(X)) will
* be maximized.
* @return (cost, t, Z) cost is -∑ᵢt(i), we also return the newly created
* slack variables t and the lower triangular matrix Z. Note that Z is not a
* matrix of symbolic::Variable but symbolic::Expression, because the
* upper-diagonal entries of Z are not variable, but expression 0.
* @pre X is a symmetric matrix.
*/
// TODO(hongkai.dai): return the lower-triangular of Z as
// VectorX<symbolic::Variable>.
std::tuple<Binding<LinearCost>, VectorX<symbolic::Variable>,
MatrixX<symbolic::Expression>>
AddMaximizeLogDeterminantCost(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X);
/**
* Impose the constraint log(det(X)) >= lower. See @ref log_determinant for
* more details.
* @param X A symmetric positive semidefinite matrix X.
* @param lower The lower bound of log(det(X))
* @return (constraint, t, Z) constraint is ∑ᵢt(i) >= lower, we also return
* the newly created slack variables t and the lower triangular matrix Z. Note
* that Z is not a matrix of symbolic::Variable but symbolic::Expression,
* because the upper-diagonal entries of Z are not variable, but expression 0.
* @pre X is a symmetric matrix.
*/
// TODO(hongkai.dai): return the lower-triangular of Z as
// VectorX<symbolic::Variable>.
std::tuple<Binding<LinearConstraint>, VectorX<symbolic::Variable>,
MatrixX<symbolic::Expression>>
AddLogDeterminantLowerBoundConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X, double lower);
//@}
/**
* @anchor maximize_geometric_mean
* @name Maximize geometric mean
* Adds the cost to maximize the geometric mean of z = Ax+b, i.e.
* power(∏ᵢz(i), 1/n), where z ∈ ℝⁿ, z(i) >= 0. Mathematically, the cost we
* add is -power(∏ᵢz(i), 1/r), where r = power(2, ceil(log₂n)), namely r is
* the smallest power of 2 that is no smaller than the size of z. For example,
* if z ∈ ℝ², then the added cost is -power(z(0)*z(1), 1/2) if z ∈ ℝ³, then
* the added cost is -power(z(0)*z(1)*z(2), 1/4).
*
* In order to add this cost, we need to introduce a set of second-order cone
* constraints. For example, to maximize power(z(0) * z(1), 1/2), we
* introduce the slack variable w(0), together with the second order cone
* constraint w(0)² ≤ z(0) * z(1), z(0) ≥ 0, z(1) ≥ 0, and we maximize w(0).
*
* To maximize power(z(0) * z(1) * z(2), 1/ 4), we introduce the slack
* variable w(0), w(1), w(2), together with the second order cone constraints
* <pre>
* w(0)² ≤ z(0) * z(1), z(0) ≥ 0, z(1) ≥ 0
* w(1)² ≤ z(2), z(2) ≥ 0
* w(2)² ≤ w(0) * w(1), w(0) ≥ 0, w(1) ≥ 0
* </pre>
* and we maximize w(2).
*/
//@{
/**
* An overloaded version of @ref maximize_geometric_mean.
* @return cost The added cost (note that since MathematicalProgram only
* minimizes the cost, the returned cost evaluates to -power(∏ᵢz(i), 1/n)
* where z = A*x+b.
* @pre A.rows() == b.rows(), A.rows() >= 2.
*/
Binding<LinearCost> AddMaximizeGeometricMeanCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorX<symbolic::Variable>>& x);
/**
* An overloaded version of @ref maximize_geometric_mean.
* We add the cost to maximize the geometric mean of x, i.e., c*power(∏ᵢx(i),
* 1/n).
* @param c The positive coefficient of the geometric mean cost, @default
* is 1.
* @return cost The added cost (note that since MathematicalProgram only
* minimizes the cost, the returned cost evaluates to -c * power(∏ᵢx(i), 1/n).
* @pre x.rows() >= 2.
* @pre c > 0.
*/
Binding<LinearCost> AddMaximizeGeometricMeanCost(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x, double c = 1.0);
//@}
/**
* Adds a generic constraint to the program. This should
* only be used if a more specific type of constraint is not
* available, as it may require the use of a significantly more
* expensive solver.
*
* @note If @p binding.evaluator()->num_constraints() == 0, then this
* constraint is not added into the MathematicalProgram. We return @p binding
* directly.
*/
Binding<Constraint> AddConstraint(const Binding<Constraint>& binding);
/**
* Adds one row of constraint lb <= e <= ub where @p e is a symbolic
* expression.
* @throws std::exception if
* 1. <tt>lb <= e <= ub</tt> is a trivial constraint such as 1 <= 2 <= 3.
* 2. <tt>lb <= e <= ub</tt> is unsatisfiable such as 1 <= -5 <= 3
*
* @param e A symbolic expression of the decision variables.
* @param lb A scalar, the lower bound.
* @param ub A scalar, the upper bound.
*
* The resulting constraint may be a BoundingBoxConstraint, LinearConstraint,
* LinearEqualityConstraint, QuadraticConstraint, or ExpressionConstraint,
* depending on the arguments. Constraints of the form x == 1 (which could
* be created as a BoundingBoxConstraint or LinearEqualityConstraint) will be
* constructed as a LinearEqualityConstraint.
*/
Binding<Constraint> AddConstraint(const symbolic::Expression& e, double lb,
double ub);
/**
* Adds constraints represented by symbolic expressions to the program. It
* throws if <tt>lb <= v <= ub</tt> includes trivial/unsatisfiable
* constraints.
*
* @overload Binding<Constraint> AddConstraint(const symbolic::Expression& e,
* double lb, double ub)
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<Constraint> AddConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& v,
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub);
/**
* Add a constraint represented by a symbolic formula to the program. The
* input formula @p f can be of the following forms:
*
* 1. e1 <= e2
* 2. e1 >= e2
* 3. e1 == e2
* 4. A conjunction of relational formulas where each conjunct is
* a relational formula matched by 1, 2, or 3.
*
* Note that first two cases might return an object of
* Binding<BoundingBoxConstraint>, Binding<LinearConstraint>, or
* Binding<ExpressionConstraint>, depending
* on @p f. Also the third case might return an object of
* Binding<LinearEqualityConstraint> or Binding<ExpressionConstraint>.
*
* It throws an exception if
* 1. @p f is not matched with one of the above patterns. Especially, strict
* inequalities (<, >) are not allowed.
* 2. @p f is either a trivial constraint such as "1 <= 2" or an
* unsatisfiable constraint such as "2 <= 1".
* 3. It is not possible to find numerical bounds of `e1` and `e2` where @p f
* = e1 ≃ e2. We allow `e1` and `e2` to be infinite but only if there are
* no other terms. For example, `x <= ∞` is allowed. However, `x - ∞ <= 0`
* is not allowed because `x ↦ ∞` introduces `nan` in the evaluation.
*/
Binding<Constraint> AddConstraint(const symbolic::Formula& f);
/**
* Adds a constraint represented by an Eigen::Matrix<symbolic::Formula> or
* Eigen::Array<symbolic::Formula> to the program. A common use-case of this
* function is to add a constraint with the element-wise comparison between
* two Eigen matrices, using `A.array() <= B.array()`. See the following
* example.
*
* @code
* MathematicalProgram prog;
* Eigen::Matrix<double, 2, 2> A = ...;
* Eigen::Vector2d b = ...;
* auto x = prog.NewContinuousVariables(2, "x");
* prog.AddConstraint((A * x).array() <= b.array());
* @endcode
*
* A formula in @p formulas can be of the following forms:
*
* 1. e1 <= e2
* 2. e1 >= e2
* 3. e1 == e2
*
* It throws an exception if AddConstraint(const symbolic::Formula& f)
* throws an exception for f ∈ @p formulas.
*
* @overload Binding<Constraint> AddConstraint(const symbolic::Formula& f)
*
* @tparam Derived Eigen::Matrix or Eigen::Array with Formula as the Scalar.
*/
template <typename Derived>
typename std::enable_if_t<
is_eigen_scalar_same<Derived, symbolic::Formula>::value,
Binding<Constraint>>
AddConstraint(const Eigen::DenseBase<Derived>& formulas) {
return AddConstraint(internal::ParseConstraint(formulas));
}
/**
* Adds a generic constraint to the program. This should
* only be used if a more specific type of constraint is not
* available, as it may require the use of a significantly more
* expensive solver.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
template <typename C>
auto AddConstraint(std::shared_ptr<C> con, const VariableRefList& vars) {
return AddConstraint(con, ConcatenateVariableRefList(vars));
}
/**
* Adds a generic constraint to the program. This should
* only be used if a more specific type of constraint is not
* available, as it may require the use of a significantly more
* expensive solver.
* @pydrake_mkdoc_identifier{2args_con_vars}
*/
template <typename C>
auto AddConstraint(std::shared_ptr<C> con,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddConstraint(internal::CreateBinding(con, vars));
}
/**
* Adds linear constraints referencing potentially a subset
* of the decision variables (defined in the vars parameter).
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearConstraint> AddConstraint(
const Binding<LinearConstraint>& binding);
/**
* Adds linear constraints referencing potentially a subset
* of the decision variables (defined in the vars parameter).
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearConstraint> AddLinearConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const VariableRefList& vars) {
return AddLinearConstraint(A, lb, ub, ConcatenateVariableRefList(vars));
}
/**
* Adds sparse linear constraints referencing potentially a subset
* of the decision variables (defined in the vars parameter).
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearConstraint> AddLinearConstraint(
const Eigen::SparseMatrix<double>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const VariableRefList& vars) {
return AddLinearConstraint(A, lb, ub, ConcatenateVariableRefList(vars));
}
/**
* Adds linear constraints referencing potentially a subset
* of the decision variables (defined in the vars parameter).
*
* @pydrake_mkdoc_identifier{4args_A_lb_ub_dense}
*/
Binding<LinearConstraint> AddLinearConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds sparse linear constraints referencing potentially a subset
* of the decision variables (defined in the vars parameter).
*
* @pydrake_mkdoc_identifier{4args_A_lb_ub_sparse}
*/
Binding<LinearConstraint> AddLinearConstraint(
const Eigen::SparseMatrix<double>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds one row of linear constraint referencing potentially a
* subset of the decision variables (defined in the vars parameter).
* lb <= a*vars <= ub
* @param a A row vector.
* @param lb A scalar, the lower bound.
* @param ub A scalar, the upper bound.
* @param vars The decision variables on which to impose the linear
* constraint.
*/
Binding<LinearConstraint> AddLinearConstraint(
const Eigen::Ref<const Eigen::RowVectorXd>& a, double lb, double ub,
const VariableRefList& vars) {
return AddLinearConstraint(a, lb, ub, ConcatenateVariableRefList(vars));
}
/**
* Adds one row of linear constraint referencing potentially a
* subset of the decision variables (defined in the vars parameter).
* lb <= a*vars <= ub
* @param a A row vector.
* @param lb A scalar, the lower bound.
* @param ub A scalar, the upper bound.
* @param vars The decision variables on which to impose the linear
* constraint.
*/
Binding<LinearConstraint> AddLinearConstraint(
const Eigen::Ref<const Eigen::RowVectorXd>& a, double lb, double ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddLinearConstraint(a, Vector1d(lb), Vector1d(ub), vars);
}
/**
* Adds one row of linear constraint lb <= e <= ub where @p e is a symbolic
* expression.
* @throws std::exception if
* 1. @p e is a non-linear expression.
* 2. <tt>lb <= e <= ub</tt> is a trivial constraint such as 1 <= 2 <= 3.
* 3. <tt>lb <= e <= ub</tt> is unsatisfiable such as 1 <= -5 <= 3
*
* @param e A linear symbolic expression in the form of <tt>c0 + c1 * v1 +
* ... + cn * vn</tt> where @c c_i is a constant and @v_i is a variable.
* @param lb A scalar, the lower bound.
* @param ub A scalar, the upper bound.
*/
Binding<LinearConstraint> AddLinearConstraint(const symbolic::Expression& e,
double lb, double ub);
/**
* Adds linear constraints represented by symbolic expressions to the
* program. It throws if @v includes a non-linear expression or <tt>lb <= v <=
* ub</tt> includes trivial/unsatisfiable constraints.
*/
Binding<LinearConstraint> AddLinearConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& v,
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub);
/**
* Add a linear constraint represented by a symbolic formula to the
* program. The input formula @p f can be of the following forms:
*
* 1. e1 <= e2
* 2. e1 >= e2
* 3. e1 == e2
* 4. A conjunction of relational formulas where each conjunct is
* a relational formula matched by 1, 2, or 3.
*
* Note that first two cases might return an object of
* Binding<BoundingBoxConstraint> depending on @p f. Also the third case
* returns an object of Binding<LinearEqualityConstraint>.
*
* It throws an exception if
* 1. @p f is not matched with one of the above patterns. Especially, strict
* inequalities (<, >) are not allowed.
* 2. @p f includes a non-linear expression.
* 3. @p f is either a trivial constraint such as "1 <= 2" or an
* unsatisfiable constraint such as "2 <= 1".
* 4. It is not possible to find numerical bounds of `e1` and `e2` where @p f
* = e1 ≃ e2. We allow `e1` and `e2` to be infinite but only if there are
* no other terms. For example, `x <= ∞` is allowed. However, `x - ∞ <= 0`
* is not allowed because `x ↦ ∞` introduces `nan` in the evaluation.
*/
Binding<LinearConstraint> AddLinearConstraint(const symbolic::Formula& f);
/**
* Add a linear constraint represented by an Eigen::Array<symbolic::Formula>
* to the program. A common use-case of this function is to add a linear
* constraint with the element-wise comparison between two Eigen matrices,
* using `A.array() <= B.array()`. See the following example.
*
* @code
* MathematicalProgram prog;
* Eigen::Matrix<double, 2, 2> A;
* auto x = prog.NewContinuousVariables(2, "x");
* Eigen::Vector2d b;
* ... // set up A and b
* prog.AddLinearConstraint((A * x).array() <= b.array());
* @endcode
*
* A formula in @p formulas can be of the following forms:
*
* 1. e1 <= e2
* 2. e1 >= e2
* 3. e1 == e2
*
* It throws an exception if AddLinearConstraint(const symbolic::Formula& f)
* throws an exception for f ∈ @p formulas.
* @tparam Derived An Eigen Array type of Formula.
*/
Binding<LinearConstraint> AddLinearConstraint(
const Eigen::Ref<const Eigen::Array<symbolic::Formula, Eigen::Dynamic,
Eigen::Dynamic>>& formulas);
/**
* Adds linear equality constraints referencing potentially a
* subset of the decision variables.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearEqualityConstraint> AddConstraint(
const Binding<LinearEqualityConstraint>& binding);
/**
* Adds one row of linear constraint e = b where @p e is a symbolic
* expression.
* @throws std::exception if
* 1. @p e is a non-linear expression.
* 2. @p e is a constant.
*
* @param e A linear symbolic expression in the form of <tt>c0 + c1 * x1 +
* ... + cn * xn</tt> where @c c_i is a constant and @x_i is a variable.
* @param b A scalar.
* @return The newly added linear equality constraint, together with the
* bound variable.
*/
Binding<LinearEqualityConstraint> AddLinearEqualityConstraint(
const symbolic::Expression& e, double b);
/**
* Adds a linear equality constraint represented by a symbolic formula to the
* program. The input formula @p f is either an equality formula (`e1 == e2`)
* or a conjunction of equality formulas.
*
* It throws an exception if
*
* 1. @p f is neither an equality formula nor a conjunction of equalities.
* 2. @p f includes a non-linear expression.
*/
Binding<LinearEqualityConstraint> AddLinearEqualityConstraint(
const symbolic::Formula& f);
/**
* Adds linear equality constraints \f$ v = b \f$, where \p v(i) is a symbolic
* linear expression.
* @throws std::exception if
* 1. @p v(i) is a non-linear expression.
* 2. @p v(i) is a constant.
*
* @tparam DerivedV An Eigen Matrix type of Expression. A column vector.
* @tparam DerivedB An Eigen Matrix type of double. A column vector.
* @param v v(i) is a linear symbolic expression in the form of
* <tt> c0 + c1 * x1 + ... + cn * xn </tt> where ci is a constant and @xi is
* a variable.
* @param b A vector of doubles.
* @return The newly added linear equality constraint, together with the
* bound variables.
*/
template <typename DerivedV, typename DerivedB>
typename std::enable_if_t<
is_eigen_vector_expression_double_pair<DerivedV, DerivedB>::value,
Binding<LinearEqualityConstraint>>
AddLinearEqualityConstraint(const Eigen::MatrixBase<DerivedV>& v,
const Eigen::MatrixBase<DerivedB>& b) {
return AddConstraint(internal::ParseLinearEqualityConstraint(v, b));
}
/**
* Adds a linear equality constraint for a matrix of linear expression @p V,
* such that V(i, j) = B(i, j). If V is a symmetric matrix, then the user
* may only want to constrain the lower triangular part of V.
* This function is meant to provide convenience to the user, it incurs
* additional copy and memory allocation. For faster speed, add each column
* of the matrix equality in a for loop.
* @tparam DerivedV An Eigen Matrix type of Expression. The number of columns
* at compile time should not be 1.
* @tparam DerivedB An Eigen Matrix type of double.
* @param V An Eigen Matrix of symbolic expressions. V(i, j) should be a
* linear expression.
* @param B An Eigen Matrix of doubles.
* @param lower_triangle If true, then only the lower triangular part of @p V
* is constrained, otherwise the whole matrix V is constrained. @default is
* false.
* @return The newly added linear equality constraint, together with the
* bound variables.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
template <typename DerivedV, typename DerivedB>
typename std::enable_if_t<
is_eigen_nonvector_expression_double_pair<DerivedV, DerivedB>::value,
Binding<LinearEqualityConstraint>>
AddLinearEqualityConstraint(const Eigen::MatrixBase<DerivedV>& V,
const Eigen::MatrixBase<DerivedB>& B,
bool lower_triangle = false) {
return AddConstraint(
internal::ParseLinearEqualityConstraint(V, B, lower_triangle));
}
/** AddLinearEqualityConstraint
*
* Adds linear equality constraints referencing potentially a subset of
* the decision variables.
*
* Example: to add two equality constraints which only depend on two of the
* elements of x, you could use
* @code{.cc}
* auto x = prog.NewContinuousVariables(6,"myvar");
* Eigen::Matrix2d Aeq;
* Aeq << -1, 2,
* 1, 1;
* Eigen::Vector2d beq(1, 3);
* prog.AddLinearEqualityConstraint(Aeq, beq, {x.segment<1>(2),
* x.segment<1>(5)});
* @endcode
* The code above imposes constraints
* @f[-x(2) + 2x(5) = 1 @f]
* @f[ x(2) + x(5) = 3 @f]
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearEqualityConstraint> AddLinearEqualityConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Aeq,
const Eigen::Ref<const Eigen::VectorXd>& beq,
const VariableRefList& vars) {
return AddLinearEqualityConstraint(Aeq, beq,
ConcatenateVariableRefList(vars));
}
/** AddLinearEqualityConstraint
*
* Adds linear equality constraints referencing potentially a subset of
* the decision variables using a sparse A matrix.
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearEqualityConstraint> AddLinearEqualityConstraint(
const Eigen::SparseMatrix<double>& Aeq,
const Eigen::Ref<const Eigen::VectorXd>& beq,
const VariableRefList& vars) {
return AddLinearEqualityConstraint(Aeq, beq,
ConcatenateVariableRefList(vars));
}
/** AddLinearEqualityConstraint
*
* Adds linear equality constraints referencing potentially a subset of
* the decision variables.
*
* Example: to add two equality constraints which only depend on two of the
* elements of x, you could use
* @code{.cc}
* auto x = prog.NewContinuousVariables(6,"myvar");
* Eigen::Matrix2d Aeq;
* Aeq << -1, 2,
* 1, 1;
* Eigen::Vector2d beq(1, 3);
* // Imposes constraint
* // -x(0) + 2x(1) = 1
* // x(0) + x(1) = 3
* prog.AddLinearEqualityConstraint(Aeq, beq, x.head<2>());
* @endcode
*
* @pydrake_mkdoc_identifier{3args_Aeq_beq_dense}
*/
Binding<LinearEqualityConstraint> AddLinearEqualityConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Aeq,
const Eigen::Ref<const Eigen::VectorXd>& beq,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/** AddLinearEqualityConstraint
*
* Adds linear equality constraints referencing potentially a subset of
* the decision variables using a sparse A matrix.
* @pydrake_mkdoc_identifier{3args_Aeq_beq_sparse}
*/
Binding<LinearEqualityConstraint> AddLinearEqualityConstraint(
const Eigen::SparseMatrix<double>& Aeq,
const Eigen::Ref<const Eigen::VectorXd>& beq,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds one row of linear equality constraint referencing potentially a subset
* of decision variables.
* @f[
* ax = beq
* @f]
* @param a A row vector.
* @param beq A scalar.
* @param vars The decision variables on which the constraint is imposed.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearEqualityConstraint> AddLinearEqualityConstraint(
const Eigen::Ref<const Eigen::RowVectorXd>& a, double beq,
const VariableRefList& vars) {
return AddLinearEqualityConstraint(a, beq,
ConcatenateVariableRefList(vars));
}
/**
* Adds one row of linear equality constraint referencing potentially a subset
* of decision variables.
* @f[
* ax = beq
* @f]
* @param a A row vector.
* @param beq A scalar.
* @param vars The decision variables on which the constraint is imposed.
*/
Binding<LinearEqualityConstraint> AddLinearEqualityConstraint(
const Eigen::Ref<const Eigen::RowVectorXd>& a, double beq,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddLinearEqualityConstraint(a, Vector1d(beq), vars);
}
/**
* Adds bounding box constraints referencing potentially a subest of the
* decision variables.
* @param binding Binds a BoundingBoxConstraint with some decision variables,
* such that
* binding.evaluator()->lower_bound()(i) <= binding.variables()(i)
* <= binding.evaluator().upper_bound()(i)
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<BoundingBoxConstraint> AddConstraint(
const Binding<BoundingBoxConstraint>& binding);
/** AddBoundingBoxConstraint
*
* Adds bounding box constraints referencing potentially a
* subset of the decision variables (defined in the vars parameter).
* Example
* \code{.cc}
* MathematicalProgram prog;
* auto x = prog.NewContinuousVariables<2>("x");
* auto y = prog.NewContinuousVariables<1>("y");
* Eigen::Vector3d lb(0, 1, 2);
* Eigen::Vector3d ub(1, 2, 3);
* // Imposes the constraint
* // 0 ≤ x(0) ≤ 1
* // 1 ≤ x(1) ≤ 2
* // 2 ≤ y ≤ 3
* prog.AddBoundingBoxConstraint(lb, ub, {x, y});
* \endcode
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<BoundingBoxConstraint> AddBoundingBoxConstraint(
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const VariableRefList& vars) {
return AddBoundingBoxConstraint(lb, ub, ConcatenateVariableRefList(vars));
}
/**
* Adds bounding box constraints referencing potentially a subset of the
* decision variables.
* @param lb The lower bound.
* @param ub The upper bound.
* @param vars Will imposes constraint lb(i, j) <= vars(i, j) <= ub(i, j).
* @return The newly constructed BoundingBoxConstraint.
*/
Binding<BoundingBoxConstraint> AddBoundingBoxConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub,
const Eigen::Ref<const MatrixXDecisionVariable>& vars);
/**
* Adds bounds for a single variable.
* @param lb Lower bound.
* @param ub Upper bound.
* @param var The decision variable.
*/
Binding<BoundingBoxConstraint> AddBoundingBoxConstraint(
double lb, double ub, const symbolic::Variable& var) {
MatrixDecisionVariable<1, 1> var_matrix(var);
return AddBoundingBoxConstraint(Vector1d(lb), Vector1d(ub), var_matrix);
}
/**
* Adds the same scalar lower and upper bound to every variable in the list.
* @param lb Lower bound.
* @param ub Upper bound.
* @param vars The decision variables.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<BoundingBoxConstraint> AddBoundingBoxConstraint(
double lb, double ub, const VariableRefList& vars) {
return AddBoundingBoxConstraint(lb, ub, ConcatenateVariableRefList(vars));
}
/**
* Adds the same scalar lower and upper bound to every variable in @p vars.
* @tparam Derived An Eigen Vector type with Variable as the scalar
* type.
* @param lb Lower bound.
* @param ub Upper bound.
* @param vars The decision variables.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
template <typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Derived::Scalar, symbolic::Variable> &&
Derived::ColsAtCompileTime == 1,
Binding<BoundingBoxConstraint>>
AddBoundingBoxConstraint(double lb, double ub,
const Eigen::MatrixBase<Derived>& vars) {
const int kSize = Derived::RowsAtCompileTime;
return AddBoundingBoxConstraint(
Eigen::Matrix<double, kSize, 1>::Constant(vars.size(), lb),
Eigen::Matrix<double, kSize, 1>::Constant(vars.size(), ub), vars);
}
/**
* Adds the same scalar lower and upper bound to every variable in @p vars.
* @tparam Derived An Eigen::Matrix with Variable as the scalar
* type. The matrix has unknown number of columns at compile time, or has
* more than one column.
* @param lb Lower bound.
* @param ub Upper bound.
* @param vars The decision variables.
*/
template <typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Derived::Scalar, symbolic::Variable> &&
Derived::ColsAtCompileTime != 1,
Binding<BoundingBoxConstraint>>
AddBoundingBoxConstraint(double lb, double ub,
const Eigen::MatrixBase<Derived>& vars) {
const int kSize =
Derived::RowsAtCompileTime != Eigen::Dynamic &&
Derived::ColsAtCompileTime != Eigen::Dynamic
? Derived::RowsAtCompileTime * Derived::ColsAtCompileTime
: Eigen::Dynamic;
Eigen::Matrix<symbolic::Variable, kSize, 1> flat_vars(vars.size());
for (int j = 0; j < vars.cols(); ++j) {
for (int i = 0; i < vars.rows(); ++i) {
flat_vars(j * vars.rows() + i) = vars(i, j);
}
}
return AddBoundingBoxConstraint(
Eigen::Matrix<double, kSize, 1>::Constant(vars.size(), lb),
Eigen::Matrix<double, kSize, 1>::Constant(vars.size(), ub), flat_vars);
}
/** Adds quadratic constraint.
The quadratic constraint is of the form
lb ≤ .5 xᵀQx + bᵀx ≤ ub
where `x` might be a subset of the decision variables in this
MathematicalProgram.
Notice that if your quadratic constraint is convex, and you intend to solve
the problem with a convex solver (like Mosek), then it is better to
reformulate it with a second order cone constraint. See
https://docs.mosek.com/10.1/capi/prob-def-quadratic.html#a-recommendation for
an explanation.
@exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<QuadraticConstraint> AddConstraint(
const Binding<QuadraticConstraint>& binding);
/** Adds quadratic constraint
lb ≤ .5 xᵀQx + bᵀx ≤ ub
Notice that if your quadratic constraint is convex, and you intend to solve
the problem with a convex solver (like Mosek), then it is better to
reformulate it with a second order cone constraint. See
https://docs.mosek.com/10.1/capi/prob-def-quadratic.html#a-recommendation for
an explanation.
@param vars x in the documentation above.
@param hessian_type Whether the Hessian is positive semidefinite, negative
semidefinite or indefinite. Drake will check the type if
hessian_type=std::nullopt. Specifying the hessian type will speed this
method up.
@pre hessian_type should be correct if it is not std::nullopt, as we will
blindly trust it in the downstream code.
*/
Binding<QuadraticConstraint> AddQuadraticConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double lb, double ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars,
std::optional<QuadraticConstraint::HessianType> hessian_type =
std::nullopt);
/** Adds quadratic constraint
lb ≤ .5 xᵀQx + bᵀx ≤ ub
Notice that if your quadratic constraint is convex, and you intend to solve
the problem with a convex solver (like Mosek), then it is better to
reformulate it with a second order cone constraint. See
https://docs.mosek.com/10.1/capi/prob-def-quadratic.html#a-recommendation for
an explanation.
@param vars x in the documentation above.
@param hessian_type Whether the Hessian is positive semidefinite, negative
semidefinite or indefinite. Drake will check the type if
hessian_type=std::nullopt. Specifying the hessian type will speed this
method up.
@pre hessian_type should be correct if it is not std::nullopt, as we will
blindly trust it in the downstream code.
*/
Binding<QuadraticConstraint> AddQuadraticConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double lb, double ub,
const VariableRefList& vars,
std::optional<QuadraticConstraint::HessianType> hessian_type =
std::nullopt);
/** Overloads AddQuadraticConstraint, impose lb <= e <= ub where `e` is a
quadratic expression.
Notice that if your quadratic constraint is convex, and you intend to solve
the problem with a convex solver (like Mosek), then it is better to
reformulate it with a second order cone constraint. See
https://docs.mosek.com/10.1/capi/prob-def-quadratic.html#a-recommendation for
an explanation.
*/
Binding<QuadraticConstraint> AddQuadraticConstraint(
const symbolic::Expression& e, double lb, double ub,
std::optional<QuadraticConstraint::HessianType> hessian_type =
std::nullopt);
/**
* Adds Lorentz cone constraint referencing potentially a subset
* of the decision variables.
* The linear expression @f$ z=Ax+b @f$ is in the Lorentz cone.
* A vector \f$ z \in\mathbb{R}^n \f$ is in the Lorentz cone, if
* <!--
* z(0) >= sqrt{z(1)² + ... + z(n-1)²}
* -->
* @f[
* z_0 \ge \sqrt{z_1^2 + ... + z_{n-1}^2}
* @f]
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LorentzConeConstraint> AddConstraint(
const Binding<LorentzConeConstraint>& binding);
/**
* Adds Lorentz cone constraint referencing potentially a subset of the
* decision variables.
* @param v An Eigen::Vector of symbolic::Expression. Constraining that
* \f[
* v_0 \ge \sqrt{v_1^2 + ... + v_{n-1}^2}
* \f]
* @return The newly constructed Lorentz cone constraint with the bounded
* variables.
* For example, to add the Lorentz cone constraint
*
* x+1 >= sqrt(y² + 2y + x² + 5),
* = sqrt((y+1)²+x²+2²)
* The user could call
* @code{cc}
* Vector4<symbolic::Expression> v(x+1, y+1, x, 2.);
* prog.AddLorentzConeConstraint(v);
* @endcode
* @param eval_type The evaluation type when evaluating the lorentz cone
* constraint in generic optimization. Refer to
* LorentzConeConstraint::EvalType for more details.
*/
Binding<LorentzConeConstraint> AddLorentzConeConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v,
LorentzConeConstraint::EvalType eval_type =
LorentzConeConstraint::EvalType::kConvexSmooth);
/**
* Adds Lorentz cone constraint on the linear expression v1 and quadratic
* expression v2, such that v1 >= sqrt(v2)
* @param linear_expression The linear expression v1.
* @param quadratic_expression The quadratic expression v2.
* @param tol The tolerance to determine if the matrix in v2 is positive
* semidefinite or not. @see DecomposePositiveQuadraticForm for more
* explanation. @default is 0.
* @param eval_type The evaluation type when evaluating the lorentz cone
* constraint in generic optimization. Refer to
* LorentzConeConstraint::EvalType for more details.
* @retval binding The newly added Lorentz cone constraint, together with the
* bound variables.
* @pre
* 1. `v1` is a linear expression, in the form of c'*x + d.
* 2. `v2` is a quadratic expression, in the form of
* <pre>
* x'*Q*x + b'x + a
* </pre>
* Also the quadratic expression has to be convex, namely Q is a
* positive semidefinite matrix, and the quadratic expression needs
* to be non-negative for any x.
* @throws std::exception if the preconditions are not satisfied.
*
* Notice this constraint is equivalent to the vector [z;y] is within a
* Lorentz cone, where
* <pre>
* z = v1
* y = R * x + d
* </pre>
* while (R, d) satisfies y'*y = x'*Q*x + b'*x + a
* For example, to add the Lorentz cone constraint
*
* x+1 >= sqrt(y² + 2y + x² + 4),
* the user could call
* @code{cc}
* prog.AddLorentzConeConstraint(x+1, pow(y, 2) + 2 * y + pow(x, 2) + 4);
* @endcode
*/
Binding<LorentzConeConstraint> AddLorentzConeConstraint(
const symbolic::Expression& linear_expression,
const symbolic::Expression& quadratic_expression, double tol = 0,
LorentzConeConstraint::EvalType eval_type =
LorentzConeConstraint::EvalType::kConvexSmooth);
/**
* Adds Lorentz cone constraint referencing potentially a subset of the
* decision variables (defined in the vars parameter).
* The linear expression @f$ z=Ax+b @f$ is in the Lorentz cone.
* A vector \f$ z \in\mathbb{R}^n \f$ is in the Lorentz cone, if
* <!--
* z(0) >= sqrt{z(1)² + ... + z(n-1)²}
* -->
* @f[
* z_0 \ge \sqrt{z_1^2 + ... + z_{n-1}^2}
* @f]
* @param A A @f$\mathbb{R}^{n\times m}@f$ matrix, whose number of columns
* equals to the size of the decision variables.
* @param b A @f$\mathbb{R}^n@f$ vector, whose number of rows equals to the
* size of the decision variables.
* @param vars The list of @f$ m @f$ decision variables.
* @param eval_type The evaluation type when evaluating the lorentz cone
* constraint in generic optimization. Refer to
* LorentzConeConstraint::EvalType for more details.
* @return The newly added Lorentz cone constraint.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LorentzConeConstraint> AddLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b, const VariableRefList& vars,
LorentzConeConstraint::EvalType eval_type =
LorentzConeConstraint::EvalType::kConvexSmooth) {
return AddLorentzConeConstraint(A, b, ConcatenateVariableRefList(vars),
eval_type);
}
/**
* Adds Lorentz cone constraint referencing potentially a subset of the
* decision variables (defined in the vars parameter).
* The linear expression @f$ z=Ax+b @f$ is in the Lorentz cone.
* A vector \f$ z \in\mathbb{R}^n \f$ is in the Lorentz cone, if
* <!--
* z(0) >= sqrt{z(1)² + ... + z(n-1)²}
* -->
* @f[
* z_0 \ge \sqrt{z_1^2 + ... + z_{n-1}^2}
* @f]
* @param A A @f$\mathbb{R}^{n\times m}@f$ matrix, whose number of columns
* equals to the size of the decision variables.
* @param b A @f$\mathbb{R}^n@f$ vector, whose number of rows equals to the
* size of the decision variables.
* @param vars The Eigen vector of @f$ m @f$ decision variables.
* @param eval_type The evaluation type when evaluating the lorentz cone
* constraint in generic optimization. Refer to
* LorentzConeConstraint::EvalType for more details.
* @return The newly added Lorentz cone constraint.
*
* For example, to add the Lorentz cone constraint
*
* x+1 >= sqrt(y² + 2y + x² + 5) = sqrt((y+1)² + x² + 2²),
* the user could call
* @code{cc}
* Eigen::Matrix<double, 4, 2> A;
* Eigen::Vector4d b;
* A << 1, 0, 0, 1, 1, 0, 0, 0;
* b << 1, 1, 0, 2;
* // A * [x;y] + b = [x+1; y+1; x; 2]
* prog.AddLorentzConeConstraint(A, b, Vector2<symbolic::Variable>(x, y));
* @endcode
*/
Binding<LorentzConeConstraint> AddLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars,
LorentzConeConstraint::EvalType eval_type =
LorentzConeConstraint::EvalType::kConvexSmooth);
/**
* Imposes that a vector @f$ x\in\mathbb{R}^m @f$ lies in Lorentz cone. Namely
* @f[
* x_0 \ge \sqrt{x_1^2 + .. + x_{m-1}^2}
* @f]
* <!-->
* x(0) >= sqrt(x(1)² + ... + x(m-1)²)
* <-->
* @param vars The stacked column of vars should lie within the Lorentz cone.
* @param eval_type The evaluation type when evaluating the lorentz cone
* constraint in generic optimization. Refer to
* LorentzConeConstraint::EvalType for more details.
* @return The newly added Lorentz cone constraint.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LorentzConeConstraint> AddLorentzConeConstraint(
const VariableRefList& vars,
LorentzConeConstraint::EvalType eval_type =
LorentzConeConstraint::EvalType::kConvexSmooth) {
return AddLorentzConeConstraint(ConcatenateVariableRefList(vars),
eval_type);
}
/**
* Imposes that a vector @f$ x\in\mathbb{R}^m @f$ lies in Lorentz cone. Namely
* @f[
* x_0 \ge \sqrt{x_1^2 + .. + x_{m-1}^2}
* @f]
* <!-->
* x(0) >= sqrt(x(1)² + ... + x(m-1)²)
* <-->
* @param vars The stacked column of vars should lie within the Lorentz cone.
* @param eval_type The evaluation type when evaluating the lorentz cone
* constraint in generic optimization. Refer to
* LorentzConeConstraint::EvalType for more details.
* @return The newly added Lorentz cone constraint.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
template <int rows>
Binding<LorentzConeConstraint> AddLorentzConeConstraint(
const Eigen::MatrixBase<VectorDecisionVariable<rows>>& vars,
LorentzConeConstraint::EvalType eval_type =
LorentzConeConstraint::EvalType::kConvexSmooth) {
Eigen::Matrix<double, rows, rows> A(vars.rows(), vars.rows());
A.setIdentity();
Eigen::Matrix<double, rows, 1> b(vars.rows());
b.setZero();
return AddLorentzConeConstraint(A, b, vars, eval_type);
}
/**
* Adds a rotated Lorentz cone constraint referencing potentially a subset
* of decision variables. The linear expression @f$ z=Ax+b @f$ is in rotated
* Lorentz cone.
* A vector \f$ z \in\mathbb{R}^n \f$ is in the rotated Lorentz cone, if
* <!--
* z(0)*z(1) >= z(2)² + ... + z(n-1)²
* -->
* @f[
* z_0z_1 \ge z_2^2 + ... + z_{n-1}^2
* @f]
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<RotatedLorentzConeConstraint> AddConstraint(
const Binding<RotatedLorentzConeConstraint>& binding);
/**
* Adds rotated Lorentz cone constraint on the linear expression v1, v2 and
* quadratic expression u, such that v1 * v2 >= u, v1 >= 0, v2 >= 0
* @param linear_expression1 The linear expression v1.
* @param linear_expression2 The linear expression v2.
* @param quadratic_expression The quadratic expression u.
* @param tol The tolerance to determine if the matrix in v2 is positive
* semidefinite or not. @see DecomposePositiveQuadraticForm for more
* explanation. @default is 0.
* @retval binding The newly added rotated Lorentz cone constraint, together
* with the bound variables.
* @pre
* 1. `linear_expression1` is a linear (affine) expression, in the form of
* v1 = c1'*x + d1.
* 2. `linear_expression2` is a linear (affine) expression, in the form of
* v2 = c2'*x + d2.
* 2. `quadratic_expression` is a quadratic expression, in the form of
* <pre>
* u = x'*Q*x + b'x + a
* </pre>
* Also the quadratic expression has to be convex, namely Q is a
* positive semidefinite matrix, and the quadratic expression needs
* to be non-negative for any x.
* @throws std::exception if the preconditions are not satisfied.
*
* For example, to add the rotated Lorentz cone constraint
*
* (x+1)(x+y) >= x²+z²+2z+5
* x+1 >= 0
* x+y >= 0
* The user could call
* @code{cc}
* prog.AddRotatedLorentzConeConstraint(x+1, x+y, pow(x, 2) + pow(z, 2) +
* 2*z+5);
* @endcode
*/
Binding<RotatedLorentzConeConstraint> AddRotatedLorentzConeConstraint(
const symbolic::Expression& linear_expression1,
const symbolic::Expression& linear_expression2,
const symbolic::Expression& quadratic_expression, double tol = 0);
/**
* Adds a constraint that a symbolic expression @param v is in the rotated
* Lorentz cone, i.e.,
* \f[
* v_0v_1 \ge v_2^2 + ... + v_{n-1}^2\\
* v_0 \ge 0, v_1 \ge 0
* \f]
* @param v A linear expression of variables, \f$ v = A x + b\f$, where \f$ A,
* b \f$ are given matrices of the correct size, \f$ x \f$ is the vector of
* decision variables.
* @retval binding The newly added rotated Lorentz cone constraint, together
* with the bound variables.
*
* For example, to add the rotated Lorentz cone constraint
*
* (x+1)(x+y) >= x²+z²+2z+5 = x² + (z+1)² + 2²
* x+1 >= 0
* x+y >= 0
* The user could call
* @code{cc}
* Eigen::Matrix<symbolic::Expression, 5, 1> v;
* v << x+1, x+y, x, z+1, 2;
* prog.AddRotatedLorentzConeConstraint(v);
* @endcode
*/
Binding<RotatedLorentzConeConstraint> AddRotatedLorentzConeConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v);
/**
* Adds a rotated Lorentz cone constraint referencing potentially a subset
* of decision variables, The linear expression @f$ z=Ax+b @f$ is in rotated
* Lorentz cone.
* A vector \f$ z \in\mathbb{R}^n \f$ is in the rotated Lorentz cone, if
* <!--
* z(0)*z(1) >= z(2)² + ... + z(n-1)²
* -->
* @f[
* z_0z_1 \ge z_2^2 + ... + z_{n-1}^2
* @f]
* where @f$ A\in\mathbb{R}^{n\times m}, b\in\mathbb{R}^n@f$ are given
* matrices.
* @param A A matrix whose number of columns equals to the size of the
* decision variables.
* @param b A vector whose number of rows equals to the size of the decision
* variables.
* @param vars The decision variables on which the constraint is imposed.
*/
Binding<RotatedLorentzConeConstraint> AddRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b, const VariableRefList& vars) {
return AddRotatedLorentzConeConstraint(A, b,
ConcatenateVariableRefList(vars));
}
/**
* Adds a rotated Lorentz cone constraint referencing potentially a subset
* of decision variables, The linear expression @f$ z=Ax+b @f$ is in rotated
* Lorentz cone.
* A vector \f$ z \in\mathbb{R}^n \f$ is in the rotated Lorentz cone, if
* <!--
* z(0)*z(1) >= z(2)² + ... + z(n-1)²
* -->
* @f[
* z_0z_1 \ge z_2^2 + ... + z_{n-1}^2
* @f]
* where @f$ A\in\mathbb{R}^{n\times m}, b\in\mathbb{R}^n@f$ are given
* matrices.
* @param A A matrix whose number of columns equals to the size of the
* decision variables.
* @param b A vector whose number of rows equals to the size of the decision
* variables.
* @param vars The decision variables on which the constraint is imposed.
*/
Binding<RotatedLorentzConeConstraint> AddRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Impose that a vector @f$ x\in\mathbb{R}^m @f$ is in rotated Lorentz cone.
* Namely
* @f[
* x_0 x_1 \ge x_2^2 + ... + x_{m-1}^2\\
* x_0 \ge 0, x_1 \ge 0
* @f]
* <!-->
* x(0)*x(1) >= x(2)^2 + ... x(m-1)^2
* x(0) >= 0, x(1) >= 0
* <-->
* @param vars The stacked column of vars lies in the rotated Lorentz cone.
* @return The newly added rotated Lorentz cone constraint.
*/
Binding<RotatedLorentzConeConstraint> AddRotatedLorentzConeConstraint(
const VariableRefList& vars) {
return AddRotatedLorentzConeConstraint(ConcatenateVariableRefList(vars));
}
/**
* Impose that a vector @f$ x\in\mathbb{R}^m @f$ is in rotated Lorentz cone.
* Namely
* @f[
* x_0 x_1 \ge x_2^2 + ... + x_{m-1}^2\\
* x_0 \ge 0, x_1 \ge 0
* @f]
* <!-->
* x(0)*x(1) >= x(2)^2 + ... x(m-1)^2
* x(0) >= 0, x(1) >= 0
* <-->
* @param vars The stacked column of vars lies in the rotated Lorentz cone.
* @return The newly added rotated Lorentz cone constraint.
*/
template <int rows>
Binding<RotatedLorentzConeConstraint> AddRotatedLorentzConeConstraint(
const Eigen::MatrixBase<VectorDecisionVariable<rows>>& vars) {
Eigen::Matrix<double, rows, rows> A(vars.rows(), vars.rows());
A.setIdentity();
Eigen::Matrix<double, rows, 1> b(vars.rows());
b.setZero();
return AddRotatedLorentzConeConstraint(A, b, vars);
}
/** Add the convex quadratic constraint 0.5xᵀQx + bᵀx + c <= 0 as a
* rotated Lorentz cone constraint [rᵀx+s, 1, Px+q] is in the rotated Lorentz
* cone. When solving the optimization problem using conic solvers (like
* Mosek, Gurobi, SCS, etc), it is numerically preferable to impose the
* convex quadratic constraint as rotated Lorentz cone constraint. See
* https://docs.mosek.com/latest/capi/prob-def-quadratic.html#a-recommendation
* @throw exception if this quadratic constraint is not convex (Q is not
* positive semidefinite)
* @param Q The Hessian of the quadratic constraint. Should be positive
* semidefinite.
* @param b The linear coefficient of the quadratic constraint.
* @param c The constant term of the quadratic constraint.
* @param vars x in the documentation above.
* @param psd_tol If the minimal eigenvalue of Q is smaller than -psd_tol,
* then throw an exception. @default = 0.
*/
Binding<RotatedLorentzConeConstraint>
AddQuadraticAsRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double c,
const Eigen::Ref<const VectorX<symbolic::Variable>>& vars,
double psd_tol = 0.);
/**
* Adds a linear complementarity constraints referencing a subset of
* the decision variables.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearComplementarityConstraint> AddConstraint(
const Binding<LinearComplementarityConstraint>& binding);
/**
* Adds a linear complementarity constraints referencing a subset of
* the decision variables.
*/
Binding<LinearComplementarityConstraint> AddLinearComplementarityConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& M,
const Eigen::Ref<const Eigen::VectorXd>& q, const VariableRefList& vars) {
return AddLinearComplementarityConstraint(M, q,
ConcatenateVariableRefList(vars));
}
/**
* Adds a linear complementarity constraints referencing a subset of
* the decision variables.
*/
Binding<LinearComplementarityConstraint> AddLinearComplementarityConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& M,
const Eigen::Ref<const Eigen::VectorXd>& q,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds a polynomial constraint to the program referencing a subset
* of the decision variables (defined in the vars parameter).
*/
Binding<Constraint> AddPolynomialConstraint(
const Eigen::Ref<const MatrixX<Polynomiald>>& polynomials,
const std::vector<Polynomiald::VarType>& poly_vars,
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub,
const VariableRefList& vars) {
return AddPolynomialConstraint(polynomials, poly_vars, lb, ub,
ConcatenateVariableRefList(vars));
}
/**
* Adds a polynomial constraint to the program referencing a subset
* of the decision variables (defined in the vars parameter).
*/
Binding<Constraint> AddPolynomialConstraint(
const Eigen::Ref<const MatrixX<Polynomiald>>& polynomials,
const std::vector<Polynomiald::VarType>& poly_vars,
const Eigen::Ref<const Eigen::MatrixXd>& lb,
const Eigen::Ref<const Eigen::MatrixXd>& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds a positive semidefinite constraint on a symmetric matrix.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<PositiveSemidefiniteConstraint> AddConstraint(
const Binding<PositiveSemidefiniteConstraint>& binding);
/**
* Adds a positive semidefinite constraint on a symmetric matrix.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<PositiveSemidefiniteConstraint> AddConstraint(
std::shared_ptr<PositiveSemidefiniteConstraint> con,
const Eigen::Ref<const MatrixXDecisionVariable>& symmetric_matrix_var);
/**
* Adds a positive semidefinite constraint on a symmetric matrix.
*
* @throws std::exception in Debug mode if @p symmetric_matrix_var is not
* symmetric.
* @param symmetric_matrix_var A symmetric MatrixDecisionVariable object.
*/
Binding<PositiveSemidefiniteConstraint> AddPositiveSemidefiniteConstraint(
const Eigen::Ref<const MatrixXDecisionVariable>& symmetric_matrix_var);
/**
* Adds a positive semidefinite constraint on a symmetric matrix of symbolic
* expressions @p e. We create a new symmetric matrix of variables M being
* positive semidefinite, with the linear equality constraint e == M.
* @param e Imposes constraint "e is positive semidefinite".
* @pre{1. e is symmetric.
* 2. e(i, j) is linear for all i, j
* }
* @return The newly added positive semidefinite constraint, with the bound
* variable M that are also newly added.
*
* For example, to add a constraint that
*
* ⌈x + 1 2x + 3 x+y⌉
* |2x+ 3 2 0| is positive semidefinite
* ⌊x + y 0 x⌋
* The user could call
* @code{cc}
* Matrix3<symbolic::Expression> e
* e << x+1, 2*x+3, x+y,
* 2*x+3, 2, 0,
* x+y, 0, x;
* prog.AddPositiveSemidefiniteConstraint(e);
* @endcode
*/
Binding<PositiveSemidefiniteConstraint> AddPositiveSemidefiniteConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& e) {
// TODO(jwnimmer-tri) Move this whole function definition into the cc file.
DRAKE_THROW_UNLESS(e.rows() == e.cols());
DRAKE_ASSERT(CheckStructuralEquality(e, e.transpose().eval()));
const MatrixXDecisionVariable M = NewSymmetricContinuousVariables(e.rows());
// Adds the linear equality constraint that M = e.
AddLinearEqualityConstraint(
e - M, Eigen::MatrixXd::Zero(e.rows(), e.rows()), true);
return AddPositiveSemidefiniteConstraint(M);
}
/**
* Adds a constraint that the principal submatrix of a symmetric matrix
* composed of the indices in minor_indices is positive semidefinite.
*
* @pre The passed @p symmetric_matrix_var is a symmetric matrix.
* @pre All values in `minor_indices` lie in the range [0,
* symmetric_matrix_var.rows() - 1].
* @param symmetric_matrix_var A symmetric MatrixDecisionVariable object.
* @see AddPositiveSemidefiniteConstraint.
*/
Binding<PositiveSemidefiniteConstraint> AddPrincipalSubmatrixIsPsdConstraint(
const Eigen::Ref<const MatrixXDecisionVariable>& symmetric_matrix_var,
const std::set<int>& minor_indices);
/**
* Adds a constraint the that the principal submatrix of a symmetric matrix of
* expressions composed of the indices in minor_indices is positive
* semidefinite.
*
* @pre The passed @p symmetric_matrix_var is a symmetric matrix.
* @pre All values in `minor_indices` lie in the range [0,
* symmetric_matrix_var.rows() - 1].
* @param e Imposes constraint "e is positive semidefinite".
* @see AddPositiveSemidefiniteConstraint.
*/
Binding<PositiveSemidefiniteConstraint> AddPrincipalSubmatrixIsPsdConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& e,
const std::set<int>& minor_indices);
/**
* Adds a linear matrix inequality constraint to the program.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<LinearMatrixInequalityConstraint> AddConstraint(
const Binding<LinearMatrixInequalityConstraint>& binding);
/**
* Adds a linear matrix inequality constraint to the program.
*/
Binding<LinearMatrixInequalityConstraint> AddLinearMatrixInequalityConstraint(
std::vector<Eigen::MatrixXd> F, const VariableRefList& vars) {
return AddLinearMatrixInequalityConstraint(
std::move(F), ConcatenateVariableRefList(vars));
}
/**
* Adds a linear matrix inequality constraint to the program.
*/
Binding<LinearMatrixInequalityConstraint> AddLinearMatrixInequalityConstraint(
std::vector<Eigen::MatrixXd> F,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Adds the constraint that a symmetric matrix is diagonally dominant with
* non-negative diagonal entries.
* A symmetric matrix X is diagonally dominant with non-negative diagonal
* entries if
* X(i, i) >= ∑ⱼ |X(i, j)| ∀ j ≠ i
* namely in each row, the diagonal entry is larger than the sum of the
* absolute values of all other entries in the same row. A matrix being
* diagonally dominant with non-negative diagonals is a sufficient (but not
* necessary) condition of a matrix being positive semidefinite.
* Internally we will create a matrix Y as slack variables, such that Y(i, j)
* represents the absolute value |X(i, j)| ∀ j ≠ i. The diagonal entries
* Y(i, i) = X(i, i)
* The users can refer to "DSOS and SDSOS Optimization: More Tractable
* Alternatives to Sum of Squares and Semidefinite Optimization" by Amir Ali
* Ahmadi and Anirudha Majumdar, with arXiv link
* https://arxiv.org/abs/1706.02586
* @param X The matrix X. We will use 0.5(X+Xᵀ) as the "symmetric version" of
* X.
* @return Y The slack variable. Y(i, j) represents |X(i, j)| ∀ j ≠ i, with
* the constraint Y(i, j) >= X(i, j) and Y(i, j) >= -X(i, j). Y is a symmetric
* matrix. The diagonal entries Y(i, i) = X(i, i)
*/
MatrixX<symbolic::Expression> AddPositiveDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X);
/**
* 1. Tightens the positive semidefinite @p constraint with a positive
* diagonally dominant constraint.
* 2. Adds the positive diagonally dominant constraint into this
* MathematicalProgram.
* 3. Removes the positive semidefinite @p constraint, if it had already been
* registered in this MathematicalProgram.
*
* This provides a polyhedral (i.e. linear) sufficient, but not
* necessary, condition for the variables in @p constraint to be positive
* semidefinite.
*
* @pre The decision variables contained in constraint have been registered
* with this MathematicalProgram.
* @return The return of AddPositiveDiagonallyDominantMatrixConstraint applied
* to the variables in @p constraint.
*/
MatrixX<symbolic::Expression> TightenPsdConstraintToDd(
const Binding<PositiveSemidefiniteConstraint>& constraint);
/**
* @anchor add_dd_dual
* @name Diagonally dominant dual cone constraint
* Adds the constraint that a symmetric matrix is in the dual cone of the
* diagonally dominant matrices which is denoted DD*. This set is a polyhedral
* (linear) outer approximation to the PSD cone. This follows from the fact
* that since DD ⊆ PSD, then PSD* ⊆ DD*, and since PSD is self-dual, we have
* that PSD = PSD* and so DD ⊆ PSD = PSD* ⊆ DD*.
*
* A symmetric matrix X is in DD* if and only if vᵢᵀXvᵢ ≥ 0 for all vᵢ,
* where vᵢ is a non-zero vector with at most two entries set to ±1 and all
* other entries set to 0. There are 4 * (n choose 2) + 2 * n of these
* vectors, but notice that vᵢᵀXvᵢ = (-vᵢ)ᵀX(vᵢ) and so we only need to add
* all choices with different partities of which there are 2 * (n choose 2) +
* n = n². Therefore, if X is a matrix of size n x n, this function adds
* exactly n² linear constraints.
*
* This is a consequence of the characterization of DD given in "Cones
* of diagonally dominant matrices" by Barker and Carlson which can be found
* at https://msp.org/pjm/1975/57-1/p03.xhtml.
*/
//@{
/**
* This is an overloaded variant of @ref add_dd_dual
* "diagonally dominant dual cone constraint"
* @param X The matrix X. We will use 0.5(X+Xᵀ) as the "symmetric version" of
* X.
* @pre X(i, j) should be a linear expression of decision variables.
* @return A linear constraint of size n² encoding vᵢᵀXvᵢ ≥ 0
*
* @pydrake_mkdoc_identifier{expression}
*/
Binding<LinearConstraint>
AddPositiveDiagonallyDominantDualConeMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X);
/**
* This is an overloaded variant of @ref add_dd_dual
* "diagonally dominant dual cone constraint"
* @param X The matrix X. We will use 0.5(X+Xᵀ) as the "symmetric version" of
* X.
* @return A linear constraint of size n² encoding vᵢᵀXvᵢ ≥ 0
*
* @pydrake_mkdoc_identifier{variable}
*/
Binding<LinearConstraint>
AddPositiveDiagonallyDominantDualConeMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X);
//@}
/**
* 1. Relaxes the positive semidefinite @p constraint with a diagonally
* dominant dual cone constraint.
* 2. Adds the diagonally dominant dual cone constraint into this
* MathematicalProgram.
* 3. Removes the positive semidefinite @p constraint, if it had already been
* registered in this MathematicalProgram.
*
* This provides a polyhedral (i.e. linear) necessary, but not
* sufficient, condition for the variables in @p constraint to be positive
* semidefinite.
*
* @pre The decision variables contained in constraint have been registered
* with this MathematicalProgram.
* @return The return of AddPositiveDiagonallyDominantDualConeMatrixConstraint
* applied to the variables in @p constraint.
*/
Binding<LinearConstraint> RelaxPsdConstraintToDdDualCone(
const Binding<PositiveSemidefiniteConstraint>& constraint);
/**
* @anchor addsdd
* @name Scaled diagonally dominant matrix constraint
* Adds the constraint that a symmetric matrix is scaled diagonally dominant
* (sdd). A matrix X is sdd if there exists a diagonal matrix D, such that
* the product DXD is diagonally dominant with non-negative diagonal entries,
* namely
* d(i)X(i, i) ≥ ∑ⱼ |d(j)X(i, j)| ∀ j ≠ i
* where d(i) = D(i, i).
* X being sdd is equivalent to the existence of symmetric matrices Mⁱʲ∈ ℝⁿˣⁿ,
* i < j, such that all entries in Mⁱʲ are 0, except Mⁱʲ(i, i), Mⁱʲ(i, j),
* Mⁱʲ(j, j). (Mⁱʲ(i, i), Mⁱʲ(j, j), Mⁱʲ(i, j)) is in the rotated
* Lorentz cone, and X = ∑ᵢⱼ Mⁱʲ.
*
* The users can refer to "DSOS and SDSOS Optimization: More Tractable
* Alternatives to Sum of Squares and Semidefinite Optimization" by Amir Ali
* Ahmadi and Anirudha Majumdar, with arXiv link
* https://arxiv.org/abs/1706.02586.
*/
//@{
/**
* This is an overloaded variant of @ref addsdd
* "scaled diagonally dominant matrix constraint"
* @param X The matrix X to be constrained scaled diagonally dominant.
* X.
* @pre X(i, j) should be a linear expression of decision variables.
* @return M A vector of vectors of 2 x 2 symmetric matrices M. For i < j,
* M[i][j] is
* <pre>
* [Mⁱʲ(i, i), Mⁱʲ(i, j)]
* [Mⁱʲ(i, j), Mⁱʲ(j, j)].
* </pre>
* Note that M[i][j](0, 1) = Mⁱʲ(i, j) = (X(i, j) + X(j, i)) / 2
* for i >= j, M[i][j] is the zero matrix.
*
* @pydrake_mkdoc_identifier{expression}
*/
std::vector<std::vector<Matrix2<symbolic::Expression>>>
AddScaledDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X);
/**
* This is an overloaded variant of @ref addsdd
* "scaled diagonally dominant matrix constraint"
* @param X The symmetric matrix X to be constrained scaled diagonally
* dominant.
* @return M For i < j M[i][j] contains the slack variables, mentioned in
* @ref addsdd "scaled diagonally dominant matrix constraint". For i >= j,
* M[i][j] contains default-constructed variables (with get_id() == 0).
*
* @pydrake_mkdoc_identifier{variable}
*/
std::vector<std::vector<Matrix2<symbolic::Variable>>>
AddScaledDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X);
//@}
/**
* 1. Tightens the positive semidefinite @p constraint with a scaled
* diagonally dominant constraint.
* 2. Adds the scaled diagonally dominant constraint into this
* MathematicalProgram.
* 3. Removes the positive semidefinite @p constraint, if it had already been
* registered in this MathematicalProgram.
*
* This provides a second-order cone sufficient, but not
* necessary, condition for the variables in @p constraint to be positive
* semidefinite.
*
* @pre The decision variables contained in constraint have been registered
* with this MathematicalProgram.
* @return The return of AddScaledDiagonallyDominantMatrixConstraint applied
* to the variables in @p constraint.
*/
std::vector<std::vector<Matrix2<symbolic::Variable>>>
TightenPsdConstraintToSdd(
const Binding<PositiveSemidefiniteConstraint>& constraint);
/**
* @anchor add_sdd_dual
* @name Scaled diagonally dominant dual cone constraint
* Adds the constraint that a symmetric matrix is in the dual cone of the
* scaled diagonally dominant matrices which is denoted SDD*. The set SDD* is
* an SOCP outer approximation to the PSD cone that is tighter than DD*. This
* follows from the fact that DD ⊆ SDD ⊆ PSD = PSD* ⊆ SDD* ⊆ DD*.
*
* A symmetric matrix X is in SDD* if and only if all 2 x 2 principal minors
* of X are psd. This can be encoded by ensuring that VᵢⱼᵀXVᵢⱼ is psd for all
* Vᵢⱼ, where Vᵢⱼ is the n x 2 matrix such that Vᵢⱼ(i, 0) = 1, V(j, 1) = 1,
* namely Vᵢⱼ = [eᵢ eⱼ].
* This can be encoded using 1/2 * n * (n-1) RotatedLorentzCone constraints
* which we return in this function.
*
* This can be seen by noting that
* VᵢⱼᵀXVᵢⱼ = ⌈ Xᵢᵢ Xᵢⱼ⌉
⌊ Xⱼᵢ Xⱼⱼ⌋
* is psd if and only if VⱼᵢᵀXVⱼᵢ as they are simply permutations of each
* other. Therefore, it suffices to only add the constraint for i ≥ j.
* Moreover, notice that VᵢᵢᵀXVᵢᵢ = ⌈ Xᵢᵢ 0⌉ ⌊ 0 0⌋ is psd if and only if
* Xᵢᵢ ≥ 0. This linear constraint is already implied by VᵢⱼᵀXVᵢⱼ is psd for
* every i ≠ j and so is redundant. Therefore, we only add
* RotatedLorentzConeConstraints for i > j.
*
* This characterization can be found in Section 3.3 of "Sum of Squares Basis
* Pursuit with Linear and Second Order Cone Programming" by Ahmadi and Hall
* with arXiv link https://arxiv.org/abs/1510.01597
*/
//@{
/**
* This is an overloaded variant of @ref add_sdd_dual
* "scaled diagonally dominant dual cone constraint"
* @param X The matrix X. We will use 0.5(X+Xᵀ) as the "symmetric version" of
* X.
* @pre X(i, j) should be a linear expression of decision variables.
* @return A vector of RotatedLorentzConeConstraint constraints of length
* 1/2 * n * (n-1) encoding VᵢⱼᵀXVᵢⱼ is psd
* @pydrake_mkdoc_identifier{expression}
*/
std::vector<Binding<RotatedLorentzConeConstraint>>
AddScaledDiagonallyDominantDualConeMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X);
/**
* This is an overloaded variant of @ref add_sdd_dual
* "scaled diagonally dominant dual cone constraint"
* @param X The matrix X. We will use 0.5(X+Xᵀ) as the "symmetric version" of
* X.
* @return A vector of RotatedLorentzConeConstraint constraints of length
* 1/2 * n * (n-1) encoding VᵢⱼᵀXVᵢⱼ is psd
* @pydrake_mkdoc_identifier{variable}
*/
std::vector<Binding<RotatedLorentzConeConstraint>>
AddScaledDiagonallyDominantDualConeMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X);
//@}
/**
* 1. Relaxes the positive semidefinite @p constraint with a scaled diagonally
* dominant dual cone constraint.
* 2. Adds the scaled diagonally dominant dual cone constraint into this
* MathematicalProgram.
* 3. Removes the positive semidefinite @p constraint, if it had already been
* registered in this MathematicalProgram.
*
* This provides a second-order cone necessary, but not
* sufficient, condition for the variables in @p constraint to be positive
* semidefinite.
*
* @pre The decision variables contained in constraint have been registered
* with this MathematicalProgram.
* @return The return of AddScaledDiagonallyDominantDualConeMatrixConstraint
* applied to the variables in @p constraint.
*/
std::vector<Binding<RotatedLorentzConeConstraint>>
RelaxPsdConstraintToSddDualCone(
const Binding<PositiveSemidefiniteConstraint>& constraint);
/**
* Adds constraints that a given polynomial @p p is a sums-of-squares (SOS),
* that is, @p p can be decomposed into `mᵀQm`, where m is the @p
* monomial_basis. It returns the coefficients matrix Q, which is positive
* semidefinite.
* @param type The type of the polynomial. @default is kSos, but the user can
* also use kSdsos and kDsos. Refer to NonnegativePolynomial for details on
* different types of sos polynomials.
* @param gram_name The name of the gram matrix for print out.
*
* @note It calls `Reparse` to enforce `p` to have this MathematicalProgram's
* indeterminates if necessary.
*/
MatrixXDecisionVariable AddSosConstraint(
const symbolic::Polynomial& p,
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
NonnegativePolynomial type = NonnegativePolynomial::kSos,
const std::string& gram_name = "S");
/**
* Adds constraints that a given polynomial @p p is a sums-of-squares (SOS),
* that is, @p p can be decomposed into `mᵀQm`, where m is a monomial
* basis selected from the sparsity of @p p. It returns a pair of constraint
* bindings expressing:
* - The coefficients matrix Q, which is positive semidefinite.
* - The monomial basis m.
* @param type The type of the polynomial. @default is kSos, but the user can
* also use kSdsos and kDsos. Refer to NonnegativePolynomial for the details
* on different type of sos polynomials.
* @param gram_name The name of the gram matrix for print out.
*
* @note It calls `Reparse` to enforce `p` to have this MathematicalProgram's
* indeterminates if necessary.
*/
std::pair<MatrixXDecisionVariable, VectorX<symbolic::Monomial>>
AddSosConstraint(const symbolic::Polynomial& p,
NonnegativePolynomial type = NonnegativePolynomial::kSos,
const std::string& gram_name = "S");
/**
* Adds constraints that a given symbolic expression @p e is a
* sums-of-squares (SOS), that is, @p p can be decomposed into `mᵀQm`,
* where m is the @p monomial_basis. Note that it decomposes @p e into a
* polynomial with respect to `indeterminates()` in this mathematical
* program. It returns the coefficients matrix Q, which is positive
* semidefinite.
* @param type Refer to NonnegativePolynomial class documentation.
* @param gram_name The name of the gram matrix for print out.
*/
MatrixXDecisionVariable AddSosConstraint(
const symbolic::Expression& e,
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
NonnegativePolynomial type = NonnegativePolynomial::kSos,
const std::string& gram_name = "S");
/**
* Adds constraints that a given symbolic expression @p e is a sums-of-squares
* (SOS), that is, @p e can be decomposed into `mᵀQm`. Note that it decomposes
* @p e into a polynomial with respect to `indeterminates()` in this
* mathematical program. It returns a pair expressing:
* - The coefficients matrix Q, which is positive semidefinite.
* - The monomial basis m.
* @param type Refer to NonnegativePolynomial class documentation.
* @param gram_name The name of the gram matrix for print out.
*/
std::pair<MatrixXDecisionVariable, VectorX<symbolic::Monomial>>
AddSosConstraint(const symbolic::Expression& e,
NonnegativePolynomial type = NonnegativePolynomial::kSos,
const std::string& gram_name = "S");
/**
* Constraining that two polynomials are the same (i.e., they have the same
* coefficients for each monomial). This function is often used in
* sum-of-squares optimization.
* We will impose the linear equality constraint that the coefficient of a
* monomial in @p p1 is the same as the coefficient of the same monomial in @p
* p2.
* @param p1 Note that p1's indeterminates should have been registered as
* indeterminates in this MathematicalProgram object, and p1's coefficients
* are affine functions of decision variables in this MathematicalProgram
* object.
* @param p2 Note that p2's indeterminates should have been registered as
* indeterminates in this MathematicalProgram object, and p2's coefficients
* are affine functions of decision variables in this MathematicalProgram
* object.
*
* @note It calls `Reparse` to enforce `p1` and `p2` to have this
* MathematicalProgram's indeterminates.
*/
std::vector<Binding<LinearEqualityConstraint>>
AddEqualityConstraintBetweenPolynomials(const symbolic::Polynomial& p1,
const symbolic::Polynomial& p2);
/**
* Adds the exponential cone constraint that
* z = binding.evaluator()->A() * binding.variables() +
* binding.evaluator()->b()
* should be in the exponential cone. Namely
* {(z₀, z₁, z₂) | z₀ ≥ z₁ * exp(z₂ / z₁), z₁ > 0}.
* @param binding The binding of ExponentialConeConstraint and its bound
* variables.
*
* @exclude_from_pydrake_mkdoc{Not bound in pydrake.}
*/
Binding<ExponentialConeConstraint> AddConstraint(
const Binding<ExponentialConeConstraint>& binding);
/**
* Adds an exponential cone constraint, that z = A * vars + b should be in
* the exponential cone. Namely {z₀, z₁, z₂ | z₀ ≥ z₁ * exp(z₂ / z₁), z₁ >
* 0}.
* @param A The A matrix in the documentation above. A must have 3 rows.
* @param b The b vector in the documentation above.
* @param vars The variables bound with this constraint.
*/
Binding<ExponentialConeConstraint> AddExponentialConeConstraint(
const Eigen::Ref<const Eigen::SparseMatrix<double>>& A,
const Eigen::Ref<const Eigen::Vector3d>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars);
/**
* Add the constraint that z is in the exponential cone.
* @param z The expression in the exponential cone.
* @pre each entry in `z` is a linear expression of the decision variables.
*/
Binding<ExponentialConeConstraint> AddExponentialConeConstraint(
const Eigen::Ref<const Vector3<symbolic::Expression>>& z);
/**
* Gets the initial guess for a single variable.
* @pre @p decision_variable has been registered in the optimization program.
* @throws std::exception if the pre condition is not satisfied.
*/
[[nodiscard]] double GetInitialGuess(
const symbolic::Variable& decision_variable) const;
/**
* Gets the initial guess for some variables.
* @pre Each variable in @p decision_variable_mat has been registered in the
* optimization program.
* @throws std::exception if the pre condition is not satisfied.
*/
template <typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Derived::Scalar, symbolic::Variable>,
MatrixLikewise<double, Derived>>
GetInitialGuess(
const Eigen::MatrixBase<Derived>& decision_variable_mat) const {
MatrixLikewise<double, Derived> decision_variable_values(
decision_variable_mat.rows(), decision_variable_mat.cols());
for (int i = 0; i < decision_variable_mat.rows(); ++i) {
for (int j = 0; j < decision_variable_mat.cols(); ++j) {
decision_variable_values(i, j) =
GetInitialGuess(decision_variable_mat(i, j));
}
}
return decision_variable_values;
}
/**
* Sets the initial guess for a single variable @p decision_variable.
* The guess is stored as part of this program.
* @pre decision_variable is a registered decision variable in the program.
* @throws std::exception if precondition is not satisfied.
*/
void SetInitialGuess(const symbolic::Variable& decision_variable,
double variable_guess_value);
/**
* Sets the initial guess for the decision variables stored in
* @p decision_variable_mat to be @p x0.
* The guess is stored as part of this program.
*/
template <typename DerivedA, typename DerivedB>
void SetInitialGuess(const Eigen::MatrixBase<DerivedA>& decision_variable_mat,
const Eigen::MatrixBase<DerivedB>& x0) {
DRAKE_DEMAND(decision_variable_mat.rows() == x0.rows());
DRAKE_DEMAND(decision_variable_mat.cols() == x0.cols());
for (int i = 0; i < decision_variable_mat.rows(); ++i) {
for (int j = 0; j < decision_variable_mat.cols(); ++j) {
SetInitialGuess(decision_variable_mat(i, j), x0(i, j));
}
}
}
/**
* Set the initial guess for ALL decision variables.
* Note that variables begin with a default initial guess of NaN to indicate
* that no guess is available.
* @param x0 A vector of appropriate size (num_vars() x 1).
*/
template <typename Derived>
void SetInitialGuessForAllVariables(const Eigen::MatrixBase<Derived>& x0) {
DRAKE_ASSERT(x0.rows() == num_vars() && x0.cols() == 1);
x_initial_guess_ = x0;
}
/**
* Updates the value of a single @p decision_variable inside the @p values
* vector to be @p decision_variable_new_value.
* The other decision variables' values in @p values are unchanged.
* @param decision_variable a registered decision variable in this program.
* @param decision_variable_new_value the variable's new values.
* @param[in,out] values The vector to be tweaked; must be of size num_vars().
*/
void SetDecisionVariableValueInVector(
const symbolic::Variable& decision_variable,
double decision_variable_new_value,
EigenPtr<Eigen::VectorXd> values) const;
/**
* Updates the values of some @p decision_variables inside the @p values
* vector to be @p decision_variables_new_values.
* The other decision variables' values in @p values are unchanged.
* @param decision_variables registered decision variables in this program.
* @param decision_variables_new_values the variables' respective new values;
* must have the same rows() and cols() sizes and @p decision_variables.
* @param[in,out] values The vector to be tweaked; must be of size num_vars().
*/
void SetDecisionVariableValueInVector(
const Eigen::Ref<const MatrixXDecisionVariable>& decision_variables,
const Eigen::Ref<const Eigen::MatrixXd>& decision_variables_new_values,
EigenPtr<Eigen::VectorXd> values) const;
/**
* @anchor set_solver_option
* @name Set solver options
* Set the options (parameters) for a specific solver. Refer to SolverOptions
* class for more details on the supported options of each solver.
*/
//@{
/**
* See @ref set_solver_option for more details.
* Set the double-valued options.
* @pydrake_mkdoc_identifier{double_option}
*/
void SetSolverOption(const SolverId& solver_id,
const std::string& solver_option, double option_value) {
solver_options_.SetOption(solver_id, solver_option, option_value);
}
/**
* See @ref set_solver_option for more details.
* Set the integer-valued options.
* @pydrake_mkdoc_identifier{int_option}
*/
void SetSolverOption(const SolverId& solver_id,
const std::string& solver_option, int option_value) {
solver_options_.SetOption(solver_id, solver_option, option_value);
}
/**
* See @ref set_solver_option for more details.
* Set the string-valued options.
* @pydrake_mkdoc_identifier{string_option}
*/
void SetSolverOption(const SolverId& solver_id,
const std::string& solver_option,
const std::string& option_value) {
solver_options_.SetOption(solver_id, solver_option, option_value);
}
/**
* Overwrite the stored solver options inside MathematicalProgram with the
* provided solver options.
*/
void SetSolverOptions(const SolverOptions& solver_options) {
solver_options_ = solver_options;
}
//@}
/**
* Returns the solver options stored inside MathematicalProgram.
*/
const SolverOptions& solver_options() const { return solver_options_; }
const std::unordered_map<std::string, double>& GetSolverOptionsDouble(
const SolverId& solver_id) const {
return solver_options_.GetOptionsDouble(solver_id);
}
const std::unordered_map<std::string, int>& GetSolverOptionsInt(
const SolverId& solver_id) const {
return solver_options_.GetOptionsInt(solver_id);
}
const std::unordered_map<std::string, std::string>& GetSolverOptionsStr(
const SolverId& solver_id) const {
return solver_options_.GetOptionsStr(solver_id);
}
/**
* Getter for all callbacks.
*/
const std::vector<Binding<VisualizationCallback>>& visualization_callbacks()
const {
return visualization_callbacks_;
}
/**
* Getter for all generic costs.
*/
const std::vector<Binding<Cost>>& generic_costs() const {
return generic_costs_;
} // e.g. for snopt_user_fun
/**
* Getter for all generic constraints
*/
const std::vector<Binding<Constraint>>& generic_constraints() const {
return generic_constraints_;
} // e.g. for snopt_user_fun
/**
* Getter for linear equality constraints. Note that this only includes
* constraints that were added explicitly as LinearEqualityConstraint or
* which were added symbolically (and their equality constraint nature was
* uncovered). There may be bounding_box_constraints() and
* linear_constraints() whose lower bounds also equal their upper bounds.
*/
const std::vector<Binding<LinearEqualityConstraint>>&
linear_equality_constraints() const {
return linear_equality_constraints_;
}
/** Getter for linear costs. */
const std::vector<Binding<LinearCost>>& linear_costs() const {
return linear_costs_;
}
/** Getter for quadratic costs. */
const std::vector<Binding<QuadraticCost>>& quadratic_costs() const {
return quadratic_costs_;
}
/** Getter for l2norm costs. */
const std::vector<Binding<L2NormCost>>& l2norm_costs() const {
return l2norm_costs_;
}
/** Getter for linear *inequality* constraints. Note that this does not
* include linear_equality_constraints() nor bounding_box_constraints(). See
* also GetAllLinearConstraints(). */
const std::vector<Binding<LinearConstraint>>& linear_constraints() const {
return linear_constraints_;
}
/** Getter for quadratic constraints. */
const std::vector<Binding<QuadraticConstraint>>& quadratic_constraints()
const {
return quadratic_constraints_;
}
/** Getter for Lorentz cone constraints. */
const std::vector<Binding<LorentzConeConstraint>>& lorentz_cone_constraints()
const {
return lorentz_cone_constraint_;
}
/** Getter for rotated Lorentz cone constraints. */
const std::vector<Binding<RotatedLorentzConeConstraint>>&
rotated_lorentz_cone_constraints() const {
return rotated_lorentz_cone_constraint_;
}
/** Getter for positive semidefinite constraints. */
const std::vector<Binding<PositiveSemidefiniteConstraint>>&
positive_semidefinite_constraints() const {
return positive_semidefinite_constraint_;
}
/** Getter for linear matrix inequality constraints. */
const std::vector<Binding<LinearMatrixInequalityConstraint>>&
linear_matrix_inequality_constraints() const {
return linear_matrix_inequality_constraint_;
}
/** Getter for exponential cone constraints. */
const std::vector<Binding<ExponentialConeConstraint>>&
exponential_cone_constraints() const {
return exponential_cone_constraints_;
}
/** Getter for all bounding box constraints */
const std::vector<Binding<BoundingBoxConstraint>>& bounding_box_constraints()
const {
return bbox_constraints_;
}
/** Getter for all linear complementarity constraints.*/
const std::vector<Binding<LinearComplementarityConstraint>>&
linear_complementarity_constraints() const {
return linear_complementarity_constraints_;
}
/**
* Getter returning all costs.
* @returns Vector of all cost bindings.
* @note The group ordering may change as more cost types are added.
*/
[[nodiscard]] std::vector<Binding<Cost>> GetAllCosts() const;
/**
* Getter returning all linear constraints (both linear equality and
* inequality constraints). Note that this does *not* include bounding box
* constraints, which are technically also linear.
* @returns Vector of all linear constraint bindings.
*/
[[nodiscard]] std::vector<Binding<LinearConstraint>> GetAllLinearConstraints()
const;
/**
* Getter for returning all constraints.
* @returns Vector of all constraint bindings.
* @note The group ordering may change as more constraint types are added.
*/
[[nodiscard]] std::vector<Binding<Constraint>> GetAllConstraints() const;
/** Getter for number of variables in the optimization program */
int num_vars() const { return decision_variables_.size(); }
/** Gets the number of indeterminates in the optimization program */
int num_indeterminates() const { return indeterminates_.size(); }
/** Getter for the initial guess */
const Eigen::VectorXd& initial_guess() const { return x_initial_guess_; }
/** Returns the index of the decision variable. Internally the solvers thinks
* all variables are stored in an array, and it accesses each individual
* variable using its index. This index is used when adding constraints
* and costs for each solver.
* @pre{@p var is a decision variable in the mathematical program, otherwise
* this function throws a runtime error.}
*/
[[nodiscard]] int FindDecisionVariableIndex(
const symbolic::Variable& var) const;
/**
* Returns the indices of the decision variables. Internally the solvers
* thinks all variables are stored in an array, and it accesses each
* individual
* variable using its index. This index is used when adding constraints
* and costs for each solver.
* @pre{@p vars are decision variables in the mathematical program, otherwise
* this function throws a runtime error.}
*/
[[nodiscard]] std::vector<int> FindDecisionVariableIndices(
const Eigen::Ref<const VectorXDecisionVariable>& vars) const;
/** Returns the index of the indeterminate. Internally a solver
* thinks all indeterminates are stored in an array, and it accesses each
* individual indeterminate using its index. This index is used when adding
* constraints and costs for each solver.
* @pre @p var is a indeterminate in the mathematical program,
* otherwise this function throws a runtime error.
*/
[[nodiscard]] size_t FindIndeterminateIndex(
const symbolic::Variable& var) const;
/**
* Evaluates the value of some binding, for some input value for all
* decision variables.
* @param binding A Binding whose variables are decision variables in this
* program.
* @param prog_var_vals The value of all the decision variables in this
* program.
* @throws std::exception if the size of `prog_var_vals` is invalid.
*/
template <typename C, typename DerivedX>
typename std::enable_if_t<is_eigen_vector<DerivedX>::value,
VectorX<typename DerivedX::Scalar>>
EvalBinding(const Binding<C>& binding,
const Eigen::MatrixBase<DerivedX>& prog_var_vals) const {
using Scalar = typename DerivedX::Scalar;
if (prog_var_vals.rows() != num_vars()) {
std::ostringstream oss;
oss << "The input binding variable is not in the right size. Expects "
<< num_vars() << " rows, but it actually has " << prog_var_vals.rows()
<< " rows.\n";
throw std::logic_error(oss.str());
}
VectorX<Scalar> binding_x(binding.GetNumElements());
VectorX<Scalar> binding_y(binding.evaluator()->num_outputs());
for (int i = 0; i < static_cast<int>(binding.GetNumElements()); ++i) {
binding_x(i) =
prog_var_vals(FindDecisionVariableIndex(binding.variables()(i)));
}
binding.evaluator()->Eval(binding_x, &binding_y);
return binding_y;
}
/**
* Evaluates a set of bindings (plural version of `EvalBinding`).
* @param bindings List of bindings.
* @param prog
* @param prog_var_vals The value of all the decision variables in this
* program.
* @return All binding values, concatenated into a single vector.
* @throws std::exception if the size of `prog_var_vals` is invalid.
*/
template <typename C, typename DerivedX>
typename std::enable_if_t<is_eigen_vector<DerivedX>::value,
VectorX<typename DerivedX::Scalar>>
EvalBindings(const std::vector<Binding<C>>& bindings,
const Eigen::MatrixBase<DerivedX>& prog_var_vals) const {
// TODO(eric.cousineau): Minimize memory allocations when it becomes a
// major performance bottleneck.
using Scalar = typename DerivedX::Scalar;
int num_y{};
for (auto& binding : bindings) {
num_y += binding.evaluator()->num_outputs();
}
VectorX<Scalar> y(num_y);
int offset_y{};
for (auto& binding : bindings) {
VectorX<Scalar> binding_y = EvalBinding(binding, prog_var_vals);
y.segment(offset_y, binding_y.size()) = binding_y;
offset_y += binding_y.size();
}
DRAKE_DEMAND(offset_y == num_y);
return y;
}
/**
* Given the value of all decision variables, namely
* this.decision_variable(i) takes the value prog_var_vals(i), returns the
* vector that contains the value of the variables in binding.variables().
* @param binding binding.variables() must be decision variables in this
* MathematicalProgram.
* @param prog_var_vals The value of ALL the decision variables in this
* program.
* @return binding_variable_vals binding_variable_vals(i) is the value of
* binding.variables()(i) in prog_var_vals.
*/
template <typename C, typename DerivedX>
typename std::enable_if_t<is_eigen_vector<DerivedX>::value,
VectorX<typename DerivedX::Scalar>>
GetBindingVariableValues(
const Binding<C>& binding,
const Eigen::MatrixBase<DerivedX>& prog_var_vals) const {
DRAKE_DEMAND(prog_var_vals.rows() == num_vars());
VectorX<typename DerivedX::Scalar> result(binding.GetNumElements());
for (int i = 0; i < static_cast<int>(binding.GetNumElements()); ++i) {
result(i) =
prog_var_vals(FindDecisionVariableIndex(binding.variables()(i)));
}
return result;
}
/** Evaluates all visualization callbacks registered with the
* MathematicalProgram.
*
* @param prog_var_vals The value of all the decision variables in this
* program.
* @throws std::exception if the size does not match.
*/
void EvalVisualizationCallbacks(
const Eigen::Ref<const Eigen::VectorXd>& prog_var_vals) const;
/**
* Evaluates the evaluator in @p binding at the initial guess.
* @return The value of @p binding at the initial guess.
*/
template <typename C>
Eigen::VectorXd EvalBindingAtInitialGuess(const Binding<C>& binding) const {
return EvalBinding(binding, x_initial_guess_);
}
/**
* Evaluates CheckSatisfied for the constraint in @p binding using the value
* of ALL of the decision variables in this program.
* @throws std::exception if the size of `prog_var_vals` is invalid.
*/
[[nodiscard]] bool CheckSatisfied(
const Binding<Constraint>& binding,
const Eigen::Ref<const Eigen::VectorXd>& prog_var_vals,
double tol = 1e-6) const;
/**
* Evaluates CheckSatisfied for the all of the constraints in @p binding using
* the value of ALL of the decision variables in this program.
* @returns true iff all of the constraints are satisfied.
* @throws std::exception if the size of `prog_var_vals` is invalid.
* @pydrake_mkdoc_identifier{vector}
*/
[[nodiscard]] bool CheckSatisfied(
const std::vector<Binding<Constraint>>& bindings,
const Eigen::Ref<const Eigen::VectorXd>& prog_var_vals,
double tol = 1e-6) const;
/**
* Evaluates CheckSatisfied for the constraint in @p binding at the initial
* guess.
*/
[[nodiscard]] bool CheckSatisfiedAtInitialGuess(
const Binding<Constraint>& binding, double tol = 1e-6) const;
/**
* Evaluates CheckSatisfied for the all of the constraints in @p bindings at
* the initial guess.
* @returns true iff all of the constraints are satisfied.
* @pydrake_mkdoc_identifier{vector}
*/
[[nodiscard]] bool CheckSatisfiedAtInitialGuess(
const std::vector<Binding<Constraint>>& bindings,
double tol = 1e-6) const;
/** Getter for all decision variables in the program. */
Eigen::Map<const VectorX<symbolic::Variable>> decision_variables() const {
return Eigen::Map<const VectorX<symbolic::Variable>>(
decision_variables_.data(), decision_variables_.size());
}
/** Getter for the decision variable with index @p i in the program. */
const symbolic::Variable& decision_variable(int i) const {
DRAKE_ASSERT(i >= 0);
DRAKE_ASSERT(i < static_cast<int>(decision_variables_.size()));
return decision_variables_[i];
}
/** Getter for all indeterminates in the program. */
Eigen::Map<const VectorX<symbolic::Variable>> indeterminates() const {
return Eigen::Map<const VectorX<symbolic::Variable>>(
indeterminates_.data(), indeterminates_.size());
}
/** Getter for the indeterminate with index @p i in the program. */
const symbolic::Variable& indeterminate(int i) const {
DRAKE_ASSERT(i >= 0);
DRAKE_ASSERT(i < static_cast<int>(indeterminates_.size()));
return indeterminates_[i];
}
/// Getter for the required capability on the solver, given the
/// cost/constraint/variable types in the program.
const ProgramAttributes& required_capabilities() const {
return required_capabilities_;
}
/**
* Returns the mapping from a decision variable ID to its index in the vector
* containing all the decision variables in the mathematical program.
*/
const std::unordered_map<symbolic::Variable::Id, int>&
decision_variable_index() const {
return decision_variable_index_;
}
/**
* Returns the mapping from an indeterminate ID to its index in the vector
* containing all the indeterminates in the mathematical program.
*/
const std::unordered_map<symbolic::Variable::Id, int>& indeterminates_index()
const {
return indeterminates_index_;
}
/**
* @anchor variable_scaling
* @name Variable scaling
* Some solvers (e.g. SNOPT) work better if the decision variables values
* are on the same scale. Hence, internally we scale the variable as
* snopt_var_value = var_value / scaling_factor.
* This scaling factor is only used inside the solve, so
* users don't need to manually scale the variables every time they appears in
* cost and constraints. When the users set the initial guess, or getting the
* result from MathematicalProgramResult::GetSolution(), the values are
* unscaled. Namely, MathematicalProgramResult::GetSolution(var) returns the
* value of var, not var_value / scaling_factor.
*
* The feature of variable scaling is currently only implemented for SNOPT and
* OSQP.
*/
//@{
/**
* Returns the mapping from a decision variable index to its scaling factor.
*
* See @ref variable_scaling "Variable scaling" for more information.
*/
const std::unordered_map<int, double>& GetVariableScaling() const {
return var_scaling_map_;
}
/**
* Setter for the scaling @p s of decision variable @p var.
* @param var the decision variable to be scaled.
* @param s scaling factor (must be positive).
*
* See @ref variable_scaling "Variable scaling" for more information.
*/
void SetVariableScaling(const symbolic::Variable& var, double s);
/**
* Clears the scaling factors for decision variables.
*
* See @ref variable_scaling "Variable scaling" for more information.
*/
void ClearVariableScaling() { var_scaling_map_.clear(); }
//@}
/**
* Remove `var` from this program's decision variable.
* @note after removing the variable, the indices of some remaining variables
* inside this MathematicalProgram will change.
* @return the index of `var` in this optimization program. return -1 if `var`
* is not a decision variable.
* @throw exception if `var` is bound with any cost or constraint.
* @throw exception if `var` is not a decision variable of the program.
*/
int RemoveDecisionVariable(const symbolic::Variable& var);
/**
* @anchor remove_cost_constraint
* @name Remove costs, constraints or callbacks.
* Removes costs, constraints or visualization callbacks from this program. If
* this program contains multiple costs/constraints/callbacks objects matching
* the given argument, then all of these costs/constraints/callbacks are
* removed. If this program doesn't contain the specified
* cost/constraint/callback, then the code does nothing. We regard two
* costs/constraints/callbacks being equal, if their evaluators point to the
* same object, and the associated variables are also the same.
* @note If two costs/constraints/callbacks represent the same expression, but
* their evaluators point to different objects, then they are NOT regarded the
* same. For example, if we have
* @code{.cc}
* auto cost1 = prog.AddLinearCost(x[0] + x[1]);
* auto cost2 = prog.AddLinearCost(x[0] + x[1]);
* // cost1 and cost2 represent the same cost, but cost1.evaluator() and
* // cost2.evaluator() point to different objects. So after removing cost1,
* // cost2 still lives in prog.
* prog.RemoveCost(cost1);
* // This will print true.
* std::cout << (prog.linear_costs()[0] == cost2) << "\n";
* @endcode
*/
// @{
/** Removes @p cost from this mathematical program.
* See @ref remove_cost_constraint "Remove costs, constraints or callbacks"
* for more details.
* @return number of cost objects removed from this program. If this program
* doesn't contain @p cost, then returns 0. If this program contains multiple
* @p cost objects, then returns the repetition of @p cost in this program.
*/
int RemoveCost(const Binding<Cost>& cost);
/** Removes @p constraint from this mathematical program.
* See @ref remove_cost_constraint "Remove costs, constraints or callbacks"
* for more details.
* @return number of constraint objects removed from this program. If this
* program doesn't contain @p constraint, then returns 0. If this program
* contains multiple
* @p constraint objects, then returns the repetition of @p constraint in this
* program.
*/
int RemoveConstraint(const Binding<Constraint>& constraint);
/** Removes @p callback from this mathematical program.
* See @ref remove_cost_constraint "Remove costs, constraints or callbacks"
* for more details.
* @return number of callback objects removed from this program. If this
* program doesn't contain @p callback, then returns 0. If this program
* contains multiple
* @p callback objects, then returns the repetition of @p callback in this
* program.
*/
int RemoveVisualizationCallback(
const Binding<VisualizationCallback>& callback);
//@}
private:
// Copy constructor is private for use in implementing Clone().
explicit MathematicalProgram(const MathematicalProgram&);
static void AppendNanToEnd(int new_var_size, Eigen::VectorXd* vector);
// Removes a binding of a constraint/constraint, @p removal, from a given
// vector of bindings, @p existings. If @p removal does not belong to @p
// existings, then do nothing. If @p removal appears multiple times in @p
// existings, then all matching terms are removed. After removing @p removal,
// we check if we need to erase @p affected_capability from
// required_capabilities_.
// @return The number of @p removal object in @p existings.
template <typename C>
int RemoveCostOrConstraintImpl(const Binding<C>& removal,
ProgramAttribute affected_capability,
std::vector<Binding<C>>* existings);
/**
* Check and update if this program requires @p query_capability
* This method should be called after changing stored
* costs/constraints/callbacks.
*/
void UpdateRequiredCapability(ProgramAttribute query_capability);
template <typename T>
void NewVariables_impl(
VarType type, const T& names, bool is_symmetric,
Eigen::Ref<MatrixXDecisionVariable> decision_variable_matrix) {
CheckVariableType(type);
int rows = decision_variable_matrix.rows();
int cols = decision_variable_matrix.cols();
DRAKE_ASSERT(!is_symmetric || rows == cols);
int num_new_vars = 0;
if (!is_symmetric) {
num_new_vars = rows * cols;
} else {
num_new_vars = rows * (rows + 1) / 2;
}
DRAKE_ASSERT(static_cast<int>(names.size()) == num_new_vars);
int row_index = 0;
int col_index = 0;
for (int i = 0; i < num_new_vars; ++i) {
decision_variables_.emplace_back(names[i], type);
const int new_var_index = decision_variables_.size() - 1;
decision_variable_index_.insert(std::make_pair(
decision_variables_[new_var_index].get_id(), new_var_index));
decision_variable_matrix(row_index, col_index) =
decision_variables_[new_var_index];
// If the matrix is not symmetric, then store the variable in column
// major.
if (!is_symmetric) {
if (row_index + 1 < rows) {
++row_index;
} else {
++col_index;
row_index = 0;
}
} else {
// If the matrix is symmetric, then the decision variables are the lower
// triangular part of the symmetric matrix, also stored in column major.
if (row_index != col_index) {
decision_variable_matrix(col_index, row_index) =
decision_variable_matrix(row_index, col_index);
}
if (row_index + 1 < rows) {
++row_index;
} else {
++col_index;
row_index = col_index;
}
}
}
AppendNanToEnd(num_new_vars, &x_initial_guess_);
}
MatrixXDecisionVariable NewVariables(VarType type, int rows, int cols,
bool is_symmetric,
const std::vector<std::string>& names);
template <typename T>
void NewIndeterminates_impl(
const T& names, Eigen::Ref<MatrixXIndeterminate> indeterminates_matrix) {
const int rows = indeterminates_matrix.rows();
const int cols = indeterminates_matrix.cols();
const int num_new_vars = rows * cols;
DRAKE_ASSERT(static_cast<int>(names.size()) == num_new_vars);
int row_index = 0;
int col_index = 0;
for (int i = 0; i < num_new_vars; ++i) {
indeterminates_.emplace_back(names[i]);
const int new_var_index = indeterminates_.size() - 1;
indeterminates_index_.insert(std::make_pair(
indeterminates_[new_var_index].get_id(), new_var_index));
indeterminates_matrix(row_index, col_index) =
indeterminates_[new_var_index];
// store the indeterminate in column major.
if (row_index + 1 < rows) {
++row_index;
} else {
++col_index;
row_index = 0;
}
}
}
/*
* Given a matrix of decision variables, checks if every entry in the
* matrix is a decision variable in the program; throws a runtime
* error if any variable is not a decision variable in the program.
* @param vars A vector of variables.
*/
void CheckIsDecisionVariable(const VectorXDecisionVariable& vars) const;
/*
* Ensure a binding is valid *before* adding it to the program.
* @pre The binding has not yet been registered.
* @pre The decision variables have been registered.
* @throws std::exception if the binding is invalid.
* @returns true if the binding is non-trivial (>= 1 output); when false,
* this program should avoid adding the binding to its internal state.
*/
template <typename C>
[[nodiscard]] bool CheckBinding(const Binding<C>& binding) const;
/*
* Adds new variables to MathematicalProgram.
*/
template <int Rows, int Cols>
MatrixDecisionVariable<Rows, Cols> NewVariables(
VarType type, const typename NewVariableNames<Rows, Cols>::type& names,
int rows, int cols) {
DRAKE_DEMAND(rows >= 0 && cols >= 0);
MatrixDecisionVariable<Rows, Cols> decision_variable_matrix;
decision_variable_matrix.resize(rows, cols);
NewVariables_impl(type, names, false, decision_variable_matrix);
return decision_variable_matrix;
}
/*
* Adds symmetric matrix variables to optimization program. Only the lower
* triangular part of the matrix is used as decision variables.
* @param names The names of the stacked columns of the lower triangular part
* of the matrix.
*/
template <int Rows>
MatrixDecisionVariable<Rows, Rows> NewSymmetricVariables(
VarType type, const typename NewSymmetricVariableNames<Rows>::type& names,
int rows = Rows) {
MatrixDecisionVariable<Rows, Rows> decision_variable_matrix(rows, rows);
NewVariables_impl(type, names, true, decision_variable_matrix);
return decision_variable_matrix;
}
/*
* Create a new free polynomial, and add its coefficients as decision
* variables.
*/
symbolic::Polynomial NewFreePolynomialImpl(
const symbolic::Variables& indeterminates, int degree,
const std::string& coeff_name,
// TODO(jwnimmer-tri) Fix this to not depend on all of "monomial_util.h"
// for just this tiny enum (e.g., use a bare int == 0,1,2 instead).
symbolic::internal::DegreeType degree_type);
void CheckVariableType(VarType var_type);
// maps the ID of a symbolic variable to the index of the variable stored
// in the optimization program.
std::unordered_map<symbolic::Variable::Id, int> decision_variable_index_{};
// Use std::vector here instead of Eigen::VectorX because std::vector performs
// much better when pushing new variables into the container.
std::vector<symbolic::Variable> decision_variables_;
std::unordered_map<symbolic::Variable::Id, int> indeterminates_index_;
// Use std::vector here instead of Eigen::VectorX because std::vector performs
// much better when pushing new variables into the container.
std::vector<symbolic::Variable> indeterminates_;
std::vector<Binding<VisualizationCallback>> visualization_callbacks_;
std::vector<Binding<Cost>> generic_costs_;
std::vector<Binding<QuadraticCost>> quadratic_costs_;
std::vector<Binding<LinearCost>> linear_costs_;
std::vector<Binding<L2NormCost>> l2norm_costs_;
// note: linear_constraints_ does not include linear_equality_constraints_
std::vector<Binding<Constraint>> generic_constraints_;
std::vector<Binding<LinearConstraint>> linear_constraints_;
std::vector<Binding<LinearEqualityConstraint>> linear_equality_constraints_;
std::vector<Binding<BoundingBoxConstraint>> bbox_constraints_;
std::vector<Binding<QuadraticConstraint>> quadratic_constraints_;
std::vector<Binding<LorentzConeConstraint>> lorentz_cone_constraint_;
std::vector<Binding<RotatedLorentzConeConstraint>>
rotated_lorentz_cone_constraint_;
std::vector<Binding<PositiveSemidefiniteConstraint>>
positive_semidefinite_constraint_;
std::vector<Binding<LinearMatrixInequalityConstraint>>
linear_matrix_inequality_constraint_;
std::vector<Binding<ExponentialConeConstraint>> exponential_cone_constraints_;
// Invariant: The bindings in this list must be non-overlapping, when calling
// Linear Complementarity solver like Moby. If this constraint is solved
// through a nonlinear optimization solver (like SNOPT) instead, then we allow
// the bindings to be overlapping.
// TODO(ggould-tri) can this constraint be relaxed?
std::vector<Binding<LinearComplementarityConstraint>>
linear_complementarity_constraints_;
Eigen::VectorXd x_initial_guess_;
// The actual per-solver customization options.
SolverOptions solver_options_;
ProgramAttributes required_capabilities_;
std::unordered_map<int, double> var_scaling_map_{};
};
std::ostream& operator<<(std::ostream& os, const MathematicalProgram& prog);
} // namespace solvers
} // namespace drake
DRAKE_FORMATTER_AS(, drake::solvers, MathematicalProgram, x, x.to_string())
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/create_cost.h | #pragma once
#include <memory>
#include <optional>
#include <type_traits>
#include <utility>
#include "drake/common/symbolic/expression.h"
#include "drake/solvers/binding.h"
#include "drake/solvers/cost.h"
#include "drake/solvers/function.h"
namespace drake {
namespace solvers {
namespace internal {
/*
* Assist MathematicalProgram::AddLinearCost(...).
*/
Binding<LinearCost> ParseLinearCost(const symbolic::Expression& e);
/*
* Assist MathematicalProgram::AddQuadraticCost(...).
*/
Binding<QuadraticCost> ParseQuadraticCost(
const symbolic::Expression& e,
std::optional<bool> is_convex = std::nullopt);
/*
* Assist MathematicalProgram::AddPolynomialCost(...).
*/
Binding<PolynomialCost> ParsePolynomialCost(const symbolic::Expression& e);
/*
* Assist MathematicalProgram::AddL2NormCost(...)
*/
Binding<L2NormCost> ParseL2NormCost(const symbolic::Expression& e,
double psd_tol, double coefficient_tol);
/*
* Assist MathematicalProgram::AddCost(...).
*/
Binding<Cost> ParseCost(const symbolic::Expression& e);
// TODO(eric.cousineau): Remove this when functor cost is no longer exposed
// externally, and must be explicitly called.
/**
* Enables us to catch and provide a meaningful assertion if a Constraint is
* passed in, when we should have a Cost.
* @tparam F The class to test if it is convertible to variants of C.
* @tparam C Intended to be either Cost or Constraint.
*/
template <typename F, typename C>
struct is_binding_compatible
: std::bool_constant<(std::is_convertible_v<F, C>) ||
(std::is_convertible_v<F, std::shared_ptr<C>>) ||
(std::is_convertible_v<F, std::unique_ptr<C>>) ||
(std::is_convertible_v<F, Binding<C>>)> {};
/**
* Template condition to check if @p F is a candidate to be used to construct a
* FunctionCost object for generic costs.
* @tparam T The type to be tested.
* @note Constraint is used to ensure that we do not preclude cost objects
* that lost their CostShim type somewhere in the process.
*/
template <typename F>
struct is_cost_functor_candidate
: std::bool_constant<(!is_binding_compatible<F, Cost>::value) &&
(!std::is_convertible_v<F, symbolic::Expression>)> {};
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/evaluator_base.cc | #include "drake/solvers/evaluator_base.h"
#include <set>
#include "drake/common/drake_throw.h"
#include "drake/common/nice_type_name.h"
#include "drake/common/symbolic/latex.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::make_shared;
using std::shared_ptr;
namespace drake {
namespace solvers {
std::ostream& EvaluatorBase::Display(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
const int num_vars = this->num_vars();
DRAKE_THROW_UNLESS(vars.rows() == num_vars || num_vars == Eigen::Dynamic);
return this->DoDisplay(os, vars);
}
std::ostream& EvaluatorBase::Display(std::ostream& os) const {
if (this->num_vars() == Eigen::Dynamic) {
symbolic::Variable dynamic_var("dynamic_sized_variable");
return this->DoDisplay(os, Vector1<symbolic::Variable>(dynamic_var));
}
return this->DoDisplay(
os, symbolic::MakeVectorContinuousVariable(this->num_vars(), "$"));
}
std::ostream& EvaluatorBase::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
// Display the evaluator's most derived type name.
os << NiceTypeName::RemoveNamespaces(NiceTypeName::Get(*this));
// Append the description (when provided).
const std::string& description = get_description();
if (!description.empty()) {
os << " described as '" << description << "'";
}
// Append the bound decision variables (when provided).
const int vars_rows = vars.rows();
os << " with " << vars_rows << " decision variables";
for (int i = 0; i < vars_rows; ++i) {
os << " " << vars(i).get_name();
}
os << "\n";
return os;
}
std::string EvaluatorBase::ToLatex(const VectorX<symbolic::Variable>& vars,
int precision) const {
const int num_vars = this->num_vars();
DRAKE_THROW_UNLESS(vars.rows() == num_vars || num_vars == Eigen::Dynamic);
std::string tag = "";
if (!get_description().empty()) {
tag = fmt::format(" \\tag{{{}}}", get_description());
}
return this->DoToLatex(vars, precision) + tag;
}
std::string EvaluatorBase::DoToLatex(const VectorX<symbolic::Variable>& vars,
int) const {
// Fall back to the default display if no latex display is provided.
const int vars_rows = vars.rows();
std::stringstream ss;
ss << "\\text{" << NiceTypeName::RemoveNamespaces(NiceTypeName::Get(*this))
<< "}(";
for (int i = 0; i < vars_rows; ++i) {
if (i > 0) { ss << ", "; }
ss << symbolic::ToLatex(vars(i));
}
ss << ")";
return ss.str();
}
namespace {
// Check if each entry of gradient_sparsity_pattern is within [0, rows) and [0,
// cols), and if there are any repeated entries in gradient_sparsity_pattern.
void CheckGradientSparsityPattern(
const std::vector<std::pair<int, int>>& gradient_sparsity_pattern, int rows,
int cols) {
std::set<std::pair<int, int>> nonzero_entries;
for (const auto& nonzero_entry : gradient_sparsity_pattern) {
if (nonzero_entry.first < 0 || nonzero_entry.first >= rows) {
throw std::invalid_argument(
"Constraint::SetSparsityPattern(): row index out of range.");
}
if (nonzero_entry.second < 0 || nonzero_entry.second >= cols) {
throw std::invalid_argument(
"Constraint::SetSparsityPattern(): column index out of range.");
}
auto it = nonzero_entries.find(nonzero_entry);
if (it != nonzero_entries.end()) {
throw std::invalid_argument(
"Constraint::SetSparsityPatten(): was given entries with repeated "
"values.");
}
nonzero_entries.insert(it, nonzero_entry);
}
}
} // namespace
void EvaluatorBase::SetGradientSparsityPattern(
const std::vector<std::pair<int, int>>& gradient_sparsity_pattern) {
if (kDrakeAssertIsArmed) {
CheckGradientSparsityPattern(gradient_sparsity_pattern, num_outputs(),
num_vars());
}
gradient_sparsity_pattern_.emplace(gradient_sparsity_pattern);
}
std::ostream& operator<<(std::ostream& os, const EvaluatorBase& e) {
return e.Display(os);
}
void PolynomialEvaluator::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
double_evaluation_point_temp_.clear();
for (size_t i = 0; i < poly_vars_.size(); i++) {
double_evaluation_point_temp_[poly_vars_[i]] = x[i];
}
y->resize(num_outputs());
for (int i = 0; i < num_outputs(); i++) {
(*y)[i] =
polynomials_[i].EvaluateMultivariate(double_evaluation_point_temp_);
}
}
void PolynomialEvaluator::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
taylor_evaluation_point_temp_.clear();
for (size_t i = 0; i < poly_vars_.size(); i++) {
taylor_evaluation_point_temp_[poly_vars_[i]] = x[i];
}
y->resize(num_outputs());
for (int i = 0; i < num_outputs(); i++) {
(*y)[i] =
polynomials_[i].EvaluateMultivariate(taylor_evaluation_point_temp_);
}
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/osqp_solver.cc | #include "drake/solvers/osqp_solver.h"
#include <optional>
#include <unordered_map>
#include <vector>
#include <osqp.h>
#include "drake/common/text_logging.h"
#include "drake/math/eigen_sparse_triplet.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
namespace {
void ParseQuadraticCosts(const MathematicalProgram& prog,
Eigen::SparseMatrix<c_float>* P,
std::vector<c_float>* q, double* constant_cost_term) {
DRAKE_ASSERT(static_cast<int>(q->size()) == prog.num_vars());
// Loop through each quadratic costs in prog, and compute the Hessian matrix
// P, the linear cost q, and the constant cost term.
std::vector<Eigen::Triplet<c_float>> P_triplets;
for (const auto& quadratic_cost : prog.quadratic_costs()) {
const VectorXDecisionVariable& x = quadratic_cost.variables();
// x_indices are the indices of the variables x (the variables bound with
// this quadratic cost) in the program decision variables.
const std::vector<int> x_indices = prog.FindDecisionVariableIndices(x);
// Add quadratic_cost.Q to the Hessian P.
// Since OSQP 0.6.0 the P matrix is required to be upper triangular, so
// we only add upper triangular entries to P_triplets.
const Eigen::MatrixXd& Q = quadratic_cost.evaluator()->Q();
for (int col = 0; col < Q.cols(); ++col) {
for (int row = 0; (row <= col) && (row < Q.rows()); ++row) {
const double value = Q(row, col);
if (value == 0.0) {
continue;
}
const int x_row = x_indices[row];
const int x_col = x_indices[col];
P_triplets.emplace_back(x_row, x_col, static_cast<c_float>(value));
}
}
// Add quadratic_cost.b to the linear cost term q.
for (int i = 0; i < x.rows(); ++i) {
q->at(x_indices[i]) += quadratic_cost.evaluator()->b()(i);
}
// Add quadratic_cost.c to constant term
*constant_cost_term += quadratic_cost.evaluator()->c();
}
// Scale the matrix P in the cost.
// Note that the linear term is scaled in ParseLinearCosts().
const auto& scale_map = prog.GetVariableScaling();
if (!scale_map.empty()) {
for (auto& triplet : P_triplets) {
// Column
const auto column = scale_map.find(triplet.col());
if (column != scale_map.end()) {
triplet = Eigen::Triplet<double>(triplet.row(), triplet.col(),
triplet.value() * (column->second));
}
// Row
const auto row = scale_map.find(triplet.row());
if (row != scale_map.end()) {
triplet = Eigen::Triplet<double>(triplet.row(), triplet.col(),
triplet.value() * (row->second));
}
}
}
P->resize(prog.num_vars(), prog.num_vars());
P->setFromTriplets(P_triplets.begin(), P_triplets.end());
}
void ParseLinearCosts(const MathematicalProgram& prog, std::vector<c_float>* q,
double* constant_cost_term) {
// Add the linear costs to the osqp cost.
DRAKE_ASSERT(static_cast<int>(q->size()) == prog.num_vars());
// Loop over the linear costs stored inside prog.
for (const auto& linear_cost : prog.linear_costs()) {
for (int i = 0; i < static_cast<int>(linear_cost.GetNumElements()); ++i) {
// Append the linear cost term to q.
if (linear_cost.evaluator()->a()(i) != 0) {
const int x_index =
prog.FindDecisionVariableIndex(linear_cost.variables()(i));
q->at(x_index) += linear_cost.evaluator()->a()(i);
}
}
// Add the constant cost term to constant_cost_term.
*constant_cost_term += linear_cost.evaluator()->b();
}
// Scale the vector q in the cost.
const auto& scale_map = prog.GetVariableScaling();
if (!scale_map.empty()) {
for (const auto& [index, scale] : scale_map) {
q->at(index) *= scale;
}
}
}
// OSQP defines its own infinity in osqp/include/glob_opts.h.
c_float ConvertInfinity(double val) {
if (std::isinf(val)) {
if (val > 0) {
return OSQP_INFTY;
}
return -OSQP_INFTY;
}
return static_cast<c_float>(val);
}
// Will call this function to parse both LinearConstraint and
// LinearEqualityConstraint.
template <typename C>
void ParseLinearConstraints(
const MathematicalProgram& prog,
const std::vector<Binding<C>>& linear_constraints,
std::vector<Eigen::Triplet<c_float>>* A_triplets, std::vector<c_float>* l,
std::vector<c_float>* u, int* num_A_rows,
std::unordered_map<Binding<Constraint>, int>* constraint_start_row) {
// Loop over the linear constraints, stack them to get l, u and A.
for (const auto& constraint : linear_constraints) {
const std::vector<int> x_indices =
prog.FindDecisionVariableIndices(constraint.variables());
const std::vector<Eigen::Triplet<double>> Ai_triplets =
math::SparseMatrixToTriplets(constraint.evaluator()->get_sparse_A());
const Binding<Constraint> constraint_cast =
internal::BindingDynamicCast<Constraint>(constraint);
constraint_start_row->emplace(constraint_cast, *num_A_rows);
// Append constraint.A to osqp A.
for (const auto& Ai_triplet : Ai_triplets) {
A_triplets->emplace_back(*num_A_rows + Ai_triplet.row(),
x_indices[Ai_triplet.col()],
static_cast<c_float>(Ai_triplet.value()));
}
const int num_Ai_rows = constraint.evaluator()->num_constraints();
l->reserve(l->size() + num_Ai_rows);
u->reserve(u->size() + num_Ai_rows);
for (int i = 0; i < num_Ai_rows; ++i) {
l->push_back(ConvertInfinity(constraint.evaluator()->lower_bound()(i)));
u->push_back(ConvertInfinity(constraint.evaluator()->upper_bound()(i)));
}
*num_A_rows += num_Ai_rows;
}
}
void ParseBoundingBoxConstraints(
const MathematicalProgram& prog,
std::vector<Eigen::Triplet<c_float>>* A_triplets, std::vector<c_float>* l,
std::vector<c_float>* u, int* num_A_rows,
std::unordered_map<Binding<Constraint>, int>* constraint_start_row) {
// Loop over the linear constraints, stack them to get l, u and A.
for (const auto& constraint : prog.bounding_box_constraints()) {
const Binding<Constraint> constraint_cast =
internal::BindingDynamicCast<Constraint>(constraint);
constraint_start_row->emplace(constraint_cast, *num_A_rows);
// Append constraint.A to osqp A.
for (int i = 0; i < static_cast<int>(constraint.GetNumElements()); ++i) {
A_triplets->emplace_back(
*num_A_rows + i,
prog.FindDecisionVariableIndex(constraint.variables()(i)),
static_cast<c_float>(1));
}
const int num_Ai_rows = constraint.evaluator()->num_constraints();
l->reserve(l->size() + num_Ai_rows);
u->reserve(u->size() + num_Ai_rows);
for (int i = 0; i < num_Ai_rows; ++i) {
l->push_back(ConvertInfinity(constraint.evaluator()->lower_bound()(i)));
u->push_back(ConvertInfinity(constraint.evaluator()->upper_bound()(i)));
}
*num_A_rows += num_Ai_rows;
}
}
void ParseAllLinearConstraints(
const MathematicalProgram& prog, Eigen::SparseMatrix<c_float>* A,
std::vector<c_float>* l, std::vector<c_float>* u,
std::unordered_map<Binding<Constraint>, int>* constraint_start_row) {
std::vector<Eigen::Triplet<c_float>> A_triplets;
l->clear();
u->clear();
int num_A_rows = 0;
ParseLinearConstraints(prog, prog.linear_constraints(), &A_triplets, l, u,
&num_A_rows, constraint_start_row);
ParseLinearConstraints(prog, prog.linear_equality_constraints(), &A_triplets,
l, u, &num_A_rows, constraint_start_row);
ParseBoundingBoxConstraints(prog, &A_triplets, l, u, &num_A_rows,
constraint_start_row);
// Scale the matrix A.
// Note that we only scale the columns of A, because the constraint has the
// form l <= Ax <= u where the scaling of x enters the columns of A instead of
// rows of A.
const auto& scale_map = prog.GetVariableScaling();
if (!scale_map.empty()) {
for (auto& triplet : A_triplets) {
auto column = scale_map.find(triplet.col());
if (column != scale_map.end()) {
triplet = Eigen::Triplet<double>(triplet.row(), triplet.col(),
triplet.value() * (column->second));
}
}
}
A->resize(num_A_rows, prog.num_vars());
A->setFromTriplets(A_triplets.begin(), A_triplets.end());
}
// Convert an Eigen::SparseMatrix to csc_matrix, to be used by osqp.
// Make sure the input Eigen sparse matrix is compressed, by calling
// makeCompressed() function.
// The caller of this function is responsible for freeing the memory allocated
// here.
csc* EigenSparseToCSC(const Eigen::SparseMatrix<c_float>& mat) {
// A csc matrix is in the compressed column major.
c_float* values =
static_cast<c_float*>(c_malloc(sizeof(c_float) * mat.nonZeros()));
c_int* inner_indices =
static_cast<c_int*>(c_malloc(sizeof(c_int) * mat.nonZeros()));
c_int* outer_indices =
static_cast<c_int*>(c_malloc(sizeof(c_int) * (mat.cols() + 1)));
for (int i = 0; i < mat.nonZeros(); ++i) {
values[i] = *(mat.valuePtr() + i);
inner_indices[i] = static_cast<c_int>(*(mat.innerIndexPtr() + i));
}
for (int i = 0; i < mat.cols() + 1; ++i) {
outer_indices[i] = static_cast<c_int>(*(mat.outerIndexPtr() + i));
}
return csc_matrix(mat.rows(), mat.cols(), mat.nonZeros(), values,
inner_indices, outer_indices);
}
template <typename T1, typename T2>
void SetOsqpSolverSetting(const std::unordered_map<std::string, T1>& options,
const std::string& option_name,
T2* osqp_setting_field) {
const auto it = options.find(option_name);
if (it != options.end()) {
*osqp_setting_field = it->second;
}
}
template <typename T1, typename T2>
void SetOsqpSolverSettingWithDefaultValue(
const std::unordered_map<std::string, T1>& options,
const std::string& option_name, T2* osqp_setting_field,
const T1& default_field_value) {
const auto it = options.find(option_name);
if (it != options.end()) {
*osqp_setting_field = it->second;
} else {
*osqp_setting_field = default_field_value;
}
}
void SetOsqpSolverSettings(const SolverOptions& solver_options,
OSQPSettings* settings) {
const std::unordered_map<std::string, double>& options_double =
solver_options.GetOptionsDouble(OsqpSolver::id());
const std::unordered_map<std::string, int>& options_int =
solver_options.GetOptionsInt(OsqpSolver::id());
SetOsqpSolverSetting(options_double, "rho", &(settings->rho));
SetOsqpSolverSetting(options_double, "sigma", &(settings->sigma));
SetOsqpSolverSetting(options_int, "max_iter", &(settings->max_iter));
SetOsqpSolverSetting(options_double, "eps_abs", &(settings->eps_abs));
SetOsqpSolverSetting(options_double, "eps_rel", &(settings->eps_rel));
SetOsqpSolverSetting(options_double, "eps_prim_inf",
&(settings->eps_prim_inf));
SetOsqpSolverSetting(options_double, "eps_dual_inf",
&(settings->eps_dual_inf));
SetOsqpSolverSetting(options_double, "alpha", &(settings->alpha));
SetOsqpSolverSetting(options_double, "delta", &(settings->delta));
// Default polish to true, to get an accurate solution.
SetOsqpSolverSettingWithDefaultValue(options_int, "polish",
&(settings->polish), 1);
SetOsqpSolverSetting(options_int, "polish_refine_iter",
&(settings->polish_refine_iter));
// The fallback value for console verbosity is the value set by drake options.
int verbose_console = solver_options.get_print_to_console() != 0;
SetOsqpSolverSettingWithDefaultValue(options_int, "verbose",
&(settings->verbose), verbose_console);
SetOsqpSolverSetting(options_int, "scaled_termination",
&(settings->scaled_termination));
SetOsqpSolverSetting(options_int, "check_termination",
&(settings->check_termination));
SetOsqpSolverSetting(options_int, "warm_start", &(settings->warm_start));
SetOsqpSolverSetting(options_int, "scaling", &(settings->scaling));
SetOsqpSolverSetting(options_int, "adaptive_rho", &(settings->adaptive_rho));
SetOsqpSolverSettingWithDefaultValue(options_int, "adaptive_rho_interval",
&(settings->adaptive_rho_interval),
ADAPTIVE_RHO_FIXED);
SetOsqpSolverSetting(options_double, "adaptive_rho_tolerance",
&(settings->adaptive_rho_tolerance));
SetOsqpSolverSetting(options_double, "adaptive_rho_fraction",
&(settings->adaptive_rho_fraction));
SetOsqpSolverSetting(options_double, "time_limit", &(settings->time_limit));
}
template <typename C>
void SetDualSolution(
const std::vector<Binding<C>>& constraints,
const Eigen::VectorXd& all_dual_solution,
const std::unordered_map<Binding<Constraint>, int>& constraint_start_row,
MathematicalProgramResult* result) {
for (const auto& constraint : constraints) {
// OSQP uses the dual variable `y` as the negation of the shadow price, so
// we need to negate `all_dual_solution` as Drake interprets dual solution
// as the shadow price.
const Binding<Constraint> constraint_cast =
internal::BindingDynamicCast<Constraint>(constraint);
result->set_dual_solution(
constraint,
-all_dual_solution.segment(constraint_start_row.at(constraint_cast),
constraint.evaluator()->num_constraints()));
}
}
} // namespace
bool OsqpSolver::is_available() {
return true;
}
void OsqpSolver::DoSolve(const MathematicalProgram& prog,
const Eigen::VectorXd& initial_guess,
const SolverOptions& merged_options,
MathematicalProgramResult* result) const {
OsqpSolverDetails& solver_details =
result->SetSolverDetailsType<OsqpSolverDetails>();
// OSQP solves a convex quadratic programming problem
// min 0.5 xᵀPx + qᵀx
// s.t l ≤ Ax ≤ u
// OSQP is written in C, so this function will be in C style.
// Get the cost for the QP.
Eigen::SparseMatrix<c_float> P_sparse;
std::vector<c_float> q(prog.num_vars(), 0);
double constant_cost_term{0};
ParseQuadraticCosts(prog, &P_sparse, &q, &constant_cost_term);
ParseLinearCosts(prog, &q, &constant_cost_term);
// linear_constraint_start_row[binding] stores the starting row index in A
// corresponding to the linear constraint `binding`.
std::unordered_map<Binding<Constraint>, int> constraint_start_row;
// Parse the linear constraints.
Eigen::SparseMatrix<c_float> A_sparse;
std::vector<c_float> l, u;
ParseAllLinearConstraints(prog, &A_sparse, &l, &u, &constraint_start_row);
// Now pass the constraint and cost to osqp data.
OSQPData* data = nullptr;
// Populate data.
data = static_cast<OSQPData*>(c_malloc(sizeof(OSQPData)));
data->n = prog.num_vars();
data->m = A_sparse.rows();
data->P = EigenSparseToCSC(P_sparse);
data->q = q.data();
data->A = EigenSparseToCSC(A_sparse);
data->l = l.data();
data->u = u.data();
// Define Solver settings as default.
// Problem settings
OSQPSettings* settings =
static_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings)));
osqp_set_default_settings(settings);
SetOsqpSolverSettings(merged_options, settings);
// If any step fails, it will set the solution_result and skip other steps.
std::optional<SolutionResult> solution_result;
// Setup workspace.
OSQPWorkspace* work = nullptr;
if (!solution_result) {
const c_int osqp_setup_err = osqp_setup(&work, data, settings);
if (osqp_setup_err != 0) {
solution_result = SolutionResult::kInvalidInput;
}
}
if (!solution_result && initial_guess.array().isFinite().all()) {
const c_int osqp_warm_err = osqp_warm_start_x(
work, initial_guess.data());
if (osqp_warm_err != 0) {
solution_result = SolutionResult::kInvalidInput;
}
}
// Solve problem.
if (!solution_result) {
DRAKE_THROW_UNLESS(work != nullptr);
const c_int osqp_solve_err = osqp_solve(work);
if (osqp_solve_err != 0) {
solution_result = SolutionResult::kInvalidInput;
}
}
// Extract results.
if (!solution_result) {
DRAKE_THROW_UNLESS(work->info != nullptr);
solver_details.iter = work->info->iter;
solver_details.status_val = work->info->status_val;
solver_details.primal_res = work->info->pri_res;
solver_details.dual_res = work->info->dua_res;
solver_details.setup_time = work->info->setup_time;
solver_details.solve_time = work->info->solve_time;
solver_details.polish_time = work->info->polish_time;
solver_details.run_time = work->info->run_time;
solver_details.rho_updates = work->info->rho_updates;
switch (work->info->status_val) {
case OSQP_SOLVED:
case OSQP_SOLVED_INACCURATE: {
const Eigen::Map<Eigen::Matrix<c_float, Eigen::Dynamic, 1>> osqp_sol(
work->solution->x, prog.num_vars());
// Scale solution back if `scale_map` is not empty.
const auto& scale_map = prog.GetVariableScaling();
if (!scale_map.empty()) {
drake::VectorX<double> scaled_sol = osqp_sol.cast<double>();
for (const auto& [index, scale] : scale_map) {
scaled_sol(index) *= scale;
}
result->set_x_val(scaled_sol);
} else {
result->set_x_val(osqp_sol.cast<double>());
}
result->set_optimal_cost(work->info->obj_val + constant_cost_term);
solver_details.y =
Eigen::Map<Eigen::VectorXd>(work->solution->y, work->data->m);
solution_result = SolutionResult::kSolutionFound;
SetDualSolution(prog.linear_constraints(), solver_details.y,
constraint_start_row, result);
SetDualSolution(prog.linear_equality_constraints(), solver_details.y,
constraint_start_row, result);
SetDualSolution(prog.bounding_box_constraints(), solver_details.y,
constraint_start_row, result);
break;
}
case OSQP_PRIMAL_INFEASIBLE:
case OSQP_PRIMAL_INFEASIBLE_INACCURATE: {
solution_result = SolutionResult::kInfeasibleConstraints;
result->set_optimal_cost(MathematicalProgram::kGlobalInfeasibleCost);
break;
}
case OSQP_DUAL_INFEASIBLE:
case OSQP_DUAL_INFEASIBLE_INACCURATE: {
solution_result = SolutionResult::kDualInfeasible;
break;
}
case OSQP_MAX_ITER_REACHED: {
solution_result = SolutionResult::kIterationLimit;
break;
}
default: {
solution_result = SolutionResult::kSolverSpecificError;
break;
}
}
}
result->set_solution_result(solution_result.value());
// Clean workspace.
osqp_cleanup(work);
c_free(data->P->x);
c_free(data->P->i);
c_free(data->P->p);
c_free(data->P);
c_free(data->A->x);
c_free(data->A->i);
c_free(data->A->p);
c_free(data->A);
c_free(data);
c_free(settings);
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/clarabel_solver_common.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/clarabel_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 {
ClarabelSolver::ClarabelSolver()
: SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied,
&UnsatisfiedProgramAttributes) {}
ClarabelSolver::~ClarabelSolver() = default;
SolverId ClarabelSolver::id() {
static const never_destroyed<SolverId> singleton{"Clarabel"};
return singleton.access();
}
bool ClarabelSolver::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(), "ClarabelSolver", explanation);
}
} // namespace
bool ClarabelSolver::ProgramAttributesSatisfied(
const MathematicalProgram& prog) {
return CheckAttributes(prog, nullptr);
}
std::string ClarabelSolver::UnsatisfiedProgramAttributes(
const MathematicalProgram& prog) {
std::string explanation;
CheckAttributes(prog, &explanation);
return explanation;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/osqp_solver.h | #pragma once
#include <string>
#include "drake/common/drake_copyable.h"
#include "drake/solvers/solver_base.h"
namespace drake {
namespace solvers {
/** The OSQP solver details after calling Solve() function. The user can call
MathematicalProgramResult::get_solver_details<OsqpSolver>() to obtain the
details. */
struct OsqpSolverDetails {
/// Number of iterations taken.
int iter{};
/// Status of the solver at termination. Please refer to
/// https://github.com/oxfordcontrol/osqp/blob/master/include/constants.h
int status_val{};
/// Norm of primal residue.
double primal_res{};
/// Norm of dual residue.
double dual_res{};
/// Time taken for setup phase (seconds).
double setup_time{};
/// Time taken for solve phase (seconds).
double solve_time{};
/// Time taken for polish phase (seconds).
double polish_time{};
/// Total OSQP time (seconds).
double run_time{};
/// Number of rho updates.
int rho_updates{};
/// y contains the solution for the Lagrangian multiplier associated with
/// l <= Ax <= u. The Lagrangian multiplier is set only when OSQP solves
/// the problem. Notice that the order of the linear constraints are linear
/// inequality first, and then linear equality constraints.
Eigen::VectorXd y{};
};
/** A wrapper to call [OSQP](https://osqp.org/) using Drake's
MathematicalProgram.
For details about OSQP's available options, refer to the
[OSQP manual](https://osqp.org/docs/interfaces/solver_settings.html).
Drake uses OSQP's default values for all options except following:
- Drake defaults to `polish=true` (upstream default is `false`).
- Drake defaults to `adaptive_rho_interval=ADAPTIVE_RHO_FIXED` to make the
output deterministic (upstream default is `0`, which uses non-deterministic
timing measurements to establish the interval). N.B. Generally the interval
should be an integer multiple of `check_termination`, so if you choose to
override either option you should probably override both at once. */
class OsqpSolver final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(OsqpSolver)
/// Type of details stored in MathematicalProgramResult.
using Details = OsqpSolverDetails;
OsqpSolver();
~OsqpSolver() 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&);
static std::string UnsatisfiedProgramAttributes(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/clp_solver_common.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/clp_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 {
ClpSolver::ClpSolver()
: SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied,
&UnsatisfiedProgramAttributes) {}
ClpSolver::~ClpSolver() = default;
SolverId ClpSolver::id() {
static const never_destroyed<SolverId> singleton{"CLP"};
return singleton.access();
}
bool ClpSolver::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::kLinearCost,
ProgramAttribute::kQuadraticCost});
return internal::CheckConvexSolverAttributes(
prog, solver_capabilities.access(), "ClpSolver", explanation);
}
} // namespace
bool ClpSolver::ProgramAttributesSatisfied(const MathematicalProgram& prog) {
return CheckAttributes(prog, nullptr);
}
std::string ClpSolver::UnsatisfiedProgramAttributes(
const MathematicalProgram& prog) {
std::string explanation;
CheckAttributes(prog, &explanation);
return explanation;
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/ipopt_solver_internal.cc | #include "drake/solvers/ipopt_solver_internal.h"
#include <algorithm>
#include <limits>
#include "drake/common/text_logging.h"
using Ipopt::Index;
using Ipopt::IpoptCalculatedQuantities;
using Ipopt::IpoptData;
using Ipopt::Number;
using Ipopt::SolverReturn;
namespace drake {
namespace solvers {
namespace internal {
namespace {
/// @param[out] lb Array of constraint lower bounds, parallel to @p ub
/// @param[out] ub Array of constraint upper bounds, parallel to @p lb
int GetConstraintBounds(const Constraint& c, Number* lb, Number* ub) {
const Eigen::VectorXd& lower_bound = c.lower_bound();
const Eigen::VectorXd& upper_bound = c.upper_bound();
for (int i = 0; i < c.num_constraints(); i++) {
lb[i] = lower_bound(i);
ub[i] = upper_bound(i);
}
return c.num_constraints();
}
/// @param[out] num_grad number of gradients
/// @return number of constraints
int GetNumGradients(const Constraint& c, int var_count, Index* num_grad) {
const int num_constraints = c.num_constraints();
*num_grad = num_constraints * var_count;
return num_constraints;
}
template <typename C>
void SetConstraintDualVariableIndex(
const Binding<C>& binding, int constraint_index,
std::unordered_map<Binding<Constraint>, int>* constraint_dual_start_index) {
const Binding<Constraint> binding_cast =
internal::BindingDynamicCast<Constraint>(binding);
constraint_dual_start_index->emplace(binding_cast, constraint_index);
}
void SetBoundingBoxConstraintDualSolution(
const MathematicalProgram& prog, const Number* const z_L,
const Number* const z_U,
const std::unordered_map<Binding<BoundingBoxConstraint>,
std::pair<std::vector<int>, std::vector<int>>>&
bb_con_dual_variable_indices,
MathematicalProgramResult* result) {
for (const auto& binding : prog.bounding_box_constraints()) {
std::vector<int> lower_dual_indices, upper_dual_indices;
std::tie(lower_dual_indices, upper_dual_indices) =
bb_con_dual_variable_indices.at(binding);
Eigen::VectorXd dual_solution =
Eigen::VectorXd::Zero(binding.GetNumElements());
for (int i = 0; i < static_cast<int>(binding.GetNumElements()); ++i) {
if (lower_dual_indices[i] != -1) {
// Ipopt always returns a non-negative z_L. The definition of shadow
// price means the dual variable for the lower bound is also
// non-negative.
dual_solution(i) = z_L[lower_dual_indices[i]];
}
// Ipopt always returns a non-negative z_U. But the definition of shadow
// price means that the dual variable for the upper bound is negative, so
// we need to negate z_U to get the dual solution.
if (upper_dual_indices[i] != -1 &&
z_U[upper_dual_indices[i]] >= dual_solution(i)) {
// At most one side of the bounds can be active, so theoretically at
// most one of z_U[upper_dual_indices[i]] or z_L[lower_dual_indices[i]]
// can be non-zero. In practice, due to small numerical errors, both
// z_U[upper_dual_indices[i]] and z_L[lower_dual_indices[i]] can be
// non-zero, with one of them being very small number. We choose the
// side with larger dual variable value as the active side (by comparing
// z_U[upper_dual_indices[i] >= dual_solution(i)).
dual_solution(i) = -z_U[upper_dual_indices[i]];
}
}
result->set_dual_solution(binding, dual_solution);
}
}
template <typename C>
void SetConstraintDualSolution(
const Binding<C>& binding, const Eigen::VectorXd& lambda,
const std::unordered_map<Binding<Constraint>, int>&
constraint_dual_start_index,
MathematicalProgramResult* result) {
const Binding<Constraint> binding_cast =
internal::BindingDynamicCast<Constraint>(binding);
// Ipopt defines multiplier as the negative of the shadow price, hence we have
// to negate lambda.
result->set_dual_solution(
binding_cast,
-lambda.segment(constraint_dual_start_index.at(binding_cast),
binding.evaluator()->num_constraints()));
}
void SetAllConstraintDualSolution(
const MathematicalProgram& prog, const Eigen::VectorXd& lambda,
const std::unordered_map<Binding<Constraint>, int>&
constraint_dual_start_index,
MathematicalProgramResult* result) {
for (const auto& binding : prog.generic_constraints()) {
SetConstraintDualSolution(binding, lambda, constraint_dual_start_index,
result);
}
for (const auto& binding : prog.quadratic_constraints()) {
SetConstraintDualSolution(binding, lambda, constraint_dual_start_index,
result);
}
for (const auto& binding : prog.lorentz_cone_constraints()) {
SetConstraintDualSolution(binding, lambda, constraint_dual_start_index,
result);
}
for (const auto& binding : prog.rotated_lorentz_cone_constraints()) {
SetConstraintDualSolution(binding, lambda, constraint_dual_start_index,
result);
}
for (const auto& binding : prog.linear_constraints()) {
SetConstraintDualSolution(binding, lambda, constraint_dual_start_index,
result);
}
for (const auto& binding : prog.linear_equality_constraints()) {
SetConstraintDualSolution(binding, lambda, constraint_dual_start_index,
result);
}
}
/// @param constraint_idx The starting row number for the constraint
/// being described.
///
/// Parameters @p iRow and @p jCol are used in the same manner as
/// described in
/// http://www.coin-or.org/Ipopt/documentation/node23.html for the
/// eval_jac_g() function (in the mode where it's requesting the
/// sparsity structure of the Jacobian). The triplet format is also
/// described in
/// http://www.coin-or.org/Ipopt/documentation/node38.html#app.triplet
///
/// @return the number of row/column pairs filled in.
size_t GetGradientMatrix(
const MathematicalProgram& prog, const Constraint& c,
const Eigen::Ref<const VectorXDecisionVariable>& variables,
Index constraint_idx, Index* iRow, Index* jCol) {
const int m = c.num_constraints();
size_t grad_index = 0;
for (int i = 0; i < static_cast<int>(m); ++i) {
for (int j = 0; j < variables.rows(); ++j) {
iRow[grad_index] = constraint_idx + i;
jCol[grad_index] = prog.FindDecisionVariableIndex(variables(j));
grad_index++;
}
}
return grad_index;
}
Eigen::VectorXd MakeEigenVector(Index n, const Number* x) {
Eigen::VectorXd xvec(n);
for (Index i = 0; i < n; i++) {
xvec[i] = x[i];
}
return xvec;
}
/// Evaluate a constraint, storing the result of the evaluation into
/// @p result and gradients into @p grad. @p grad is the sparse
/// matrix data for which the structure was defined in
/// GetGradientMatrix.
///
/// @return number of gradient entries populated.
template <typename ConstraintType>
size_t EvaluateConstraint(const MathematicalProgram& prog,
const Eigen::VectorXd& xvec,
const Binding<ConstraintType>& binding,
Number* result, Number* grad) {
Constraint* c = binding.evaluator().get();
// For constraints which don't use all of the variables in the X
// input, extract a subset into the AutoDiffVecXd this_x to evaluate
// the constraint (we actually do this for all constraints. One
// potential optimization might be to detect if the initial "tx" has
// the correct geometry (e.g. the constraint uses all decision
// variables in the same order they appear in xvec), but this is not
// currently done).
int num_v_variables = binding.variables().rows();
Eigen::VectorXd this_x(num_v_variables);
for (int i = 0; i < num_v_variables; ++i) {
this_x(i) = xvec(prog.FindDecisionVariableIndex(binding.variables()(i)));
}
if (!grad) {
// We don't want the gradient info, so just call the VectorXd version of
// Eval.
Eigen::VectorXd ty(c->num_constraints());
c->Eval(this_x, &ty);
// Store the results.
for (int i = 0; i < c->num_constraints(); i++) {
result[i] = ty(i);
}
return 0;
}
// Run the version which calculates gradients.
// Leverage the fact that the gradient is equal to the A matrix for linear
// constraints.
if constexpr (std::is_same_v<ConstraintType, LinearEqualityConstraint> ||
std::is_same_v<ConstraintType, LinearConstraint>) {
auto A = static_cast<ConstraintType*>(c)->get_sparse_A();
// Verify that A has the proper size.
DRAKE_ASSERT(A.rows() == c->num_constraints());
DRAKE_ASSERT(A.cols() == binding.variables().rows());
// Evaluate the constraint.
Eigen::VectorXd ty(c->num_constraints());
c->Eval(this_x, &ty);
// Set the result and the gradient.
size_t grad_idx = 0;
for (int i = 0; i < ty.rows(); i++) {
result[i] = ty(i);
for (int j = 0; j < binding.variables().rows(); j++) {
grad[grad_idx++] = A.coeff(i, j);
}
}
return grad_idx;
} else {
// Otherwise, use auto-diff.
AutoDiffVecXd ty(c->num_constraints());
c->Eval(math::InitializeAutoDiff(this_x), &ty);
// Store the results. Since IPOPT directly knows the bounds of the
// constraint, we don't need to apply any bounding information here.
for (int i = 0; i < c->num_constraints(); i++) {
result[i] = ty(i).value();
}
// Extract the appropriate derivatives from our result into the
// gradient array.
size_t grad_idx = 0;
DRAKE_ASSERT(ty.rows() == c->num_constraints());
for (int i = 0; i < ty.rows(); i++) {
if (ty(i).derivatives().size() > 0) {
for (int j = 0; j < binding.variables().rows(); j++) {
grad[grad_idx++] = ty(i).derivatives()(j);
}
} else {
for (int j = 0; j < binding.variables().rows(); j++) {
grad[grad_idx++] = 0;
}
}
}
return grad_idx;
}
}
} // namespace
ResultCache::ResultCache(size_t x_size, size_t result_size, size_t grad_size) {
// The choice of infinity as the default value below is arbitrary.
x.resize(x_size, std::numeric_limits<double>::infinity());
result.resize(result_size, std::numeric_limits<double>::infinity());
grad.resize(grad_size, std::numeric_limits<double>::infinity());
}
/// @param n The size of the array located at @p x_in.
bool ResultCache::is_x_equal(Ipopt::Index n, const Ipopt::Number* x_in) {
DRAKE_ASSERT(n == static_cast<Index>(x.size()));
return !std::memcmp(x.data(), x_in, x.size() * sizeof(Number));
}
// Sugar to copy an IPOPT bare array into `x`.
void ResultCache::SetX(const Ipopt::Index n, const Ipopt::Number* x_arg) {
DRAKE_ASSERT(static_cast<Index>(x.size()) == n);
grad_valid = false;
if (n == 0) {
return;
}
DRAKE_ASSERT(x_arg != nullptr);
std::memcpy(x.data(), x_arg, n * sizeof(Number));
}
// Sugar to copy one of our member fields into an IPOPT bare array.
void ResultCache::Extract(const std::vector<Ipopt::Number>& cache_data,
const Ipopt::Index dest_size, Ipopt::Number* dest) {
DRAKE_ASSERT(static_cast<Index>(cache_data.size()) == dest_size);
if (dest_size == 0) {
return;
}
DRAKE_ASSERT(dest != nullptr);
std::memcpy(dest, cache_data.data(), dest_size * sizeof(Number));
}
IpoptSolver_NLP::IpoptSolver_NLP(const MathematicalProgram& problem,
const Eigen::VectorXd& x_init,
MathematicalProgramResult* result)
: problem_(&problem), x_init_{x_init}, result_(result) {}
bool IpoptSolver_NLP::get_nlp_info(
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
Index& n, Index& m, Index& nnz_jac_g,
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
Index& nnz_h_lag, IndexStyleEnum& index_style) {
n = problem_->num_vars();
// The IPOPT interface defines eval_f() and eval_grad_f() as
// outputting a single number for the result, and the size of the
// output gradient array at the same order as the x variables.
// Initialize the cost cache with those dimensions.
cost_cache_.reset(new ResultCache(n, 1, n));
m = 0;
nnz_jac_g = 0;
Index num_grad = 0;
for (const auto& c : problem_->generic_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->quadratic_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->lorentz_cone_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->rotated_lorentz_cone_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->linear_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->linear_equality_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
constraint_cache_.reset(new ResultCache(n, m, nnz_jac_g));
nnz_h_lag = 0;
index_style = C_STYLE;
return true;
}
bool IpoptSolver_NLP::get_bounds_info(Index n, Number* x_l, Number* x_u,
Index m, Number* g_l, Number* g_u) {
unused(m);
DRAKE_ASSERT(n == static_cast<Index>(problem_->num_vars()));
for (Index i = 0; i < n; i++) {
x_l[i] = -std::numeric_limits<double>::infinity();
x_u[i] = std::numeric_limits<double>::infinity();
}
for (auto const& binding : problem_->bounding_box_constraints()) {
const auto& c = binding.evaluator();
const auto& lower_bound = c->lower_bound();
const auto& upper_bound = c->upper_bound();
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
const int idx =
problem_->FindDecisionVariableIndex(binding.variables()(k));
x_l[idx] = std::max(lower_bound(k), x_l[idx]);
x_u[idx] = std::min(upper_bound(k), x_u[idx]);
}
}
// Set the indices of the dual variables corresponding to each bounding box
// constraint. Ipopt stores the dual variables in z_L and z_U.
for (const auto& binding : problem_->bounding_box_constraints()) {
std::vector<int> lower_dual_indices(binding.evaluator()->num_constraints(),
-1);
std::vector<int> upper_dual_indices(binding.evaluator()->num_constraints(),
-1);
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
const int idx =
problem_->FindDecisionVariableIndex(binding.variables()(k));
if (x_l[idx] == binding.evaluator()->lower_bound()(k)) {
lower_dual_indices[k] = idx;
}
if (x_u[idx] == binding.evaluator()->upper_bound()(k)) {
upper_dual_indices[k] = idx;
}
}
bb_con_dual_variable_indices_.emplace(
binding, std::make_pair(lower_dual_indices, upper_dual_indices));
}
size_t constraint_idx = 0; // offset into g_l and g_u output arrays
for (const auto& c : problem_->generic_constraints()) {
SetConstraintDualVariableIndex(c, constraint_idx,
&constraint_dual_start_index_);
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->quadratic_constraints()) {
SetConstraintDualVariableIndex(c, constraint_idx,
&constraint_dual_start_index_);
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->lorentz_cone_constraints()) {
SetConstraintDualVariableIndex(c, constraint_idx,
&constraint_dual_start_index_);
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->rotated_lorentz_cone_constraints()) {
SetConstraintDualVariableIndex(c, constraint_idx,
&constraint_dual_start_index_);
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->linear_constraints()) {
SetConstraintDualVariableIndex(c, constraint_idx,
&constraint_dual_start_index_);
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->linear_equality_constraints()) {
SetConstraintDualVariableIndex(c, constraint_idx,
&constraint_dual_start_index_);
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
return true;
}
bool IpoptSolver_NLP::get_starting_point(Index n, bool init_x, Number* x,
bool init_z, Number* z_L, Number* z_U,
Index m, bool init_lambda,
Number* lambda) {
unused(z_L, z_U, m, lambda);
if (init_x) {
DRAKE_ASSERT(x_init_.size() == n);
for (Index i = 0; i < n; i++) {
if (!std::isnan(x_init_[i])) {
x[i] = x_init_[i];
} else {
x[i] = 0.0;
}
}
}
// We don't currently use any solver options which require
// populating z_L, z_U or lambda. Assert that IPOPT doesn't
// expect us to in case any such options get turned on.
DRAKE_ASSERT(!init_z);
DRAKE_ASSERT(!init_lambda);
return true;
}
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
bool IpoptSolver_NLP::eval_f(Index n, const Number* x, bool new_x,
Number& obj_value) {
if (new_x || !cost_cache_->is_x_equal(n, x)) {
EvaluateCosts(n, x);
}
DRAKE_ASSERT(cost_cache_->result.size() == 1);
obj_value = cost_cache_->result[0];
return true;
}
bool IpoptSolver_NLP::eval_grad_f(Index n, const Number* x, bool new_x,
Number* grad_f) {
if (new_x || !cost_cache_->is_x_equal(n, x)) {
EvaluateCosts(n, x);
}
ResultCache::Extract(cost_cache_->grad, n, grad_f);
return true;
}
bool IpoptSolver_NLP::eval_g(Index n, const Number* x, bool new_x, Index m,
Number* g) {
if (new_x || !constraint_cache_->is_x_equal(n, x)) {
EvaluateConstraints(n, x, false);
}
ResultCache::Extract(constraint_cache_->result, m, g);
return true;
}
bool IpoptSolver_NLP::eval_jac_g(Index n, const Number* x, bool new_x, Index m,
Index nele_jac, Index* iRow, Index* jCol,
Number* values) {
unused(m);
if (values == nullptr) {
DRAKE_ASSERT(iRow != nullptr);
DRAKE_ASSERT(jCol != nullptr);
int constraint_idx = 0; // Passed into GetGradientMatrix as
// the starting row number for the
// constraint being described.
int grad_idx = 0; // Offset into iRow, jCol output variables.
// Incremented by the number of triplets
// populated by each call to
// GetGradientMatrix.
for (const auto& c : problem_->generic_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->quadratic_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->lorentz_cone_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->rotated_lorentz_cone_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->linear_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->linear_equality_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
DRAKE_ASSERT(static_cast<Index>(grad_idx) == nele_jac);
return true;
}
DRAKE_ASSERT(iRow == nullptr);
DRAKE_ASSERT(jCol == nullptr);
// We're being asked for the actual values.
if (new_x || !constraint_cache_->grad_valid ||
!constraint_cache_->is_x_equal(n, x)) {
EvaluateConstraints(n, x, true);
}
ResultCache::Extract(constraint_cache_->grad, nele_jac, values);
return true;
}
void IpoptSolver_NLP::finalize_solution(SolverReturn status, Index n,
const Number* x, const Number* z_L,
const Number* z_U, Index m,
const Number* g, const Number* lambda,
Number obj_value,
const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq) {
unused(ip_data, ip_cq);
status_ = status;
z_L_ = Eigen::Map<const Eigen::VectorXd>(z_L, n);
z_U_ = Eigen::Map<const Eigen::VectorXd>(z_U, n);
g_ = Eigen::Map<const Eigen::VectorXd>(g, m);
lambda_ = Eigen::Map<const Eigen::VectorXd>(lambda, m);
SetBoundingBoxConstraintDualSolution(*problem_, z_L, z_U,
bb_con_dual_variable_indices_, result_);
SetAllConstraintDualSolution(*problem_, lambda_,
constraint_dual_start_index_, result_);
result_->set_solution_result(SolutionResult::kSolverSpecificError);
switch (status) {
case Ipopt::SUCCESS: {
result_->set_solution_result(SolutionResult::kSolutionFound);
break;
}
case Ipopt::STOP_AT_ACCEPTABLE_POINT: {
// This case happens because the user requested more lenient solution
// acceptability criteria so it is counted as solved.
result_->set_solution_result(SolutionResult::kSolutionFound);
break;
}
case Ipopt::LOCAL_INFEASIBILITY: {
result_->set_solution_result(SolutionResult::kInfeasibleConstraints);
break;
}
case Ipopt::DIVERGING_ITERATES: {
result_->set_solution_result(SolutionResult::kUnbounded);
result_->set_optimal_cost(MathematicalProgram::kUnboundedCost);
break;
}
case Ipopt::MAXITER_EXCEEDED: {
result_->set_solution_result(SolutionResult::kIterationLimit);
drake::log()->warn(
"IPOPT terminated after exceeding the maximum iteration limit. "
"Hint: Remember that IPOPT is an interior-point method "
"and performs badly if any variables are unbounded.");
break;
}
default: {
result_->set_solution_result(SolutionResult::kSolverSpecificError);
break;
}
}
Eigen::VectorXd solution(n);
for (Index i = 0; i < n; i++) {
solution(i) = x[i];
}
result_->set_x_val(solution.cast<double>());
if (result_->get_solution_result() != SolutionResult::kUnbounded) {
result_->set_optimal_cost(obj_value);
}
}
void IpoptSolver_NLP::EvaluateCosts(Index n, const Number* x) {
const Eigen::VectorXd xvec = MakeEigenVector(n, x);
problem_->EvalVisualizationCallbacks(xvec);
AutoDiffVecXd ty(1);
Eigen::VectorXd this_x;
cost_cache_->SetX(n, x);
cost_cache_->result[0] = 0;
cost_cache_->grad.assign(n, 0);
for (auto const& binding : problem_->GetAllCosts()) {
int num_v_variables = binding.GetNumElements();
this_x.resize(num_v_variables);
for (int i = 0; i < num_v_variables; ++i) {
this_x(i) =
xvec(problem_->FindDecisionVariableIndex(binding.variables()(i)));
}
binding.evaluator()->Eval(math::InitializeAutoDiff(this_x), &ty);
cost_cache_->result[0] += ty(0).value();
if (ty(0).derivatives().size() > 0) {
for (int j = 0; j < num_v_variables; ++j) {
const size_t vj_index =
problem_->FindDecisionVariableIndex(binding.variables()(j));
cost_cache_->grad[vj_index] += ty(0).derivatives()(j);
}
}
cost_cache_->grad_valid = true;
// We do not need to add code for ty(0).derivatives().size() == 0, since
// cost_cache_->grad would be unchanged if the derivative has zero size.
}
}
void IpoptSolver_NLP::EvaluateConstraints(Index n, const Number* x,
bool eval_gradient) {
const Eigen::VectorXd xvec = MakeEigenVector(n, x);
constraint_cache_->SetX(n, x);
Number* result = constraint_cache_->result.data();
Number* grad = eval_gradient ? constraint_cache_->grad.data() : nullptr;
for (const auto& c : problem_->generic_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, c, result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->quadratic_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, c, result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->lorentz_cone_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, c, result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->rotated_lorentz_cone_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, c, result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->linear_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, c, result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->linear_equality_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, c, result, grad);
result += c.evaluator()->num_constraints();
}
if (eval_gradient) {
constraint_cache_->grad_valid = true;
}
}
} // namespace internal
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solution_result.h | #pragma once
#include <ostream>
#include <string>
#include "drake/common/fmt.h"
namespace drake {
namespace solvers {
enum SolutionResult {
/** Found the optimal solution. */
kSolutionFound = 0,
/** Invalid input. */
kInvalidInput = -1,
/** The primal is infeasible. */
kInfeasibleConstraints = -2,
/** The primal is unbounded. */
kUnbounded = -3,
/** Solver-specific error. (Try
MathematicalProgramResult::get_solver_details() or enabling verbose solver
output.) */
kSolverSpecificError = -4,
/** The primal is either infeasible or unbounded. */
kInfeasibleOrUnbounded = -5,
/** Reaches the iteration limits. */
kIterationLimit = -6,
/** Dual problem is infeasible. In this case we cannot infer the status of the
primal problem. */
kDualInfeasible = -7,
/** The initial (invalid) solution result. This value should be overwritten by
the solver during Solve(). */
kSolutionResultNotSet = -8
};
std::string to_string(SolutionResult solution_result);
std::ostream& operator<<(std::ostream& os, SolutionResult solution_result);
} // namespace solvers
} // namespace drake
DRAKE_FORMATTER_AS(, drake::solvers, SolutionResult, x,
drake::solvers::to_string(x))
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/no_scs.cc | /* clang-format off to disable clang-format-includes */
#include "drake/solvers/scs_solver.h"
/* clang-format on */
#include <stdexcept>
namespace drake {
namespace solvers {
bool ScsSolver::is_available() {
return false;
}
void ScsSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&,
const SolverOptions&,
MathematicalProgramResult*) const {
throw std::runtime_error(
"The SCS bindings were not compiled. You'll need to use a different "
"solver.");
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/branch_and_bound.h | #pragma once
#include <list>
#include <map>
#include <memory>
#include <unordered_map>
#include <utility>
#include "drake/common/name_value.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mathematical_program_result.h"
namespace drake {
namespace solvers {
/**
* A node in the branch-and-bound (bnb) tree.
* The whole branch-and-bound tree solves the mixed-integer problem
* min f(x) (1)
* s.t g(x) ≤ 0
* z ∈ {0, 1}
* where the binary variables z are a subset of the decision variables x.
* In this node, we will fix some binary variables to either 0 and 1, and relax
* the rest of the binary variables to continuous variables between 0 and 1.
* Namely we will solve the following problem with all variables being
* continuous
* min f(x) (2)
* s.t g(x) ≤ 0
* z_fixed = b_fixed
* 0 ≤ z_relaxed ≤ 1
* where z_fixed, z_relaxed is a partition of the original binary variables z.
* z_fixed is the fixed binary variables, z_relaxed is the relaxed binary
* variables. b_fixed is a vector containing the assigned values of the fixed
* binary variables z_fixed, b_fixed only contains value either 0 or 1.
*
* Each node is created from its parent node, by fixing one binary variable to
* either 0 or 1.
*/
class MixedIntegerBranchAndBoundNode {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MixedIntegerBranchAndBoundNode)
/** Construct the root node from an optimization program.
* For the mixed-integer optimization program
* min f(x) (1)
* s.t g(x) ≤ 0
* z ∈ {0, 1}
* we will construct a root node for this mixed-integer program. In the root
* node, it enforces all the costs and constraints in the original program,
* except the binary constraint z ∈ {0, 1}. Instead, it enforces the relaxed
* constraint to 0 ≤ z ≤ 1. So the root node contains the program
* min f(x) (2)
* s.t g(x) ≤ 0
* 0 ≤ z ≤ 1
* This optimization program is solved during the node construction.
* @param prog The mixed-integer optimization program (1) in the
* documentation above.
* @param solver_id The ID of the solver for the optimization program.
* @retval (node, map_old_vars_to_new_vars) node is the root node of the tree,
* that contains the optimization program (2) in the documentation above. This
* root node has no parent. We also need to recreate new decision variables in
* the root node, from the original optimization program (1), since the binary
* variables will be converted to continuous variables in (2). We thus return
* the map from the old variables to the new variables.
* @pre prog should contain binary variables.
* @pre solver_id can be either Gurobi or Scs.
* @throws std::exception if the preconditions are not met.
*/
static std::pair<
std::unique_ptr<MixedIntegerBranchAndBoundNode>,
std::unordered_map<symbolic::Variable::Id, symbolic::Variable>>
ConstructRootNode(const MathematicalProgram& prog, const SolverId& solver_id);
/**
* Branches on @p binary_variable, and creates two child nodes. In the left
* child node, the binary variable is fixed to 0. In the right node, the
* binary variable is fixed to 1. Solves the optimization program in each
* child node.
* @param binary_variable This binary variable is fixed to either 0 or 1 in
* the child node.
* @pre binary_variable is in remaining_binary_variables_;
* @throws std::exception if the preconditions are not met.
*/
void Branch(const symbolic::Variable& binary_variable);
/** Returns true if a node is the root.
* A root node has no parent.
*/
[[nodiscard]] bool IsRoot() const;
/** Determine if a node is a leaf or not.
* A leaf node has no child nodes.
*/
bool IsLeaf() const { return !left_child_ && !right_child_; }
/**
* Getter for the mathematical program.
*/
const MathematicalProgram* prog() const { return prog_.get(); }
/**
* Getter for the mathematical program result.
*/
const MathematicalProgramResult* prog_result() const {
return prog_result_.get();
}
/** Getter for the left child. */
const MixedIntegerBranchAndBoundNode* left_child() const {
return left_child_.get();
}
/** Getter for the mutable left child. */
MixedIntegerBranchAndBoundNode* mutable_left_child() {
return left_child_.get();
}
/** Getter for the right child. */
const MixedIntegerBranchAndBoundNode* right_child() const {
return right_child_.get();
}
/** Getter for the mutable right child. */
MixedIntegerBranchAndBoundNode* mutable_right_child() {
return right_child_.get();
}
/** Getter for the parent node. */
const MixedIntegerBranchAndBoundNode* parent() const { return parent_; }
/** Getter for the mutable parent node. */
MixedIntegerBranchAndBoundNode* mutable_parent() { return parent_; }
/**
* Getter for the binary variable, whose value was not fixed in
* the parent node, but is fixed to either 0 or 1 in this node.
*/
const symbolic::Variable& fixed_binary_variable() const {
return fixed_binary_variable_;
}
/**
* Getter for the value of the binary variable, which was not fixed in the
* parent node, but is fixed to either 0 or 1 in this node.
*/
int fixed_binary_value() const { return fixed_binary_value_; }
/**
* Getter for the remaining binary variables in this node.
*/
const std::list<symbolic::Variable>& remaining_binary_variables() const {
return remaining_binary_variables_;
}
/** Getter for the solution result when solving the optimization program. */
SolutionResult solution_result() const { return solution_result_; }
/**
* Getter for optimal_solution_is_integral.
* @pre The optimization problem is solved successfully.
* @throws std::exception if the precondition is not satisfied.
*/
[[nodiscard]] bool optimal_solution_is_integral() const;
/** Getter for solver id. */
const SolverId& solver_id() const { return solver_id_; }
/** If the mathematical program in this node has been solved and the result is
* stored inside this node, then we say this node has been explored. */
[[nodiscard]] bool is_explored() const;
/** Returns the total number of explored nodes in the subtree
* (including this node if it has been explored).
*/
[[nodiscard]] int NumExploredNodesInSubtree() const;
private:
// If the solution to a binary variable is either less than integral_tol or
// larger than 1 - integral_tol, then we regard the solution to be binary.
// This method set this tolerance.
void set_integral_tolerance(double integral_tol) {
integral_tol_ = integral_tol;
}
// Constructs an empty node. Clone the input mathematical program to this
// node. The child and the parent nodes are all nullptr.
// @param prog The optimization program whose binary variable constraints are
// all relaxed to 0 ≤ z ≤ 1.
// @param binary_variables The list of binary variables in the mixed-integer
// problem.
MixedIntegerBranchAndBoundNode(
const MathematicalProgram& prog,
const std::list<symbolic::Variable>& binary_variables,
const SolverId& solver_id);
// Fix a binary variable to a binary value. Add a constraint z = 0 or z = 1 to
// the optimization program. Remove this binary variable from the
// remaining_binary_variables_ list; set the binary_var_ and
// binary_var_value_.
void FixBinaryVariable(const symbolic::Variable& binary_variable,
bool binary_value);
// Check if the optimal solution to the program in this node satisfies all
// integral constraints.
// Only call this function AFTER the program is solved.
void CheckOptimalSolutionIsIntegral();
enum class OptimalSolutionIsIntegral {
kTrue, ///< The program in this node has been solved, and the solution to
/// all binary variables satisfies the integral constraints.
kFalse, ///< The program in this node has been solved, and the solution to
/// some binary variables does not satisfy the integral constraints.
kUnknown, ///< Either the program in this node has not been solved, or we
/// have not checked if the solution satisfy the integral
/// constraints yet.
};
// Stores the optimization program in this node.
std::unique_ptr<MathematicalProgram> prog_;
std::unique_ptr<MathematicalProgramResult> prog_result_;
std::unique_ptr<MixedIntegerBranchAndBoundNode> left_child_;
std::unique_ptr<MixedIntegerBranchAndBoundNode> right_child_;
MixedIntegerBranchAndBoundNode* parent_;
// The newly fixed binary variable z, in the decision variables x.
// The value of z was not fixed in the parent node, but is fixed in this
// node.
symbolic::Variable fixed_binary_variable_;
// The value of the newly fixed binary variable z, in the decision variables
// x. The value of z was not fixed in the parent node, but is fixed in this
// node.
int fixed_binary_value_;
// The variables that were binary in the original mixed-integer optimization
// problem, but whose value has not been fixed to either 0 or 1 yet.
std::list<symbolic::Variable> remaining_binary_variables_;
// The solution result of the optimization program.
SolutionResult solution_result_;
// Whether the optimal solution in this node satisfies all integral
// constraints.
OptimalSolutionIsIntegral optimal_solution_is_integral_;
SolverId solver_id_;
// If the solution to a binary variable is either less than integral_tol or
// larger than 1 - integral_tol, then we regard the solution to be binary.
double integral_tol_{1E-5};
};
/**
* Given a mixed-integer optimization problem (MIP) (or more accurately, mixed
* binary problem), solve this problem through branch-and-bound process. We will
* first replace all the binary variables with continuous variables, and relax
* the integral constraint on the binary variables z ∈ {0, 1} with continuous
* constraints 0 ≤ z ≤ 1. In the subsequent steps, at each node of the tree,
* we will fix some binary variables to either 0 or 1, and solve the rest of
* the variables.
* Notice that we will create a new set of variables in the branch-and-bound
* process, since we need to replace the binary variables with continuous
* variables.
*/
class MixedIntegerBranchAndBound {
public:
/**
* Different methods to pick a branching variable.
*/
enum class VariableSelectionMethod {
kUserDefined, ///< User defined.
kLeastAmbivalent, ///< Pick the variable whose value is closest to 0 or 1.
kMostAmbivalent, ///< Pick the variable whose value is closest to 0.5
};
/**
* Different methods to pick a branching node.
*/
enum class NodeSelectionMethod {
kUserDefined, ///< User defined.
kDepthFirst, ///< Pick the node with the most binary variables fixed.
kMinLowerBound, ///< Pick the node with the smallest optimal cost.
};
/** Configuration settings for the MixedIntegerBranchAndBound constructor. */
struct Options {
Options() {}
/** Passes this object to an Archive.
Refer to @ref yaml_serialization "YAML Serialization" for background. */
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(max_explored_nodes));
}
/** The maximal number of explored nodes in the tree. The branch and bound
* process will terminate if the tree has explored this number of nodes.
* max_explored_nodes <= 0 means that we don't put an upper bound on the
* number of explored nodes. */
int max_explored_nodes{-1};
};
/**
* The function signature for the user defined method to pick a branching node
* or a branching variable.
*/
using NodeSelectFun = std::function<MixedIntegerBranchAndBoundNode*(
const MixedIntegerBranchAndBound&)>;
using VariableSelectFun = std::function<const symbolic::Variable*(
const MixedIntegerBranchAndBoundNode&)>;
/** The function signature for user defined node callback function. */
using NodeCallbackFun = std::function<void(
const MixedIntegerBranchAndBoundNode&, MixedIntegerBranchAndBound* bnb)>;
/**
* Construct a branch-and-bound tree from a mixed-integer optimization
* program.
* @param prog A mixed-integer optimization program.
* @param solver_id The ID of the solver for the optimization.
*/
explicit MixedIntegerBranchAndBound(const MathematicalProgram& prog,
const SolverId& solver_id,
Options options = Options{});
/**
* Solve the mixed-integer problem (MIP) through a branch and bound process.
* @retval solution_result If solution_result=SolutionResult::kSolutionFound,
* then the best solutions are stored inside solutions(). The user
* can access the value of each variable(s) through GetSolution(...).
* If solution_result=SolutionResult::kInfeasibleConstraints, then the
* mixed-integer problem is primal infeasible.
* If solution_result=SolutionResult::kUnbounded, then the mixed-integer
* problem is primal unbounded.
*/
SolutionResult Solve();
/** Get the optimal cost. */
[[nodiscard]] double GetOptimalCost() const;
/**
* Get the n'th sub-optimal cost.
* The costs are sorted in the ascending order. The sub-optimal costs do not
* include the optimal cost.
* @param nth_suboptimal_cost The n'th sub-optimal cost.
* @pre `nth_suboptimal_cost` is between 0 and solutions().size() - 1.
* @throws std::exception if the precondition is not satisfied.
*/
[[nodiscard]] double GetSubOptimalCost(int nth_suboptimal_cost) const;
/**
* Get the n'th best integral solution for a variable.
* The best solutions are sorted in the ascending order based on their costs.
* Each solution is found in a separate node in the branch-and-bound tree, so
* the values of the binary variables are different in each solution.
* @param mip_var A variable in the original MIP.
* @param nth_best_solution. The index of the best integral solution.
* @pre `mip_var` is a variable in the original MIP.
* @pre `nth_best_solution` is between 0 and solutions().size().
* @throws std::exception if the preconditions are not satisfied.
*/
[[nodiscard]] double GetSolution(const symbolic::Variable& mip_var,
int nth_best_solution = 0) const;
/**
* Get the n'th best integral solution for some variables.
* The best solutions are sorted in the ascending order based on their costs.
* Each solution is found in a separate node in the branch-and-bound tree, so
* @param mip_vars Variables in the original MIP.
* @param nth_best_solution. The index of the best integral solution.
* @pre `mip_vars` are variables in the original MIP.
* @pre `nth_best_solution` is between 0 and solutions().size().
* @throws std::exception if the preconditions are not satisfied.
*/
template <typename Derived>
[[nodiscard]] typename std::enable_if_t<
std::is_same_v<typename Derived::Scalar, symbolic::Variable>,
MatrixLikewise<double, Derived>>
GetSolution(const Eigen::MatrixBase<Derived>& mip_vars,
int nth_best_solution = 0) const {
MatrixLikewise<double, Derived> value(mip_vars.rows(), mip_vars.cols());
for (int i = 0; i < mip_vars.rows(); ++i) {
for (int j = 0; j < mip_vars.cols(); ++j) {
value(i, j) = GetSolution(mip_vars(i, j), nth_best_solution);
}
}
return value;
}
/**
* Given an old variable in the original mixed-integer program, return the
* corresponding new variable in the branch-and-bound process.
* @param old_variable A variable in the original mixed-integer program.
* @retval new_variable The corresponding variable in the branch-and-bound
* procedure.
* @pre old_variable is a variable in the mixed-integer program, passed in the
* constructor of this MixedIntegerBranchAndBound.
* @throws std::exception if the pre-condition fails.
*/
[[nodiscard]] const symbolic::Variable& GetNewVariable(
const symbolic::Variable& old_variable) const;
/**
* Given a matrix of old variables in the original mixed-integer program,
* return a matrix of corresponding new variables in the branch-and-bound
* process.
* @param old_variables Variables in the original mixed-integer program.
* @retval new_variables The corresponding variables in the branch-and-bound
* procedure.
*/
template <typename Derived>
typename std::enable_if_t<
is_eigen_scalar_same<Derived, symbolic::Variable>::value,
MatrixLikewise<symbolic::Variable, Derived>>
GetNewVariables(const Eigen::MatrixBase<Derived>& old_variables) const {
MatrixLikewise<symbolic::Variable, Derived> new_variables;
new_variables.resize(old_variables.rows(), old_variables.cols());
for (int i = 0; i < old_variables.rows(); ++i) {
for (int j = 0; j < old_variables.cols(); ++j) {
new_variables(i, j) = GetNewVariable(old_variables(i, j));
}
}
return new_variables;
}
/**
* The user can choose the method to pick a node for branching. We provide
* options such as "depth first" or "min lower bound".
* @param node_selection_method The option to pick a node. If the option is
* NodeSelectionMethod::kUserDefined, then the user should also provide the
* method to pick a node through SetUserDefinedNodeSelectionFunction.
*/
void SetNodeSelectionMethod(NodeSelectionMethod node_selection_method) {
node_selection_method_ = node_selection_method;
}
/**
* Set the user-defined method to pick the branching node. This method is
* used if the user calls
* SetNodeSelectionMethod(NodeSelectionMethod::kUserDefined).
*
* For example, if the user has defined a function LeftMostNode that would
* return the left-most unfathomed node in the tree, then the user could do
* \code{.cc}
* MixedIntegerBranchAndBoundNode* LeftMostNodeInSubTree(
* const MixedIntegerBranchAndBound& branch_and_bound,
* const MixedIntegerBranchAndBoundNode& subtree_root) {
* // Starting from the subtree root, find the left most leaf node that is
* not fathomed.
* blah
* }
*
* MixedIntegerBranchAndBound bnb(...);
* bnb.SetNodeSelectionMethod(
* MixedIntegerBranchAndBound::NodeSelectionMethod::kUserDefined);
* // Use a lambda function as the NodeSelectionFun
* bnb->SetUserDefinedNodeSelectionFunction([](
* const MixedIntegerBranchAndBound& branch_and_bound) {
* return LeftMostNodeInSubTree(branch_and_bound,
* *(branch_and_bound.root()));
* \endcode
* A more detailed example can be found in
* solvers/test/branch_and_bound_test.cc
* in TestSetUserDefinedNodeSelectionFunction.
* @note The user defined function should pick an un-fathomed leaf node for
* branching.
* @throws std::exception if the node is not a leaf node, or it is
* fathomed.
*/
void SetUserDefinedNodeSelectionFunction(NodeSelectFun fun) {
node_selection_userfun_ = fun;
}
/**
* The user can choose the method to pick a variable for branching in each
* node. We provide options such as "most ambivalent" or "least ambivalent".
* @param variable_selection_method The option to pick a variable. If the
* option is VariableSelectionMethod::kUserDefined, then the user should also
* provide the method to pick a variable through
* SetUserDefinedVariableSelectionFunction(...).
*/
void SetVariableSelectionMethod(
VariableSelectionMethod variable_selection_method) {
variable_selection_method_ = variable_selection_method;
}
/**
* Set the user-defined method to pick the branching variable. This method is
* used if the user calls
* SetVariableSelectionMethod(VariableSelectionMethod::kUserDefined).
*
* For example, if the user has defined a function FirstVariable, that would
* return the first un-fixed binary variable in this branch as
* \code{.cc}
* SymbolicVariable* FirstVariable(const MixedIntegerBranchAndBoundNode& node)
* {
* return node.remaining_binary_variables().begin();
* }
* \endcode
* The user can then set the branch-and-bound to use this function to select
* the branching variable as
* \code{.cc}
* MixedIntegerBranchAndBound bnb(...);
* bnb.SetVariableSelectionMethod(
* MixedIntegerBranchAndBound:VariableSelectionMethod::kUserDefined);
* // Set VariableSelectFun by using a function pointer.
* bnb.SetUserDefinedVariableSelectionFunction(FirstVariable);
* \endcode
*/
void SetUserDefinedVariableSelectionFunction(VariableSelectFun fun) {
variable_selection_userfun_ = fun;
}
/** Set the flag to true if the user wants to search an integral solution
* in each node, after the optimization problem in that node is solved.
* The program can search for an integral solution based on the solution to
* the optimization program in the node, by rounding the binary variables
* to the nearest integer value, and solve for the continuous variables.
* If a solution is obtained in this new program, then this solution is
* an integral solution to the mixed-integer program.
*/
void SetSearchIntegralSolutionByRounding(bool flag) {
search_integral_solution_by_rounding_ = flag;
}
/**
* The user can set a defined callback function in each node. This function is
* called after the optimization is solved in each node.
*/
void SetUserDefinedNodeCallbackFunction(NodeCallbackFun fun) {
node_callback_userfun_ = fun;
}
/**
* If a leaf node is fathomed, then there is no need to branch on this node
* any more. A leaf node is fathomed is any of the following conditions are
* satisfied:
*
* 1. The optimization problem in the node is infeasible.
* 2. The optimal cost of the node is larger than the best upper bound.
* 3. The optimal solution to the node satisfies all the integral constraints.
* 4. All binary variables are fixed to either 0 or 1 in this node.
*
* @param leaf_node A leaf node to check if it is fathomed.
* @pre The node should be a leaf node.
* @throws std::exception if the precondition is not satisfied.
*/
[[nodiscard]] bool IsLeafNodeFathomed(
const MixedIntegerBranchAndBoundNode& leaf_node) const;
/**
* Getter for the root node. Note that this is aliased for the lifetime of
* this object.
*/
[[nodiscard]] const MixedIntegerBranchAndBoundNode* root() const {
return root_.get();
}
/** Getter for the best upper bound. */
[[nodiscard]] double best_upper_bound() const { return best_upper_bound_; }
/** Getter for the best lower bound. */
[[nodiscard]] double best_lower_bound() const { return best_lower_bound_; }
/**
* Getter for the solutions.
* Returns a list of solutions, together with the costs evaluated at the
* solutions. The solutions are sorted in the ascending order based on the
* cost.
*/
[[nodiscard]] const std::multimap<double, Eigen::VectorXd>& solutions()
const {
return solutions_;
}
/** Setter for the absolute gap tolerance.
* The branch-and-bound will terminate if its difference between its best
* upper bound and best lower bound is below this gap tolerance.
*/
void set_absolute_gap_tol(double tol) { absolute_gap_tol_ = tol; }
/** Getter for the absolute gap tolerance. */
[[nodiscard]] double absolute_gap_tol() const { return absolute_gap_tol_; }
/** Setter for the relative gap tolerance.
* The branch-and-bound will terminate if
* (best_upper_bound() - best_lower_bound()) / abs(best_lower_bound())
* is smaller than this tolerance.
*/
void set_relative_gap_tol(double tol) { relative_gap_tol_ = tol; }
/** Geeter for the relative gap tolerance. */
[[nodiscard]] double relative_gap_tol() const { return relative_gap_tol_; }
private:
// Forward declaration the tester class.
friend class MixedIntegerBranchAndBoundTester;
/**
* Pick one node to branch.
*/
[[nodiscard]] MixedIntegerBranchAndBoundNode* PickBranchingNode() const;
/**
* Pick the node with the minimal lower bound.
*/
[[nodiscard]] MixedIntegerBranchAndBoundNode* PickMinLowerBoundNode() const;
/**
* Pick the node with the most binary variables fixed.
*/
[[nodiscard]] MixedIntegerBranchAndBoundNode* PickDepthFirstNode() const;
/**
* Pick the branching variable in a node.
*/
[[nodiscard]] const symbolic::Variable* PickBranchingVariable(
const MixedIntegerBranchAndBoundNode& node) const;
/**
* Branch on a node, solves the optimization, and update the best lower and
* upper bounds.
* @param node. The node to be branched.
* @param branching_variable. Branch on this variable in the node.
*/
void BranchAndUpdate(MixedIntegerBranchAndBoundNode* node,
const symbolic::Variable& branching_variable);
/**
* Update the solutions (solutions_) and the best upper bound, with an
* integral solution and its cost.
* @param solution. The integral solution.
* @param cost. The cost evaluated at this integral solution.
*/
void UpdateIntegralSolution(const Eigen::Ref<const Eigen::VectorXd>& solution,
double cost);
/**
* The branch-and-bound has converged if the gap between the best upper bound
* and the best lower bound is less than the tolerance.
*/
[[nodiscard]] bool HasConverged() const;
/** Call the callback function in each node. */
void NodeCallback(const MixedIntegerBranchAndBoundNode& node);
/**
* Search for an integral solution satisfying all the constraints in this
* node, together with the integral constraints in the original mixed-integer
* program. It will construct a new optimization program, same as the one
* in this node, but the remaining binary variables are all rounded to
* the binary value that is closest to the solution of the optimization
* program in this node.
* @note this function is only called if the following conditions are
* satisfied:
* 1. The optimization problem in this node is feasible.
* 2. The optimal solution to the problem in this node is not integral.
* 3. The user called SetSearchIntegralSolutionByRounding(true);
*
* @note This method will change the data field such as solutions_ and/or
* best_upper_bound_, if an integral solution is found.
*/
void SearchIntegralSolutionByRounding(
const MixedIntegerBranchAndBoundNode& node);
// The root node of the tree.
std::unique_ptr<MixedIntegerBranchAndBoundNode> root_;
Options options_;
// We re-created the decision variables in the optimization program in the
// branch-and-bound. All nodes uses the same new set of decision variables,
// which is different from the variables in the original mixed-integer program
// (the one passed in the constructor of MixedIntegerBranchAndBound). This map
// is used to find the corresponding new variable from the old variable in the
// mixed-integer program.
std::unordered_map<symbolic::Variable::Id, symbolic::Variable>
map_old_vars_to_new_vars_;
// The best upper bound of the mixed-integer optimization optimal cost. An
// upper bound is obtained by evaluating the cost at a solution satisfying all
// the constraints (including the integral constraints) in the mixed-integer
// problem.
double best_upper_bound_;
// The best lower bound of the mixed-integer optimization optimal cost. This
// best lower bound is obtained by taking the minimal of the optimal cost in
// each leaf node.
double best_lower_bound_;
// Solutions found so far. Each entry in this list contains both the
// cost and the decision variable values. This list is sorted in the
// ascending order based on the cost, and it contains at most
// max_num_solutions_ elements.
std::multimap<double, Eigen::VectorXd> solutions_;
int max_num_solutions_{10};
// The branch and bound process will terminate when the best upper bound is
// sufficiently close to the best lower bound, that is, when either of the
// following conditions is satisfied:
// 1. (best_upper_bound_ - best_lower_bound_) / abs(best_lower_bound_) <
// relative_gap_tol
// 2. best_upper_bound_ - best_lower_bound_ < absolute_gap_tol_;
double absolute_gap_tol_ = 1E-2;
double relative_gap_tol_ = 1E-2;
VariableSelectionMethod variable_selection_method_ =
VariableSelectionMethod::kMostAmbivalent;
NodeSelectionMethod node_selection_method_ =
NodeSelectionMethod::kMinLowerBound;
bool search_integral_solution_by_rounding_ = false;
// The user defined function to pick a branching variable. Default is null.
VariableSelectFun variable_selection_userfun_ = nullptr;
// The user defined function to pick a branching node. Default is null.
NodeSelectFun node_selection_userfun_ = nullptr;
// The user defined callback function in each node. Default is null.
NodeCallbackFun node_callback_userfun_ = nullptr;
};
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/solvers/solver_id.cc | #include "drake/solvers/solver_id.h"
#include <atomic>
#include <utility>
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
namespace drake {
namespace solvers {
namespace {
int get_next_id() {
// Note that id 0 is reserved for the moved-from SolverId. As a result, we
// have an invariant "get_next_id() > 0".
static never_destroyed<std::atomic<int>> next_id{1};
return next_id.access()++;
}
} // namespace
SolverId::SolverId(std::string name)
: id_{get_next_id()}, name_{std::move(name)} {
if (name_.length() > 15) {
static const logging::Warn log_once(
"The SolverId(name='{}') exceeds the recommended name length of 15.",
name_);
}
}
bool operator==(const SolverId& a, const SolverId& b) {
return a.id_ == b.id_;
}
bool operator!=(const SolverId& a, const SolverId& b) {
return a.id_ != b.id_;
}
std::ostream& operator<<(std::ostream& os, const SolverId& self) {
// N.B. The ID is _not_ exposed to callers.
os << self.name();
return os;
}
} // namespace solvers
} // namespace drake
| 0 |
Subsets and Splits