repo_id
stringclasses 205
values | file_path
stringlengths 33
141
| content
stringlengths 1
307k
| __index_level_0__
int64 0
0
|
---|---|---|---|
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/create_constraint_test.cc | #include "drake/solvers/create_constraint.h"
#include <limits>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
#include "drake/solvers/constraint.h"
using drake::symbolic::Expression;
namespace drake {
namespace solvers {
namespace {
using Eigen::Vector2d;
using symbolic::Variable;
const double kInf = std::numeric_limits<double>::infinity();
void CheckParseQuadraticConstraint(
const Expression& e, double lb, double ub,
std::optional<QuadraticConstraint::HessianType> hessian_type,
QuadraticConstraint::HessianType hessian_type_expected) {
Binding<QuadraticConstraint> binding =
internal::ParseQuadraticConstraint(e, lb, ub, hessian_type);
const Expression binding_expression{
0.5 * binding.variables().dot(binding.evaluator()->Q() *
binding.variables()) +
binding.evaluator()->b().dot(binding.variables())};
if (!std::isinf(lb)) {
EXPECT_TRUE(symbolic::test::PolynomialEqual(
symbolic::Polynomial(e - lb),
symbolic::Polynomial(binding_expression -
binding.evaluator()->lower_bound()(0)),
1E-10));
} else {
EXPECT_TRUE(std::isinf(binding.evaluator()->lower_bound()(0)));
}
if (!std::isinf(ub)) {
EXPECT_TRUE(symbolic::test::PolynomialEqual(
symbolic::Polynomial(e - ub),
symbolic::Polynomial(binding_expression -
binding.evaluator()->upper_bound()(0)),
1E-10));
} else {
EXPECT_TRUE(std::isinf(binding.evaluator()->upper_bound()(0)));
}
EXPECT_EQ(binding.evaluator()->hessian_type(), hessian_type_expected);
}
class ParseQuadraticConstraintTest : public ::testing::Test {
public:
ParseQuadraticConstraintTest() { x_ << x0_, x1_; }
protected:
symbolic::Variable x0_{"x0"};
symbolic::Variable x1_{"x1"};
Vector2<symbolic::Variable> x_;
};
TEST_F(ParseQuadraticConstraintTest, Test0) {
CheckParseQuadraticConstraint(
x0_ * x0_, 1, 1, QuadraticConstraint::HessianType::kPositiveSemidefinite,
QuadraticConstraint::HessianType::kPositiveSemidefinite);
CheckParseQuadraticConstraint(x0_ * x1_, 1, 1,
QuadraticConstraint::HessianType::kIndefinite,
QuadraticConstraint::HessianType::kIndefinite);
CheckParseQuadraticConstraint(
x0_ * x0_ + 2 * x0_, 0, 2,
QuadraticConstraint::HessianType::kPositiveSemidefinite,
QuadraticConstraint::HessianType::kPositiveSemidefinite);
CheckParseQuadraticConstraint(
x0_ * x0_ + 2 * x0_ + 3, 0, 2, std::nullopt,
QuadraticConstraint::HessianType::kPositiveSemidefinite);
CheckParseQuadraticConstraint(
x0_ * x0_ + 2 * x0_ * x1_ + 4 * x1_ * x1_, -kInf, 1, std::nullopt,
QuadraticConstraint::HessianType::kPositiveSemidefinite);
CheckParseQuadraticConstraint(
x0_ * x0_ + 2 * x0_ * x1_ + 4 * x1_ * x1_, 1, kInf, std::nullopt,
QuadraticConstraint::HessianType::kPositiveSemidefinite);
CheckParseQuadraticConstraint(
x0_ * x0_ + 2 * x0_ * x1_ + 4 * x1_ * x1_ + 2, 1, kInf, std::nullopt,
QuadraticConstraint::HessianType::kPositiveSemidefinite);
CheckParseQuadraticConstraint(
-x0_ * x0_ + 2 * x0_ * x1_ - 4 * x1_ * x1_ + 2, -kInf, 3, std::nullopt,
QuadraticConstraint::HessianType::kNegativeSemidefinite);
CheckParseQuadraticConstraint(
-x0_ * x0_ + 2 * x1_, -kInf, 3, std::nullopt,
QuadraticConstraint::HessianType::kNegativeSemidefinite);
}
void CheckParseLorentzConeConstraint(
const Expression& linear_expression, const Expression& quadratic_expression,
LorentzConeConstraint::EvalType eval_type) {
Binding<LorentzConeConstraint> binding = internal::ParseLorentzConeConstraint(
linear_expression, quadratic_expression, 0., eval_type);
EXPECT_EQ(binding.evaluator()->eval_type(), eval_type);
const Eigen::MatrixXd A = binding.evaluator()->A();
const Eigen::VectorXd b = binding.evaluator()->b();
const VectorX<Expression> z = A * binding.variables() + b;
EXPECT_TRUE(symbolic::test::PolynomialEqual(
symbolic::Polynomial(z(0)), symbolic::Polynomial(linear_expression),
1E-10));
EXPECT_TRUE(symbolic::test::PolynomialEqual(
symbolic::Polynomial(z.tail(z.rows() - 1).squaredNorm()),
symbolic::Polynomial(quadratic_expression), 1E-10));
}
void CheckParseRotatedLorentzConeConstraint(
const Eigen::Ref<const VectorX<Expression>>& v) {
Binding<RotatedLorentzConeConstraint> binding =
internal::ParseRotatedLorentzConeConstraint(v);
const Eigen::MatrixXd A = binding.evaluator()->A();
const Eigen::VectorXd b = binding.evaluator()->b();
const VectorX<Expression> z = A * binding.variables() + b;
for (int i = 0; i < z.rows(); ++i) {
EXPECT_TRUE(symbolic::test::PolynomialEqual(
symbolic::Polynomial(z(i)), symbolic::Polynomial(v(i)), 1E-10));
}
}
void CheckParseRotatedLorentzConeConstraint(
const Expression& linear_expression1, const Expression& linear_expression2,
const Expression& quadratic_expression, const double tol = 0) {
Binding<RotatedLorentzConeConstraint> binding =
internal::ParseRotatedLorentzConeConstraint(
linear_expression1, linear_expression2, quadratic_expression, tol);
const Eigen::MatrixXd A = binding.evaluator()->A();
const Eigen::VectorXd b = binding.evaluator()->b();
const VectorX<Expression> z = A * binding.variables() + b;
const double tol_check{1E-10};
EXPECT_TRUE(symbolic::test::PolynomialEqual(
symbolic::Polynomial(z(0)), symbolic::Polynomial(linear_expression1),
tol_check));
EXPECT_TRUE(symbolic::test::PolynomialEqual(
symbolic::Polynomial(z(1)), symbolic::Polynomial(linear_expression2),
tol_check));
EXPECT_TRUE(symbolic::test::PolynomialEqual(
symbolic::Polynomial(
z.tail(z.rows() - 2).cast<Expression>().squaredNorm()),
symbolic::Polynomial(quadratic_expression), tol_check));
}
class ParseLorentzConeConstraintTest : public ::testing::Test {
public:
ParseLorentzConeConstraintTest()
: x0_{"x0"}, x1_{"x1"}, x2_{"x2"}, x3_{"x3"} {
x_ << x0_, x1_, x2_, x3_;
}
protected:
symbolic::Variable x0_;
symbolic::Variable x1_;
symbolic::Variable x2_;
symbolic::Variable x3_;
Vector4<symbolic::Variable> x_;
};
TEST_F(ParseLorentzConeConstraintTest, Test0) {
// Test x(0) >= sqrt(x(1)² + x(2)² + ... + x(n-1)²)
CheckParseLorentzConeConstraint(
x_(0), x_.tail<3>().cast<Expression>().squaredNorm(),
LorentzConeConstraint::EvalType::kConvexSmooth);
}
TEST_F(ParseLorentzConeConstraintTest, Test1) {
// Test 2 * x(0) >= sqrt(x(1)² + x(2)² + ... + x(n-1)²)
CheckParseLorentzConeConstraint(
2 * x_(0), x_.tail<3>().cast<Expression>().squaredNorm(),
LorentzConeConstraint::EvalType::kConvexSmooth);
}
TEST_F(ParseLorentzConeConstraintTest, Test2) {
// Test 2 * x(0) + 3 * x(1) + 2 >= sqrt(x(1)² + x(2)² + ... + x(n-1)²)
CheckParseLorentzConeConstraint(2 * x_(0) + 3 * x_(1) + 2,
x_.tail<3>().cast<Expression>().squaredNorm(),
LorentzConeConstraint::EvalType::kConvex);
}
TEST_F(ParseLorentzConeConstraintTest, Test3) {
// Test x(0) >= sqrt(2x(1)² + x(2)² + 3x(3)² + 2)
CheckParseLorentzConeConstraint(
x_(0), 2 * x_(1) * x_(1) + x_(2) * x_(2) + 3 * x_(3) * x_(3) + 2,
LorentzConeConstraint::EvalType::kConvex);
}
TEST_F(ParseLorentzConeConstraintTest, Test4) {
// Test x(0) + 2x(2) + 3 >= sqrt((x(1) + x(0) + 2x(3)-1)² + 3(-x(0)+2x(3)+1)²
// + 3)
CheckParseLorentzConeConstraint(x_(0) + 2 * x_(2) + 3,
2 * pow(x_(1) + x_(0) + 2 * x_(3) - 1, 2) +
3 * pow(-x_(0) + 2 * x_(3) + 1, 2) + 3,
LorentzConeConstraint::EvalType::kConvex);
}
TEST_F(ParseLorentzConeConstraintTest, Test5) {
// Test 2 >= sqrt((x(1)+2x(2))² + (x(2)-x(0)+2)² + 3)
CheckParseLorentzConeConstraint(
2, pow(x_(1) + 2 * x_(2), 2) + pow(x_(2) - x_(0) + 2, 2) + 3,
LorentzConeConstraint::EvalType::kConvex);
}
TEST_F(ParseLorentzConeConstraintTest, Test6) {
// The linear expression is not actually linear.
EXPECT_THROW(unused(internal::ParseLorentzConeConstraint(
2 * x_(0) * x_(1), x_(0) * x_(0) + x_(1) * x_(1))),
std::runtime_error);
}
TEST_F(ParseLorentzConeConstraintTest, Test7) {
// The quadratic expression is actually linear.
EXPECT_THROW(
unused(internal::ParseLorentzConeConstraint(2 * x_(0), x_(0) + x_(1))),
std::runtime_error);
}
TEST_F(ParseLorentzConeConstraintTest, Test8) {
// The quadratic expression is actually cubic.
EXPECT_THROW(unused(internal::ParseLorentzConeConstraint(
2 * x_(0), pow(x_(1), 3) + x_(2))),
std::runtime_error);
}
TEST_F(ParseLorentzConeConstraintTest, Test9) {
// The quadratic expression is not positive semidefinite.
EXPECT_THROW(unused(internal::ParseLorentzConeConstraint(
x_(0), pow(x_(1) + 2 * x_(2) + 1, 2) - x_(3))),
std::runtime_error);
EXPECT_THROW(unused(internal::ParseLorentzConeConstraint(
x_(0), pow(x_(1) + x_(2) + 2, 2) - 1)),
std::runtime_error);
}
class ParseRotatedLorentzConeConstraintTest : public ::testing::Test {
public:
ParseRotatedLorentzConeConstraintTest()
: x0_{"x0"}, x1_{"x1"}, x2_{"x2"}, x3_{"x3"} {
x_ << x0_, x1_, x2_, x3_;
}
protected:
symbolic::Variable x0_;
symbolic::Variable x1_;
symbolic::Variable x2_;
symbolic::Variable x3_;
Vector4<symbolic::Variable> x_;
};
TEST_F(ParseRotatedLorentzConeConstraintTest, Test0) {
// x(0) * x(1) >= x(2)² + x(3)², x(0) >= 0, x(1) >= 0
CheckParseRotatedLorentzConeConstraint(x_.cast<Expression>());
CheckParseRotatedLorentzConeConstraint(x_(0), x_(1),
x_(2) * x_(2) + x_(3) * x_(3));
}
TEST_F(ParseRotatedLorentzConeConstraintTest, Test1) {
// (x(0) + 2) * (2 * x(1) + x(0) + 1) >= x(2)² + x(3)²
// x(0) + 2 >= 0
// 2 * x(1) + x(0) + 1 >= 0
Vector4<Expression> expression;
expression << x_(0) + 2, 2 * x_(1) + x_(0) + 1, x_(2), x_(3);
CheckParseRotatedLorentzConeConstraint(expression);
CheckParseRotatedLorentzConeConstraint(expression(0), expression(1),
x_(2) * x_(2) + x_(3) * x_(3));
}
TEST_F(ParseRotatedLorentzConeConstraintTest, Test2) {
// (x(0) - x(1) + 2) * (3 * x(2)) >= (x(1) + x(2))² + (x(2) + 2 * x(3) + 2)² +
// 5
Eigen::Matrix<Expression, 5, 1> expression;
expression << x_(0) - x_(1) + 2, 3 * x_(2), x_(1) + x_(2),
x_(2) + 2 * x_(3) + 2, std::sqrt(5);
CheckParseRotatedLorentzConeConstraint(expression);
CheckParseRotatedLorentzConeConstraint(
expression(0), expression(1),
pow(x_(1) + x_(2), 2) + pow(x_(2) + 2 * x_(3) + 2, 2) + 5,
4 * std::numeric_limits<double>::epsilon());
}
TEST_F(ParseRotatedLorentzConeConstraintTest, Test3) {
// Throw a runtime error when the precondition is not satisfied.
Eigen::Matrix<Expression, 4, 1> expression;
expression << 2 * x_(0) * x_(1), x_(2), x_(3), 1;
EXPECT_THROW(unused(internal::ParseRotatedLorentzConeConstraint(expression)),
std::runtime_error);
EXPECT_THROW(unused(internal::ParseRotatedLorentzConeConstraint(
x_(0) * x_(1), x_(1), x_(2) * x_(2) + 1)),
std::runtime_error);
EXPECT_THROW(unused(internal::ParseRotatedLorentzConeConstraint(
x_(1), x_(0) * x_(1), x_(2) * x_(2) + 1)),
std::runtime_error);
EXPECT_THROW(unused(internal::ParseRotatedLorentzConeConstraint(
x_(0), x_(1), x_(2) * x_(2) - 1)),
std::runtime_error);
}
class MaybeParseLinearConstraintTest : public ::testing::Test {
public:
MaybeParseLinearConstraintTest() {}
protected:
const symbolic::Variable x0_{"x0"};
const symbolic::Variable x1_{"x1"};
const symbolic::Variable x2_{"x2"};
const Vector3<symbolic::Variable> x_{x0_, x1_, x2_};
};
TEST_F(MaybeParseLinearConstraintTest, TestBoundingBoxConstraint) {
// Parse a bounding box constraint
auto check_bounding_box_constraint =
[](const Binding<Constraint>& constraint, double lower_expected,
double upper_expected, const symbolic::Variable& var) {
const Binding<BoundingBoxConstraint> bounding_box_constraint =
internal::BindingDynamicCast<BoundingBoxConstraint>(constraint);
EXPECT_EQ(bounding_box_constraint.variables().size(), 1);
EXPECT_EQ(bounding_box_constraint.variables()(0), var);
EXPECT_EQ(bounding_box_constraint.evaluator()->num_constraints(), 1);
EXPECT_EQ(bounding_box_constraint.evaluator()->lower_bound()(0),
lower_expected);
EXPECT_EQ(bounding_box_constraint.evaluator()->upper_bound()(0),
upper_expected);
};
check_bounding_box_constraint(
*(internal::MaybeParseLinearConstraint(x0_, 1, 2)), 1, 2, x0_);
check_bounding_box_constraint(
*(internal::MaybeParseLinearConstraint(-x0_, 1, 2)), -2, -1, x0_);
check_bounding_box_constraint(
*(internal::MaybeParseLinearConstraint(2 * x0_, 1, 2)), 0.5, 1, x0_);
check_bounding_box_constraint(
*(internal::MaybeParseLinearConstraint(-2 * x0_, 1, 2)), -1, -0.5, x0_);
check_bounding_box_constraint(
*(internal::MaybeParseLinearConstraint(x0_ + 1, 1, 2)), 0, 1, x0_);
check_bounding_box_constraint(
*(internal::MaybeParseLinearConstraint(x0_ + 1 + 2, 1, 2)), -2, -1, x0_);
check_bounding_box_constraint(
*(internal::MaybeParseLinearConstraint(2 * x0_ + 1 + 2, 1, 2)), -1, -0.5,
x0_);
check_bounding_box_constraint(
*(internal::MaybeParseLinearConstraint(-2 * x0_ + 1 + 2, 1, 2)), 0.5, 1,
x0_);
}
TEST_F(MaybeParseLinearConstraintTest, TestLinearEqualityConstraint) {
// Parse linear equality constraint.
auto check_linear_equality_constraint =
[](const Binding<Constraint>& constraint,
const Eigen::Ref<const Eigen::RowVectorXd>& a,
const Eigen::Ref<const VectorX<symbolic::Variable>>& vars,
double bound, double tol = 1E-14) {
const Binding<LinearEqualityConstraint> linear_eq_constraint =
internal::BindingDynamicCast<LinearEqualityConstraint>(constraint);
if (vars.size() != 0) {
EXPECT_EQ(linear_eq_constraint.variables(), vars);
} else {
EXPECT_EQ(linear_eq_constraint.variables().size(), 0);
}
EXPECT_EQ(linear_eq_constraint.evaluator()->num_constraints(), 1);
EXPECT_TRUE(CompareMatrices(
linear_eq_constraint.evaluator()->GetDenseA(), a, tol));
EXPECT_NEAR(linear_eq_constraint.evaluator()->lower_bound()(0), bound,
tol);
};
// without a constant term in the expression.
check_linear_equality_constraint(
*internal::MaybeParseLinearConstraint(x_(0) + 2 * x_(1), 1, 1),
Eigen::RowVector2d(1, 2), Vector2<symbolic::Variable>(x_(0), x_(1)), 1);
// with a constant term in the expression.
check_linear_equality_constraint(
*internal::MaybeParseLinearConstraint(x_(0) + 2 * x_(1) + 2 + 1, 3, 3),
Eigen::RowVector2d(1, 2), Vector2<symbolic::Variable>(x_(0), x_(1)), 0);
// Check a constant expression.
check_linear_equality_constraint(
*internal::MaybeParseLinearConstraint(2, 3, 3), Eigen::RowVectorXd(0),
VectorX<symbolic::Variable>(0), 1);
}
TEST_F(MaybeParseLinearConstraintTest, TestLinearConstraint) {
// Parse linear inequality constraint.
auto check_linear_constraint =
[](const Binding<Constraint>& constraint,
const Eigen::Ref<const Eigen::RowVectorXd>& a,
const Eigen::Ref<const VectorX<symbolic::Variable>>& vars, double lb,
double ub, double tol = 1E-14) {
const Binding<LinearConstraint> linear_constraint =
internal::BindingDynamicCast<LinearConstraint>(constraint);
if (vars.size() != 0) {
EXPECT_EQ(linear_constraint.variables(), vars);
} else {
EXPECT_EQ(linear_constraint.variables().size(), 0);
}
EXPECT_EQ(linear_constraint.evaluator()->num_constraints(), 1);
EXPECT_TRUE(CompareMatrices(linear_constraint.evaluator()->GetDenseA(),
a, tol));
EXPECT_NEAR(linear_constraint.evaluator()->lower_bound()(0), lb, tol);
EXPECT_NEAR(linear_constraint.evaluator()->upper_bound()(0), ub, tol);
};
// without a constant term in the expression.
check_linear_constraint(
*internal::MaybeParseLinearConstraint(x_(0) + 2 * x_(1), 1, 2),
Eigen::RowVector2d(1, 2), Vector2<symbolic::Variable>(x_(0), x_(1)), 1,
2);
// with a constant term in the expression.
check_linear_constraint(
*internal::MaybeParseLinearConstraint(x_(0) + 2 * x_(1) + 2 + 1, 3, 4),
Eigen::RowVector2d(1, 2), Vector2<symbolic::Variable>(x_(0), x_(1)), 0,
1);
// Check a constant expression.
check_linear_constraint(*internal::MaybeParseLinearConstraint(2, 3, 4),
Eigen::RowVectorXd(0), VectorX<symbolic::Variable>(0),
1, 2);
check_linear_constraint(
*internal::MaybeParseLinearConstraint(0 * x_(0) + 2, 3, 4),
Eigen::RowVectorXd(0), VectorX<symbolic::Variable>(0), 1, 2);
}
TEST_F(MaybeParseLinearConstraintTest, NonlinearConstraint) {
EXPECT_EQ(internal::MaybeParseLinearConstraint(x_(0) * x_(0), 1, 2).get(),
nullptr);
EXPECT_EQ(internal::MaybeParseLinearConstraint(sin(x_(0)), 1, 2).get(),
nullptr);
}
GTEST_TEST(ParseConstraintTest, FalseFormula) {
// ParseConstraint with some formula being false.
symbolic::Variable x("x");
// ParseConstraint for a vector of symbolic::Formula
DRAKE_EXPECT_THROWS_MESSAGE(
internal::ParseConstraint(
Vector2<symbolic::Formula>(x >= 0, symbolic::Expression(1) >= 2)),
"ParseConstraint is called with formulas\\(1, 0\\) being always false");
// ParseConstraint for a single symbolic::Formula
DRAKE_EXPECT_THROWS_MESSAGE(
internal::ParseConstraint(symbolic::Expression(1) >= 2),
"ParseConstraint is called with a formula being always false.");
}
GTEST_TEST(ParseLinearEqualityConstraintTest, FalseFormula) {
// ParseLinearEqualityConstraint with some formula being false.
symbolic::Variable x("x");
// ParseLinearEqualityConstraint for a set of symbolic::Formula
DRAKE_EXPECT_THROWS_MESSAGE(
internal::ParseLinearEqualityConstraint(
std::set<symbolic::Formula>({x == 0, symbolic::Expression(1) == 2})),
"ParseLinearEqualityConstraint is called with one of formulas being "
"always false.");
// ParseLinearEqualityConstraint for a single symbolic::Formula
DRAKE_EXPECT_THROWS_MESSAGE(
internal::ParseLinearEqualityConstraint(symbolic::Expression(1) == 2),
"ParseLinearEqualityConstraint is called with a formula being always "
"false.");
}
GTEST_TEST(ParseConstraintTest, TrueFormula) {
// Call ParseConstraint with a formula being always True.
auto binding1 = internal::ParseConstraint(symbolic::Expression(1) >= 0);
EXPECT_NE(dynamic_cast<BoundingBoxConstraint*>(binding1.evaluator().get()),
nullptr);
EXPECT_EQ(binding1.evaluator()->num_constraints(), 0);
EXPECT_EQ(binding1.variables().rows(), 0);
// Call ParseConstraint with a vector of formulas, some of the formulas being
// always True.
symbolic::Variable x("x");
auto binding2 = internal::ParseConstraint(
Vector2<symbolic::Formula>(x >= 1, symbolic::Expression(1) >= 0));
EXPECT_EQ(binding2.evaluator()->num_constraints(), 1);
EXPECT_TRUE(
binding2.evaluator()->CheckSatisfied((Vector1d() << 2).finished()));
EXPECT_FALSE(
binding2.evaluator()->CheckSatisfied((Vector1d() << 0).finished()));
// Call ParseConstraint with a vector of formulas all being True.
auto binding3 = internal::ParseConstraint(Vector2<symbolic::Formula>(
symbolic::Expression(1) >= 0, symbolic::Expression(2) >= 1));
EXPECT_NE(dynamic_cast<BoundingBoxConstraint*>(binding3.evaluator().get()),
nullptr);
EXPECT_EQ(binding3.evaluator()->num_constraints(), 0);
EXPECT_EQ(binding3.variables().rows(), 0);
// Call ParseLinearEqualityConstraint with a set of formulas, while some
// formulas being always true.
auto binding4 = internal::ParseLinearEqualityConstraint(
std::set<symbolic::Formula>({2 * x == 1, symbolic::Expression(1) == 1}));
EXPECT_EQ(binding4.evaluator()->num_constraints(), 1);
EXPECT_TRUE(
binding4.evaluator()->CheckSatisfied((Vector1d() << 0.5).finished()));
EXPECT_FALSE(
binding4.evaluator()->CheckSatisfied((Vector1d() << 1).finished()));
// Call ParseLinearEqualityConstraint with a set of formulas all being True.
auto binding5 =
internal::ParseLinearEqualityConstraint(std::set<symbolic::Formula>(
{symbolic::Expression(1) == 1, symbolic::Expression(2) == 2}));
EXPECT_EQ(binding5.evaluator()->num_constraints(), 0);
// Call ParseLinearEqualityConstraint with a single formula being always true.
auto binding6 =
internal::ParseLinearEqualityConstraint(symbolic::Expression(1) == 1);
EXPECT_EQ(binding6.evaluator()->num_constraints(), 0);
EXPECT_EQ(binding6.variables().rows(), 0);
}
// Confirm that ParseConstraint also parses the quadratic constraint.
GTEST_TEST(ParseConstraintTest, Quadratic) {
symbolic::Variable x0("x0"), x1("x1");
Binding<Constraint> binding =
internal::ParseConstraint(-x0 * x0 + 2 * x1, -kInf, 3);
EXPECT_NE(dynamic_cast<QuadraticConstraint*>(binding.evaluator().get()),
nullptr);
// A vector of quadratic constraints is an ExpressionConstraint (not
// quadratic).
binding = internal::ParseConstraint(
Vector2<Expression>(x0 * x0 + 2 * x1, x1 * x1), Vector2d::Constant(-kInf),
Vector2d::Constant(3));
EXPECT_NE(dynamic_cast<ExpressionConstraint*>(binding.evaluator().get()),
nullptr);
// A scalar non-polynomial constraint is an ExpressionConstraint (not
// quadratic).
binding = internal::ParseConstraint(x0 * x0 + 2 * x1 + sin(x1), -kInf, 3);
EXPECT_NE(dynamic_cast<ExpressionConstraint*>(binding.evaluator().get()),
nullptr);
// A polynomial constraint of degree > 2 is an ExpressionConstraint (not
// quadratic).
binding = internal::ParseConstraint(x0 * x0 * x1 + 2 * x1, -kInf, 3);
EXPECT_NE(dynamic_cast<ExpressionConstraint*>(binding.evaluator().get()),
nullptr);
}
GTEST_TEST(ParseConstraintTest, FormulaWithInfiniteLowerOrUpperBounds) {
Variable x0("x0"), x1("x1");
Vector2<Variable> x(x0, x1);
Vector2d b(0.12, kInf);
Binding<Constraint> binding =
internal::ParseConstraint(x <= b);
EXPECT_TRUE(CompareMatrices(binding.evaluator()->upper_bound(), b));
binding = internal::ParseConstraint(-b <= x);
// Note: The constraints are sorted via get_operands(f) which returns a
// std::set. This one gets flipped.
EXPECT_TRUE(CompareMatrices(binding.evaluator()->lower_bound(),
-Vector2d(b[1], b[0])));
binding = internal::ParseConstraint(b >= x);
EXPECT_TRUE(CompareMatrices(binding.evaluator()->upper_bound(), b));
binding = internal::ParseConstraint(x >= -b);
EXPECT_TRUE(CompareMatrices(binding.evaluator()->lower_bound(), -b));
DRAKE_EXPECT_THROWS_MESSAGE(internal::ParseConstraint(x <= -b),
".*an upper bound of -inf.*");
DRAKE_EXPECT_THROWS_MESSAGE(internal::ParseConstraint(b <= x),
".*a lower bound of.*");
DRAKE_EXPECT_THROWS_MESSAGE(internal::ParseConstraint(-b >= x),
".*an upper bound of -inf.*");
DRAKE_EXPECT_THROWS_MESSAGE(internal::ParseConstraint(x >= b),
".*a lower bound of.*");
}
std::shared_ptr<RotatedLorentzConeConstraint>
CheckParseQuadraticAsRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double c,
double zero_tol = 0.) {
const auto dut =
internal::ParseQuadraticAsRotatedLorentzConeConstraint(Q, b, c, zero_tol);
// Make sure that dut.A() * x + dub.t() in rotated Lorentz cone is the same
// expression as 0.5xᵀQx + bᵀx + c<=0.
const Eigen::MatrixXd A_dense = dut->A_dense();
EXPECT_TRUE(
CompareMatrices(A_dense.row(1), Eigen::RowVectorXd::Zero(Q.rows())));
EXPECT_EQ(dut->b()(1), 1);
const double tol = 1E-12;
// Check the Hessian.
EXPECT_TRUE(
CompareMatrices(A_dense.bottomRows(A_dense.rows() - 2).transpose() *
A_dense.bottomRows(A_dense.rows() - 2),
0.25 * (Q + Q.transpose()), tol));
// Check the linear coefficient.
EXPECT_TRUE(
CompareMatrices(2 * A_dense.bottomRows(A_dense.rows() - 2).transpose() *
dut->b().tail(dut->b().rows() - 2) -
A_dense.row(0).transpose(),
b, tol));
EXPECT_NEAR(dut->b().tail(dut->b().rows() - 2).squaredNorm() - dut->b()(0), c,
tol);
return dut;
}
GTEST_TEST(ParseQuadraticAsRotatedLorentzConeConstraint, Test) {
CheckParseQuadraticAsRotatedLorentzConeConstraint(
(Vector1d() << 1).finished(), Vector1d::Zero(), 1);
CheckParseQuadraticAsRotatedLorentzConeConstraint(
(Vector1d() << 1).finished(), (Vector1d() << 2).finished(), 1);
// Strictly positive Hessian.
CheckParseQuadraticAsRotatedLorentzConeConstraint(Eigen::Matrix2d::Identity(),
Eigen::Vector2d(1, 3), 2);
// Hessian is positive semidefinite but not positive definite. b is in the
// range space of F.
auto dut = CheckParseQuadraticAsRotatedLorentzConeConstraint(
2 * Eigen::Matrix2d::Ones(), Eigen::Vector2d(2, 2), 0.5);
EXPECT_EQ(dut->A().rows(), 3);
// Hessian is positive semidefinite but not positive definite, b is not in the
// range space of F.
dut = CheckParseQuadraticAsRotatedLorentzConeConstraint(
2 * Eigen::Matrix2d::Ones(), Eigen::Vector2d(2, 3), -0.5);
EXPECT_EQ(dut->A().rows(), 3);
// Hessian is almost positive semidefinite with one eigenvalue slightly
// negative.
Eigen::Matrix2d Q_almost_psd;
// clang-format off
Q_almost_psd << 1, 1,
1, 1 - 1E-12;
// clang-format on
DRAKE_EXPECT_THROWS_MESSAGE(
internal::ParseQuadraticAsRotatedLorentzConeConstraint(
Q_almost_psd, Eigen::Vector2d(2, 3), -0.5),
".* is not positive semidefinite.*");
CheckParseQuadraticAsRotatedLorentzConeConstraint(
Q_almost_psd, Eigen::Vector2d(2, 3), -0.5, 1E-10);
}
GTEST_TEST(ParseQuadraticAsRotatedLorentzConeConstraint, TestException) {
const Eigen::MatrixXd Q = Eigen::Vector2d(1, -2).asDiagonal();
DRAKE_EXPECT_THROWS_MESSAGE(
internal::ParseQuadraticAsRotatedLorentzConeConstraint(
Q, Eigen::Vector2d(1, 3), -2),
".* is not positive semidefinite.*");
}
} // namespace
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/semidefinite_program_examples.h | #pragma once
#include <optional>
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/solver_interface.h"
namespace drake {
namespace solvers {
namespace test {
/// Test a trivial semidefinite problem.
/// min S(0, 0) + S(1, 1)
/// s.t S(1, 0) = 1
/// S is p.s.d
/// The analytical solution is
/// S = [1 1]
/// [1 1]
void TestTrivialSDP(const SolverInterface& solver, double tol);
// Solve a semidefinite programming problem.
// Find the common Lyapunov function for linear systems
// xdot = Ai*x
// The condition is
// min 0
// s.t P is positive definite
// - (Ai'*P + P*Ai) is positive definite
void FindCommonLyapunov(const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options,
double tol);
/*
* Given some ellipsoids ℰᵢ : xᵀQᵢx + 2 bᵢᵀx ≤ 1, i = 1, 2, ..., n, find an
* ellipsoid xᵀPx + 2cᵀx ≤ 1 as an outer approximation for the union of
* ellipsoids ℰᵢ.
*
* Using s-lemma, the ellipsoid xᵀPx + 2cᵀx ≤ 1 contains the ellipsoid ℰᵢ,
* if and only if there exists a scalar sᵢ ≥ 0 such that
*
* (1 - xᵀPx - cᵀx) - sᵢ(1 - xᵀQᵢx - bᵢᵀx) ≥ 0 ∀x.
*
* This is equivalent to requiring that the matrix
*
* ⎡sᵢQᵢ - P sᵢbᵢ - c⎤
* ⎣sᵢbᵢᵀ - cᵀ 1 - sᵢ⎦
*
* is positive semidefinite.
*
* In order to find a tight outer approximation, we choose to maximize the
* trace of P. The optimization problem becomes
*
* min_{P, c, si} -trace(P)
* s.t ⎡sᵢQᵢ - P sᵢbᵢ - c⎤ is p.s.d
* ⎣sᵢbᵢᵀ - cᵀ 1 - sᵢ⎦
* P is p.s.d
*/
void FindOuterEllipsoid(const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options,
double tol);
// Solve an eigen value problem through a semidefinite programming.
// Minimize the maximum eigen value of a matrix that depends affinely on a
// variable x
// min z
// s.t z * Identity - x1 * F1 - ... - xn * Fn is p.s.d
// A * x <= b
// C * x = d
void SolveEigenvalueProblem(const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options,
double tol);
/// Solve an SDP with a second order cone constraint. This example is taken from
/// https://docs.mosek.com/10.1/capi/tutorial-sdo-shared.html
void SolveSDPwithSecondOrderConeExample1(const SolverInterface& solver,
double tol);
/** Solve an SDP with second order cone constraints. Notice that the variables
* appear in the second order cone constraints appear also in the positive
* semidefinite constraint.
* min X(0, 0) + X(1, 1) + x(0)
* s.t X(0, 0) + 2 * X(1, 1) + X(2, 2) + 3 * x(0) = 3
* X(0, 0) >= sqrt((X(1, 1) + x(0))² + (X(1, 1) + X(2, 2))²)
* X(1, 0) + X(2, 1) = 1
* X is psd, x(0) >= 0
*/
void SolveSDPwithSecondOrderConeExample2(const SolverInterface& solver,
double tol);
/** Solve an SDP with two PSD constraint, where each PSD constraint has
* duplicate entries and the two PSD matrix share a common variables.
* min 2 * x0 + x2
* s.t [x0 x1] is psd
* [x1 x0]
* [x0 x2] is psd
* [x2 x0]
* x1 == 1
* The optimal solution will be x = (1, 1, -1).
*/
void SolveSDPwithOverlappingVariables(const SolverInterface& solver,
double tol);
/** Solve an SDP with quadratic cost and two PSD constraints, where each PSD
* constraint has duplicate entries and the two PSD matrix share a common
* variables.
* min x0² + 2*x0 + x2
* s.t ⎡x0 x1⎤ is psd
* ⎣x1 x0⎦
* ⎡x0 x2⎤ is psd
* ⎣x2 x0⎦
* x1 == 1
*
* The optimal solution will be x = (1, 1, -1).
*/
void SolveSDPwithQuadraticCosts(const SolverInterface& solver, double tol);
/**
* Test a simple SDP with only PSD constraint and bounding box constraint.
* min x1
* s.t ⎡x0 x1⎤ is psd
* ⎣x1 x2⎦
* x0 <= 4
* x2 <= 1
*/
void TestSDPDualSolution1(const SolverInterface& solver, double tol);
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/unrevised_lemke_solver_test.cc | #include "drake/solvers/unrevised_lemke_solver.h"
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace solvers {
const double epsilon = 5e-14;
// Run the solver and test against the expected result.
template <typename Derived>
void RunLCP(const Eigen::MatrixBase<Derived>& M, const Eigen::VectorXd& q,
const Eigen::VectorXd& expected_z_in) {
UnrevisedLemkeSolver<double> l;
Eigen::VectorXd expected_z = expected_z_in;
// NOTE: We don't necessarily expect the unregularized fast solver to succeed,
// hence we don't test the result.
Eigen::VectorXd lemke_z;
int num_pivots;
bool result = l.SolveLcpLemke(M, q, &lemke_z, &num_pivots);
ASSERT_TRUE(result);
EXPECT_TRUE(CompareMatrices(lemke_z, expected_z, epsilon,
MatrixCompareType::absolute));
EXPECT_GT(num_pivots, 0); // We do not test any trivial LCPs.
}
// Checks that the solver detects a dimensional mismatch between the LCP matrix
// and vector.
GTEST_TEST(TestUnrevisedLemke, DimensionalMismatch) {
UnrevisedLemkeSolver<double> lcp;
MatrixX<double> M(3, 3);
VectorX<double> q(4);
// Zero tolerance is arbitrary.
const double zero_tol = 1e-15;
// Verify that solver catches M not matching q.
int num_pivots;
VectorX<double> z;
EXPECT_THROW(lcp.SolveLcpLemke(M, q, &z, &num_pivots, zero_tol),
std::logic_error);
// Verify that solver catches non-square M.
M.resize(3, 4);
EXPECT_THROW(lcp.SolveLcpLemke(M, q, &z, &num_pivots, zero_tol),
std::logic_error);
}
// Checks the robustness of the algorithm to a known test problem that results
// in cycling.
GTEST_TEST(TestUnrevisedLemke, TestCycling) {
Eigen::Matrix<double, 3, 3> M;
// clang-format off
M <<
1, 2, 0,
0, 1, 2,
2, 0, 1;
// clang-format on
Eigen::Matrix<double, 3, 1> q;
q << -1, -1, -1;
Eigen::VectorXd expected_z(3);
expected_z << 1.0 / 3, 1.0 / 3, 1.0 / 3;
RunLCP(M, q, expected_z);
}
// Tests a simple linear complementarity problem.
GTEST_TEST(TestUnrevisedLemke, TestSimple) {
// Create a 9x9 diagonal matrix from the vector [1 2 3 4 5 6 7 8 9].
MatrixX<double> M =
(Eigen::Matrix<double, 9, 1>() << 1, 2, 3, 4, 5, 6, 7, 8, 9)
.finished()
.asDiagonal();
Eigen::Matrix<double, 9, 1> q;
q << -1, -1, -1, -1, -1, -1, -1, -1, -1;
Eigen::VectorXd expected_z(9);
expected_z << 1, 1.0 / 2, 1.0 / 3, 1.0 / 4, 1.0 / 5, 1.0 / 6, 1.0 / 7,
1.0 / 8, 1.0 / 9;
RunLCP(M, q, expected_z);
}
// Tests that the artificial variable is always selected in a tie
// (Example 4.4.16 in [Cottle 1992]). We know Lemke's algorithm can solve
// this one since the matrix is symmetric and positive semi-definite.
// Lemke implementations without the necessary special-case code can terminate
// on an unblocked variable (i.e., fail to find the solution when one is known
// to exist).
// NOTE: This is a necessary but not sufficient test that the special-case code
// is working. This test failed before the special-case code was added, but it's
// possible that the test could succeed using other strategies for selecting
// one of multiple valid blocking indices. For example, Miranda and Fackler's
// Lemke solver uses a random blocking variable selection when multiple are
// possible.
GTEST_TEST(TestUnrevisedLemke, TestPSD) {
MatrixX<double> M(2, 2);
// clang-format off
M << 1, -1,
-1, 1;
// clang-format on
Eigen::Vector2d q;
q << 1, -1;
Eigen::VectorXd expected_z(2);
expected_z << 0, 1;
RunLCP(M, q, expected_z);
}
GTEST_TEST(TestUnrevisedLemke, TestProblem1) {
// Problem from example 10.2.1 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 16, 16> M;
M.setIdentity();
for (int i = 0; i < M.rows() - 1; i++) {
for (int j = i + 1; j < M.cols(); j++) {
M(i, j) = 2;
}
}
Eigen::Matrix<double, 1, 16> q;
q.fill(-1);
Eigen::Matrix<double, 1, 16> z;
z.setZero();
z(15) = 1;
RunLCP(M, q, z);
}
GTEST_TEST(TestUnrevisedLemke, TestProblem2) {
// Problem from example 10.2.2 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 2, 2> M;
M.fill(1);
Eigen::Matrix<double, 1, 2> q;
q.fill(-1);
// This problem also has valid solutions (0, 1) and (0.5, 0.5).
Eigen::Matrix<double, 1, 2> z;
z << 1, 0;
RunLCP(M, q, z);
}
GTEST_TEST(TestUnrevisedLemke, TestProblem3) {
// Problem from example 10.2.3 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 3, 3> M;
// clang-format off
M <<
0, -1, 2,
2, 0, -2,
-1, 1, 0;
// clang-format on
Eigen::Matrix<double, 1, 3> q;
q << -3, 6, -1;
Eigen::Matrix<double, 1, 3> z;
z << 0, 1, 3;
RunLCP(M, q, z);
}
GTEST_TEST(TestUnrevisedLemke, TestProblem4) {
// Problem from example 10.2.4 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 4, 4> M;
// clang-format off
M <<
0, 0, 10, 20,
0, 0, 30, 15,
10, 20, 0, 0,
30, 15, 0, 0;
// clang-format on
Eigen::Matrix<double, 1, 4> q;
q.fill(-1);
// This solution is the third in the book, which it explicitly
// states cannot be found using the Lemke-Howson algorithm.
Eigen::VectorXd z(4);
z << 1. / 90., 2. / 45., 1. / 90., 2. / 45.;
UnrevisedLemkeSolver<double> l;
int num_pivots;
bool result = l.SolveLcpLemke(M, q, &z, &num_pivots);
EXPECT_FALSE(result);
}
GTEST_TEST(TestUnrevisedLemke, TestProblem6) {
// Problem from example 10.2.9 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 4, 4> M;
// clang-format off
M <<
11, 0, 10, -1,
0, 11, 10, -1,
10, 10, 21, -1,
1, 1, 1, 0; // Note that the (3, 3) position is incorrectly
// shown in the book with the value 1.
// clang-format on
// Pick a couple of arbitrary points in the [0, 23] range.
for (double l = 1; l <= 23; l += 15) {
Eigen::Matrix<double, 1, 4> q;
q << 50, 50, l, -6;
Eigen::Matrix<double, 1, 4> z;
// clang-format off
z << (l + 16.) / 13.,
(l + 16.) / 13.,
(2. * (23 - l)) / 13.,
(1286. - (9. * l)) / 13;
// clang-format on
RunLCP(M, q, z);
}
// Try again with a value > 23 and verify that Lemke is still successful.
Eigen::Matrix<double, 1, 4> q;
q << 50, 50, 100, -6;
Eigen::Matrix<double, 1, 4> z;
z << 3, 3, 0, 83;
RunLCP(M, q, z);
}
GTEST_TEST(TestUnrevisedLemke, TestEmpty) {
Eigen::MatrixXd empty_M(0, 0);
Eigen::VectorXd empty_q(0);
Eigen::VectorXd z;
UnrevisedLemkeSolver<double> l;
int num_pivots;
bool result = l.SolveLcpLemke(empty_M, empty_q, &z, &num_pivots);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
}
// Verifies that z is zero on LCP solver failure.
GTEST_TEST(TestUnrevisedLemke, TestFailure) {
Eigen::MatrixXd neg_M(1, 1);
Eigen::VectorXd neg_q(1);
// This LCP is unsolvable: -z - 1 cannot be greater than zero when z is
// restricted to be non-negative.
neg_M(0, 0) = -1;
neg_q[0] = -1;
Eigen::VectorXd z;
UnrevisedLemkeSolver<double> l;
int num_pivots;
bool result = l.SolveLcpLemke(neg_M, neg_q, &z, &num_pivots);
LinearComplementarityConstraint constraint(neg_M, neg_q);
EXPECT_FALSE(result);
ASSERT_EQ(z.size(), neg_q.size());
EXPECT_EQ(z[0], 0.0);
EXPECT_FALSE(constraint.CheckSatisfied(z));
}
GTEST_TEST(TestUnrevisedLemke, TestSolutionQuality) {
// Set the LCP and the solution.
VectorX<double> q(1), z(1);
MatrixX<double> M(1, 1);
M(0, 0) = 1;
q[0] = -1;
z[0] = 1 - std::numeric_limits<double>::epsilon();
// Check solution quality without a tolerance specified.
UnrevisedLemkeSolver<double> lcp;
EXPECT_TRUE(lcp.IsSolution(M, q, z));
// Check solution quality with a tolerance specified.
EXPECT_TRUE(lcp.IsSolution(M, q, z, 3e-16));
}
GTEST_TEST(TestUnrevisedLemke, ZeroTolerance) {
// Compute the zero tolerance for several matrices.
// An scalar matrix- should be _around_ machine epsilon.
const double eps = std::numeric_limits<double>::epsilon();
MatrixX<double> M(1, 1);
M(0, 0) = 1;
EXPECT_NEAR(UnrevisedLemkeSolver<double>::ComputeZeroTolerance(M), eps,
10 * eps);
// An scalar matrix * 1e10. Should be _around_ machine epsilon * 1e10.
M(0, 0) = 1e10;
EXPECT_NEAR(UnrevisedLemkeSolver<double>::ComputeZeroTolerance(M), 1e10 * eps,
1e11 * eps);
// A 100 x 100 identity matrix. Should be _around_ 100 * machine epsilon.
M = MatrixX<double>::Identity(10, 10);
EXPECT_NEAR(UnrevisedLemkeSolver<double>::ComputeZeroTolerance(M), 1e2 * eps,
1e3 * eps);
}
// Checks that warmstarting works as anticipated.
GTEST_TEST(TestUnrevisedLemke, WarmStarting) {
MatrixX<double> M(3, 3);
// clang-format off
M <<
1, 2, 0,
0, 1, 2,
2, 0, 1;
// clang-format on
Eigen::Matrix<double, 3, 1> q;
q << -1, -1, -1;
// Solve the problem once.
int num_pivots;
Eigen::VectorXd expected_z(3);
expected_z << 1.0 / 3, 1.0 / 3, 1.0 / 3;
Eigen::VectorXd z;
UnrevisedLemkeSolver<double> lcp;
bool result = lcp.SolveLcpLemke(M, q, &z, &num_pivots);
ASSERT_TRUE(result);
ASSERT_TRUE(
CompareMatrices(z, expected_z, epsilon, MatrixCompareType::absolute));
// Verify that more than one pivot was required.
EXPECT_GE(num_pivots, 1);
// Solve the problem with a slightly different q and verify that exactly
// one pivot was required.
q *= 2;
expected_z *= 2;
result = lcp.SolveLcpLemke(M, q, &z, &num_pivots);
ASSERT_TRUE(result);
ASSERT_TRUE(
CompareMatrices(z, expected_z, epsilon, MatrixCompareType::absolute));
EXPECT_EQ(num_pivots, 1);
}
// Checks that an LCP with a trivial solution is solvable without any pivots.
GTEST_TEST(TestUnrevisedLemke, Trivial) {
MatrixX<double> M = MatrixX<double>::Identity(3, 3);
Eigen::Matrix<double, 3, 1> q;
q << 1, 1, 1;
// Solve the problem.
int num_pivots;
Eigen::VectorXd expected_z(3);
expected_z << 0, 0, 0;
Eigen::VectorXd z;
UnrevisedLemkeSolver<double> lcp;
bool result = lcp.SolveLcpLemke(M, q, &z, &num_pivots);
ASSERT_TRUE(result);
ASSERT_TRUE(
CompareMatrices(z, expected_z, epsilon, MatrixCompareType::absolute));
ASSERT_EQ(num_pivots, 0);
}
// A class for testing various private functions in the Lemke solver.
class UnrevisedLemkePrivateTests : public testing::Test {
protected:
void SetUp() {
typedef UnrevisedLemkeSolver<double>::LCPVariable LCPVariable;
// clang-format off
M_.resize(3, 3);
M_ <<
0, -1, 2,
2, 0, -2,
-1, 1, 0;
// clang-format on
q_.resize(3, 1);
q_ << -3, 6, -1;
// Set the LCP variables. Start with all z variables independent and all w
// variables dependent.
const int n = 3;
lcp_.indep_variables_.resize(n + 1);
lcp_.dep_variables_.resize(n);
for (int i = 0; i < n; ++i) {
lcp_.dep_variables_[i] = LCPVariable(false, i);
lcp_.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.
lcp_.indep_variables_[n] = LCPVariable(true, n);
}
UnrevisedLemkeSolver<double> lcp_; // The solver itself.
MatrixX<double> M_; // The LCP matrix used in pivoting tests.
MatrixX<double> q_; // The LCP vector used in pivoting tests.
int kArtificial{3}; // Index of the artificial variable.
};
// Tests proper operation of selecting a sub-matrix from a matrix that is
// augmented with a covering vector.
TEST_F(UnrevisedLemkePrivateTests, SelectSubMatrixWithCovering) {
MatrixX<double> result;
// After augmentation, the matrix will be:
// 1 0 0 1
// 0 1 0 1
// 0 0 1 1
MatrixX<double> M = MatrixX<double>::Identity(3, 3);
// Select the upper-left 2x2
lcp_.SelectSubMatrixWithCovering(M, {0, 1}, {0, 1}, &result);
ASSERT_EQ(result.rows(), 2);
ASSERT_EQ(result.cols(), 2);
MatrixX<double> expected(result.rows(), result.cols());
// clang-format off
expected << 1, 0,
0, 1;
// clang-format on
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Select the lower-right 2x2.
lcp_.SelectSubMatrixWithCovering(M, {1, 2}, {2, 3}, &result);
ASSERT_EQ(result.rows(), 2);
ASSERT_EQ(result.cols(), 2);
// clang-format off
expected << 0, 1,
1, 1;
// clang-format on
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Select the right 3x3, with columns reversed.
lcp_.SelectSubMatrixWithCovering(M, {0, 1, 2}, {3, 2, 1}, &result);
ASSERT_EQ(result.rows(), 3);
ASSERT_EQ(result.cols(), 3);
expected = MatrixX<double>(result.rows(), result.cols());
// clang-format off
expected << 1, 0, 0,
1, 0, 1,
1, 1, 0;
// clang-format on
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Select the right 3x3, with rows reversed.
lcp_.SelectSubMatrixWithCovering(M, {2, 1, 0}, {1, 2, 3}, &result);
ASSERT_EQ(result.rows(), 3);
ASSERT_EQ(result.cols(), 3);
expected = MatrixX<double>(result.rows(), result.cols());
// clang-format off
expected << 0, 1, 1,
1, 0, 1,
0, 0, 1;
// clang-format on
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Select the entire matrix.
lcp_.SelectSubMatrixWithCovering(M, {0, 1, 2}, {0, 1, 2, 3}, &result);
expected = MatrixX<double>(result.rows(), result.cols());
// clang-format off
expected << 1, 0, 0, 1,
0, 1, 0, 1,
0, 0, 1, 1;
// clang-format on
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
}
// Tests proper operation of selecting a sub-column from a matrix that is
// augmented with a covering vector.
TEST_F(UnrevisedLemkePrivateTests, SelectSubColumnWithCovering) {
// After augmentation, the matrix will be:
// 1 0 0 1
// 0 1 0 1
// 0 0 1 1
MatrixX<double> M = MatrixX<double>::Identity(3, 3);
VectorX<double> result;
// Get a single row, first column.
VectorX<double> expected(1);
expected << 1;
lcp_.SelectSubColumnWithCovering(M, {0}, 0 /* column */, &result);
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Get another single row from the first column.
expected << 0;
lcp_.SelectSubColumnWithCovering(M, {1}, 0 /* column */, &result);
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Get first and third rows in forward order, first column.
lcp_.SelectSubColumnWithCovering(M, {0, 2}, 0 /* column */, &result);
expected = VectorX<double>(2);
expected << 1, 0;
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Get first and third rows in reverse order, second column.
lcp_.SelectSubColumnWithCovering(M, {2, 0}, 1 /* column */, &result);
expected << 0, 0;
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Get all three rows in forward order, third column.
lcp_.SelectSubColumnWithCovering(M, {0, 1, 2}, 2 /* column */, &result);
expected = VectorX<double>(3);
expected << 0, 0, 1;
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Get all three rows in reverse order, third column.
lcp_.SelectSubColumnWithCovering(M, {2, 1, 0}, 2 /* column */, &result);
expected << 1, 0, 0;
EXPECT_TRUE(
CompareMatrices(result, expected, epsilon, MatrixCompareType::absolute));
// Get one row from the fourth column.
lcp_.SelectSubColumnWithCovering(M, {0}, 3 /* column */, &result);
EXPECT_EQ(result.lpNorm<1>(), 1);
// Get two rows from the fourth column.
lcp_.SelectSubColumnWithCovering(M, {0, 1}, 3 /* column */, &result);
EXPECT_EQ(result.lpNorm<1>(), 2);
// Get three rows from the fourth column.
lcp_.SelectSubColumnWithCovering(M, {0, 1, 2}, 3 /* column */, &result);
EXPECT_EQ(result.lpNorm<1>(), 3);
}
// Tests proper operation of selecting a sub-vector from a vector.
TEST_F(UnrevisedLemkePrivateTests, SelectSubVector) {
// Set the vector.
VectorX<double> v(3);
v << 0, 1, 2;
// One element (the middle one).
VectorX<double> result;
lcp_.SelectSubVector(v, {1}, &result);
EXPECT_EQ(result.size(), 1);
EXPECT_EQ(result[0], 1);
// Two elements (the ends).
lcp_.SelectSubVector(v, {0, 2}, &result);
EXPECT_EQ(result.size(), 2);
EXPECT_EQ(result[0], 0);
EXPECT_EQ(result[1], 2);
// All three elements, not ordered sequentially.
lcp_.SelectSubVector(v, {0, 2, 1}, &result);
EXPECT_EQ(result.size(), 3);
EXPECT_EQ(result[0], 0);
EXPECT_EQ(result[1], 2);
EXPECT_EQ(result[2], 1);
}
// Verifies proper operation of SetSubVector().
TEST_F(UnrevisedLemkePrivateTests, SetSubVector) {
// Construct a zero vector that will be used repeatedly for reinitialization.
VectorX<double> zero(3);
zero << 0, 0, 0;
// Set a single element.
VectorX<double> result = zero;
VectorX<double> v_sub(1);
v_sub << 1;
lcp_.SetSubVector(v_sub, {0}, &result);
EXPECT_EQ(result[0], 1.0);
EXPECT_EQ(result.norm(), 1.0); // Verify no other elements were set.
// Set another single element, this time at the end.
result = zero;
lcp_.SetSubVector(v_sub, {2}, &result);
EXPECT_EQ(result[2], 1.0);
EXPECT_EQ(result.norm(), 1.0); // Verify no other elements were set.
// Set two elements, one at either end.
v_sub = VectorX<double>(2);
v_sub << 2, 3;
lcp_.SetSubVector(v_sub, {0, 2}, &result);
EXPECT_EQ(result[0], 2);
EXPECT_EQ(result[1], 0);
EXPECT_EQ(result[2], 3);
// Set an entire vector, in reverse order.
v_sub = VectorX<double>(3);
v_sub << 1, 2, 3;
lcp_.SetSubVector(v_sub, {2, 1, 0}, &result);
EXPECT_EQ(result[0], 3);
EXPECT_EQ(result[1], 2);
EXPECT_EQ(result[2], 1);
}
// Checks whether ValidateIndices(), which checks that a vector of indices used
// to select a sub-block of a matrix or vector is within range and unique.
TEST_F(UnrevisedLemkePrivateTests, ValidateIndices) {
// Verifies that a proper set of indices works.
const int first_set_size = 3;
EXPECT_TRUE(lcp_.ValidateIndices({0, 1, 2}, first_set_size));
// Verifies that indices need not be in sorted order.
EXPECT_TRUE(lcp_.ValidateIndices({2, 1, 0}, first_set_size));
// Verifies that ValidateIndices() catches a repeated index.
EXPECT_FALSE(lcp_.ValidateIndices({0, 1, 1}, first_set_size));
// Verifies that ValidateIndices() catches indices out of range.
EXPECT_FALSE(lcp_.ValidateIndices({0, 1, 4}, first_set_size));
EXPECT_FALSE(lcp_.ValidateIndices({0, 1, -1}, first_set_size));
// ** Two-index set tests **.
// Verifies that a proper set of indices works.
const int second_set_size = 7;
EXPECT_TRUE(lcp_.ValidateIndices({0, 1, 2}, {3, 4, 5, 6}, first_set_size,
second_set_size));
// Verifies that indices need not be in sorted order.
EXPECT_TRUE(lcp_.ValidateIndices({2, 1, 0}, {6, 5, 4, 3}, first_set_size,
second_set_size));
// Verifies that ValidateIndices() catches a single repeated index.
EXPECT_FALSE(lcp_.ValidateIndices({0, 1, 1}, {3, 4, 5, 6}, first_set_size,
second_set_size));
// Verifies that ValidateIndices() catches indices out of range.
EXPECT_FALSE(lcp_.ValidateIndices({0, 1, 4}, {3, 4, 5, 6}, first_set_size,
second_set_size));
EXPECT_FALSE(lcp_.ValidateIndices({0, 1, -1}, {3, 4, 5, 6}, first_set_size,
second_set_size));
}
// Verifies proper operation of IsEachUnique(), which checks whether LCP
// variables in a vector are unique.
TEST_F(UnrevisedLemkePrivateTests, IsEachUnique) {
// Create two variables with the same index, but one z and one w. These should
// be reported as unique.
EXPECT_TRUE(
lcp_.IsEachUnique({UnrevisedLemkeSolver<double>::LCPVariable(true, 0),
UnrevisedLemkeSolver<double>::LCPVariable(false, 0)}));
// Create two variables with different indices, but both z. These should be
// reported as unique.
EXPECT_TRUE(
lcp_.IsEachUnique({UnrevisedLemkeSolver<double>::LCPVariable(true, 0),
UnrevisedLemkeSolver<double>::LCPVariable(true, 1)}));
// Create two variables with different indices, but both w. These should be
// reported as unique.
EXPECT_TRUE(
lcp_.IsEachUnique({UnrevisedLemkeSolver<double>::LCPVariable(false, 0),
UnrevisedLemkeSolver<double>::LCPVariable(false, 1)}));
// Create two identical variables. These should not be reported as unique.
EXPECT_FALSE(
lcp_.IsEachUnique({UnrevisedLemkeSolver<double>::LCPVariable(false, 0),
UnrevisedLemkeSolver<double>::LCPVariable(false, 0)}));
EXPECT_FALSE(
lcp_.IsEachUnique({UnrevisedLemkeSolver<double>::LCPVariable(true, 1),
UnrevisedLemkeSolver<double>::LCPVariable(true, 1)}));
}
// Tests that pivoting works as expected, using Example 4.7.7 from
// [Cottle 1992], p. 273.
TEST_F(UnrevisedLemkePrivateTests, LemkePivot) {
typedef UnrevisedLemkeSolver<double>::LCPVariable LCPVariable;
// Use the computed zero tolerance.
double zero_tol = lcp_.ComputeZeroTolerance(M_);
// Use the blocking index that Cottle provides us with.
const int blocking_index = 0;
auto blocking = lcp_.dep_variables_[blocking_index];
int driving_index = blocking.index();
std::swap(lcp_.dep_variables_[blocking_index],
lcp_.indep_variables_[kArtificial]);
// Case 1: Driving variable is from 'z'.
// Compute the pivot and verify the result.
VectorX<double> q_bar(3);
VectorX<double> M_bar_col(3);
ASSERT_TRUE(
lcp_.LemkePivot(M_, q_, driving_index, zero_tol, &M_bar_col, &q_bar));
VectorX<double> M_bar_col_expected(3);
VectorX<double> q_bar_expected(3);
M_bar_col_expected << 0, 2, -1;
q_bar_expected << 3, 9, 2;
EXPECT_TRUE(CompareMatrices(M_bar_col, M_bar_col_expected, epsilon,
MatrixCompareType::absolute));
// Case 2: Driving variable is from 'w'. We use the second-to-last tableaux
// from Example 4.4.7.
lcp_.dep_variables_[0] = LCPVariable(true, 3); // artificial variable
lcp_.dep_variables_[1] = LCPVariable(false, 0);
lcp_.dep_variables_[2] = LCPVariable(true, 2);
lcp_.indep_variables_[0] = LCPVariable(false, 1);
lcp_.indep_variables_[1] = LCPVariable(false, 2);
lcp_.indep_variables_[2] = LCPVariable(true, 2);
lcp_.indep_variables_[3] = LCPVariable(true, 0);
driving_index = 0;
ASSERT_TRUE(
lcp_.LemkePivot(M_, q_, driving_index, zero_tol, &M_bar_col, &q_bar));
M_bar_col_expected << 0, -1, -0.5;
q_bar_expected << 1, 5, 3;
EXPECT_TRUE(CompareMatrices(M_bar_col, M_bar_col_expected, epsilon,
MatrixCompareType::absolute));
// Case 3: Pivoting in artificial variable (no M bar column passed in).
// This is equivalent to the last tableaux of Example 4.4.7.
lcp_.dep_variables_[0] = LCPVariable(true, 1);
lcp_.dep_variables_[1] = LCPVariable(false, 0);
lcp_.dep_variables_[2] = LCPVariable(true, 2);
lcp_.indep_variables_[0] = LCPVariable(false, 1);
lcp_.indep_variables_[1] = LCPVariable(false, 2);
lcp_.indep_variables_[2] = LCPVariable(true, 3); // artificial variable
lcp_.indep_variables_[3] = LCPVariable(true, 0);
driving_index = 2;
ASSERT_TRUE(
lcp_.LemkePivot(M_, q_, driving_index, zero_tol, nullptr, &q_bar));
q_bar_expected << 0, 1, 3;
}
TEST_F(UnrevisedLemkePrivateTests, ConstructLemkeSolution) {
typedef UnrevisedLemkeSolver<double>::LCPVariable LCPVariable;
// Set the variables as expected in the last tableaux of Example 4.4.7.
lcp_.dep_variables_[0] = LCPVariable(true, 1);
lcp_.dep_variables_[1] = LCPVariable(false, 0);
lcp_.dep_variables_[2] = LCPVariable(true, 2);
lcp_.indep_variables_[0] = LCPVariable(false, 1);
lcp_.indep_variables_[1] = LCPVariable(false, 2);
lcp_.indep_variables_[2] = LCPVariable(true, 3); // artificial variable
lcp_.indep_variables_[3] = LCPVariable(true, 0);
// Set the location of the artificial variable.
int artificial_index_loc = 2;
// Use the computed zero tolerance.
double zero_tol = lcp_.ComputeZeroTolerance(M_);
// Verify that the operation completes successfully.
VectorX<double> z;
ASSERT_TRUE(
lcp_.ConstructLemkeSolution(M_, q_, artificial_index_loc, zero_tol, &z));
// Verify that the solution is as expected.
VectorX<double> z_expected(3);
z_expected << 0, 1, 3;
EXPECT_TRUE(
CompareMatrices(z, z_expected, epsilon, MatrixCompareType::absolute));
}
// Verifies that DetermineIndexSets() works as expected.
TEST_F(UnrevisedLemkePrivateTests, DetermineIndexSets) {
typedef UnrevisedLemkeSolver<double>::LCPVariable LCPVariable;
// Set indep_variables_ and dep_variables_ as in Equation (1) of [1].
// Note: this equation must be kept up-to-date with equations in [1].
lcp_.dep_variables_[0] = LCPVariable(true, 3); // artificial variable.
lcp_.dep_variables_[1] = LCPVariable(false, 1);
lcp_.dep_variables_[2] = LCPVariable(true, 2);
lcp_.indep_variables_[0] = LCPVariable(false, 0);
lcp_.indep_variables_[1] = LCPVariable(false, 2);
lcp_.indep_variables_[2] = LCPVariable(true, 1);
lcp_.indep_variables_[3] = LCPVariable(true, 0);
// Compute the index sets (uses indep_variables_ and dep_variables_).
lcp_.DetermineIndexSets();
// Verify that the sets have indices we expect (from [1]).
ASSERT_EQ(lcp_.index_sets_.alpha.size(), 2);
EXPECT_EQ(lcp_.index_sets_.alpha[0], 0);
EXPECT_EQ(lcp_.index_sets_.alpha[1], 2);
ASSERT_EQ(lcp_.index_sets_.alpha_prime.size(), 2);
EXPECT_EQ(lcp_.index_sets_.alpha_prime[0], 0);
EXPECT_EQ(lcp_.index_sets_.alpha_prime[1], 1);
ASSERT_EQ(lcp_.index_sets_.beta.size(), 2);
EXPECT_EQ(lcp_.index_sets_.beta[0], 2);
EXPECT_EQ(lcp_.index_sets_.beta[1], 3);
ASSERT_EQ(lcp_.index_sets_.beta_prime.size(), 2);
EXPECT_EQ(lcp_.index_sets_.beta_prime[0], 2);
EXPECT_EQ(lcp_.index_sets_.beta_prime[1], 0);
EXPECT_EQ(lcp_.index_sets_.alpha_bar.size(), 1);
EXPECT_EQ(lcp_.index_sets_.alpha_bar[0], 1);
EXPECT_EQ(lcp_.index_sets_.alpha_bar_prime.size(), 1);
EXPECT_EQ(lcp_.index_sets_.alpha_bar_prime[0], 1);
EXPECT_EQ(lcp_.index_sets_.beta_bar.size(), 2);
EXPECT_EQ(lcp_.index_sets_.beta_bar[0], 0);
EXPECT_EQ(lcp_.index_sets_.beta_bar[1], 1);
EXPECT_EQ(lcp_.index_sets_.beta_bar_prime.size(), 2);
EXPECT_EQ(lcp_.index_sets_.beta_bar_prime[0], 3);
EXPECT_EQ(lcp_.index_sets_.beta_bar_prime[1], 2);
}
// Verifies that finding the index of the complement of an independent variable
// works as expected.
TEST_F(UnrevisedLemkePrivateTests, FindComplementIndex) {
// From the setup of the LCP solver designated by SetUp(), all z variables
// (including the artificial one are independent). The query variable will
// be w1, meaning that we expect the second variable (i.e., z1) to be
// the complement.
typedef UnrevisedLemkeSolver<double>::LCPVariable LCPVariable;
LCPVariable query(false /* w */, 1);
// We have to manually set the mapping from independent variables to their
// indices, since the solver normally maintains this for us.
for (int i = 0; i < static_cast<int>(lcp_.indep_variables_.size()); ++i)
lcp_.indep_variables_indices_[lcp_.indep_variables_[i]] = i;
// Since the indices of the LCP variables from SetUp()
// correspond to their array indices, verification is straightforward.
EXPECT_EQ(lcp_.FindComplementIndex(query), 1);
}
TEST_F(UnrevisedLemkePrivateTests, FindBlockingIndex) {
// Use the computed zero tolerance.
double zero_tol = lcp_.ComputeZeroTolerance(M_);
// Ratios are taken from '1' column (the q vector) in the first tableaux from
// Example 4.3.3. Note that this is the exact procedure used to find the first
// blocking variable, which means we can check our answer against Cottle's.
VectorX<double> col(3);
col << -3, 6, 1;
VectorX<double> ratios = col;
// Index should be the first one.
int blocking_index = -1;
ASSERT_TRUE(lcp_.FindBlockingIndex(zero_tol, col, ratios, &blocking_index));
EXPECT_EQ(blocking_index, 0);
// Repeat the procedure using the second tableaux from Example 4.3.3. We
// now compute the ratios manually using component-wise division of the column
// marked '1' over the column marked 'z1'.
col << 0, 2, -1;
// NOTE: we replace 3.0 / 0 with infinity below to avoid divide by zero
// warnings from the compiler.
const double inf = std::numeric_limits<double>::infinity();
ratios << inf, 9.0 / 2, 2.0 / -1.0;
ASSERT_TRUE(lcp_.FindBlockingIndex(zero_tol, col, ratios, &blocking_index));
EXPECT_EQ(blocking_index, 2); // Blocking index must be the last entry.
// Repeat the procedure, now using strictly positive column entries; no
// blocking index should be possible.
col << 0, 2, 1;
ASSERT_FALSE(lcp_.FindBlockingIndex(zero_tol, col, ratios, &blocking_index));
EXPECT_EQ(blocking_index, -1); // Check that blocking index is invalid.
}
TEST_F(UnrevisedLemkePrivateTests, FindBlockingIndexCycling) {
// Use the computed zero tolerance.
double zero_tol = lcp_.ComputeZeroTolerance(M_);
// We will have the column be the same as the ratios. This means that there
// will be exactly two valid ratios, both identical.
VectorX<double> col(3);
col << -3, -3, 1;
VectorX<double> ratios = col;
// Index should be the first one.
int blocking_index = -1;
ASSERT_TRUE(lcp_.FindBlockingIndex(zero_tol, col, ratios, &blocking_index));
EXPECT_EQ(blocking_index, 0);
// Repeat the procedure again. Index should be the next one.
ASSERT_TRUE(lcp_.FindBlockingIndex(zero_tol, col, ratios, &blocking_index));
EXPECT_EQ(blocking_index, 1);
// If we repeat one more time, there are no indices remaining.
ASSERT_FALSE(lcp_.FindBlockingIndex(zero_tol, col, ratios, &blocking_index));
EXPECT_EQ(blocking_index, -1); // Check that blocking index is invalid.
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/rotation_constraint_test.cc | #include "drake/solvers/rotation_constraint.h"
#include <random>
#include <gtest/gtest.h>
#include "drake/common/symbolic/expression.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/math/random_rotation.h"
#include "drake/math/rotation_matrix.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mosek_solver.h"
#include "drake/solvers/solve.h"
using Eigen::Matrix3d;
using Eigen::Vector3d;
using drake::symbolic::Expression;
using std::sqrt;
namespace drake {
namespace solvers {
namespace {
void AddObjective(MathematicalProgram* prog,
const Eigen::Ref<const MatrixDecisionVariable<3, 3>>& R,
const Eigen::Ref<const Matrix3d>& R_desired) {
const auto R_error = R - R_desired;
// sigma >= |error|_2
MatrixDecisionVariable<1, 1> sigma =
prog->NewContinuousVariables<1, 1>("sigma");
// trace(R_errorᵀ * R_error) = sum_{i,j} R_error(i,j)²
prog->AddLorentzConeConstraint(
sigma(0), (R_error.transpose() * R_error).trace(), 1E-15);
// min sigma
prog->AddCost(sigma(0));
}
// Iterates over possible setting of the RPY limits flag, and for each setting
// evaluates a mesh of points within those limits. This test confirms that
// of the rotation matrices generated from rotations with those limits are
// still feasible after the RPY limits constraints have been applied.
class TestRpyLimitsFixture : public ::testing::TestWithParam<int> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TestRpyLimitsFixture)
TestRpyLimitsFixture() = default;
};
TEST_P(TestRpyLimitsFixture, TestRpyLimits) {
const int limits = GetParam();
// Add brace scope to avoid reflowing all of this code.
{
MathematicalProgram prog;
auto Rvar = NewRotationMatrixVars(&prog);
AddBoundingBoxConstraintsImpliedByRollPitchYawLimits(
&prog, Rvar, static_cast<RollPitchYawLimits>(limits));
auto bb_constraints = prog.bounding_box_constraints();
// Bounds are loose, so just test that feasible points are indeed feasible.
const double rmin = (limits & kRoll_0_to_PI) ? 0
: (limits & kRoll_NegPI_2_to_PI_2) ? -M_PI_2
: -M_PI;
const double rmax = (limits & kRoll_NegPI_2_to_PI_2) ? M_PI_2 : M_PI;
const double pmin = (limits & kPitch_0_to_PI) ? 0
: (limits & kPitch_NegPI_2_to_PI_2) ? -M_PI_2
: -M_PI;
const double pmax = (limits & kPitch_NegPI_2_to_PI_2) ? M_PI_2 : M_PI;
const double ymin = (limits & kYaw_0_to_PI) ? 0
: (limits & kYaw_NegPI_2_to_PI_2) ? -M_PI_2
: -M_PI;
const double ymax = (limits & kYaw_NegPI_2_to_PI_2) ? M_PI_2 : M_PI;
for (double roll = rmin; roll <= rmax; roll += M_PI / 6) {
for (double pitch = pmin; pitch <= pmax; pitch += M_PI / 6) {
for (double yaw = ymin; yaw <= ymax; yaw += M_PI / 6) {
const drake::math::RollPitchYaw<double> rpy(roll, pitch, yaw);
Matrix3d R = rpy.ToMatrix3ViaRotationMatrix();
Eigen::Map<Eigen::Matrix<double, 9, 1>> vecR(R.data(), R.size());
prog.SetInitialGuessForAllVariables(vecR);
for (const auto& b : bb_constraints) {
const Eigen::VectorXd x = prog.EvalBindingAtInitialGuess(b);
const Eigen::VectorXd& lb = b.evaluator()->lower_bound();
const Eigen::VectorXd& ub = b.evaluator()->upper_bound();
for (int i = 0; i < x.size(); i++) {
constexpr double threshold = 1e-15;
EXPECT_GE(x(i), lb(i) - threshold);
EXPECT_LE(x(i), ub(i) + threshold);
}
}
}
}
}
}
}
INSTANTIATE_TEST_SUITE_P(RotationTest, TestRpyLimitsFixture,
::testing::Range(1 << 1, 1 << 7, 2));
// Sets up and solves an optimization:
// <pre>
// min_R sum_{i,j} |R(i,j) - R_desired(i,j)|^2
// </pre>
// where the columans (and rows) of R_desired are outside the unit ball.
// Confirms that the SpectralPSD constraint results in a matrix with columns
// and rows of unit length (or less), and that the actual PSD constraint (typed
// in a very different way here) was satisfied.
GTEST_TEST(RotationTest, TestSpectralPsd) {
MathematicalProgram prog;
auto Rvar = NewRotationMatrixVars(&prog);
// R_desired is outside the unit ball.
AddObjective(&prog, Rvar, 2 * Eigen::Matrix<double, 3, 3>::Ones());
AddRotationMatrixSpectrahedralSdpConstraint(&prog, Rvar);
MathematicalProgramResult result = Solve(prog);
ASSERT_TRUE(result.is_success());
Matrix3d R = result.GetSolution(Rvar);
double tol = 1e-6;
EXPECT_LE(R.col(0).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.col(1).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.col(2).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.row(0).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.row(1).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.row(2).lpNorm<2>(), 1 + tol);
// Check eq 10 in https://arxiv.org/pdf/1403.4914.pdf
Eigen::Matrix4d U;
// clang-format off
// NOLINTNEXTLINE(whitespace/comma)
U << 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),
// NOLINTNEXTLINE(whitespace/comma)
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),
// NOLINTNEXTLINE(whitespace/comma)
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),
// NOLINTNEXTLINE(whitespace/comma)
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);
// clang-format on
const Eigen::Array4d lambda_mag{U.eigenvalues().array().real()};
for (int i = 0; i < 4; i++) EXPECT_GE(lambda_mag(i), -tol);
}
// Sets up and solves an optimization:
// <pre>
// min_R sum_{i,j} |R(i,j) - R_desired(i,j)|^2
// </pre>
// where the columns (and rows) of R_desired are outside the unit ball.
// Confirms that the Orthonormal SOCP constraints result in a solution matrix
// with columns and rows of unit length or less, and that the specific
// orthogonality relaxation implemented by the routine is satisfied.
GTEST_TEST(RotationTest, TestOrthonormal) {
MathematicalProgram prog;
auto Rvar = NewRotationMatrixVars(&prog);
// R_desired is outside the unit ball.
AddObjective(&prog, Rvar, 2 * Eigen::Matrix<double, 3, 3>::Ones());
AddRotationMatrixOrthonormalSocpConstraint(&prog, Rvar);
MathematicalProgramResult result = Solve(prog);
ASSERT_TRUE(result.is_success());
Matrix3d R = result.GetSolution(Rvar);
double tol = 1e-4;
EXPECT_LE(R.col(0).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.col(1).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.col(2).lpNorm<2>(), 1 + tol);
EXPECT_LE(2 * std::abs(R.col(0).dot(R.col(1))),
2 - R.col(0).dot(R.col(0)) - R.col(1).dot(R.col(1)) + tol);
EXPECT_LE(2 * std::abs(R.col(1).dot(R.col(2))),
2 - R.col(1).dot(R.col(1)) - R.col(2).dot(R.col(2)) + tol);
EXPECT_LE(2 * std::abs(R.col(0).dot(R.col(2))),
2 - R.col(0).dot(R.col(0)) - R.col(2).dot(R.col(2)) + tol);
EXPECT_LE(R.row(0).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.row(1).lpNorm<2>(), 1 + tol);
EXPECT_LE(R.row(2).lpNorm<2>(), 1 + tol);
EXPECT_LE(2 * std::abs(R.row(0).dot(R.row(1))),
2 - R.row(0).dot(R.row(0)) - R.row(1).dot(R.row(1)) + tol);
EXPECT_LE(2 * std::abs(R.row(1).dot(R.row(2))),
2 - R.row(0).dot(R.row(0)) - R.row(1).dot(R.row(1)) + tol);
EXPECT_LE(2 * std::abs(R.row(0).dot(R.row(2))),
2 - R.row(0).dot(R.row(0)) - R.row(1).dot(R.row(1)) + tol);
}
} // namespace
} // namespace solvers
} // namespace drake
int main(int argc, char** argv) {
// Ensure that we have the MOSEK license for the entire duration of this test,
// so that we do not have to release and re-acquire the license for every
// test.
auto mosek_license = drake::solvers::MosekSolver::AcquireLicense();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/mixed_integer_rotation_constraint_test.cc | #include "drake/solvers/mixed_integer_rotation_constraint.h"
#include <random>
#include <gtest/gtest.h>
#include "drake/common/symbolic/expression.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/math/gray_code.h"
#include "drake/math/random_rotation.h"
#include "drake/math/rotation_matrix.h"
#include "drake/solvers/gurobi_solver.h"
#include "drake/solvers/integer_optimization_util.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mosek_solver.h"
#include "drake/solvers/rotation_constraint.h"
#include "drake/solvers/solve.h"
using Eigen::Matrix3d;
using Eigen::Vector3d;
using drake::math::RotationMatrixd;
using drake::symbolic::Expression;
using std::sqrt;
namespace drake {
namespace solvers {
namespace {
bool IsFeasibleCheck(
const MathematicalProgram& prog,
const std::shared_ptr<LinearEqualityConstraint>& feasibility_constraint,
const Eigen::Ref<const Matrix3d>& R_sample) {
Eigen::Map<const Eigen::Matrix<double, 9, 1>> R_sample_vec(R_sample.data());
feasibility_constraint->UpdateLowerBound(R_sample_vec);
feasibility_constraint->UpdateUpperBound(R_sample_vec);
return Solve(prog).is_success();
}
class TestMixedIntegerRotationConstraint {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TestMixedIntegerRotationConstraint)
TestMixedIntegerRotationConstraint(
MixedIntegerRotationConstraintGenerator::Approach approach,
int num_intervals_per_half_axis)
: prog_(),
R_(NewRotationMatrixVars(&prog_)),
approach_(approach),
num_intervals_per_half_axis_(num_intervals_per_half_axis),
feasibility_constraint_{prog_
.AddLinearEqualityConstraint(
Eigen::Matrix<double, 9, 9>::Identity(),
Eigen::Matrix<double, 9, 1>::Zero(),
{R_.col(0), R_.col(1), R_.col(2)})
.evaluator()} {}
bool IsFeasible(const Eigen::Ref<const Eigen::Matrix3d>& R_to_check) {
return IsFeasibleCheck(prog_, feasibility_constraint_, R_to_check);
}
bool IsFeasible(const RotationMatrixd& R_to_check) {
return IsFeasible(R_to_check.matrix());
}
void TestExactRotationMatrix() {
// If R is exactly on SO(3), test whether it also satisfies our relaxation.
// Test a few valid rotation matrices.
RotationMatrixd R_test; // Identity matrix.
EXPECT_TRUE(IsFeasible(R_test));
R_test = RotationMatrixd::MakeZRotation(M_PI_4) * R_test;
EXPECT_TRUE(IsFeasible(R_test));
R_test = RotationMatrixd::MakeYRotation(M_PI_4) * R_test;
EXPECT_TRUE(IsFeasible(R_test));
R_test = RotationMatrixd::MakeZRotation(M_PI_2);
EXPECT_TRUE(IsFeasible(R_test));
R_test = RotationMatrixd::MakeZRotation(-M_PI_2);
EXPECT_TRUE(IsFeasible(R_test));
R_test = RotationMatrixd::MakeYRotation(M_PI_2);
EXPECT_TRUE(IsFeasible(R_test));
R_test = RotationMatrixd::MakeYRotation(-M_PI_2);
EXPECT_TRUE(IsFeasible(R_test));
// This one caught a bug (in the loop finding the most conservative linear
// constraint for a given region) during random testing.
Matrix3d R_check;
R_check << 0.17082017792981191, 0.65144498431260445, -0.73921573253413542,
-0.82327804434149443, -0.31781600529013027, -0.47032568342231595,
-0.54132589862048197, 0.68892119955432829, 0.48203096610835455;
EXPECT_TRUE(IsFeasible(R_check));
std::mt19937 generator(41);
for (int i = 0; i < 40; i++) {
R_test = math::UniformlyRandomRotationMatrix(&generator);
EXPECT_TRUE(IsFeasible(R_test));
}
}
void TestInexactRotationMatrix() {
// If R is not exactly on SO(3), test whether it is infeasible for our SO(3)
// relaxation.
// Checks the dot product constraints.
Eigen::Matrix3d R_test =
Matrix3d::Constant(1.0 / sqrt(3.0)); // All rows and columns are
// on the unit sphere.
EXPECT_FALSE(IsFeasible(R_test));
// All in different octants, all unit length, but not orthogonal.
// R.col(0).dot(R.col(1)) = 1/3;
R_test(0, 1) *= -1.0;
R_test(2, 1) *= -1.0;
R_test(0, 2) *= -1.0;
R_test(1, 2) *= -1.0;
// Requires 2 intervals per half axis to catch.
if (num_intervals_per_half_axis_ == 1 &&
approach_ == MixedIntegerRotationConstraintGenerator::Approach::
kBoxSphereIntersection)
EXPECT_TRUE(IsFeasible(R_test));
else
EXPECT_FALSE(IsFeasible(R_test));
// Checks the det(R)=-1 case.
// (only ruled out by the cross-product constraint).
R_test = Matrix3d::Identity();
R_test(2, 2) = -1;
EXPECT_FALSE(IsFeasible(R_test));
R_test = RotationMatrixd::MakeZRotation(M_PI_4).matrix() * R_test;
EXPECT_FALSE(IsFeasible(R_test));
R_test = RotationMatrixd::MakeYRotation(M_PI_4).matrix() * R_test;
EXPECT_FALSE(IsFeasible(R_test));
// Checks a few cases just outside the L1 ball. If we use the formulation
// that replaces the bilinear term with another variable in the McCormick
// envelope, then it should always be infeasible. Otherwise should be
// feasible for num_intervals_per_half_axis_=1, but infeasible for
// num_intervals_per_half_axis_>1.
R_test = RotationMatrixd::MakeYRotation(M_PI_4).matrix();
R_test(2, 0) -= 0.1;
EXPECT_GT(R_test.col(0).lpNorm<1>(), 1.0);
EXPECT_GT(R_test.row(2).lpNorm<1>(), 1.0);
if (num_intervals_per_half_axis_ == 1 &&
approach_ == MixedIntegerRotationConstraintGenerator::Approach::
kBoxSphereIntersection)
EXPECT_TRUE(IsFeasible(R_test));
else
EXPECT_FALSE(IsFeasible(R_test));
}
virtual ~TestMixedIntegerRotationConstraint() = default;
protected:
MathematicalProgram prog_;
MatrixDecisionVariable<3, 3> R_;
MixedIntegerRotationConstraintGenerator::Approach approach_;
int num_intervals_per_half_axis_;
std::shared_ptr<LinearEqualityConstraint> feasibility_constraint_;
};
class TestMixedIntegerRotationConstraintGenerator
: public TestMixedIntegerRotationConstraint,
public ::testing::TestWithParam<
std::tuple<MixedIntegerRotationConstraintGenerator::Approach, int,
IntervalBinning>> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TestMixedIntegerRotationConstraintGenerator)
TestMixedIntegerRotationConstraintGenerator()
: TestMixedIntegerRotationConstraint(std::get<0>(GetParam()),
std::get<1>(GetParam())),
interval_binning_(std::get<2>(GetParam())),
rotation_generator_(approach_, num_intervals_per_half_axis_,
interval_binning_),
ret(rotation_generator_.AddToProgram(R_, &prog_)) {}
~TestMixedIntegerRotationConstraintGenerator() = default;
protected:
IntervalBinning interval_binning_;
MixedIntegerRotationConstraintGenerator rotation_generator_;
MixedIntegerRotationConstraintGenerator::ReturnType ret;
};
TEST_P(TestMixedIntegerRotationConstraintGenerator, TestConstructor) {
EXPECT_TRUE(CompareMatrices(
rotation_generator_.phi(),
Eigen::VectorXd::LinSpaced(2 * num_intervals_per_half_axis_ + 1, -1, 1),
1E-12));
EXPECT_TRUE(CompareMatrices(
rotation_generator_.phi_nonnegative(),
Eigen::VectorXd::LinSpaced(num_intervals_per_half_axis_ + 1, 0, 1),
1E-12));
}
TEST_P(TestMixedIntegerRotationConstraintGenerator, TestBinaryAssignment) {
const RotationMatrixd R_test = RotationMatrixd::MakeZRotation(0.1);
auto b_constraint = prog_.AddBoundingBoxConstraint(0, 0, ret.B_[0][0]);
auto UpdateBConstraint =
[&b_constraint](const Eigen::Ref<const Eigen::VectorXd>& b_val) {
b_constraint.evaluator()->UpdateLowerBound(b_val);
b_constraint.evaluator()->UpdateUpperBound(b_val);
};
switch (interval_binning_) {
case IntervalBinning::kLinear: {
switch (num_intervals_per_half_axis_) {
case 1:
UpdateBConstraint(Eigen::Vector2d(0, 1));
EXPECT_TRUE(IsFeasible(R_test));
UpdateBConstraint(Eigen::Vector2d(1, 0));
EXPECT_FALSE(IsFeasible(R_test));
break;
case 2:
UpdateBConstraint(Eigen::Vector4d(0, 0, 0, 1));
EXPECT_TRUE(IsFeasible(R_test));
UpdateBConstraint(Eigen::Vector4d(0, 0, 1, 0));
EXPECT_FALSE(IsFeasible(R_test));
break;
default:
GTEST_FAIL() << "Unsuppored num_intervals_per_half_axis_.";
}
break;
}
case IntervalBinning::kLogarithmic: {
switch (num_intervals_per_half_axis_) {
case 1: {
UpdateBConstraint(Vector1d(1));
EXPECT_TRUE(IsFeasible(R_test));
UpdateBConstraint(Vector1d(0));
EXPECT_FALSE(IsFeasible(R_test));
break;
}
case 2: {
UpdateBConstraint(Eigen::Vector2d(1, 0));
EXPECT_TRUE(IsFeasible(R_test));
UpdateBConstraint(Eigen::Vector2d(0, 1));
EXPECT_FALSE(IsFeasible(R_test));
break;
}
default:
throw std::runtime_error("Unsupported num_intervals_per_half_axis_.");
}
break;
}
}
}
TEST_P(TestMixedIntegerRotationConstraintGenerator, ExactRotationMatrix) {
TestExactRotationMatrix();
}
TEST_P(TestMixedIntegerRotationConstraintGenerator, InexactRotationMatrix) {
TestInexactRotationMatrix();
}
INSTANTIATE_TEST_SUITE_P(
RotationTest, TestMixedIntegerRotationConstraintGenerator,
::testing::Combine(
::testing::ValuesIn<
std::vector<MixedIntegerRotationConstraintGenerator::Approach>>(
{MixedIntegerRotationConstraintGenerator::Approach::
kBilinearMcCormick,
MixedIntegerRotationConstraintGenerator::Approach::
kBoxSphereIntersection,
MixedIntegerRotationConstraintGenerator::Approach::kBoth}),
::testing::ValuesIn<std::vector<int>>({1, 2}),
::testing::ValuesIn<std::vector<IntervalBinning>>(
{IntervalBinning::kLinear, IntervalBinning::kLogarithmic})));
class TestRotationMatrixBoxSphereIntersection
: public TestMixedIntegerRotationConstraint,
public ::testing::TestWithParam<int> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TestRotationMatrixBoxSphereIntersection)
TestRotationMatrixBoxSphereIntersection()
: TestMixedIntegerRotationConstraint(
MixedIntegerRotationConstraintGenerator::Approach::
kBoxSphereIntersection,
GetParam()) {
AddRotationMatrixBoxSphereIntersectionMilpConstraints(
R_, num_intervals_per_half_axis_, &prog_);
}
~TestRotationMatrixBoxSphereIntersection() override {}
};
TEST_P(TestRotationMatrixBoxSphereIntersection, ExactRotationMatrix) {
TestExactRotationMatrix();
}
TEST_P(TestRotationMatrixBoxSphereIntersection, InexactRotationMatrix) {
TestInexactRotationMatrix();
}
INSTANTIATE_TEST_SUITE_P(RotationTest, TestRotationMatrixBoxSphereIntersection,
::testing::ValuesIn<std::vector<int>>({1, 2}));
// Make sure that no two row or column vectors in R, which satisfies the
// mixed-integer relaxation, can lie in either the same or the opposite orthant.
class TestOrthant
: public ::testing::TestWithParam<
std::tuple<int, int, bool, std::pair<int, int>, bool,
MixedIntegerRotationConstraintGenerator::Approach>> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TestOrthant)
TestOrthant() : prog_(), R_(NewRotationMatrixVars(&prog_)) {
const int num_bin = std::get<0>(GetParam());
const int orthant = std::get<1>(GetParam());
const bool is_row_vector = std::get<2>(GetParam());
const int idx0 = std::get<3>(GetParam()).first;
const int idx1 = std::get<3>(GetParam()).second;
const bool is_same_orthant = std::get<4>(GetParam());
const auto approach = std::get<5>(GetParam());
DRAKE_DEMAND(idx0 != idx1);
DRAKE_DEMAND(idx0 >= 0);
DRAKE_DEMAND(idx1 >= 0);
DRAKE_DEMAND(idx0 <= 2);
DRAKE_DEMAND(idx1 <= 2);
MixedIntegerRotationConstraintGenerator rotation_generator(
approach, num_bin, IntervalBinning::kLinear);
rotation_generator.AddToProgram(R_, &prog_);
MatrixDecisionVariable<3, 3> R_hat = R_;
if (is_row_vector) {
R_hat = R_.transpose();
}
Eigen::Vector3d vec0_lb =
Eigen::Vector3d::Constant(-std::numeric_limits<double>::infinity());
Eigen::Vector3d vec0_ub =
Eigen::Vector3d::Constant(std::numeric_limits<double>::infinity());
// positive or negative x axis?
if (orthant & (1 << 2)) {
vec0_lb(0) = 1E-3;
} else {
vec0_ub(0) = -1E-3;
}
// positive or negative y axis?
if (orthant & (1 << 1)) {
vec0_lb(1) = 1E-3;
} else {
vec0_ub(1) = -1E-3;
}
// positive or negative z axis?
if (orthant & (1 << 0)) {
vec0_lb(2) = 1E-3;
} else {
vec0_ub(2) = -1E-3;
}
// If we want to verify vec1 and vec2 cannot be in the SAME orthant,
// then set vec1_lb = vec0_lb, vec1_ub = vec0_ub;
// otherwise if we want to verify vec1 and vec2 cannot be in the OPPOSITE
// orthant, then set vec1_lb = -vec1_ub, vec1_ub = -vec0_lb.
Eigen::Vector3d vec1_lb = vec0_lb;
Eigen::Vector3d vec1_ub = vec0_ub;
if (!is_same_orthant) {
vec1_lb = -vec0_ub;
vec1_ub = -vec0_lb;
}
prog_.AddBoundingBoxConstraint(vec0_lb, vec0_ub, R_hat.col(idx0));
prog_.AddBoundingBoxConstraint(vec1_lb, vec1_ub, R_hat.col(idx1));
}
~TestOrthant() override {}
protected:
MathematicalProgram prog_;
MatrixDecisionVariable<3, 3> R_;
};
TEST_P(TestOrthant, test) {
GurobiSolver gurobi_solver;
if (gurobi_solver.available()) {
MathematicalProgramResult result;
gurobi_solver.Solve(prog_, {}, {}, &result);
SolutionResult sol_result = result.get_solution_result();
// Since no two row or column vectors in R can lie in either the same of the
// opposite orthant, the program should be infeasible.
EXPECT_TRUE(sol_result == SolutionResult::kInfeasibleOrUnbounded ||
sol_result == SolutionResult::kInfeasibleConstraints);
}
}
std::array<std::pair<int, int>, 3> vector_indices() {
std::array<std::pair<int, int>, 3> idx = {{{0, 1}, {0, 2}, {1, 2}}};
return idx;
}
INSTANTIATE_TEST_SUITE_P(
RotationTest, TestOrthant,
::testing::Combine(
::testing::ValuesIn<std::vector<int>>(
{1}), // # of intervals per half axis
::testing::ValuesIn<std::vector<int>>({0, 1, 2, 3, 4, 5, 6,
7}), // orthant index
::testing::ValuesIn<std::vector<bool>>(
{false, true}), // row vector or column vector
::testing::ValuesIn<std::array<std::pair<int, int>, 3>>(
vector_indices()), // vector indices
::testing::ValuesIn<std::vector<bool>>(
{false, true}), // same or opposite orthant
::testing::ValuesIn<
std::vector<MixedIntegerRotationConstraintGenerator::Approach>>(
{MixedIntegerRotationConstraintGenerator::Approach::
kBoxSphereIntersection,
MixedIntegerRotationConstraintGenerator::Approach::
kBoxSphereIntersection}))); // box-sphere intersection or
// bilinear McCormick.
} // namespace
} // namespace solvers
} // namespace drake
int main(int argc, char** argv) {
// Ensure that we have the MOSEK license for the entire duration of this test,
// so that we do not have to release and re-acquire the license for every
// test.
auto mosek_license = drake::solvers::MosekSolver::AcquireLicense();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/scs_solver_test.cc | #include "drake/solvers/scs_solver.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/test/exponential_cone_program_examples.h"
#include "drake/solvers/test/l2norm_cost_examples.h"
#include "drake/solvers/test/linear_program_examples.h"
#include "drake/solvers/test/mathematical_program_test_util.h"
#include "drake/solvers/test/quadratic_program_examples.h"
#include "drake/solvers/test/second_order_cone_program_examples.h"
#include "drake/solvers/test/semidefinite_program_examples.h"
#include "drake/solvers/test/sos_examples.h"
namespace drake {
namespace solvers {
namespace test {
namespace {
// Our ScsSolver binding uses `eps = 1e-5` by default. For testing, we'll
// allow for some small cumulative error beyond that.
constexpr double kTol = 1e-3;
} // namespace
GTEST_TEST(LinearProgramTest, Test0) {
// Test a linear program with only equality constraint.
// min x(0) + 2 * x(1)
// s.t x(0) + x(1) = 2
// The problem is unbounded.
MathematicalProgram prog;
const auto x = prog.NewContinuousVariables<2>("x");
prog.AddLinearCost(x(0) + 2 * x(1));
prog.AddLinearConstraint(x(0) + x(1) == 2);
ScsSolver solver;
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded);
}
// Now add the constraint x(1) <= 1. The problem is
// min x(0) + 2 * x(1)
// s.t x(0) + x(1) = 2
// x(1) <= 1
// the problem should still be unbounded.
prog.AddBoundingBoxConstraint(-std::numeric_limits<double>::infinity(), 1,
x(1));
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded);
}
// Now add the constraint x(0) <= 5. The problem is
// min x(0) + 2x(1)
// s.t x(0) + x(1) = 2
// x(1) <= 1
// x(0) <= 5
// the problem should be feasible. The optimal cost is -1, with x = (5, -3)
prog.AddBoundingBoxConstraint(-std::numeric_limits<double>::infinity(), 5,
x(0));
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
EXPECT_NEAR(result.get_optimal_cost(), -1, kTol);
const Eigen::Vector2d x_expected(5, -3);
EXPECT_TRUE(CompareMatrices(result.GetSolution(x), x_expected, kTol,
MatrixCompareType::absolute));
}
// Now change the cost to 3x(0) - x(1) + 5, and add the constraint 2 <= x(0)
// The problem is
// min 3x(0) - x(1) + 5
// s.t x(0) + x(1) = 2
// 2 <= x(0) <= 5
// x(1) <= 1
// The optimal cost is 11, the optimal solution is x = (2, 0)
prog.AddLinearCost(2 * x(0) - 3 * x(1) + 5);
prog.AddBoundingBoxConstraint(2, 6, x(0));
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
EXPECT_NEAR(result.get_optimal_cost(), 11, kTol);
const Eigen::Vector2d x_expected(2, 0);
EXPECT_TRUE(CompareMatrices(result.GetSolution(x), x_expected, kTol,
MatrixCompareType::absolute));
}
}
GTEST_TEST(LinearProgramTest, Test1) {
// Test a linear program with only equality constraints
// min x(0) + 2 * x(1)
// s.t x(0) + x(1) = 1
// 2x(0) + x(1) = 2
// x(0) - 2x(1) = 3
// This problem is infeasible.
MathematicalProgram prog;
const auto x = prog.NewContinuousVariables<2>("x");
prog.AddLinearCost(x(0) + 2 * x(1));
prog.AddLinearEqualityConstraint(x(0) + x(1) == 1 && 2 * x(0) + x(1) == 2);
prog.AddLinearEqualityConstraint(x(0) - 2 * x(1) == 3);
ScsSolver scs_solver;
if (scs_solver.available()) {
auto result = scs_solver.Solve(prog, {}, {});
EXPECT_EQ(result.get_solution_result(),
SolutionResult::kInfeasibleConstraints);
}
}
GTEST_TEST(LinearProgramTest, Test2) {
// Test a linear program with bounding box, linear equality and inequality
// constraints
// min x(0) + 2 * x(1) + 3 * x(2) + 2
// s.t x(0) + x(1) = 2
// x(0) + 2x(2) = 3
// -2 <= x(0) + 4x(1) <= 10
// -5 <= x(1) + 2x(2) <= 9
// -x(0) + 2x(2) <= 7
// -x(1) + 3x(2) >= -10
// x(0) <= 10
// 1 <= x(2) <= 9
// The optimal cost is 8, with x = (1, 1, 1)
MathematicalProgram prog;
const auto x = prog.NewContinuousVariables<3>();
prog.AddLinearCost(x(0) + 2 * x(1) + 3 * x(2) + 2);
prog.AddLinearEqualityConstraint(x(0) + x(1) == 2 && x(0) + 2 * x(2) == 3);
Eigen::Matrix<double, 3, 3> A;
// clang-format off
A << 1, 4, 0,
0, 1, 2,
-1, 0, 2;
// clang-format on
prog.AddLinearConstraint(
A, Eigen::Vector3d(-2, -5, -std::numeric_limits<double>::infinity()),
Eigen::Vector3d(10, 9, 7), x);
prog.AddLinearConstraint(-x(1) + 3 * x(2) >= -10);
prog.AddBoundingBoxConstraint(-std::numeric_limits<double>::infinity(), 10,
x(0));
prog.AddBoundingBoxConstraint(1, 9, x(2));
ScsSolver scs_solver;
if (scs_solver.available()) {
auto result = scs_solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
EXPECT_NEAR(result.get_optimal_cost(), 8, kTol);
EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector3d(1, 1, 1),
kTol, MatrixCompareType::absolute));
}
}
TEST_P(LinearProgramTest, TestLP) {
ScsSolver solver;
prob()->RunProblem(&solver);
}
INSTANTIATE_TEST_SUITE_P(
SCSTest, LinearProgramTest,
::testing::Combine(::testing::ValuesIn(linear_cost_form()),
::testing::ValuesIn(linear_constraint_form()),
::testing::ValuesIn(linear_problems())));
TEST_F(InfeasibleLinearProgramTest0, TestInfeasible) {
ScsSolver solver;
if (solver.available()) {
auto result = solver.Solve(*prog_, {}, {});
EXPECT_EQ(result.get_solution_result(),
SolutionResult::kInfeasibleConstraints);
EXPECT_EQ(result.get_optimal_cost(),
MathematicalProgram::kGlobalInfeasibleCost);
}
}
TEST_F(UnboundedLinearProgramTest0, TestUnbounded) {
ScsSolver solver;
if (solver.available()) {
auto result = solver.Solve(*prog_, {}, {});
EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded);
EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kUnboundedCost);
EXPECT_TRUE(result.GetSolution(prog_->decision_variables())
.array()
.isFinite()
.all());
}
}
TEST_F(DuplicatedVariableLinearProgramTest1, Test) {
ScsSolver solver;
if (solver.is_available()) {
CheckSolution(solver, std::nullopt, 1E-5);
}
}
GTEST_TEST(TestLPDualSolution1, Test) {
ScsSolver solver;
if (solver.is_available()) {
TestLPDualSolution1(solver, kTol);
}
}
GTEST_TEST(TestLPDualSolution2, Test) {
ScsSolver solver;
if (solver.available()) {
TestLPDualSolution2(solver, kTol);
}
}
GTEST_TEST(TestLPDualSolution3, Test) {
ScsSolver solver;
if (solver.available()) {
TestLPDualSolution3(solver, kTol);
}
}
GTEST_TEST(TestLPDualSolution4, Test) {
ScsSolver solver;
if (solver.available()) {
TestLPDualSolution4(solver, kTol);
}
}
GTEST_TEST(TestLPDualSolution5, Test) {
ScsSolver solver;
if (solver.available()) {
TestLPDualSolution5(solver, kTol);
}
}
TEST_P(TestEllipsoidsSeparation, TestSOCP) {
ScsSolver scs_solver;
if (scs_solver.available()) {
SolveAndCheckSolution(scs_solver, {}, kTol);
}
}
INSTANTIATE_TEST_SUITE_P(
SCSTest, TestEllipsoidsSeparation,
::testing::ValuesIn(GetEllipsoidsSeparationProblems()));
TEST_P(TestQPasSOCP, TestSOCP) {
ScsSolver scs_solver;
if (scs_solver.available()) {
SolveAndCheckSolution(scs_solver, kTol);
}
}
INSTANTIATE_TEST_SUITE_P(SCSTest, TestQPasSOCP,
::testing::ValuesIn(GetQPasSOCPProblems()));
TEST_P(TestFindSpringEquilibrium, TestSOCP) {
ScsSolver scs_solver;
if (scs_solver.available()) {
SolveAndCheckSolution(scs_solver, {}, kTol);
}
}
INSTANTIATE_TEST_SUITE_P(
SCSTest, TestFindSpringEquilibrium,
::testing::ValuesIn(GetFindSpringEquilibriumProblems()));
GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem1) {
MaximizeGeometricMeanTrivialProblem1 prob;
ScsSolver solver;
if (solver.available()) {
const auto result = solver.Solve(prob.prog(), {}, {});
// Practically I observe SCS requires looser tolerance for this test. I
// don't know why.
prob.CheckSolution(result, 3 * kTol);
}
}
GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem2) {
MaximizeGeometricMeanTrivialProblem2 prob;
ScsSolver solver;
if (solver.available()) {
const auto result = solver.Solve(prob.prog(), {}, {});
prob.CheckSolution(result, kTol);
}
}
GTEST_TEST(TestSOCP, SmallestEllipsoidCoveringProblem) {
ScsSolver solver;
SolveAndCheckSmallestEllipsoidCoveringProblems(solver, {}, kTol);
}
GTEST_TEST(TestSOCP, LorentzConeDual) {
ScsSolver solver;
SolverOptions solver_options;
TestSocpDualSolution1(solver, solver_options, kTol);
}
GTEST_TEST(TestSOCP, RotatedLorentzConeDual) {
ScsSolver solver;
SolverOptions solver_options;
TestSocpDualSolution2(solver, solver_options, kTol);
}
GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable1) {
ScsSolver solver;
TestSocpDuplicatedVariable1(solver, std::nullopt, 1E-6);
}
GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable2) {
ScsSolver solver;
TestSocpDuplicatedVariable2(solver, std::nullopt, 1E-6);
}
GTEST_TEST(TestL2NormCost, ShortestDistanceToThreePoints) {
ScsSolver solver;
ShortestDistanceToThreePoints tester{};
tester.CheckSolution(solver, std::nullopt, 1E-4);
}
GTEST_TEST(TestL2NormCost, ShortestDistanceFromCylinderToPoint) {
ScsSolver solver;
ShortestDistanceFromCylinderToPoint tester{};
tester.CheckSolution(solver);
}
GTEST_TEST(TestL2NormCost, ShortestDistanceFromPlaneToTwoPoints) {
ScsSolver solver;
ShortestDistanceFromPlaneToTwoPoints tester{};
tester.CheckSolution(solver, std::nullopt, 5E-4);
}
TEST_P(QuadraticProgramTest, TestQP) {
ScsSolver solver;
if (solver.available()) {
prob()->RunProblem(&solver);
}
}
INSTANTIATE_TEST_SUITE_P(
ScsTest, QuadraticProgramTest,
::testing::Combine(::testing::ValuesIn(quadratic_cost_form()),
::testing::ValuesIn(linear_constraint_form()),
::testing::ValuesIn(quadratic_problems())));
GTEST_TEST(QPtest, TestUnitBallExample) {
ScsSolver solver;
if (solver.available()) {
TestQPonUnitBallExample(solver);
}
}
GTEST_TEST(TestDuplicatedVariableQuadraticProgram, Test) {
ScsSolver solver;
if (solver.available()) {
TestDuplicatedVariableQuadraticProgram(solver, 1E-5);
}
}
GTEST_TEST(TestSemidefiniteProgram, TrivialSDP) {
ScsSolver scs_solver;
if (scs_solver.available()) {
TestTrivialSDP(scs_solver, kTol);
}
}
GTEST_TEST(TestSemidefiniteProgram, CommonLyapunov) {
ScsSolver scs_solver;
if (scs_solver.available()) {
FindCommonLyapunov(scs_solver, {}, kTol);
}
}
GTEST_TEST(TestSemidefiniteProgram, OuterEllipsoid) {
ScsSolver scs_solver;
if (scs_solver.available()) {
FindOuterEllipsoid(scs_solver, {}, kTol);
}
}
GTEST_TEST(TestSemidefiniteProgram, EigenvalueProblem) {
ScsSolver scs_solver;
if (scs_solver.available()) {
SolveEigenvalueProblem(scs_solver, {}, kTol);
}
}
GTEST_TEST(TestSemidefiniteProgram, SolveSDPwithSecondOrderConeExample1) {
ScsSolver scs_solver;
if (scs_solver.available()) {
SolveSDPwithSecondOrderConeExample1(scs_solver, kTol);
}
}
GTEST_TEST(TestSemidefiniteProgram, SolveSDPwithSecondOrderConeExample2) {
ScsSolver scs_solver;
if (scs_solver.available()) {
SolveSDPwithSecondOrderConeExample2(scs_solver, kTol);
}
}
GTEST_TEST(TestSemidefiniteProgram, SolveSDPwithOverlappingVariables) {
ScsSolver scs_solver;
if (scs_solver.available()) {
SolveSDPwithOverlappingVariables(scs_solver, kTol);
}
}
GTEST_TEST(TestExponentialConeProgram, ExponentialConeTrivialExample) {
ScsSolver solver;
if (solver.available()) {
// Currently we don't support retrieving dual solution from SCS yet.
ExponentialConeTrivialExample(solver, kTol, false);
}
}
GTEST_TEST(TestExponentialConeProgram, MinimizeKLDivengence) {
ScsSolver scs_solver;
if (scs_solver.available()) {
MinimizeKLDivergence(scs_solver, kTol);
}
}
GTEST_TEST(TestExponentialConeProgram, MinimalEllipsoidConveringPoints) {
ScsSolver scs_solver;
if (scs_solver.available()) {
MinimalEllipsoidCoveringPoints(scs_solver, kTol);
}
}
GTEST_TEST(TestExponentialConeProgram, MatrixLogDeterminantLower) {
ScsSolver scs_solver;
if (scs_solver.available()) {
MatrixLogDeterminantLower(scs_solver, kTol);
}
}
GTEST_TEST(TestScs, SetOptions) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
prog.AddLinearConstraint(x(0) + x(1) >= 1);
prog.AddQuadraticCost(x(0) * x(0) + x(1) * x(1));
ScsSolver solver;
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
const int iter_solve = result.get_solver_details<ScsSolver>().iter;
const int solved_status = result.get_solver_details<ScsSolver>().scs_status;
DRAKE_DEMAND(iter_solve >= 2);
SolverOptions solver_options;
// Now we require that SCS can only take half of the iterations before
// termination. We expect now SCS cannot solve the problem.
solver_options.SetOption(solver.solver_id(), "max_iters", iter_solve / 2);
solver.Solve(prog, {}, solver_options, &result);
EXPECT_NE(result.get_solver_details<ScsSolver>().scs_status, solved_status);
}
}
GTEST_TEST(TestScs, UnivariateQuarticSos) {
UnivariateQuarticSos dut;
ScsSolver solver;
if (solver.available()) {
const auto result = solver.Solve(dut.prog());
dut.CheckResult(result, kTol);
}
}
GTEST_TEST(TestScs, BivariateQuarticSos) {
BivariateQuarticSos dut;
ScsSolver solver;
if (solver.available()) {
const auto result = solver.Solve(dut.prog());
dut.CheckResult(result, kTol);
}
}
GTEST_TEST(TestScs, SimpleSos1) {
SimpleSos1 dut;
ScsSolver solver;
if (solver.available()) {
const auto result = solver.Solve(dut.prog());
dut.CheckResult(result, kTol);
}
}
GTEST_TEST(TestScs, MotzkinPolynomial) {
MotzkinPolynomial dut;
ScsSolver solver;
if (solver.is_available()) {
const auto result = solver.Solve(dut.prog());
dut.CheckResult(result, kTol);
}
}
GTEST_TEST(TestScs, UnivariateNonnegative1) {
UnivariateNonnegative1 dut;
ScsSolver solver;
if (solver.is_available()) {
const auto result = solver.Solve(dut.prog());
dut.CheckResult(result, kTol);
}
}
GTEST_TEST(TestScs, TestNonconvexQP) {
ScsSolver solver;
if (solver.is_available()) {
TestNonconvexQP(solver, true);
}
}
GTEST_TEST(TestScs, TestVerbose) {
// This is a code coverage test, not a functional test. If the code that
// handles verbosity options has a segfault or always throws an exception,
// then this would catch it.
MathematicalProgram prog{};
auto x = prog.NewContinuousVariables<2>();
prog.AddLinearConstraint(x[0] + x[1] == 1);
prog.AddLinearCost(x[0]);
ScsSolver solver;
if (solver.is_available()) {
SolverOptions options;
options.SetOption(CommonSolverOption::kPrintToConsole, 1);
MathematicalProgramResult result;
solver.Solve(prog, std::nullopt, options, &result);
// Set the common option to no print, but SCS option to print. The more
// specific SCS option should dominate over the common option, and SCS
// should print to the console.
options.SetOption(CommonSolverOption::kPrintToConsole, 0);
options.SetOption(solver.id(), "verbose", 1);
solver.Solve(prog, std::nullopt, options, &result);
}
}
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/choose_best_solver_test.cc | #include "drake/solvers/choose_best_solver.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.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/mathematical_program_result.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 {
class ChooseBestSolverTest : public ::testing::Test {
public:
ChooseBestSolverTest()
: prog_{},
x_{prog_.NewContinuousVariables<3>()},
clarabel_solver_{std::make_unique<ClarabelSolver>()},
clp_solver_{std::make_unique<ClpSolver>()},
linear_system_solver_{std::make_unique<LinearSystemSolver>()},
equality_constrained_qp_solver_{
std::make_unique<EqualityConstrainedQPSolver>()},
mosek_solver_{std::make_unique<MosekSolver>()},
gurobi_solver_{std::make_unique<GurobiSolver>()},
osqp_solver_{std::make_unique<OsqpSolver>()},
moby_lcp_solver_{std::make_unique<MobyLCPSolver<double>>()},
snopt_solver_{std::make_unique<SnoptSolver>()},
ipopt_solver_{std::make_unique<IpoptSolver>()},
nlopt_solver_{std::make_unique<NloptSolver>()},
csdp_solver_{std::make_unique<CsdpSolver>()},
scs_solver_{std::make_unique<ScsSolver>()} {}
~ChooseBestSolverTest() {}
void CheckBestSolver(const SolverId& expected_solver_id) const {
const SolverId solver_id = ChooseBestSolver(prog_);
EXPECT_EQ(solver_id, expected_solver_id);
// Ensure GetKnownSolvers is comprehensive.
EXPECT_TRUE(GetKnownSolvers().contains(solver_id));
}
void CheckMakeSolver(const SolverInterface& solver) const {
auto new_solver = MakeSolver(solver.solver_id());
EXPECT_EQ(new_solver->solver_id(), solver.solver_id());
// Ensure GetKnownSolvers is comprehensive.
EXPECT_TRUE(GetKnownSolvers().contains(solver.solver_id()));
}
void CheckBestSolver(const std::vector<SolverInterface*>& solvers) {
bool is_any_solver_available = false;
for (const auto solver : solvers) {
if (solver->available()) {
is_any_solver_available = true;
break;
}
}
if (!is_any_solver_available) {
DRAKE_EXPECT_THROWS_MESSAGE(
ChooseBestSolver(prog_),
"There is no available solver for the optimization program");
} else {
const SolverId solver_id = ChooseBestSolver(prog_);
for (const auto solver : solvers) {
if (solver->available()) {
EXPECT_EQ(solver_id, solver->solver_id());
return;
}
}
}
}
protected:
MathematicalProgram prog_;
VectorDecisionVariable<3> x_;
std::unique_ptr<ClarabelSolver> clarabel_solver_;
std::unique_ptr<ClpSolver> clp_solver_;
std::unique_ptr<LinearSystemSolver> linear_system_solver_;
std::unique_ptr<EqualityConstrainedQPSolver> equality_constrained_qp_solver_;
std::unique_ptr<MosekSolver> mosek_solver_;
std::unique_ptr<GurobiSolver> gurobi_solver_;
std::unique_ptr<OsqpSolver> osqp_solver_;
std::unique_ptr<MobyLCPSolver<double>> moby_lcp_solver_;
std::unique_ptr<SnoptSolver> snopt_solver_;
std::unique_ptr<IpoptSolver> ipopt_solver_;
std::unique_ptr<NloptSolver> nlopt_solver_;
std::unique_ptr<CsdpSolver> csdp_solver_;
std::unique_ptr<ScsSolver> scs_solver_;
};
TEST_F(ChooseBestSolverTest, LinearSystemSolver) {
prog_.AddLinearEqualityConstraint(x_(0) + x_(1), 1);
CheckBestSolver(LinearSystemSolver::id());
}
TEST_F(ChooseBestSolverTest, EqualityConstrainedQPSolver) {
prog_.AddQuadraticCost(x_(0) * x_(0));
prog_.AddLinearEqualityConstraint(x_(0) + x_(1), 1);
CheckBestSolver(EqualityConstrainedQPSolver::id());
}
void CheckGetAvailableSolvers(const MathematicalProgram& prog) {
const ProgramType prog_type = GetProgramType(prog);
const std::vector<SolverId> available_ids = GetAvailableSolvers(prog_type);
const auto known_solvers = GetKnownSolvers();
for (const auto& available_id : available_ids) {
EXPECT_TRUE(known_solvers.contains(available_id));
std::unique_ptr<SolverInterface> solver = MakeSolver(available_id);
EXPECT_TRUE(solver->available());
EXPECT_TRUE(solver->enabled());
EXPECT_TRUE(solver->AreProgramAttributesSatisfied(prog));
}
// Now find out the available solvers that can solve this program. These
// solvers should be in available_ids.
const std::unordered_set<SolverId> available_id_set(available_ids.begin(),
available_ids.end());
for (const auto& solver_id : known_solvers) {
const auto solver = MakeSolver(solver_id);
if (solver->available() && solver->enabled() &&
solver->AreProgramAttributesSatisfied(prog)) {
// CLP can solve some QP, but not all of them. So we don't include CLP in
// GetAvailableSolvers(kQP).
if (solver_id == ClpSolver::id() && prog_type == ProgramType::kQP) {
continue;
} else if ((solver_id == SnoptSolver::id() ||
solver_id == IpoptSolver::id() ||
solver_id == NloptSolver::id()) &&
(prog_type == ProgramType::kQuadraticCostConicConstraint)) {
// For quadratic cost with conic constraint programs, the nonlinear
// solvers (snopt/ipopt/nlopt) can solve the problem, but we don't
// recommend using these solvers, hence they are not included in
// GetAvailableSolvers(kQuadraticCostConicConstraint).
continue;
} else {
EXPECT_TRUE(available_id_set.contains(solver_id));
}
}
}
}
TEST_F(ChooseBestSolverTest, LPsolver) {
prog_.AddLinearEqualityConstraint(x_(0) + 3 * x_(1) == 3);
CheckBestSolver(LinearSystemSolver::id());
prog_.AddLinearConstraint(x_(0) + 2 * x_(1) >= 1);
prog_.AddLinearCost(x_(0) + x_(1));
CheckBestSolver({gurobi_solver_.get(), mosek_solver_.get(), clp_solver_.get(),
clarabel_solver_.get(), snopt_solver_.get(),
ipopt_solver_.get(), nlopt_solver_.get(), csdp_solver_.get(),
scs_solver_.get()});
CheckGetAvailableSolvers(prog_);
}
TEST_F(ChooseBestSolverTest, QPsolver) {
prog_.AddLinearConstraint(x_(0) + x_(1) >= 1);
prog_.AddQuadraticCost(x_(0) * x_(0));
CheckBestSolver({mosek_solver_.get(), gurobi_solver_.get(),
clarabel_solver_.get(), osqp_solver_.get(),
snopt_solver_.get(), ipopt_solver_.get(),
nlopt_solver_.get(), scs_solver_.get()});
CheckGetAvailableSolvers(prog_);
}
TEST_F(ChooseBestSolverTest, LorentzCone) {
prog_.AddLorentzConeConstraint(x_.cast<symbolic::Expression>());
CheckBestSolver({mosek_solver_.get(), gurobi_solver_.get(),
clarabel_solver_.get(), csdp_solver_.get(),
scs_solver_.get(), snopt_solver_.get(), ipopt_solver_.get(),
nlopt_solver_.get()});
prog_.AddRotatedLorentzConeConstraint(x_.cast<symbolic::Expression>());
CheckBestSolver({mosek_solver_.get(), gurobi_solver_.get(),
clarabel_solver_.get(), csdp_solver_.get(),
scs_solver_.get(), snopt_solver_.get(), ipopt_solver_.get(),
nlopt_solver_.get()});
prog_.AddPolynomialCost(pow(x_(0), 3));
CheckBestSolver(
{snopt_solver_.get(), ipopt_solver_.get(), nlopt_solver_.get()});
CheckGetAvailableSolvers(prog_);
}
TEST_F(ChooseBestSolverTest, LinearComplementarityConstraint) {
prog_.AddLinearComplementarityConstraint(Eigen::Matrix3d::Identity(),
Eigen::Vector3d::Ones(), x_);
CheckBestSolver({moby_lcp_solver_.get(), snopt_solver_.get()});
CheckGetAvailableSolvers(prog_);
prog_.AddLinearCost(x_(0) + 1);
CheckBestSolver({snopt_solver_.get()});
}
TEST_F(ChooseBestSolverTest, PositiveSemidefiniteConstraint) {
prog_.AddPositiveSemidefiniteConstraint(
(Matrix2<symbolic::Variable>() << x_(0), x_(1), x_(1), x_(2)).finished());
CheckBestSolver({mosek_solver_.get(), clarabel_solver_.get(),
csdp_solver_.get(), scs_solver_.get()});
CheckGetAvailableSolvers(prog_);
}
TEST_F(ChooseBestSolverTest, QuadraticCostConicConstraint) {
prog_.AddLorentzConeConstraint(x_.head<3>().cast<symbolic::Expression>());
prog_.AddQuadraticCost(x_(0) * x_(0));
CheckGetAvailableSolvers(prog_);
}
TEST_F(ChooseBestSolverTest, Nlp) {
prog_.AddConstraint(
std::make_shared<ExpressionConstraint>(
Vector1<symbolic::Expression>(x_(0) + symbolic::sin(x_(1))),
Vector1d(0), Vector1d(2)),
x_.head<2>());
CheckGetAvailableSolvers(prog_);
}
TEST_F(ChooseBestSolverTest, ExponentialConeConstraint) {
prog_.AddExponentialConeConstraint(x_.head<3>().cast<symbolic::Expression>());
CheckGetAvailableSolvers(prog_);
}
TEST_F(ChooseBestSolverTest, BinaryVariable) {
prog_.NewBinaryVariables<1>();
prog_.AddLinearConstraint(x_(0) + x_(1) == 1);
if (GurobiSolver::is_available()) {
CheckBestSolver(GurobiSolver::id());
} else if (MosekSolver::is_available()) {
CheckBestSolver(MosekSolver::id());
} else {
DRAKE_EXPECT_THROWS_MESSAGE(
ChooseBestSolver(prog_),
"There is no available solver for the optimization program, please "
"manually instantiate MixedIntegerBranchAndBound.*");
CheckGetAvailableSolvers(prog_);
}
}
TEST_F(ChooseBestSolverTest, UnknownProgramType) {
const auto available_solvers = GetAvailableSolvers(ProgramType::kUnknown);
EXPECT_TRUE(available_solvers.empty());
}
TEST_F(ChooseBestSolverTest, NoAvailableSolver) {
// We don't have a solver for problem with both linear complementarity
// constraint and binary variables.
prog_.AddLinearComplementarityConstraint(
Eigen::Matrix2d::Identity(), Eigen::Vector2d::Ones(), x_.tail<2>());
prog_.NewBinaryVariables<2>();
DRAKE_EXPECT_THROWS_MESSAGE(
ChooseBestSolver(prog_),
"There is no available solver for the optimization program");
}
TEST_F(ChooseBestSolverTest, MakeSolver) {
CheckMakeSolver(*linear_system_solver_);
CheckMakeSolver(*equality_constrained_qp_solver_);
CheckMakeSolver(*mosek_solver_);
CheckMakeSolver(*gurobi_solver_);
CheckMakeSolver(*clarabel_solver_);
CheckMakeSolver(*osqp_solver_);
CheckMakeSolver(*moby_lcp_solver_);
CheckMakeSolver(*snopt_solver_);
CheckMakeSolver(*ipopt_solver_);
CheckMakeSolver(*nlopt_solver_);
CheckMakeSolver(*scs_solver_);
DRAKE_EXPECT_THROWS_MESSAGE(MakeSolver(SolverId("foo")),
"MakeSolver: no matching solver foo");
}
// Checks that all of the known solvers can be instantiated.
TEST_F(ChooseBestSolverTest, KnownSolvers) {
const std::set<SolverId>& ids = GetKnownSolvers();
EXPECT_GT(ids.size(), 5);
for (const auto& id : ids) {
EXPECT_EQ(MakeSolver(id)->solver_id(), id);
}
}
GTEST_TEST(MakeFirstAvailableSolver, Test) {
const bool has_gurobi =
GurobiSolver::is_available() && GurobiSolver::is_enabled();
const bool has_scs = ScsSolver::is_available() && ScsSolver::is_enabled();
if (has_gurobi || has_scs) {
auto solver =
MakeFirstAvailableSolver({GurobiSolver::id(), ScsSolver::id()});
if (has_gurobi) {
EXPECT_EQ(solver->solver_id(), GurobiSolver::id());
} else {
EXPECT_EQ(solver->solver_id(), ScsSolver::id());
}
}
if (!has_gurobi) {
DRAKE_EXPECT_THROWS_MESSAGE(MakeFirstAvailableSolver({GurobiSolver::id()}),
".* is available and enabled.");
}
}
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/scaled_diagonally_dominant_matrix_test.cc | #include <limits>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/solve.h"
using drake::symbolic::test::ExprEqual;
namespace drake {
namespace solvers {
namespace {
bool is_zero(const symbolic::Variable& v) {
return v.is_dummy();
}
template <typename T>
void CheckOffDiagonalTerms(int nx) {
MathematicalProgram prog;
auto X = prog.NewSymmetricContinuousVariables(nx);
auto M = prog.AddScaledDiagonallyDominantMatrixConstraint(X.cast<T>());
for (int i = 0; i < nx; ++i) {
for (int j = 0; j < nx; ++j) {
// M[i][j] should be a zero matrix if i >= j.
if (i >= j) {
for (int m = 0; m < 2; ++m) {
for (int n = 0; n < 2; ++n) {
EXPECT_TRUE(is_zero(M[i][j](m, n)));
}
}
} else {
EXPECT_PRED2(ExprEqual, symbolic::Expression(M[i][j](0, 1)),
symbolic::Expression(X(i, j)));
EXPECT_PRED2(ExprEqual, symbolic::Expression(M[i][j](1, 0)),
symbolic::Expression(X(j, i)));
}
}
}
}
GTEST_TEST(ScaledDiagonallyDominantMatrixTest, AddConstraint) {
CheckOffDiagonalTerms<symbolic::Expression>(2);
CheckOffDiagonalTerms<symbolic::Variable>(2);
CheckOffDiagonalTerms<symbolic::Expression>(4);
CheckOffDiagonalTerms<symbolic::Variable>(4);
}
template <typename T>
void CheckSDDMatrix(const Eigen::Ref<const Eigen::MatrixXd>& X_val,
bool is_sdd) {
// Test if a sdd matrix satisfies the constraint.
const int nx = X_val.rows();
DRAKE_DEMAND(X_val.cols() == nx);
MathematicalProgram prog;
auto X = prog.NewSymmetricContinuousVariables(nx);
auto M = prog.AddScaledDiagonallyDominantMatrixConstraint(X.cast<T>());
for (int i = 0; i < nx; ++i) {
prog.AddBoundingBoxConstraint(X_val.col(i), X_val.col(i), X.col(i));
}
const auto result = Solve(prog);
if (is_sdd) {
EXPECT_TRUE(result.is_success());
// Since X = ∑ᵢⱼ Mⁱʲ according to the definition of scaled diagonally
// dominant matrix, we evaluate the summation of M, and compare that with X.
std::vector<std::vector<Eigen::MatrixXd>> M_val(nx);
symbolic::Environment env;
for (int i = 0; i < prog.num_vars(); ++i) {
env.insert(prog.decision_variable(i),
result.GetSolution(prog.decision_variable(i)));
}
Eigen::MatrixXd M_sum(nx, nx);
M_sum.setZero();
const double tol = 1E-6;
for (int i = 0; i < nx; ++i) {
M_val[i].resize(nx);
for (int j = i + 1; j < nx; ++j) {
M_val[i][j].resize(nx, nx);
M_val[i][j].setZero();
M_val[i][j](i, i) = symbolic::Expression(M[i][j](0, 0)).Evaluate(env);
M_val[i][j](i, j) = symbolic::Expression(M[i][j](0, 1)).Evaluate(env);
M_val[i][j](j, i) = M_val[i][j](i, j);
M_val[i][j](j, j) = symbolic::Expression(M[i][j](1, 1)).Evaluate(env);
M_sum += M_val[i][j];
// (M[i][j](0, 0); M[i][j](1, 1); M[i][j](0, 1)) should be in the
// rotated Lorentz cone.
EXPECT_GE(M_val[i][j](i, i), -tol);
EXPECT_GE(M_val[i][j](j, j), -tol);
EXPECT_GE(M_val[i][j](i, i) * M_val[i][j](j, j),
std::pow(M_val[i][j](i, j), 2) - tol);
}
}
EXPECT_TRUE(CompareMatrices(M_sum, X_val, tol));
} else {
EXPECT_FALSE(result.is_success());
EXPECT_TRUE(result.get_solution_result() ==
SolutionResult::kInfeasibleConstraints ||
result.get_solution_result() ==
SolutionResult::kInfeasibleOrUnbounded);
}
}
bool IsMatrixSDD(const Eigen::Ref<Eigen::MatrixXd>& X) {
// A matrix X is scaled diagonally dominant, if there exists a positive vector
// d, such that the matrix A defined as A(i, j) = d(j) * X(i, j) is diagonally
// dominant with positive diagonals.
// This is explained as Remark 6 of "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.
const int nx = X.rows();
MathematicalProgram prog;
auto d = prog.NewContinuousVariables(nx);
MatrixX<symbolic::Expression> A(nx, nx);
for (int i = 0; i < nx; ++i) {
for (int j = 0; j < nx; ++j) {
A(i, j) = d(j) * X(i, j);
}
}
prog.AddPositiveDiagonallyDominantMatrixConstraint(A);
prog.AddBoundingBoxConstraint(1, std::numeric_limits<double>::infinity(), d);
const auto result = Solve(prog);
return result.is_success();
}
GTEST_TEST(ScaledDiagonallyDominantMatrixTest, TestSDDMatrix) {
Eigen::Matrix4d dd_X;
// A diagonally dominant matrix.
// clang-format off
dd_X << 1, -0.2, 0.3, -0.45,
-0.2, 2, 0.5, 1,
0.3, 0.5, 3, 2,
-0.45, 1, 2, 4;
// clang-format on
CheckSDDMatrix<symbolic::Expression>(dd_X, true);
CheckSDDMatrix<symbolic::Variable>(dd_X, true);
Eigen::Matrix4d D = Eigen::Vector4d(1, 2, 3, 4).asDiagonal();
Eigen::Matrix4d sdd_X = D * dd_X * D;
CheckSDDMatrix<symbolic::Expression>(sdd_X, true);
CheckSDDMatrix<symbolic::Variable>(sdd_X, true);
D = Eigen::Vector4d(0.2, -1, -0.5, 1.2).asDiagonal();
sdd_X = D * dd_X * D;
CheckSDDMatrix<symbolic::Expression>(sdd_X, true);
CheckSDDMatrix<symbolic::Variable>(sdd_X, true);
// not_dd_X is not diagonally dominant (dd), but is scaled diagonally
// dominant.
Eigen::Matrix4d not_dd_X;
not_dd_X << 1, -0.2, 0.3, -0.55, -0.2, 2, 0.5, 1, 0.3, 0.5, 3, 2, -0.55, 1, 2,
4;
DRAKE_DEMAND(IsMatrixSDD(not_dd_X));
CheckSDDMatrix<symbolic::Expression>(not_dd_X, true);
CheckSDDMatrix<symbolic::Variable>(not_dd_X, true);
}
GTEST_TEST(ScaledDiagonallyDominantMatrixTest, TestNotSDDMatrix) {
Eigen::Matrix4d not_sdd_X;
// Not a diagonally dominant matrix.
// clang-format off
not_sdd_X << 1, -0.2, 0.3, -1.55,
-0.2, 2, 0.5, 1,
0.3, 0.5, 3, 2,
-1.55, 1, 2, 4;
// clang-format on
DRAKE_DEMAND(!IsMatrixSDD(not_sdd_X));
CheckSDDMatrix<symbolic::Expression>(not_sdd_X, false);
CheckSDDMatrix<symbolic::Variable>(not_sdd_X, false);
Eigen::Matrix4d D = Eigen::Vector4d(1, 2, 3, 4).asDiagonal();
not_sdd_X = D * not_sdd_X * D;
CheckSDDMatrix<symbolic::Expression>(not_sdd_X, false);
CheckSDDMatrix<symbolic::Variable>(not_sdd_X, false);
D = Eigen::Vector4d(0.2, -1, -0.5, 1.2).asDiagonal();
not_sdd_X = D * not_sdd_X * D;
CheckSDDMatrix<symbolic::Expression>(not_sdd_X, false);
CheckSDDMatrix<symbolic::Variable>(not_sdd_X, false);
}
GTEST_TEST(SdsosTest, SdsosPolynomial) {
MathematicalProgram prog;
auto x = prog.NewIndeterminates<2>("x");
Vector4<symbolic::Monomial> m;
m << symbolic::Monomial(), symbolic::Monomial(x(0)), symbolic::Monomial(x(1)),
symbolic::Monomial({{x(0), 1}, {x(1), 1}});
symbolic::Polynomial p;
std::tie(p, std::ignore) = prog.NewSosPolynomial(
m, MathematicalProgram::NonnegativePolynomial::kSdsos);
Eigen::Matrix4d dd_X;
// A diagonally dominant matrix.
// clang-format off
dd_X << 1, -0.2, 0.3, -0.45,
-0.2, 2, 0.5, 1,
0.3, 0.5, 3, 2,
-0.45, 1, 2, 4;
// clang-format on
const Eigen::Matrix4d D = Eigen::Vector4d(1, 2, 3, 4).asDiagonal();
const Eigen::Matrix4d sdd_X = D * dd_X * D;
symbolic::Polynomial p_expected;
for (int i = 0; i < sdd_X.rows(); ++i) {
for (int j = 0; j < sdd_X.cols(); ++j) {
p_expected.AddProduct(sdd_X(i, j), m(i) * m(j));
}
}
prog.AddLinearEqualityConstraint(p == p_expected);
const MathematicalProgramResult result = Solve(prog);
EXPECT_TRUE(result.is_success());
}
GTEST_TEST(SdsosTest, NotSdsosPolynomial) {
MathematicalProgram prog;
auto x = prog.NewIndeterminates<2>("x");
Vector3<symbolic::Monomial> m;
m << symbolic::Monomial(), symbolic::Monomial(x(0)), symbolic::Monomial(x(1));
// This polynomial is not sdsos, since at x = (0, -1) the polynomial is
// negative.
symbolic::Polynomial non_sdsos_poly(
1 + x(0) + 4 * x(1) + x(0) * x(0) + x(1) * x(1), symbolic::Variables(x));
const auto Q = prog.AddSosConstraint(
non_sdsos_poly, m, MathematicalProgram::NonnegativePolynomial::kSdsos);
const MathematicalProgramResult result = Solve(prog);
EXPECT_FALSE(result.is_success());
EXPECT_TRUE(
result.get_solution_result() == SolutionResult::kInfeasibleConstraints ||
result.get_solution_result() == SolutionResult::kInfeasibleOrUnbounded);
}
} // namespace
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/gurobi_solver_grb_license_file_test.cc | #include <cstdlib>
#include <optional>
#include <stdexcept>
#include <string>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/solvers/gurobi_solver.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace solvers {
namespace {
// These tests are deliberately not in gurobi_solver_test.cc to avoid causing
// license issues during tests in that file.
std::optional<std::string> GetEnvStr(const char* name) {
const char* const value = std::getenv(name);
if (!value) {
return std::nullopt;
}
return std::string(value);
}
class GrbLicenseFileTest : public ::testing::Test {
protected:
GrbLicenseFileTest()
: orig_grb_license_file_(GetEnvStr("GRB_LICENSE_FILE")) {}
void SetUp() override {
ASSERT_EQ(solver_.available(), true);
ASSERT_TRUE(orig_grb_license_file_);
// Add a variable to avoid the "Solve" function terminating without calling
// the external Gurobi solver.
prog_.NewContinuousVariables<1>();
}
void TearDown() override {
if (orig_grb_license_file_) {
const int setenv_result =
::setenv("GRB_LICENSE_FILE", orig_grb_license_file_->c_str(), 1);
EXPECT_EQ(setenv_result, 0);
}
}
const std::optional<std::string> orig_grb_license_file_;
MathematicalProgram prog_;
GurobiSolver solver_;
};
TEST_F(GrbLicenseFileTest, GrbLicenseFileSet) {
EXPECT_EQ(solver_.enabled(), true);
DRAKE_EXPECT_NO_THROW(solver_.Solve(prog_));
}
TEST_F(GrbLicenseFileTest, GrbLicenseFileUnset) {
EXPECT_EQ(solver_.enabled(), true);
const int unsetenv_result = ::unsetenv("GRB_LICENSE_FILE");
ASSERT_EQ(unsetenv_result, 0);
EXPECT_EQ(solver_.enabled(), false);
DRAKE_EXPECT_THROWS_MESSAGE(
solver_.Solve(prog_),
".*GurobiSolver has not been properly configured.*");
}
} // namespace
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/solver_base_test.cc | #include "drake/solvers/solver_base.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.h"
namespace drake {
namespace solvers {
namespace test {
namespace {
using ::testing::HasSubstr;
// A stub subclass of SolverBase, so that we can instantiate and test it.
class StubSolverBase final : public SolverBase {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(StubSolverBase)
StubSolverBase()
: SolverBase(
id(),
[this]() {
return available_;
},
[this]() {
return enabled_;
},
[this](const auto& prog) {
return satisfied_;
}) {}
// This overload passes the explain_unsatisfied functor to the base class,
// in contrast to the above constructor which leaves it defaulted.
explicit StubSolverBase(std::string explanation)
: SolverBase(
id(),
[this]() {
return available_;
},
[this]() {
return enabled_;
},
[this](const auto& prog) {
return satisfied_;
},
[this](const auto& prog) {
return satisfied_ ? "" : unsatisfied_explanation_;
}),
unsatisfied_explanation_(std::move(explanation)) {}
void DoSolve(const MathematicalProgram& prog, const Eigen::VectorXd& x_init,
const SolverOptions& options,
MathematicalProgramResult* result) const final {
result->set_solution_result(kSolutionFound);
result->set_optimal_cost(1.0);
Eigen::VectorXd x_val = x_init;
const auto& options_double = options.GetOptionsDouble(id());
if (options_double.contains("x0_solution")) {
x_val[0] = options_double.find("x0_solution")->second;
}
if (options_double.contains("x1_solution")) {
x_val[1] = options_double.find("x1_solution")->second;
}
result->set_x_val(x_val);
}
// Helper static method for SolverBase ctor.
static SolverId id() {
static const never_destroyed<SolverId> result{"stub"};
return result.access();
}
// The return values for stubbed methods.
bool available_{true};
bool enabled_{true};
bool satisfied_{true};
std::string unsatisfied_explanation_;
};
GTEST_TEST(SolverBaseTest, BasicAccessors) {
StubSolverBase dut;
EXPECT_EQ(dut.solver_id(), StubSolverBase::id());
dut.available_ = false;
EXPECT_FALSE(dut.available());
dut.available_ = true;
EXPECT_TRUE(dut.available());
dut.enabled_ = false;
EXPECT_FALSE(dut.enabled());
dut.enabled_ = true;
EXPECT_TRUE(dut.enabled());
}
// Check AreProgramAttributesSatisfied when the subclass does nothing to
// customize the error message.
GTEST_TEST(SolverBaseTest, ProgramAttributesDefault) {
const MathematicalProgram prog;
StubSolverBase dut;
dut.satisfied_ = false;
EXPECT_FALSE(dut.AreProgramAttributesSatisfied(prog));
EXPECT_THAT(dut.ExplainUnsatisfiedProgramAttributes(prog),
HasSubstr("StubSolverBase is unable to solve"));
dut.satisfied_ = true;
EXPECT_TRUE(dut.AreProgramAttributesSatisfied(prog));
EXPECT_EQ(dut.ExplainUnsatisfiedProgramAttributes(prog), "");
}
// Check AreProgramAttributesSatisfied when the subclass customizes the error
// message.
GTEST_TEST(SolverBaseTest, ProgramAttributesCustom) {
const MathematicalProgram prog;
StubSolverBase dut("Do not meddle in the affairs of wizards!");
dut.satisfied_ = false;
EXPECT_FALSE(dut.AreProgramAttributesSatisfied(prog));
EXPECT_THAT(dut.ExplainUnsatisfiedProgramAttributes(prog),
HasSubstr("affairs of wizards"));
dut.satisfied_ = true;
EXPECT_TRUE(dut.AreProgramAttributesSatisfied(prog));
EXPECT_EQ(dut.ExplainUnsatisfiedProgramAttributes(prog), "");
}
GTEST_TEST(SolverBaseTest, SolveAsOutputArgument) {
const StubSolverBase dut;
MathematicalProgram mutable_prog;
const MathematicalProgram& prog = mutable_prog;
auto vars = mutable_prog.NewContinuousVariables(2);
MathematicalProgramResult result;
// Check that the prog's initial guess and options are used.
mutable_prog.SetSolverOption(StubSolverBase::id(), "x0_solution", 10.0);
mutable_prog.SetInitialGuess(vars[1], 11.0);
dut.Solve(prog, {}, {}, &result);
EXPECT_EQ(result.get_solver_id(), StubSolverBase::id());
EXPECT_TRUE(result.is_success());
EXPECT_EQ(result.get_solution_result(), kSolutionFound);
EXPECT_EQ(result.get_optimal_cost(), 1.0);
ASSERT_EQ(result.get_x_val().size(), 2);
EXPECT_EQ(result.get_x_val()[0], 10.0);
EXPECT_EQ(result.get_x_val()[1], 11.0);
EXPECT_EQ(result.GetSolution(vars[0]), 10.0);
EXPECT_EQ(result.GetSolution(vars[1]), 11.0);
// Check that Solve()'s initial guess takes precedence.
dut.Solve(prog, Eigen::VectorXd(Vector2<double>(30.0, 31.0)), {}, &result);
EXPECT_EQ(result.get_x_val()[0], 10.0);
EXPECT_EQ(result.get_x_val()[1], 31.0);
// Check that Solve's option get merged, but prog's options still apply.
SolverOptions extra_options;
extra_options.SetOption(StubSolverBase::id(), "x1_solution", 41.0);
dut.Solve(prog, {}, extra_options, &result);
EXPECT_EQ(result.get_x_val()[0], 10.0);
EXPECT_EQ(result.get_x_val()[1], 41.0);
// Check that Solve's options win.
extra_options.SetOption(StubSolverBase::id(), "x0_solution", 40.0);
dut.Solve(prog, {}, extra_options, &result);
EXPECT_EQ(result.get_x_val()[0], 40.0);
EXPECT_EQ(result.get_x_val()[1], 41.0);
}
// Check the error message when the solver is not available.
GTEST_TEST(SolverBaseTest, AvailableError) {
const MathematicalProgram prog;
StubSolverBase dut;
dut.available_ = false;
DRAKE_EXPECT_THROWS_MESSAGE(dut.Solve(prog, {}, {}),
".*StubSolverBase has not been compiled.*");
}
// Check the error message when attributes are not satisfied.
GTEST_TEST(SolverBaseTest, ProgramAttributesError) {
const MathematicalProgram prog;
StubSolverBase dut;
dut.satisfied_ = false;
DRAKE_EXPECT_THROWS_MESSAGE(dut.Solve(prog, {}, {}),
".*StubSolverBase is unable to solve.*");
}
GTEST_TEST(SolverBaseTest, SolveAndReturn) {
const StubSolverBase dut;
const MathematicalProgram prog;
const MathematicalProgramResult result = dut.Solve(prog, {}, {});
EXPECT_EQ(result.get_solver_id(), StubSolverBase::id());
EXPECT_TRUE(result.is_success());
// Confirm that default arguments work, too.
const MathematicalProgramResult result2 = dut.Solve(prog);
EXPECT_TRUE(result2.is_success());
// We don't bother checking additional result details here, because we know
// that the solve-and-return method is implemented as a thin shim atop the
// solve-as-output-argument method.
}
GTEST_TEST(SolverBaseTest, InitialGuessSizeError) {
MathematicalProgram prog;
prog.NewContinuousVariables<2>();
StubSolverBase dut;
DRAKE_EXPECT_THROWS_MESSAGE(dut.Solve(prog, Eigen::VectorXd(3), {}),
"Solve expects initial guess of size 2, got 3.");
}
} // namespace
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/optimization_examples.cc | #include "drake/solvers/test/optimization_examples.h"
#include <gtest/gtest.h>
#include "drake/common/drake_assert.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/solvers/clarabel_solver.h"
#include "drake/solvers/clp_solver.h"
#include "drake/solvers/gurobi_solver.h"
#include "drake/solvers/ipopt_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/test/mathematical_program_test_util.h"
using Eigen::Matrix2d;
using Eigen::Matrix3d;
using Eigen::Matrix4d;
using Eigen::MatrixXd;
using Eigen::RowVector2d;
using Eigen::RowVectorXd;
using Eigen::Vector2d;
using Eigen::Vector3d;
using Eigen::Vector4d;
using Eigen::VectorXd;
using drake::symbolic::Expression;
using std::numeric_limits;
namespace drake {
namespace solvers {
namespace test {
const double kInf = std::numeric_limits<double>::infinity();
std::ostream& operator<<(std::ostream& os, CostForm value) {
os << "CostForm::";
switch (value) {
case CostForm::kGeneric: {
os << "kGeneric";
return os;
}
case CostForm::kNonSymbolic: {
os << "kNonSymbolic";
return os;
}
case CostForm::kSymbolic: {
os << "kSymbolic";
return os;
}
}
DRAKE_UNREACHABLE();
}
std::ostream& operator<<(std::ostream& os, ConstraintForm value) {
os << "ConstraintForm::";
switch (value) {
case ConstraintForm::kGeneric: {
os << "kGeneric";
return os;
}
case ConstraintForm::kNonSymbolic: {
os << "kNonSymbolic";
return os;
}
case ConstraintForm::kSymbolic: {
os << "kSymbolic";
return os;
}
case ConstraintForm::kFormula: {
os << "kFormula";
return os;
}
}
DRAKE_UNREACHABLE();
}
std::set<CostForm> linear_cost_form() {
return std::set<CostForm>{CostForm::kNonSymbolic, CostForm::kSymbolic};
}
std::set<ConstraintForm> linear_constraint_form() {
return std::set<ConstraintForm>{ConstraintForm::kNonSymbolic,
ConstraintForm::kSymbolic,
ConstraintForm::kFormula};
}
std::set<CostForm> quadratic_cost_form() {
return std::set<CostForm>{CostForm::kNonSymbolic, CostForm::kSymbolic};
}
double EvaluateSolutionCost(const MathematicalProgram& prog,
const MathematicalProgramResult& result) {
double cost{0};
for (auto const& binding : prog.GetAllCosts()) {
cost += prog.EvalBinding(binding, result.get_x_val())(0);
}
return cost;
}
/*
* Expect that the optimal cost stored by the solver in the MathematicalProgram
* be nearly the same as the cost reevaluated at the solution
*/
void ExpectSolutionCostAccurate(const MathematicalProgram& prog,
const MathematicalProgramResult& result,
double tol) {
EXPECT_NEAR(EvaluateSolutionCost(prog, result), result.get_optimal_cost(),
tol);
}
OptimizationProgram::OptimizationProgram(CostForm cost_form,
ConstraintForm constraint_form)
: cost_form_(cost_form),
constraint_form_(constraint_form),
prog_(std::make_unique<MathematicalProgram>()),
initial_guess_{} {}
void OptimizationProgram::RunProblem(SolverInterface* solver) {
if (solver->available()) {
EXPECT_TRUE(solver->AreProgramAttributesSatisfied(*prog_));
EXPECT_EQ(solver->ExplainUnsatisfiedProgramAttributes(*prog_), "");
const MathematicalProgramResult result =
RunSolver(*prog_, *solver, initial_guess());
CheckSolution(result);
}
}
double OptimizationProgram::GetSolverSolutionDefaultCompareTolerance(
SolverId solver_id) const {
if (solver_id == ClpSolver::id()) {
return 1E-8;
}
if (solver_id == MosekSolver::id()) {
return 1E-10;
}
if (solver_id == GurobiSolver::id()) {
return 1E-10;
}
if (solver_id == SnoptSolver::id()) {
return 1E-8;
}
if (solver_id == IpoptSolver::id()) {
return 1E-6;
}
if (solver_id == NloptSolver::id()) {
return 1E-6;
}
if (solver_id == OsqpSolver::id()) {
return 1E-10;
}
if (solver_id == ScsSolver::id()) {
return 1E-3; // Scs is not very accurate.
}
if (solver_id == ClarabelSolver::id()) {
return 1E-5;
}
throw std::runtime_error("Unsupported solver type.");
}
LinearSystemExample1::LinearSystemExample1()
: prog_(std::make_unique<MathematicalProgram>()),
x_{},
initial_guess_{},
b_{},
con_{} {
x_ = prog_->NewContinuousVariables<4>();
b_ = Vector4d::Random();
con_ = prog_->AddLinearEqualityConstraint(Matrix4d::Identity(), b_, x_)
.evaluator();
initial_guess_.setZero();
}
void LinearSystemExample1::CheckSolution(
const MathematicalProgramResult& result) const {
auto x_sol = result.GetSolution(x_);
EXPECT_TRUE(CompareMatrices(x_sol, b_, tol(), MatrixCompareType::absolute));
for (int i = 0; i < 4; ++i) {
EXPECT_NEAR(b_(i), x_sol(i), tol());
EXPECT_TRUE(CompareMatrices(x_sol.head(i), b_.head(i), tol(),
MatrixCompareType::absolute));
}
EXPECT_NEAR(0.0, result.get_optimal_cost(), tol());
}
LinearSystemExample2::LinearSystemExample2() : LinearSystemExample1(), y_{} {
y_ = prog()->NewContinuousVariables<2>();
prog()->AddLinearEqualityConstraint(2 * Matrix2d::Identity(),
b().topRows<2>(), y_);
}
void LinearSystemExample2::CheckSolution(
const MathematicalProgramResult& result) const {
LinearSystemExample1::CheckSolution(result);
EXPECT_TRUE(CompareMatrices(result.GetSolution(y_), b().topRows<2>() / 2,
tol(), MatrixCompareType::absolute));
EXPECT_NEAR(0.0, result.get_optimal_cost(), tol());
}
LinearSystemExample3::LinearSystemExample3() : LinearSystemExample2() {
con()->UpdateCoefficients(3 * Matrix4d::Identity(), b());
}
void LinearSystemExample3::CheckSolution(
const MathematicalProgramResult& result) const {
EXPECT_TRUE(CompareMatrices(result.GetSolution(x()), b() / 3, tol(),
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(result.GetSolution(y()), b().topRows<2>() / 2,
tol(), MatrixCompareType::absolute));
EXPECT_NEAR(0.0, result.get_optimal_cost(), tol());
}
LinearMatrixEqualityExample::LinearMatrixEqualityExample()
: prog_(std::make_unique<MathematicalProgram>()), X_{}, A_{} {
X_ = prog_->NewSymmetricContinuousVariables<3>("X");
// clang-format off
A_ << -1, -2, 3,
0, -2, 4,
0, 0, -4;
// clang-format on
prog_->AddLinearEqualityConstraint(A_.transpose() * X_ + X_ * A_,
-Eigen::Matrix3d::Identity(), true);
}
void LinearMatrixEqualityExample::CheckSolution(
const MathematicalProgramResult& result) const {
auto X_value = result.GetSolution(X_);
EXPECT_TRUE(CompareMatrices(A_.transpose() * X_value + X_value * A_,
-Eigen::Matrix3d::Identity(), 1E-8,
MatrixCompareType::absolute));
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;
es.compute(X_value);
EXPECT_TRUE((es.eigenvalues().array() >= 0).all());
EXPECT_NEAR(0.0, result.get_optimal_cost(), 1E-8);
}
NonConvexQPproblem1::NonConvexQPproblem1(CostForm cost_form,
ConstraintForm constraint_form)
: prog_(std::make_unique<MathematicalProgram>()), x_{}, x_expected_{} {
x_ = prog_->NewContinuousVariables<5>("x");
prog_->AddBoundingBoxConstraint(0, 1, x_);
switch (cost_form) {
case CostForm::kGeneric: {
prog_->AddCost(TestProblem1Cost(), x_);
break;
}
case CostForm::kNonSymbolic: {
AddQuadraticCost();
break;
}
default:
throw std::runtime_error("unsupported cost form");
}
switch (constraint_form) {
case ConstraintForm::kSymbolic: {
AddSymbolicConstraint();
break;
}
case ConstraintForm::kNonSymbolic: {
AddConstraint();
break;
}
default:
throw std::runtime_error("unsupported constraint form");
}
x_expected_ << 1, 1, 0, 1, 0;
}
Eigen::Matrix<double, 5, 1> NonConvexQPproblem1::initial_guess() const {
return (Eigen::Matrix<double, 5, 1>() << 1.01, 1.02, -0.02, 1.03, -0.05)
.finished();
}
void NonConvexQPproblem1::CheckSolution(
const MathematicalProgramResult& result) const {
const auto& x_value = result.GetSolution(x_);
EXPECT_TRUE(
CompareMatrices(x_value, x_expected_, 1E-9, MatrixCompareType::absolute));
ExpectSolutionCostAccurate(*prog_, result, 1E-5);
}
void NonConvexQPproblem1::AddConstraint() {
Eigen::Matrix<double, 1, 5> a;
a << 20, 12, 11, 7, 4;
prog_->AddLinearConstraint(a, -kInf, 40, x_);
}
void NonConvexQPproblem1::AddSymbolicConstraint() {
const auto constraint =
20 * x_(0) + 12 * x_(1) + 11 * x_(2) + 7 * x_(3) + 4 * x_(4);
prog_->AddLinearConstraint(constraint, -kInf, 40);
}
void NonConvexQPproblem1::AddQuadraticCost() {
Eigen::Matrix<double, 5, 5> Q =
-100 * Eigen::Matrix<double, 5, 5>::Identity();
Eigen::Matrix<double, 5, 1> c;
c << 42, 44, 45, 47, 47.5;
double r = -100;
prog_->AddQuadraticCost(Q, c, r, x_);
}
NonConvexQPproblem2::NonConvexQPproblem2(CostForm cost_form,
ConstraintForm constraint_form)
: prog_(std::make_unique<MathematicalProgram>()), x_{}, x_expected_{} {
x_ = prog_->NewContinuousVariables<6>("x");
prog_->AddBoundingBoxConstraint(0, 1, x_.head<5>());
prog_->AddBoundingBoxConstraint(0, kInf, x_(5));
switch (cost_form) {
case CostForm::kGeneric: {
prog_->AddCost(TestProblem2Cost(), x_);
break;
}
case CostForm::kNonSymbolic: {
AddQuadraticCost();
break;
}
default:
throw std::runtime_error("Unsupported cost form");
}
switch (constraint_form) {
case ConstraintForm::kNonSymbolic: {
AddNonSymbolicConstraint();
break;
}
case ConstraintForm::kSymbolic: {
AddSymbolicConstraint();
break;
}
default:
throw std::runtime_error("Unsupported constraint form");
}
x_expected_ << 0, 1, 0, 1, 1, 20;
}
Vector6<double> NonConvexQPproblem2::initial_guess() const {
return x_expected_ +
(Vector6<double>() << 0.01, -0.02, 0.03, -0.04, 0.05, -0.06)
.finished();
}
void NonConvexQPproblem2::CheckSolution(
const MathematicalProgramResult& result) const {
const auto& x_value = result.GetSolution(x_);
EXPECT_TRUE(
CompareMatrices(x_value, x_expected_, 1E-3, MatrixCompareType::absolute));
ExpectSolutionCostAccurate(*prog_, result, 1E-4);
}
void NonConvexQPproblem2::AddQuadraticCost() {
Eigen::Matrix<double, 6, 6> Q =
-100.0 * Eigen::Matrix<double, 6, 6>::Identity();
Q(5, 5) = 0.0;
Vector6d c{};
c << -10.5, -7.5, -3.5, -2.5, -1.5, -10.0;
prog_->AddQuadraticCost(Q, c, x_);
}
void NonConvexQPproblem2::AddNonSymbolicConstraint() {
Eigen::Matrix<double, 1, 6> a1{};
Eigen::Matrix<double, 1, 6> a2{};
a1 << 6, 3, 3, 2, 1, 0;
a2 << 10, 0, 10, 0, 0, 1;
prog_->AddLinearConstraint(a1, -kInf, 6.5, x_);
prog_->AddLinearConstraint(a2, -kInf, 20, x_);
}
void NonConvexQPproblem2::AddSymbolicConstraint() {
const symbolic::Expression constraint1{6 * x_(0) + 3 * x_(1) + 3 * x_(2) +
2 * x_(3) + x_(4)};
const symbolic::Expression constraint2{10 * x_(0) + 10 * x_(2) + x_(5)};
prog_->AddLinearConstraint(constraint1, -kInf, 6.5);
prog_->AddLinearConstraint(constraint2, -kInf, 20);
}
LowerBoundedProblem::LowerBoundedProblem(ConstraintForm constraint_form)
: prog_(std::make_unique<MathematicalProgram>()), x_{}, x_expected_{} {
x_ = prog_->NewContinuousVariables<6>("x");
Vector6d lb{};
Vector6d ub{};
lb << 0, 0, 1, 0, 1, 0;
ub << kInf, kInf, 5, 6, 5, 10;
prog_->AddBoundingBoxConstraint(lb, ub, x_);
prog_->AddCost(LowerBoundTestCost(), x_);
std::shared_ptr<Constraint> con1(new LowerBoundTestConstraint(2, 3));
prog_->AddConstraint(con1, x_);
std::shared_ptr<Constraint> con2(new LowerBoundTestConstraint(4, 5));
prog_->AddConstraint(con2, x_);
switch (constraint_form) {
case ConstraintForm::kNonSymbolic: {
AddNonSymbolicConstraint();
break;
}
case ConstraintForm::kSymbolic: {
AddSymbolicConstraint();
break;
}
default:
throw std::runtime_error("Not a supported constraint form");
}
x_expected_ << 5, 1, 5, 0, 5, 10;
}
void LowerBoundedProblem::CheckSolution(
const MathematicalProgramResult& result) const {
const auto& x_value = result.GetSolution(x_);
EXPECT_TRUE(
CompareMatrices(x_value, x_expected_, 1E-3, MatrixCompareType::absolute));
ExpectSolutionCostAccurate(*prog_, result, 1E-2);
}
Vector6<double> LowerBoundedProblem::initial_guess1() const {
std::srand(0);
Vector6d delta = 0.05 * Vector6d::Random();
return x_expected_ + delta;
}
Vector6<double> LowerBoundedProblem::initial_guess2() const {
std::srand(0);
Vector6d delta = 0.05 * Vector6d::Random();
return x_expected_ - delta;
}
void LowerBoundedProblem::AddSymbolicConstraint() {
prog_->AddLinearConstraint(x_(0) - 3 * x_(1), -kInf, 2);
prog_->AddLinearConstraint(-x_(0) + x_(1), -kInf, 2);
prog_->AddLinearConstraint(x_(0) + x_(1), -kInf, 6);
}
void LowerBoundedProblem::AddNonSymbolicConstraint() {
prog_->AddLinearConstraint(RowVector2d(1, -3), -kInf, 2, x_.head<2>());
prog_->AddLinearConstraint(RowVector2d(-1, 1), -kInf, 2, x_.head<2>());
prog_->AddLinearConstraint(RowVector2d(1, 1), -kInf, 6, x_.head<2>());
}
GloptiPolyConstrainedMinimizationProblem::
GloptiPolyConstrainedMinimizationProblem(CostForm cost_form,
ConstraintForm constraint_form)
: prog_(std::make_unique<MathematicalProgram>()),
x_{},
y_{},
expected_(0.5, 0, 3) {
x_ = prog_->NewContinuousVariables<3>("x");
y_ = prog_->NewContinuousVariables<3>("y");
prog_->AddBoundingBoxConstraint(
Eigen::Vector3d(0, 0, 0),
Eigen::Vector3d(2, std::numeric_limits<double>::infinity(), 3), x_);
prog_->AddBoundingBoxConstraint(
Eigen::Vector3d(0, 0, 0),
Eigen::Vector3d(2, std::numeric_limits<double>::infinity(), 3), y_);
switch (cost_form) {
case CostForm::kGeneric: {
AddGenericCost();
break;
}
case CostForm::kNonSymbolic: {
AddNonSymbolicCost();
break;
}
case CostForm::kSymbolic: {
AddSymbolicCost();
break;
}
default:
throw std::runtime_error("Not a supported cost form");
}
// TODO(hongkai.dai): write this in symbolic form also.
std::shared_ptr<GloptipolyConstrainedExampleConstraint> qp_con(
new GloptipolyConstrainedExampleConstraint());
prog_->AddConstraint(qp_con, x_);
prog_->AddConstraint(qp_con, y_);
switch (constraint_form) {
case ConstraintForm::kNonSymbolic: {
AddNonSymbolicConstraint();
break;
}
case ConstraintForm::kSymbolic: {
AddSymbolicConstraint();
break;
}
default:
throw std::runtime_error("Not a supported constraint form");
}
}
Vector6<double> GloptiPolyConstrainedMinimizationProblem::initial_guess()
const {
Eigen::Vector3d init = expected_ + Eigen::Vector3d(0.02, 0.01, -0.01);
return (Vector6<double>() << init, init).finished();
}
void GloptiPolyConstrainedMinimizationProblem::CheckSolution(
const MathematicalProgramResult& result) const {
const auto& x_value = result.GetSolution(x_);
const auto& y_value = result.GetSolution(y_);
EXPECT_TRUE(
CompareMatrices(x_value, expected_, 1E-4, MatrixCompareType::absolute));
EXPECT_TRUE(
CompareMatrices(y_value, expected_, 1E-4, MatrixCompareType::absolute));
ExpectSolutionCostAccurate(*prog_, result, 1E-4);
}
void GloptiPolyConstrainedMinimizationProblem::AddGenericCost() {
prog_->AddCost(GloptipolyConstrainedExampleCost(), x_);
prog_->AddCost(GloptipolyConstrainedExampleCost(), y_);
}
void GloptiPolyConstrainedMinimizationProblem::AddSymbolicCost() {
prog_->AddLinearCost(-2 * x_(0) + x_(1) - x_(2));
prog_->AddLinearCost(-2 * y_(0) + y_(1) - y_(2));
}
void GloptiPolyConstrainedMinimizationProblem::AddNonSymbolicCost() {
prog_->AddLinearCost(Eigen::Vector3d(-2, 1, -1), x_);
prog_->AddLinearCost(Eigen::Vector3d(-2, 1, -1), y_);
}
void GloptiPolyConstrainedMinimizationProblem::AddNonSymbolicConstraint() {
Eigen::Matrix<double, 2, 3> A{};
// clang-format off
A << 1, 1, 1,
0, 3, 1;
// clang-format on
prog_->AddLinearConstraint(
A, Eigen::Vector2d::Constant(-std::numeric_limits<double>::infinity()),
Eigen::Vector2d(4, 6), x_);
prog_->AddLinearConstraint(
A, Eigen::Vector2d::Constant(-std::numeric_limits<double>::infinity()),
Eigen::Vector2d(4, 6), y_);
}
void GloptiPolyConstrainedMinimizationProblem::AddSymbolicConstraint() {
Eigen::Matrix<symbolic::Expression, 2, 1> e1{};
Eigen::Matrix<symbolic::Expression, 2, 1> e2{};
// clang-format off
e1 << x_(0) + x_(1) + x_(2),
3 * x_(1) + x_(2);
e2 << y_(0) + y_(1) + y_(2),
3 * y_(1) + y_(2);
// clang-format on
prog_->AddLinearConstraint(
e1, Eigen::Vector2d::Constant(-std::numeric_limits<double>::infinity()),
Eigen::Vector2d(4, 6));
prog_->AddLinearConstraint(
e2, Eigen::Vector2d::Constant(-std::numeric_limits<double>::infinity()),
Eigen::Vector2d(4, 6));
}
MinDistanceFromPlaneToOrigin::MinDistanceFromPlaneToOrigin(
const Eigen::MatrixXd& A, const Eigen::VectorXd& b, CostForm cost_form,
ConstraintForm constraint_form)
: A_(A),
b_(b),
prog_lorentz_(std::make_unique<MathematicalProgram>()),
prog_rotated_lorentz_(std::make_unique<MathematicalProgram>()),
t_lorentz_{},
x_lorentz_(A.cols()),
t_rotated_lorentz_{},
x_rotated_lorentz_(A.cols()) {
const int kXdim = A.cols();
t_lorentz_ = prog_lorentz_->NewContinuousVariables<1>("t");
x_lorentz_ = prog_lorentz_->NewContinuousVariables(kXdim, "x");
t_rotated_lorentz_ = prog_rotated_lorentz_->NewContinuousVariables<1>("t");
x_rotated_lorentz_ =
prog_rotated_lorentz_->NewContinuousVariables(kXdim, "x");
switch (cost_form) {
case CostForm::kNonSymbolic: {
prog_lorentz_->AddLinearCost(Vector1d(1), t_lorentz_);
prog_rotated_lorentz_->AddLinearCost(Vector1d(1), t_rotated_lorentz_);
break;
}
case CostForm::kSymbolic: {
prog_lorentz_->AddLinearCost(+t_lorentz_(0));
prog_rotated_lorentz_->AddLinearCost(+t_rotated_lorentz_(0));
break;
}
default:
throw std::runtime_error("Not a supported cost form");
}
switch (constraint_form) {
case ConstraintForm::kNonSymbolic: {
AddNonSymbolicConstraint();
break;
}
case ConstraintForm::kSymbolic: {
AddSymbolicConstraint();
break;
}
default:
throw std::runtime_error("Not a supported constraint form");
}
// compute expected value
// A_hat = [A 0; 2*I A']
MatrixXd A_hat(A.rows() + A.cols(), A.rows() + A.cols());
A_hat.topLeftCorner(A.rows(), A.cols()) = A;
A_hat.topRightCorner(A.rows(), A.rows()) = MatrixXd::Zero(A.rows(), A.rows());
A_hat.bottomLeftCorner(A.cols(), A.cols()) =
2 * MatrixXd::Identity(A.cols(), A.cols());
A_hat.bottomRightCorner(A.cols(), A.rows()) = A.transpose();
VectorXd b_hat(A.rows() + A.cols());
b_hat << b, VectorXd::Zero(A.cols());
VectorXd xz_expected = A_hat.colPivHouseholderQr().solve(b_hat);
x_expected_ = xz_expected.head(kXdim);
}
void MinDistanceFromPlaneToOrigin::AddNonSymbolicConstraint() {
prog_lorentz_->AddLorentzConeConstraint({t_lorentz_, x_lorentz_});
prog_lorentz_->AddLinearEqualityConstraint(A_, b_, x_lorentz_);
// A2 * [t;x] + b = [1;t;x]
Eigen::MatrixXd A2(2 + A_.cols(), 1 + A_.cols());
A2 << Eigen::RowVectorXd::Zero(1 + A_.cols()),
Eigen::MatrixXd::Identity(1 + A_.cols(), 1 + A_.cols());
Eigen::VectorXd b2(2 + A_.cols());
b2 << 1, VectorXd::Zero(1 + A_.cols());
prog_rotated_lorentz_->AddRotatedLorentzConeConstraint(
A2, b2, {t_rotated_lorentz_, x_rotated_lorentz_});
prog_rotated_lorentz_->AddLinearEqualityConstraint(A_, b_,
x_rotated_lorentz_);
}
void MinDistanceFromPlaneToOrigin::AddSymbolicConstraint() {
VectorX<Expression> tx(1 + A_.cols());
tx(0) = +t_lorentz_(0);
for (int i = 0; i < A_.cols(); ++i) {
tx(i + 1) = +x_lorentz_(i);
}
prog_lorentz_->AddLorentzConeConstraint(tx);
// TODO(hongkai.dai): change this to symbolic form.
prog_lorentz_->AddLinearEqualityConstraint(A_ * x_lorentz_, b_);
VectorX<Expression> tx2(2 + A_.cols());
tx2(0) = 1;
tx2(1) = +t_rotated_lorentz_(0);
for (int i = 0; i < A_.cols(); ++i) {
tx2(i + 2) = +x_rotated_lorentz_(i);
}
prog_rotated_lorentz_->AddRotatedLorentzConeConstraint(tx2);
prog_rotated_lorentz_->AddLinearEqualityConstraint(A_ * x_rotated_lorentz_,
b_);
}
Eigen::VectorXd MinDistanceFromPlaneToOrigin::prog_lorentz_initial_guess()
const {
Eigen::VectorXd initial_guess(1 + A_.cols());
initial_guess(0) = x_expected_.norm() + 0.1;
initial_guess.tail(A_.cols()) = x_expected_ + 0.1 * VectorXd::Ones(A_.cols());
return initial_guess;
}
Eigen::VectorXd
MinDistanceFromPlaneToOrigin::prog_rotated_lorentz_initial_guess() const {
Eigen::VectorXd initial_guess(1 + A_.cols());
initial_guess(0) = x_expected_.squaredNorm() + 0.1;
initial_guess.tail(A_.cols()) = x_expected_ + 0.1 * VectorXd::Ones(A_.cols());
return initial_guess;
}
void MinDistanceFromPlaneToOrigin::CheckSolution(
const MathematicalProgramResult& result, bool rotated_cone) const {
if (rotated_cone) {
auto x_rotated_lorentz_value = result.GetSolution(x_rotated_lorentz_);
auto t_rotated_lorentz_value = result.GetSolution(t_rotated_lorentz_);
EXPECT_TRUE(CompareMatrices(x_rotated_lorentz_value, x_expected_, 1E-3,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(t_rotated_lorentz_value,
Vector1d(x_expected_.squaredNorm()), 1E-3,
MatrixCompareType::absolute));
ExpectSolutionCostAccurate(*prog_rotated_lorentz_, result, 1E-3);
} else {
auto x_lorentz_value = result.GetSolution(x_lorentz_);
auto t_lorentz_value = result.GetSolution(t_lorentz_);
EXPECT_TRUE(CompareMatrices(x_lorentz_value, x_expected_, 1E-3,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(t_lorentz_value, Vector1d(x_expected_.norm()),
1E-3, MatrixCompareType::absolute));
ExpectSolutionCostAccurate(*prog_lorentz_, result, 1E-3);
}
}
ConvexCubicProgramExample::ConvexCubicProgramExample() {
x_ = NewContinuousVariables<1>("x");
AddCost(pow(x_(0), 3) - 12 * x_(0));
AddBoundingBoxConstraint(0, std::numeric_limits<double>::infinity(), x_(0));
}
void ConvexCubicProgramExample::CheckSolution(
const MathematicalProgramResult& result) const {
const auto x_val = result.GetSolution(x_(0));
EXPECT_NEAR(x_val, 2, 1E-6);
}
UnitLengthProgramExample::UnitLengthProgramExample()
: MathematicalProgram(), x_(NewContinuousVariables<4>()) {
// Impose the unit length constraint xᵀx = 1, by writing it as a quadratic
// constraint 0.5xᵀQx + bᵀx = 1, where Q = 2I, and b = 0.
auto unit_length_constraint = std::make_shared<QuadraticConstraint>(
2 * Eigen::Matrix4d::Identity(), Eigen::Vector4d::Zero(), 1, 1);
AddConstraint(unit_length_constraint, x_);
}
void UnitLengthProgramExample::CheckSolution(
const MathematicalProgramResult& result, double tolerance) const {
const auto x_val = result.GetSolution(x_);
EXPECT_NEAR(x_val.squaredNorm(), 1, tolerance);
}
DistanceToTetrahedronExample::DistanceToTetrahedronExample(
double distance_expected) {
x_ = NewContinuousVariables<18>();
// Distance to the tetrahedron is fixed.
AddBoundingBoxConstraint(distance_expected, distance_expected, x_(17));
// clang-format off
A_tetrahedron_ << 1, 1, 1,
-1, 0, 0,
0, -1, 0,
0, 0, -1;
// clang-format on
b_tetrahedron_ << 1, 0, 0, 0;
auto distance_constraint =
std::make_shared<DistanceToTetrahedronNonlinearConstraint>(
A_tetrahedron_, b_tetrahedron_);
AddConstraint(distance_constraint, x_);
}
DistanceToTetrahedronExample::DistanceToTetrahedronNonlinearConstraint::
DistanceToTetrahedronNonlinearConstraint(
const Eigen::Matrix<double, 4, 3>& A_tetrahedron,
const Eigen::Vector4d& b_tetrahedron)
: Constraint(15, 18), A_tetrahedron_(A_tetrahedron) {
const double inf = std::numeric_limits<double>::infinity();
Eigen::Matrix<double, 15, 1> lower_bound, upper_bound;
lower_bound << 1, 1, -inf, 0, 0, 0, 0, 0, 0, 0, 0, -inf, -inf, -inf, -inf;
upper_bound << 1, 1, 0, 0, 0, 0, 0, inf, inf, inf, inf, b_tetrahedron;
UpdateLowerBound(lower_bound);
UpdateUpperBound(upper_bound);
}
EckhardtProblem::EckhardtProblem(bool set_sparsity_pattern)
: prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<3>()} {
prog_->AddLinearCost(-x_(0));
auto constraint = std::make_shared<EckhardtConstraint>(set_sparsity_pattern);
prog_->AddConstraint(constraint, x_);
prog_->AddBoundingBoxConstraint(Eigen::Vector3d::Zero(),
Eigen::Vector3d(100, 100, 10), x_);
}
void EckhardtProblem::CheckSolution(const MathematicalProgramResult& result,
double tol) const {
ASSERT_TRUE(result.is_success());
const auto x_val = result.GetSolution(x_);
Eigen::Vector3d x_expected(std::log(std::log(10)), std::log(10), 10.0);
EXPECT_TRUE(CompareMatrices(x_val, x_expected, tol));
EXPECT_NEAR(result.get_optimal_cost(), -x_expected(0), tol);
}
EckhardtProblem::EckhardtConstraint::EckhardtConstraint(
bool set_sparsity_pattern)
: Constraint(2, 3, Eigen::Vector2d::Zero(),
Eigen::Vector2d::Constant(kInf)) {
if (set_sparsity_pattern) {
SetGradientSparsityPattern({{0, 0}, {0, 1}, {1, 1}, {1, 2}});
}
}
void TestEckhardtDualSolution(
const SolverInterface& solver,
const Eigen::Ref<const Eigen::VectorXd>& x_initial, double tol) {
if (solver.available()) {
EckhardtProblem problem{true};
MathematicalProgramResult result;
solver.Solve(problem.prog(), x_initial, {}, &result);
EXPECT_TRUE(result.is_success());
EXPECT_TRUE(CompareMatrices(
result.GetDualSolution(problem.prog().generic_constraints()[0]),
Eigen::Vector2d(1. / std::log(10.), 1. / (10 * std::log(10.))), tol));
EXPECT_TRUE(CompareMatrices(
result.GetDualSolution(problem.prog().bounding_box_constraints()[0]),
Eigen::Vector3d(0, 0, -1. / (10 * std::log(10.))), tol));
}
}
HeatExchangerDesignProblem::HeatExchangerDesignConstraint1::
HeatExchangerDesignConstraint1()
: Constraint(1, 6, Vector1d(0), Vector1d(kInf)) {
SetGradientSparsityPattern({{0, 0}, {0, 3}, {0, 5}});
}
HeatExchangerDesignProblem::HeatExchangerDesignConstraint2::
HeatExchangerDesignConstraint2()
: Constraint(2, 7, Eigen::Vector2d::Zero(),
Eigen::Vector2d::Constant(kInf)) {
SetGradientSparsityPattern(
{{0, 0}, {0, 5}, {0, 3}, {0, 2}, {1, 1}, {1, 6}, {1, 3}});
}
HeatExchangerDesignProblem::HeatExchangerDesignProblem()
: prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<8>()} {
prog_->AddLinearConstraint(1 - 0.0025 * (x_(3) + x_(5)) >= 0);
prog_->AddLinearConstraint(1 - 0.0025 * (x_(4) + x_(6) - x_(3)) >= 0);
prog_->AddLinearConstraint(1 - 0.01 * (x_(7) - x_(4)) >= 0);
prog_->AddConstraint(std::make_shared<HeatExchangerDesignConstraint1>(),
x_.head<6>());
prog_->AddConstraint(std::make_shared<HeatExchangerDesignConstraint2>(),
x_.tail<7>());
Eigen::Matrix<double, 8, 1> x_lower, x_upper;
x_lower << 100, 1000, 1000, 10, 10, 10, 10, 10;
x_upper << 10000, 10000, 10000, 1000, 1000, 1000, 1000, 1000;
prog_->AddBoundingBoxConstraint(x_lower, x_upper, x_);
prog_->AddLinearCost(x_(0) + x_(1) + x_(2));
}
void HeatExchangerDesignProblem::CheckSolution(
const MathematicalProgramResult& result, double tol) const {
ASSERT_TRUE(result.is_success());
const auto x_val = result.GetSolution(x_);
Eigen::Matrix<double, 8, 1> x_expected;
x_expected << 579.3167, 1359.943, 5110.071, 182.0174, 295.5985, 217.9799,
286.4162, 395.5979;
EXPECT_TRUE(CompareMatrices(x_val, x_expected, tol));
EXPECT_NEAR(result.get_optimal_cost(), 7049.330923, tol);
}
EmptyGradientProblem::EmptyGradientProblem()
: prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<2>()} {
prog_->AddCost(std::make_shared<EmptyGradientProblem::EmptyGradientCost>(),
x_);
prog_->AddConstraint(
std::make_shared<EmptyGradientProblem::EmptyGradientConstraint>(), x_);
}
void EmptyGradientProblem::CheckSolution(
const MathematicalProgramResult& result) const {
EXPECT_TRUE(result.is_success());
}
EmptyGradientProblem::EmptyGradientConstraint::EmptyGradientConstraint()
: Constraint(1, 2, Vector1d(-kInf), Vector1d(0)) {}
// min_x |x|₂ s.t. 2x₀ + x₁ ≥ 1.
// The optimal solution is x = [2/5, 1/5].
void TestL2NormCost(const SolverInterface& solver, double tol) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables(2, "x");
prog.AddL2NormCost(Matrix2d::Identity(), Vector2d::Zero(), x);
prog.AddLinearConstraint(2 * x[0] + x[1] >= 1);
MathematicalProgramResult result;
solver.Solve(prog, std::nullopt, std::nullopt, &result);
EXPECT_TRUE(result.is_success());
EXPECT_NEAR(result.GetSolution(x[0]), 0.4, tol);
EXPECT_NEAR(result.GetSolution(x[1]), 0.2, tol);
}
class DummyConstraint : public Constraint {
// 0.5x² + 0.5*y² + z² = 1
public:
DummyConstraint() : Constraint(1, 3, Vector1d(1), Vector1d(1)) {}
protected:
template <typename T>
void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x,
VectorX<T>* y) const {
y->resize(1);
(*y)(0) = 0.5 * x(0) * x(0) + 0.5 * x(1) * x(1) + x(2) * x(2);
}
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override {
DoEvalGeneric<double>(x, y);
}
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override {
DoEvalGeneric<AutoDiffXd>(x, y);
}
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override {
DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y);
}
};
class DummyCost : public Cost {
// -x²-2xy - 2xz - y² - 3z²
public:
DummyCost() : Cost(3) {}
protected:
template <typename T>
void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x,
VectorX<T>* y) const {
y->resize(1);
(*y)(0) = -x(0) * x(0) - 2 * x(0) * x(1) - 2 * x(0) * x(2) - x(1) * x(1) -
3 * x(2) * x(2);
}
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override {
DoEvalGeneric<double>(x, y);
}
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override {
DoEvalGeneric<AutoDiffXd>(x, y);
}
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const override {
DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y);
}
};
DuplicatedVariableNonlinearProgram1::DuplicatedVariableNonlinearProgram1()
: prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<2>()} {
prog_->AddBoundingBoxConstraint(0, kInf, x_);
prog_->AddCost(std::make_shared<DummyCost>(),
Vector3<symbolic::Variable>(x_(0), x_(1), x_(1)));
prog_->AddConstraint(std::make_shared<DummyConstraint>(),
Vector3<symbolic::Variable>(x_(0), x_(0), x_(1)));
}
void DuplicatedVariableNonlinearProgram1::CheckSolution(
const SolverInterface& solver, const Eigen::Vector2d& x_init,
const std::optional<SolverOptions>& solver_options, double tol) const {
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(*prog_, x_init, solver_options, &result);
ASSERT_TRUE(result.is_success());
EXPECT_TRUE(CompareMatrices(
result.GetSolution(x_),
Eigen::Vector2d(1 / std::sqrt(5), 2 / std::sqrt(5)), tol));
EXPECT_NEAR(result.get_optimal_cost(), -5, tol);
}
}
QuadraticEqualityConstrainedProgram1::QuadraticEqualityConstrainedProgram1()
: prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<2>()} {
prog_->AddLinearCost(-x_(0) - 2 * x_(1));
prog_->AddQuadraticConstraint(
x_(0) * x_(0) + x_(1) * x_(1), 1, 1,
QuadraticConstraint::HessianType::kPositiveSemidefinite);
}
void QuadraticEqualityConstrainedProgram1::CheckSolution(
const SolverInterface& solver, const Eigen::Vector2d& x_init,
const std::optional<SolverOptions>& solver_options, double tol,
bool check_dual) const {
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(*prog_, x_init, solver_options, &result);
EXPECT_TRUE(result.is_success());
const auto x_sol = result.GetSolution(x_);
EXPECT_TRUE(CompareMatrices(
x_sol, Eigen::Vector2d(1 / std::sqrt(5), 2 / std::sqrt(5)), tol));
if (check_dual) {
EXPECT_TRUE(CompareMatrices(
result.GetDualSolution(prog_->quadratic_constraints()[0]),
Vector1d(-std::sqrt(5) / 2), tol));
}
}
}
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/second_order_cone_program_examples.cc | #include "drake/solvers/test/second_order_cone_program_examples.h"
#include <limits>
#include <memory>
#include <optional>
#include <utility>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/solvers/decision_variable.h"
#include "drake/solvers/test/mathematical_program_test_util.h"
namespace drake {
namespace solvers {
namespace test {
const double kInf = std::numeric_limits<double>::infinity();
std::ostream& operator<<(std::ostream& os, EllipsoidsSeparationProblem value) {
os << "EllipsoidsSeparationProblem::";
switch (value) {
case EllipsoidsSeparationProblem::kProblem0: {
os << "kProblem0";
return os;
}
case EllipsoidsSeparationProblem::kProblem1: {
os << "kProblem1";
return os;
}
case EllipsoidsSeparationProblem::kProblem2: {
os << "kProblem2";
return os;
}
case EllipsoidsSeparationProblem::kProblem3: {
os << "kProblem3";
return os;
}
}
DRAKE_UNREACHABLE();
}
std::vector<EllipsoidsSeparationProblem> GetEllipsoidsSeparationProblems() {
return {EllipsoidsSeparationProblem::kProblem0,
EllipsoidsSeparationProblem::kProblem1,
EllipsoidsSeparationProblem::kProblem2,
EllipsoidsSeparationProblem::kProblem3};
}
TestEllipsoidsSeparation::TestEllipsoidsSeparation() {
switch (GetParam()) {
case EllipsoidsSeparationProblem::kProblem0: {
x1_ = Eigen::Vector3d::Zero();
x2_ = Eigen::Vector3d::Zero();
x2_(0) = 2.0;
R1_ = 0.5 * Eigen::Matrix3d::Identity();
R2_ = Eigen::Matrix3d::Identity();
break;
}
case EllipsoidsSeparationProblem::kProblem1: {
x1_ = Eigen::Vector3d::Zero();
x2_ = Eigen::Vector3d::Zero();
x2_(0) = 1.0;
R1_ = Eigen::Matrix3d::Identity();
R2_ = Eigen::Matrix3d::Identity();
break;
}
case EllipsoidsSeparationProblem::kProblem2: {
x1_ = Eigen::Vector2d(1.0, 0.2);
x2_ = Eigen::Vector2d(0.5, 0.4);
R1_.resize(2, 2);
R1_ << 0.1, 0.6, 0.2, 1.3;
R2_.resize(2, 2);
R2_ << -0.4, 1.5, 1.7, 0.3;
break;
}
case EllipsoidsSeparationProblem::kProblem3: {
x1_ = Eigen::Vector3d(1.0, 0.2, 0.8);
x2_ = Eigen::Vector3d(3.0, -1.5, 1.9);
R1_.resize(3, 3);
R1_ << 0.2, 0.4, 0.2, -0.2, -0.1, 0.3, 0.2, 0.1, 0.1;
R2_.resize(3, 2);
R2_ << 0.1, 0.2, -0.1, 0.01, -0.2, 0.1;
break;
}
}
const int kXdim = x1_.rows();
t_ = prog_.NewContinuousVariables<2>("t");
a_ = prog_.NewContinuousVariables(kXdim, "a");
// Add Lorentz cone constraints
// t1 >= |R1'*a|
// t2 >= |R2'*a|
// Introduce matrices
// A_lorentz1 = [1 0;0 R1']
// A_lorentz2 = [1 0;0 R2']
// b_lorentz1 = 0;
// b_lorentz2 = 0;
// And both A_lorentz1*[t;a]+b_lorentz1, A_lorentz2*[t;a]+b_lorentz2 are
// in the Lorentz cone.
VectorX<symbolic::Expression> lorentz_expr1(1 + R1_.cols());
VectorX<symbolic::Expression> lorentz_expr2(1 + R2_.cols());
lorentz_expr1 << t_(0), R1_.transpose() * a_;
lorentz_expr2 << t_(1), R2_.transpose() * a_;
prog_.AddLorentzConeConstraint(lorentz_expr1);
prog_.AddLorentzConeConstraint(lorentz_expr2);
// a'*(x2 - x1) = 1
prog_.AddLinearEqualityConstraint((x2_ - x1_).transpose(), 1.0, a_);
// Add cost
auto cost = prog_.AddLinearCost(Eigen::Vector2d(1.0, 1.0), t_).evaluator();
}
void TestEllipsoidsSeparation::SolveAndCheckSolution(
const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options, double tol) {
MathematicalProgramResult result =
RunSolver(prog_, solver, {}, solver_options);
// Check the solution.
// First check if each constraint is satisfied.
const auto& a_value = result.GetSolution(a_);
const auto& R1a_value = R1_.transpose() * a_value;
const auto& R2a_value = R2_.transpose() * a_value;
EXPECT_NEAR(result.GetSolution(t_(0)), R1a_value.norm(), 100 * tol);
EXPECT_NEAR(result.GetSolution(t_(1)), R2a_value.norm(), 100 * tol);
EXPECT_NEAR((x2_ - x1_).dot(a_value), 1.0, tol);
// Now check if the solution is meaningful, that it really finds a separating
// hyperplane.
// The separating hyperplane exists if and only if p* <= 1
const double p_star = result.GetSolution(t_(0)) + result.GetSolution(t_(1));
const bool is_separated = p_star <= 1.0;
const double t1 = result.GetSolution(t_(0));
const double t2 = result.GetSolution(t_(1));
if (is_separated) {
// Then the hyperplane a' * x = 0.5 * (a'*x1 + t1 + a'*x2 - t2)
const double b1 = a_value.dot(x1_) + t1;
const double b2 = a_value.dot(x2_) - t2;
const double b = 0.5 * (b1 + b2);
// Verify that b - a'*x1 >= |R1' * a|
// a'*x2 - b >= |R2' * a|
EXPECT_GE(b - a_value.dot(x1_), (R1_.transpose() * a_value).norm());
EXPECT_GE(a_value.dot(x2_) - b, (R2_.transpose() * a_value).norm());
} else {
// Now solve another SOCP to find a point y in the intersecting region
// y = x1 + R1*u1
// y = x2 + R2*u2
// 1 >= |u1|
// 1 >= |u2|
MathematicalProgram prog_intersect;
const int kXdim = R1_.rows();
auto u1 = prog_intersect.NewContinuousVariables(R1_.cols(), "u1");
auto u2 = prog_intersect.NewContinuousVariables(R2_.cols(), "u2");
auto y = prog_intersect.NewContinuousVariables(kXdim, "y");
// Add the constraint that both
// [1; u1] and [1; u2] are in the Lorentz cone.
VectorX<symbolic::Expression> e1(1 + u1.rows());
VectorX<symbolic::Expression> e2(1 + u2.rows());
e1(0) = 1;
e2(0) = 1;
for (int i = 0; i < u1.rows(); ++i) {
e1(i + 1) = +u1(i);
}
for (int i = 0; i < u2.rows(); ++i) {
e2(i + 1) = +u2(i);
}
prog_intersect.AddLorentzConeConstraint(e1);
prog_intersect.AddLorentzConeConstraint(e2);
// Add constraint y = x1 + R1*u1
// y = x2 + R2*u2
Eigen::MatrixXd A1(y.rows(), y.rows() + R1_.cols());
A1.block(0, 0, y.rows(), y.rows()) =
Eigen::MatrixXd::Identity(y.rows(), y.rows());
A1.block(0, y.rows(), y.rows(), R1_.cols()) = -R1_;
Eigen::MatrixXd A2(y.rows(), y.rows() + R2_.cols());
A2.block(0, 0, y.rows(), y.rows()) =
Eigen::MatrixXd::Identity(y.rows(), y.rows());
A2.block(0, y.rows(), y.rows(), R2_.cols()) = -R2_;
prog_intersect.AddLinearEqualityConstraint(A1, x1_, {y, u1});
prog_intersect.AddLinearEqualityConstraint(A2, x2_, {y, u2});
result = RunSolver(prog_intersect, solver);
// Check if the constraints are satisfied
const auto& u1_value = result.GetSolution(u1);
const auto& u2_value = result.GetSolution(u2);
EXPECT_LE(u1_value.norm(), 1);
EXPECT_LE(u2_value.norm(), 1);
const auto& y_value = result.GetSolution(y);
EXPECT_TRUE(CompareMatrices(y_value, x1_ + R1_ * u1_value, tol,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(y_value, x2_ + R2_ * u2_value, tol,
MatrixCompareType::absolute));
}
}
std::ostream& operator<<(std::ostream& os, QPasSOCPProblem value) {
os << "QPasSOCPProblem::";
switch (value) {
case QPasSOCPProblem::kProblem0: {
os << "kProblem0";
return os;
}
case QPasSOCPProblem::kProblem1: {
os << "kProblem1";
return os;
}
}
DRAKE_UNREACHABLE();
}
std::vector<QPasSOCPProblem> GetQPasSOCPProblems() {
return {QPasSOCPProblem::kProblem0, QPasSOCPProblem::kProblem1};
}
TestQPasSOCP::TestQPasSOCP() {
switch (GetParam()) {
case QPasSOCPProblem::kProblem0:
// Un-constrained QP
Q_ = Eigen::Matrix2d::Identity();
c_ = Eigen::Vector2d::Ones();
A_ = Eigen::RowVector2d(0, 0);
b_lb_ = Vector1<double>(-kInf);
b_ub_ = Vector1<double>(kInf);
break;
case QPasSOCPProblem::kProblem1:
// Constrained QP
Q_ = Eigen::Matrix3d::Zero();
Q_(0, 0) = 1.0;
Q_(1, 1) = 1.3;
Q_(2, 2) = 2.0;
Q_(1, 2) = 0.01;
Q_(0, 1) = -0.2;
c_ = Eigen::Vector3d(-1.0, -2.0, 1.2);
A_.resize(2, 3);
A_ << 1, 0, 2, 0, 1, 3;
b_lb_ = Eigen::Vector2d(-1, -2);
b_ub_ = Eigen::Vector2d(2, 4);
break;
}
const int kXdim = Q_.rows();
const Eigen::MatrixXd Q_symmetric = 0.5 * (Q_ + Q_.transpose());
x_socp_ = prog_socp_.NewContinuousVariables(kXdim, "x");
y_ = prog_socp_.NewContinuousVariables<1>("y")(0);
Eigen::LLT<Eigen::MatrixXd, Eigen::Upper> lltOfQ(Q_symmetric);
Eigen::MatrixXd Q_sqrt = lltOfQ.matrixU();
VectorX<symbolic::Expression> e(2 + kXdim);
e << y_, 2, Q_sqrt * x_socp_;
prog_socp_.AddRotatedLorentzConeConstraint(e);
prog_socp_.AddLinearConstraint(A_, b_lb_, b_ub_, x_socp_);
auto cost_socp1 = std::make_shared<LinearCost>(c_.transpose());
prog_socp_.AddCost(cost_socp1, x_socp_);
prog_socp_.AddLinearCost(+y_);
x_qp_ = prog_qp_.NewContinuousVariables(kXdim, "x");
prog_qp_.AddQuadraticCost(Q_, c_, x_qp_);
prog_qp_.AddLinearConstraint(A_, b_lb_, b_ub_, x_qp_);
}
void TestQPasSOCP::SolveAndCheckSolution(const SolverInterface& solver,
double tol) {
MathematicalProgramResult result;
result = RunSolver(prog_socp_, solver);
const auto& x_socp_value = result.GetSolution(x_socp_);
const double objective_value_socp =
c_.dot(x_socp_value) + result.GetSolution(y_);
// Check the solution
const int kXdim = Q_.rows();
const Eigen::MatrixXd Q_symmetric = 0.5 * (Q_ + Q_.transpose());
const Eigen::LLT<Eigen::MatrixXd, Eigen::Upper> lltOfQ(Q_symmetric);
const Eigen::MatrixXd Q_sqrt = lltOfQ.matrixU();
EXPECT_NEAR(2 * result.GetSolution(y_), (Q_sqrt * x_socp_value).squaredNorm(),
tol);
EXPECT_GE(result.GetSolution(y_), 0);
result = RunSolver(prog_qp_, solver);
const auto& x_qp_value = result.GetSolution(x_qp_);
const Eigen::RowVectorXd x_qp_transpose = x_qp_value.transpose();
Eigen::VectorXd Q_x_qp = Q_ * x_qp_value;
double objective_value_qp = c_.dot(x_qp_value);
for (int i = 0; i < kXdim; ++i) {
objective_value_qp += 0.5 * x_qp_value(i) * Q_x_qp(i);
}
// TODO([email protected]): tighten the tolerance. socp does not really
// converge to true optimal yet.
EXPECT_TRUE(CompareMatrices(x_qp_value, x_socp_value, 200 * tol,
MatrixCompareType::absolute));
EXPECT_NEAR(objective_value_qp, objective_value_socp, tol);
}
std::ostream& operator<<(std::ostream& os, FindSpringEquilibriumProblem value) {
os << "FindSpringEquilibriumProblem::";
switch (value) {
case FindSpringEquilibriumProblem::kProblem0: {
os << "kProblem0";
return os;
}
}
DRAKE_UNREACHABLE();
}
std::vector<FindSpringEquilibriumProblem> GetFindSpringEquilibriumProblems() {
return {FindSpringEquilibriumProblem::kProblem0};
}
TestFindSpringEquilibrium::TestFindSpringEquilibrium() {
switch (GetParam()) {
case FindSpringEquilibriumProblem::kProblem0: {
weight_.resize(5);
weight_ << 1, 2, 3, 2.5, 4;
spring_rest_length_ = 0.2;
spring_stiffness_ = 10;
end_pos1_ << 0, 1;
end_pos2_ << 1, 0.9;
}
}
const int num_nodes = weight_.rows();
x_ = prog_.NewContinuousVariables(num_nodes, "x");
y_ = prog_.NewContinuousVariables(num_nodes, "y");
t_ = prog_.NewContinuousVariables(num_nodes - 1, "t");
prog_.AddBoundingBoxConstraint(end_pos1_, end_pos1_,
{x_.head<1>(), y_.head<1>()});
prog_.AddBoundingBoxConstraint(
end_pos2_, end_pos2_,
{x_.segment<1>(num_nodes - 1), y_.segment<1>(num_nodes - 1)});
prog_.AddBoundingBoxConstraint(Eigen::VectorXd::Zero(num_nodes - 1),
Eigen::VectorXd::Constant(num_nodes - 1, kInf),
t_);
// sqrt((x(i)-x(i+1))^2 + (y(i) - y(i+1))^2) <= ti + spring_rest_length
for (int i = 0; i < num_nodes - 1; ++i) {
Vector3<symbolic::Expression> lorentz_cone_expr;
lorentz_cone_expr << t_(i) + spring_rest_length_, x_(i) - x_(i + 1),
y_(i) - y_(i + 1);
prog_.AddLorentzConeConstraint(lorentz_cone_expr);
}
// Add constraint z >= t_1^2 + .. + t_(N-1)^2
z_ = prog_.NewContinuousVariables<1>("z")(0);
VectorX<symbolic::Expression> rotated_lorentz_cone_expr(1 + num_nodes);
rotated_lorentz_cone_expr << z_, 1, t_;
prog_.AddRotatedLorentzConeConstraint(rotated_lorentz_cone_expr);
prog_.AddLinearCost(spring_stiffness_ / 2 * z_);
prog_.AddLinearCost(weight_.dot(y_));
}
void TestFindSpringEquilibrium::SolveAndCheckSolution(
const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options, double tol) {
const MathematicalProgramResult result =
RunSolver(prog_, solver, {}, solver_options);
const std::optional<SolverId> solver_id = result.get_solver_id();
ASSERT_TRUE(solver_id);
const int num_nodes = weight_.rows();
for (int i = 0; i < num_nodes - 1; ++i) {
Eigen::Vector2d spring(
result.GetSolution(x_(i + 1)) - result.GetSolution(x_(i)),
result.GetSolution(y_(i + 1)) - result.GetSolution(y_(i)));
if (spring.norm() < spring_rest_length_) {
EXPECT_LE(result.GetSolution(t_(i)), 1E-3);
EXPECT_GE(result.GetSolution(t_(i)), 0 - 1E-10);
} else {
EXPECT_TRUE(std::abs(spring.norm() - spring_rest_length_ -
result.GetSolution(t_(i))) < 1E-3);
}
}
const auto& t_value = result.GetSolution(t_);
EXPECT_NEAR(result.GetSolution(z_), t_value.squaredNorm(), 1E-3);
// Now test equilibrium.
for (int i = 1; i < num_nodes - 1; i++) {
Eigen::Vector2d left_spring(
result.GetSolution(x_(i - 1)) - result.GetSolution(x_(i)),
result.GetSolution(y_(i - 1)) - result.GetSolution(y_(i)));
Eigen::Vector2d left_spring_force;
double left_spring_length = left_spring.norm();
if (left_spring_length < spring_rest_length_) {
left_spring_force.setZero();
} else {
left_spring_force = (left_spring_length - spring_rest_length_) *
spring_stiffness_ * left_spring / left_spring_length;
}
Eigen::Vector2d right_spring(
result.GetSolution(x_(i + 1)) - result.GetSolution(x_(i)),
result.GetSolution(y_(i + 1)) - result.GetSolution(y_(i)));
Eigen::Vector2d right_spring_force;
double right_spring_length = right_spring.norm();
if (right_spring_length < spring_rest_length_) {
right_spring_force.setZero();
} else {
right_spring_force = (right_spring_length - spring_rest_length_) *
spring_stiffness_ * right_spring /
right_spring_length;
}
const Eigen::Vector2d weight_i(0, -weight_(i));
EXPECT_TRUE(CompareMatrices(
weight_i + left_spring_force + right_spring_force,
Eigen::Vector2d::Zero(), tol, MatrixCompareType::absolute));
}
}
MaximizeGeometricMeanTrivialProblem1::MaximizeGeometricMeanTrivialProblem1()
: prog_{new MathematicalProgram()},
x_{prog_->NewContinuousVariables<1>()(0)},
cost_{nullptr} {
prog_->AddBoundingBoxConstraint(-kInf, 10, x_);
Eigen::Vector2d A(2, 3);
Eigen::Vector2d b(3, 2);
auto cost = prog_->AddMaximizeGeometricMeanCost(
A, b, Vector1<symbolic::Variable>(x_));
cost_ = std::make_unique<Binding<LinearCost>>(std::move(cost));
}
void MaximizeGeometricMeanTrivialProblem1::CheckSolution(
const MathematicalProgramResult& result, double tol) {
ASSERT_TRUE(result.is_success());
EXPECT_NEAR(result.GetSolution(x_), 10, tol);
const double cost_expected = -std::sqrt(23.0 * 32);
EXPECT_NEAR(result.get_optimal_cost(), cost_expected, tol);
EXPECT_NEAR(result.EvalBinding(*cost_)(0), cost_expected, tol);
}
MaximizeGeometricMeanTrivialProblem2::MaximizeGeometricMeanTrivialProblem2()
: prog_{new MathematicalProgram()},
x_{prog_->NewContinuousVariables<1>()(0)},
cost_{nullptr} {
prog_->AddBoundingBoxConstraint(-kInf, 10, x_);
const Eigen::Vector3d A(2, 3, 4);
const Eigen::Vector3d b(3, 2, 5);
auto cost = prog_->AddMaximizeGeometricMeanCost(
A, b, Vector1<symbolic::Variable>(x_));
cost_ = std::make_unique<Binding<LinearCost>>(std::move(cost));
}
void MaximizeGeometricMeanTrivialProblem2::CheckSolution(
const MathematicalProgramResult& result, double tol) {
ASSERT_TRUE(result.is_success());
EXPECT_NEAR(result.GetSolution(x_), 10, tol);
const double cost_expected = -std::pow(23 * 32 * 45, 1.0 / 4);
EXPECT_NEAR(result.get_optimal_cost(), cost_expected, tol);
EXPECT_NEAR(result.EvalBinding(*cost_)(0), cost_expected, tol);
}
SmallestEllipsoidCoveringProblem::SmallestEllipsoidCoveringProblem(
const Eigen::Ref<const Eigen::MatrixXd>& p)
: prog_{new MathematicalProgram()},
a_{prog_->NewContinuousVariables(p.rows())},
p_{p},
cost_{nullptr} {
auto cost = prog_->AddMaximizeGeometricMeanCost(a_);
cost_ = std::make_unique<Binding<LinearCost>>(std::move(cost));
const Eigen::MatrixXd p_dot_p = (p_.array() * p_.array()).matrix();
const int num_points = p.cols();
prog_->AddLinearConstraint(p_dot_p.transpose(),
Eigen::VectorXd::Constant(num_points, -kInf),
Eigen::VectorXd::Ones(num_points), a_);
}
void SmallestEllipsoidCoveringProblem::CheckSolution(
const MathematicalProgramResult& result, double tol) const {
const auto a_sol = result.GetSolution(a_);
// p_dot_a_dot_p(i) is pᵢᵀ diag(a) * pᵢ
const Eigen::RowVectorXd p_dot_a_dot_p =
a_sol.transpose() * (p_.array() * p_.array()).matrix();
// All points are within the ellipsoid.
EXPECT_TRUE((p_dot_a_dot_p.array() <= 1 + tol).all());
// At least one point is on the boundary of the ellipsoid.
const int num_points = p_.cols();
EXPECT_TRUE(
((p_dot_a_dot_p.transpose().array() - Eigen::ArrayXd::Ones(num_points))
.abs() <= Eigen::ArrayXd::Constant(num_points, tol))
.any());
const double cost_expected = -std::pow(
a_sol.prod(), 1.0 / std::pow(2, (std::ceil(std::log2(a_sol.rows())))));
EXPECT_NEAR(result.get_optimal_cost(), cost_expected, tol);
EXPECT_NEAR(result.EvalBinding(*cost_)(0), cost_expected, tol);
CheckSolutionExtra(result, tol);
}
// Cover the 4 points (1, 1), (1, -1), (-1, 1) and (-1, -1).
SmallestEllipsoidCoveringProblem1::SmallestEllipsoidCoveringProblem1()
: SmallestEllipsoidCoveringProblem(
(Eigen::Matrix<double, 2, 4>() << 1, 1, -1, -1, 1, -1, 1, -1)
.finished()) {}
void SmallestEllipsoidCoveringProblem1::CheckSolutionExtra(
const MathematicalProgramResult& result, double tol) const {
ASSERT_TRUE(result.is_success());
// The smallest ellipsoid is a = (0.5, 0.5);
const Eigen::Vector2d a_expected(0.5, 0.5);
EXPECT_TRUE(CompareMatrices(result.GetSolution(a()), a_expected, tol));
EXPECT_NEAR(result.get_optimal_cost(), -0.5, tol);
}
void SolveAndCheckSmallestEllipsoidCoveringProblems(
const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options, double tol) {
SmallestEllipsoidCoveringProblem1 prob1;
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prob1.prog(), {}, solver_options, &result);
prob1.CheckSolution(result, tol);
}
// Now try 3D points;
Eigen::Matrix<double, 3, 4> points_3d;
// arbitrary points.
// clang-format off
points_3d << 0.1, 0.2, -1.2, 0.5,
-0.3, 0.1, -2.5, 0.8,
1.2, 0.3, 1.5, 3.2;
// clang-format on
SmallestEllipsoidCoveringProblem prob_3d(points_3d);
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prob_3d.prog(), {}, solver_options, &result);
prob_3d.CheckSolution(result, tol);
}
// Now try arbitrary 4d points.
Eigen::Matrix<double, 4, 6> points_4d;
// clang-format off
points_4d << 1, 2, 3, 4, 5, 6,
0.1, 1.4, 3.2, -2.3, 0.7, -0.3,
-0.2, -3.1, 0.4, 1.5, 1.8, 1.9,
-1, -2, -3, -4, -5, -6;
// clang-format on
SmallestEllipsoidCoveringProblem prob_4d(points_4d);
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prob_4d.prog(), {}, solver_options, &result);
prob_4d.CheckSolution(result, tol);
}
}
void TestSocpDualSolution1(const SolverInterface& solver,
const SolverOptions& solver_options, double tol) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
auto constraint1 = prog.AddLorentzConeConstraint(
Vector3<symbolic::Expression>(2., 2 * x(0), 3 * x(1) + 1));
prog.AddLinearCost(x(1));
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prog, {} /* empty initial guess */, solver_options, &result);
// The dual solution for lorentz cone constraint are the values of the dual
// variables, lies in the dual cone of a Lorentz cone (which is also a
// Lorentz cone). Notice that this is NOT the shadow price as in the linear
// constraints.
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1),
Eigen::Vector3d(1. / 3, 0, 1. / 3), tol));
auto bb_con = prog.AddBoundingBoxConstraint(0.1, kInf, x(1));
solver.Solve(prog, {}, solver_options, &result);
ASSERT_TRUE(result.is_success());
EXPECT_NEAR(result.GetSolution(x(1)), 0.1, tol);
// The cost is x(1), hence the shadow price for the constraint x(1) >= 0
// should be 1.
EXPECT_TRUE(
CompareMatrices(result.GetDualSolution(bb_con), Vector1d(1.), tol));
}
}
void TestSocpDualSolution2(const SolverInterface& solver,
const SolverOptions& solver_options, double tol) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>()(0);
auto constraint1 = prog.AddRotatedLorentzConeConstraint(
Vector3<symbolic::Expression>(2., x + 1.5, x));
auto constraint2 =
prog.AddLorentzConeConstraint(Vector2<symbolic::Expression>(1, x + 1));
prog.AddLinearCost(x);
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prog, {}, solver_options, &result);
ASSERT_TRUE(result.is_success());
const Eigen::Vector3d constraint1_dual = Eigen::Vector3d(0.125, 0.5, 0.5);
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1),
constraint1_dual, tol));
// This Lorentz cone is not activated, hence its dual should be zero.
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint2),
Eigen::Vector2d(0, 0), tol));
}
}
void TestSocpDuplicatedVariable1(
const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options, double tol) {
MathematicalProgram prog;
const auto x = prog.NewContinuousVariables<2>();
// Add the constraint that
// (1, x0, sqrt(3)*x1, -sqrt(3)*x0) is in the Lorentz cone.
Eigen::Matrix<double, 4, 3> A;
A.setZero();
A(1, 0) = 1;
A(2, 1) = std::sqrt(3);
A(3, 2) = -std::sqrt(3);
prog.AddLorentzConeConstraint(A, Eigen::Vector4d(1, 0, 0, 0),
Vector3<symbolic::Variable>(x(0), x(1), x(0)));
prog.AddLinearCost(x(0) + x(1));
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prog, std::nullopt, solver_options, &result);
EXPECT_TRUE(result.is_success());
const Eigen::Vector2d x_sol = result.GetSolution(x);
EXPECT_NEAR(4 * x_sol(0) * x_sol(0) + 3 * x_sol(1) * x_sol(1), 1, tol);
}
}
void TestSocpDuplicatedVariable2(
const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options, double tol) {
MathematicalProgram prog;
// Intentionally create dummy variable to test that the constraint doesn't
// take all variables in `prog`.
auto dummy = prog.NewContinuousVariables<2>();
auto x = prog.NewContinuousVariables<2>();
// A * [x(0), x(1), x(0), x(1)] + b = [1; 2x(0); 3x(1)]
Eigen::Matrix<double, 3, 4> A;
// clang-format off
A << 1, 0, -1, 0,
3, 0, -1, 0,
2, 2, -2, 1;
// clang-format on
Eigen::Vector3d b(1, 0, 0);
prog.AddLorentzConeConstraint(A, b, {x, x});
prog.AddLinearCost(-x(0) - x(1));
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prog, std::nullopt, solver_options, &result);
EXPECT_TRUE(result.is_success());
const auto x_sol = result.GetSolution(x);
// This expected solution is obtained by solving the equation
// 4x0²+9x1² = 1
// x0+x1= sqrt(13)/6
// where x0+x1=sqrt(13)/6 is obtained from the Jensen's inequality
// (4x0²+9x1²) * (1/4 + 1/9) >= (x0+x1)²
// Also by the fact
// (4x0²+9x1²) * (1/4 + 1/9) <= (1/4 + 1/9) = 13 / 36 = (sqrt(13)/6)²
// We obtain x + y <= sqrt(13)/6 and the bound is tight.
Eigen::Vector2d x_expected(3 * std::sqrt(13) / 26, 4 * std::sqrt(13) / 78);
EXPECT_TRUE(CompareMatrices(x_sol, x_expected, tol));
}
}
void TestDegenerateSOCP(const SolverInterface& solver) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<3>();
// A * [x(0), x(1), x(2), x(1), x(2)] = [x(0); x(1)-x(1); x(2)-x(2)]
Eigen::Matrix<double, 3, 5> A;
A.setZero();
A(0, 0) = 1;
A.block<2, 2>(1, 1) = Eigen::Matrix2d::Identity();
A.block<2, 2>(1, 3) = -Eigen::Matrix2d::Identity();
prog.AddLorentzConeConstraint(A, Eigen::Vector3d::Zero(), {x, x.tail<2>()});
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prog, std::nullopt, std::nullopt, &result);
EXPECT_TRUE(result.is_success());
const auto x_sol = result.GetSolution(x);
EXPECT_GE(x_sol(0), 0);
}
}
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/mixed_integer_optimization_util_test.cc | #include "drake/solvers/mixed_integer_optimization_util.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/math/gray_code.h"
#include "drake/solvers/gurobi_solver.h"
namespace drake {
namespace solvers {
namespace {
GTEST_TEST(TestMixedIntegerUtil, TestCeilLog2) {
// Check that CeilLog2(j) returns i + 1 for all j = 2ⁱ + 1, 2ⁱ + 2, ... , 2ⁱ⁺¹
const int kMaxExponent = 15;
EXPECT_EQ(0, CeilLog2(1));
for (int i = 0; i < kMaxExponent; ++i) {
for (int j = (1 << i) + 1; j <= (1 << (i + 1)); ++j) {
EXPECT_EQ(i + 1, CeilLog2(j));
}
}
}
GTEST_TEST(TestLogarithmicSos2, TestAddSos2) {
MathematicalProgram prog;
auto lambda1 = prog.NewContinuousVariables(3, "lambda1");
auto y1 =
AddLogarithmicSos2Constraint(&prog, lambda1.cast<symbolic::Expression>());
static_assert(std::is_same_v<decltype(y1), VectorXDecisionVariable>,
"y1 should be a dynamic-sized vector.");
auto lambda2 = prog.NewContinuousVariables<3>("lambda2");
auto y2 =
AddLogarithmicSos2Constraint(&prog, lambda2.cast<symbolic::Expression>());
static_assert(std::is_same_v<decltype(y2), VectorDecisionVariable<1>>,
"y2 should be a static-sized vector.");
}
void LogarithmicSos2Test(int num_lambda, bool logarithmic_binning) {
// Solve the program
// min λᵀ * λ
// s.t sum λ = 1
// λ in sos2
// We loop over i such that only λ(i) and λ(i+1) can be strictly positive.
// The optimal cost is λ(i) = λ(i + 1) = 0.5.
MathematicalProgram prog;
auto lambda = prog.NewContinuousVariables(num_lambda, "lambda");
prog.AddCost(lambda.cast<symbolic::Expression>().dot(lambda));
VectorXDecisionVariable y;
if (logarithmic_binning) {
y = AddLogarithmicSos2Constraint(&prog,
lambda.cast<symbolic::Expression>());
} else {
y = prog.NewBinaryVariables(num_lambda - 1);
AddSos2Constraint(&prog, lambda.cast<symbolic::Expression>(),
y.cast<symbolic::Expression>());
}
int num_binary_vars = y.rows();
int num_intervals = num_lambda - 1;
auto y_assignment = prog.AddBoundingBoxConstraint(0, 1, y);
// If we use logarithmic binning, we will assign the binary variables y with
// value i, expressed in Gray code.
const auto gray_codes = math::CalculateReflectedGrayCodes(num_binary_vars);
Eigen::VectorXd y_val(y.rows());
for (int i = 0; i < num_intervals; ++i) {
y_val.setZero();
if (logarithmic_binning) {
for (int j = 0; j < num_binary_vars; ++j) {
y_val(j) = gray_codes(i, j);
}
} else {
y_val(i) = 1;
}
y_assignment.evaluator()->UpdateLowerBound(y_val);
y_assignment.evaluator()->UpdateUpperBound(y_val);
GurobiSolver gurobi_solver;
if (gurobi_solver.available()) {
auto result = gurobi_solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
const auto lambda_val = result.GetSolution(lambda);
Eigen::VectorXd lambda_val_expected = Eigen::VectorXd::Zero(num_lambda);
lambda_val_expected(i) = 0.5;
lambda_val_expected(i + 1) = 0.5;
EXPECT_TRUE(CompareMatrices(lambda_val, lambda_val_expected, 1E-5,
MatrixCompareType::absolute));
}
}
}
GTEST_TEST(TestSos2, TestClosestPointOnLineSegments) {
// We will define line segments A₀A₁, ..., A₅A₆ in 2D, where points Aᵢ are
// defined as A₀ = (0, 0), A₁ = (1, 1), A₂ = (2, 0), A₃ = (4, 2), A₅ = (6, 0),
// A₅ = (7, 1), A₆ = (8, 0). We compute the closest point P = (x, y) on the
// line segments to a given point Q.
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>()(0);
auto y = prog.NewContinuousVariables<1>()(0);
Eigen::Matrix<double, 2, 7> A;
// clang-format off
A << 0, 1, 2, 4, 6, 7, 8,
0, 1, 0, 2, 0, 1, 0;
// clang-format on
auto lambda = prog.NewContinuousVariables<7>();
auto z = prog.NewBinaryVariables<6>();
AddSos2Constraint(&prog, lambda.cast<symbolic::Expression>(),
z.cast<symbolic::Expression>());
const Vector2<symbolic::Expression> line_segment = A * lambda;
prog.AddLinearConstraint(line_segment(0) == x);
prog.AddLinearConstraint(line_segment(1) == y);
// Add a dummy cost function, which we will change in the for loop below.
Binding<QuadraticCost> cost =
prog.AddQuadraticCost(Eigen::Matrix2d::Zero(), Eigen::Vector2d::Zero(), 0,
VectorDecisionVariable<2>(x, y));
// We will test with different points Qs, each Q corresponds to a nearest
// point P on the line segments.
std::vector<std::pair<Eigen::Vector2d, Eigen::Vector2d>> Q_and_P;
Q_and_P.push_back(
std::make_pair(Eigen::Vector2d(1, 1), Eigen::Vector2d(1, 1)));
Q_and_P.push_back(
std::make_pair(Eigen::Vector2d(1.9, 1), Eigen::Vector2d(1.45, 0.55)));
Q_and_P.push_back(
std::make_pair(Eigen::Vector2d(3, 1), Eigen::Vector2d(3, 1)));
Q_and_P.push_back(
std::make_pair(Eigen::Vector2d(5, 1.2), Eigen::Vector2d(4.9, 1.1)));
Q_and_P.push_back(
std::make_pair(Eigen::Vector2d(7.5, 1.2), Eigen::Vector2d(7.15, 0.85)));
for (const auto& QP_pair : Q_and_P) {
const Eigen::Vector2d& Q = QP_pair.first;
// The cost is |P-Q|²
cost.evaluator()->UpdateCoefficients(2 * Eigen::Matrix2d::Identity(),
-2 * Q, Q.squaredNorm());
// Any mixed integer convex solver can solve this problem, here we choose
// gurobi.
GurobiSolver gurobi_solver;
if (gurobi_solver.available()) {
auto result = gurobi_solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
const Eigen::Vector2d P(
result.GetSolution(VectorDecisionVariable<2>(x, y)));
const Eigen::Vector2d P_expected = QP_pair.second;
EXPECT_TRUE(CompareMatrices(P, P_expected, 1E-6));
EXPECT_NEAR(result.get_optimal_cost(), (Q - P_expected).squaredNorm(),
1E-12);
}
}
}
GTEST_TEST(TestLogarithmicSos2, Test4Lambda) {
LogarithmicSos2Test(4, true);
}
GTEST_TEST(TestLogarithmicSos2, Test5Lambda) {
LogarithmicSos2Test(5, true);
}
GTEST_TEST(TestLogarithmicSos2, Test6Lambda) {
LogarithmicSos2Test(6, true);
}
GTEST_TEST(TestLogarithmicSos2, Test7Lambda) {
LogarithmicSos2Test(7, true);
}
GTEST_TEST(TestLogarithmicSos2, Test8Lambda) {
LogarithmicSos2Test(8, true);
}
GTEST_TEST(TestSos2, Test4Lambda) {
LogarithmicSos2Test(4, false);
}
GTEST_TEST(TestSos2, Test5Lambda) {
LogarithmicSos2Test(5, false);
}
GTEST_TEST(TestSos2, Test6Lambda) {
LogarithmicSos2Test(6, false);
}
GTEST_TEST(TestSos2, Test7Lambda) {
LogarithmicSos2Test(7, false);
}
GTEST_TEST(TestSos2, Test8Lambda) {
LogarithmicSos2Test(8, false);
}
void LogarithmicSos1Test(int num_lambda,
const Eigen::Ref<const Eigen::MatrixXi>& codes) {
// Check if we impose the constraint
// λ is in sos1
// and assign values to the binary variables,
// whether the corresponding λ(i) is 1.
MathematicalProgram prog;
auto lambda = prog.NewContinuousVariables(num_lambda);
int num_digits = CeilLog2(num_lambda);
auto y = prog.NewBinaryVariables(num_digits);
AddLogarithmicSos1Constraint(&prog, lambda.cast<symbolic::Expression>(), y,
codes);
auto binary_assignment = prog.AddBoundingBoxConstraint(0, 0, y);
for (int i = 0; i < num_lambda; ++i) {
Eigen::VectorXd code = codes.row(i).cast<double>().transpose();
binary_assignment.evaluator()->UpdateLowerBound(code);
binary_assignment.evaluator()->UpdateUpperBound(code);
GurobiSolver gurobi_solver;
if (gurobi_solver.available()) {
auto result = gurobi_solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
Eigen::VectorXd lambda_expected(num_lambda);
lambda_expected.setZero();
lambda_expected(i) = 1;
EXPECT_TRUE(CompareMatrices(result.GetSolution(lambda), lambda_expected,
1E-6, MatrixCompareType::absolute));
}
}
}
GTEST_TEST(TestLogarithmicSos1, Test2Lambda) {
Eigen::Matrix<int, 2, 1> codes;
codes << 0, 1;
LogarithmicSos1Test(2, codes);
// Test a different codes
codes << 1, 0;
LogarithmicSos1Test(2, codes);
}
GTEST_TEST(TestLogarithmicSos1, Test3Lambda) {
Eigen::Matrix<int, 3, 2> codes;
// clang-format off
codes << 0, 0,
0, 1,
1, 0;
// clang-format on
LogarithmicSos1Test(3, codes);
// Test a different codes
// clang-format off
codes << 0, 0,
0, 1,
1, 1;
// clang-format on
LogarithmicSos1Test(3, codes);
}
GTEST_TEST(TestLogarithmicSos1, Test4Lambda) {
Eigen::Matrix<int, 4, 2> codes;
// clang-format off
codes << 0, 0,
0, 1,
1, 0,
1, 1;
// clang-format on
LogarithmicSos1Test(4, codes);
// Test a different codes
// clang-format off
codes << 0, 0,
0, 1,
1, 1,
1, 0;
// clang-format on
LogarithmicSos1Test(4, codes);
}
GTEST_TEST(TestLogarithmicSos1, Test5Lambda) {
auto codes = math::CalculateReflectedGrayCodes<3>();
LogarithmicSos1Test(5, codes.topRows<5>());
}
GTEST_TEST(TestLogarithmicSos1, Test) {
MathematicalProgram prog;
VectorX<symbolic::Variable> y, lambda;
std::tie(lambda, y) = AddLogarithmicSos1Constraint(&prog, 3);
EXPECT_EQ(lambda.rows(), 3);
EXPECT_EQ(y.rows(), 2);
auto check = [&prog, &y, &lambda](const Eigen::VectorXd& lambda_val,
const Eigen::VectorXd& y_val,
bool satisfied_expected) {
Eigen::VectorXd x_val = Eigen::VectorXd::Zero(prog.num_vars());
prog.SetDecisionVariableValueInVector(y, y_val, &x_val);
prog.SetDecisionVariableValueInVector(lambda, lambda_val, &x_val);
bool satisfied = true;
for (const auto& binding : prog.GetAllConstraints()) {
satisfied =
satisfied && binding.evaluator()->CheckSatisfied(
prog.GetBindingVariableValues(binding, x_val));
}
EXPECT_EQ(satisfied, satisfied_expected);
};
check(Eigen::Vector3d(0, 0, 1), Eigen::Vector2d(1, 1), true);
check(Eigen::Vector3d(1, 0, 0), Eigen::Vector2d(1, 0), false);
check(Eigen::Vector3d(0, 1, 0), Eigen::Vector2d(0, 1), true);
check(Eigen::Vector3d(0, 0.5, 0.5), Eigen::Vector2d(1, 1), false);
check(Eigen::Vector3d(0, 0.1, 1), Eigen::Vector2d(1, 0), false);
}
GTEST_TEST(TestBilinearProductMcCormickEnvelopeSos2, AddConstraint) {
// Test if the return argument from
// AddBilinearProductMcCormickEnvelopeSos2 has the right type.
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>()(0);
auto y = prog.NewContinuousVariables<1>()(0);
auto w = prog.NewContinuousVariables<1>()(0);
const Eigen::Vector3d phi_x_static(0, 1, 2);
Eigen::VectorXd phi_x_dynamic = Eigen::VectorXd::LinSpaced(3, 0, 2);
const Eigen::Vector4d phi_y_static = Eigen::Vector4d::LinSpaced(0, 3);
Eigen::VectorXd phi_y_dynamic = Eigen::VectorXd::LinSpaced(4, 0, 3);
Vector1<symbolic::Expression> Bx = prog.NewBinaryVariables<1>();
Vector2<symbolic::Expression> By = prog.NewBinaryVariables<2>();
auto lambda1 = AddBilinearProductMcCormickEnvelopeSos2(
&prog, x, y, w, phi_x_static, phi_y_static, Bx, By,
IntervalBinning::kLogarithmic);
static_assert(std::is_same_v<decltype(lambda1), MatrixDecisionVariable<3, 4>>,
"lambda should be a static matrix");
auto lambda2 = AddBilinearProductMcCormickEnvelopeSos2(
&prog, x, y, w, phi_x_dynamic, phi_y_static, Bx, By,
IntervalBinning::kLogarithmic);
static_assert(std::is_same_v<decltype(lambda2),
MatrixDecisionVariable<Eigen::Dynamic, 4>>,
"lambda's type is incorrect");
auto lambda3 = AddBilinearProductMcCormickEnvelopeSos2(
&prog, x, y, w, phi_x_static, phi_y_dynamic, Bx, By,
IntervalBinning::kLogarithmic);
static_assert(std::is_same_v<decltype(lambda3),
MatrixDecisionVariable<3, Eigen::Dynamic>>,
"lambda's type is incorrect");
auto lambda4 = AddBilinearProductMcCormickEnvelopeSos2(
&prog, x, y, w, phi_x_dynamic, phi_y_dynamic, Bx, By,
IntervalBinning::kLogarithmic);
static_assert(
std::is_same_v<decltype(lambda4),
MatrixDecisionVariable<Eigen::Dynamic, Eigen::Dynamic>>,
"lambda's type is incorrect");
}
class BilinearProductMcCormickEnvelopeTest {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(BilinearProductMcCormickEnvelopeTest)
BilinearProductMcCormickEnvelopeTest(int num_interval_x, int num_interval_y)
: prog_{},
prog_result_{},
num_interval_x_{num_interval_x},
num_interval_y_{num_interval_y},
w_{prog_.NewContinuousVariables<1>()(0)},
x_{prog_.NewContinuousVariables<1>()(0)},
y_{prog_.NewContinuousVariables<1>()(0)},
phi_x_{Eigen::VectorXd::LinSpaced(num_interval_x_ + 1, 0, 1)},
phi_y_{Eigen::VectorXd::LinSpaced(num_interval_y_ + 1, 0, 1)} {}
virtual ~BilinearProductMcCormickEnvelopeTest() = default;
virtual Eigen::VectorXd SetBinaryValue(int active_interval,
int num_interval) const = 0;
Eigen::VectorXd SetBinaryValueLinearBinning(int active_interval,
int num_interval) const {
Eigen::VectorXd b = Eigen::VectorXd::Zero(num_interval);
b(active_interval) = 1;
return b;
}
void TestFeasiblePoint() {
auto x_constraint = prog_.AddBoundingBoxConstraint(0, 0, x_);
auto y_constraint = prog_.AddBoundingBoxConstraint(0, 0, y_);
auto w_constraint = prog_.AddBoundingBoxConstraint(0, 0, w_);
auto CheckFeasibility = [&x_constraint, &y_constraint, &w_constraint](
MathematicalProgram* prog, double x_val,
double y_val, double w_val, bool is_feasible) {
auto UpdateBound = [](Binding<BoundingBoxConstraint>* constraint,
double val) {
constraint->evaluator()->UpdateLowerBound(Vector1d(val));
constraint->evaluator()->UpdateUpperBound(Vector1d(val));
};
UpdateBound(&x_constraint, x_val);
UpdateBound(&y_constraint, y_val);
UpdateBound(&w_constraint, w_val);
prog->SetSolverOption(GurobiSolver::id(), "DualReductions", 0);
GurobiSolver solver;
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(*prog, {}, {}, &result);
EXPECT_EQ(result.get_solution_result(),
is_feasible ? SolutionResult::kSolutionFound
: SolutionResult::kInfeasibleConstraints);
}
};
// Feasible points
CheckFeasibility(&prog_, 0, 0, 0, true);
CheckFeasibility(&prog_, 0, 1, 0, true);
CheckFeasibility(&prog_, 1, 0, 0, true);
CheckFeasibility(&prog_, 1, 1, 1, true);
CheckFeasibility(&prog_, 0.5, 1, 0.5, true);
CheckFeasibility(&prog_, 1, 0.5, 0.5, true);
CheckFeasibility(&prog_, 0.5, 0.5, 0.25, true);
if (num_interval_x_ == 2 && num_interval_y_ == 2) {
CheckFeasibility(&prog_, 0.5, 0.5, 0.26, false);
CheckFeasibility(&prog_, 0.25, 0.25, 0.1, true);
CheckFeasibility(&prog_, 0.25, 0.25, 0.126, false);
CheckFeasibility(&prog_, 0.5, 0.6, 0.301, false);
}
if (num_interval_x_ == 3 && num_interval_y_ == 3) {
CheckFeasibility(&prog_, 1.0 / 3, 1.0 / 3, 0.1, false);
CheckFeasibility(&prog_, 0.5, 0.5, 0.26, true);
CheckFeasibility(&prog_, 1.0 / 3, 2.0 / 3, 2.0 / 9, true);
CheckFeasibility(&prog_, 0.5, 0.5, 5.0 / 18, true);
CheckFeasibility(&prog_, 0.5, 0.5, 5.0 / 18 + 0.001, false);
}
}
void TestLinearObjective() {
// We will assign the binary variables Bx_ and By_ to determine which
// interval is active. If we use logarithmic binning, then Bx_ and By_ take
// values in the gray code, representing integer i and j, such that x is
// constrained in [φx(i), φx(i+1)], y is constrained in [φy(j), φy(j+1)].
auto Bx_constraint =
prog_.AddBoundingBoxConstraint(Eigen::VectorXd::Zero(Bx_.rows()),
Eigen::VectorXd::Zero(Bx_.rows()), Bx_);
auto By_constraint =
prog_.AddBoundingBoxConstraint(Eigen::VectorXd::Zero(By_.rows()),
Eigen::VectorXd::Zero(By_.rows()), By_);
VectorDecisionVariable<3> xyw{x_, y_, w_};
auto cost = prog_.AddLinearCost(Eigen::Vector3d::Zero(), xyw);
Eigen::Matrix<double, 3, 8> a;
// clang-format off
a << 1, 1, 1, 1, -1, -1, -1, -1,
1, 1, -1, -1, 1, 1, -1, -1,
1, -1, 1, -1, 1, -1, 1, -1;
// clang-format on
for (int i = 0; i < num_interval_x_; ++i) {
const auto Bx_val = SetBinaryValue(i, num_interval_x_);
Bx_constraint.evaluator()->UpdateLowerBound(Bx_val);
Bx_constraint.evaluator()->UpdateUpperBound(Bx_val);
for (int j = 0; j < num_interval_y_; ++j) {
const auto By_val = SetBinaryValue(j, num_interval_y_);
By_constraint.evaluator()->UpdateLowerBound(By_val);
By_constraint.evaluator()->UpdateUpperBound(By_val);
// vertices.col(l) is the l'th vertex of the tetrahedron.
Eigen::Matrix<double, 3, 4> vertices;
vertices.row(0) << phi_x_(i), phi_x_(i), phi_x_(i + 1), phi_x_(i + 1);
vertices.row(1) << phi_y_(j), phi_y_(j + 1), phi_y_(j), phi_y_(j + 1);
vertices.row(2) = vertices.row(0).cwiseProduct(vertices.row(1));
for (int k = 0; k < a.cols(); ++k) {
cost.evaluator()->UpdateCoefficients(a.col(k));
GurobiSolver gurobi_solver;
if (gurobi_solver.available()) {
gurobi_solver.Solve(prog_, {}, {}, &prog_result_);
EXPECT_TRUE(prog_result_.is_success());
Eigen::Matrix<double, 1, 4> cost_at_vertices =
a.col(k).transpose() * vertices;
EXPECT_NEAR(prog_result_.get_optimal_cost(),
cost_at_vertices.minCoeff(), 1E-4);
TestLinearObjectiveCheck(i, j, k);
}
}
}
}
}
virtual void TestLinearObjectiveCheck(int i, int j, int k) const {}
protected:
MathematicalProgram prog_;
MathematicalProgramResult prog_result_;
const int num_interval_x_;
const int num_interval_y_;
const symbolic::Variable w_;
const symbolic::Variable x_;
const symbolic::Variable y_;
const Eigen::VectorXd phi_x_;
const Eigen::VectorXd phi_y_;
VectorXDecisionVariable Bx_;
VectorXDecisionVariable By_;
};
class BilinearProductMcCormickEnvelopeSos2Test
: public ::testing::TestWithParam<std::tuple<int, int, IntervalBinning>>,
public BilinearProductMcCormickEnvelopeTest {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(BilinearProductMcCormickEnvelopeSos2Test)
BilinearProductMcCormickEnvelopeSos2Test()
: BilinearProductMcCormickEnvelopeTest(std::get<0>(GetParam()),
std::get<1>(GetParam())),
binning_{std::get<2>(GetParam())},
Bx_size_{binning_ == IntervalBinning::kLogarithmic
? CeilLog2(num_interval_x_)
: num_interval_x_},
By_size_{binning_ == IntervalBinning::kLogarithmic
? CeilLog2(num_interval_y_)
: num_interval_y_} {
Bx_ = prog_.NewBinaryVariables(Bx_size_);
By_ = prog_.NewBinaryVariables(By_size_);
lambda_ = AddBilinearProductMcCormickEnvelopeSos2(
&prog_, x_, y_, w_, phi_x_, phi_y_, Bx_.cast<symbolic::Expression>(),
By_.cast<symbolic::Expression>(), binning_);
}
Eigen::VectorXd SetBinaryValueLogarithmicBinning(int active_interval,
int num_interval) const {
const Eigen::MatrixXi gray_codes =
math::CalculateReflectedGrayCodes(solvers::CeilLog2(num_interval));
return gray_codes.row(active_interval).cast<double>().transpose();
}
Eigen::VectorXd SetBinaryValue(int active_interval,
int num_interval) const override {
switch (binning_) {
case IntervalBinning::kLinear: {
return SetBinaryValueLinearBinning(active_interval, num_interval);
}
case IntervalBinning::kLogarithmic: {
return SetBinaryValueLogarithmicBinning(active_interval, num_interval);
}
default: {
throw std::runtime_error(
"This default case should not be reached. We add the default case "
"due to a gcc-5 pitfall.");
}
}
}
void TestLinearObjectiveCheck(int i, int j, int k) const override {
// Check that λ has the correct value, except λ(i, j), λ(i, j+1),
// λ(i+1, j) and λ(i+1, j+1), all other entries in λ are zero.
double w{0};
double x{0};
double y{0};
for (int m = 0; m <= num_interval_x_; ++m) {
for (int n = 0; n <= num_interval_y_; ++n) {
if (!((m == i && n == j) || (m == i && n == (j + 1)) ||
(m == (i + 1) && n == j) || (m == (i + 1) && n == (j + 1)))) {
EXPECT_NEAR(prog_result_.GetSolution(lambda_(m, n)), 0, 1E-5);
} else {
double lambda_mn{prog_result_.GetSolution(lambda_(m, n))};
x += lambda_mn * phi_x_(m);
y += lambda_mn * phi_y_(n);
w += lambda_mn * phi_x_(m) * phi_y_(n);
}
}
}
EXPECT_NEAR(prog_result_.GetSolution(x_), x, 1E-4);
EXPECT_NEAR(prog_result_.GetSolution(y_), y, 1E-4);
EXPECT_NEAR(prog_result_.GetSolution(w_), w, 1E-4);
}
protected:
const IntervalBinning binning_;
const int Bx_size_;
const int By_size_;
MatrixXDecisionVariable lambda_;
};
TEST_P(BilinearProductMcCormickEnvelopeSos2Test, LinearObjectiveTest) {
TestLinearObjective();
}
TEST_P(BilinearProductMcCormickEnvelopeSos2Test, FeasiblePointTest) {
TestFeasiblePoint();
}
INSTANTIATE_TEST_SUITE_P(
TestMixedIntegerUtil, BilinearProductMcCormickEnvelopeSos2Test,
::testing::Combine(::testing::ValuesIn(std::vector<int>{2, 3}),
::testing::ValuesIn(std::vector<int>{2, 3}),
::testing::ValuesIn(std::vector<IntervalBinning>{
IntervalBinning::kLogarithmic,
IntervalBinning::kLinear})));
class BilinearProductMcCormickEnvelopeMultipleChoiceTest
: public ::testing::TestWithParam<std::tuple<int, int>>,
public BilinearProductMcCormickEnvelopeTest {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(
BilinearProductMcCormickEnvelopeMultipleChoiceTest)
BilinearProductMcCormickEnvelopeMultipleChoiceTest()
: BilinearProductMcCormickEnvelopeTest(std::get<0>(GetParam()),
std::get<1>(GetParam())) {
Bx_ = prog_.NewBinaryVariables(num_interval_x_);
By_ = prog_.NewBinaryVariables(num_interval_y_);
AddBilinearProductMcCormickEnvelopeMultipleChoice(
&prog_, x_, y_, w_, phi_x_, phi_y_, Bx_.cast<symbolic::Expression>(),
By_.cast<symbolic::Expression>());
}
Eigen::VectorXd SetBinaryValue(int active_interval,
int num_interval) const override {
return SetBinaryValueLinearBinning(active_interval, num_interval);
}
};
TEST_P(BilinearProductMcCormickEnvelopeMultipleChoiceTest,
LinearObjectiveTest) {
TestLinearObjective();
}
TEST_P(BilinearProductMcCormickEnvelopeMultipleChoiceTest, FeasiblePointTest) {
TestFeasiblePoint();
}
INSTANTIATE_TEST_SUITE_P(
TestMixedIntegerUtil, BilinearProductMcCormickEnvelopeMultipleChoiceTest,
::testing::Combine(::testing::ValuesIn(std::vector<int>{2, 3}),
::testing::ValuesIn(std::vector<int>{2, 3})));
} // namespace
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/exponential_cone_program_examples.cc | #include "drake/solvers/test/exponential_cone_program_examples.h"
#include <limits>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/solvers/test/mathematical_program_test_util.h"
namespace drake {
namespace solvers {
namespace test {
const double kInf = std::numeric_limits<double>::infinity();
void ExponentialConeTrivialExample(const SolverInterface& solver, double tol,
bool check_dual) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>()(0);
auto y = prog.NewContinuousVariables<1>()(0);
auto z = prog.NewContinuousVariables<1>()(0);
auto exp_constr =
prog.AddExponentialConeConstraint(Vector3<symbolic::Expression>(x, y, z));
auto lin_eq_constr = prog.AddLinearEqualityConstraint(y + z == 1);
prog.AddLinearCost(x);
MathematicalProgramResult result;
solver.Solve(prog, {}, {}, &result);
EXPECT_TRUE(result.is_success());
// Check the solution. We can rewrite the problem as a single variable
// optimization min y * exp(1 - y / y). The gradient of this cost function is
// (y - 1)/y * exp(1-y / y). The optimal value is when the gradient is 0.
// Namely y =1
EXPECT_NEAR(result.GetSolution(y), 1, tol);
EXPECT_NEAR(result.GetSolution(z), 0, tol);
// Check the dual solution.
if (check_dual) {
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(exp_constr),
Eigen::Vector3d(1, -1, -1), tol));
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(lin_eq_constr),
Vector1d(1), tol));
}
}
void MinimizeKLDivergence(const SolverInterface& solver, double tol) {
// The probability p(x)
const Eigen::Vector4d p(0.1, 0.2, 0.3, 0.4);
MathematicalProgram prog;
// q is the other probability distribution
const auto q = prog.NewContinuousVariables<4>();
// A valid probability should sum up to 1.
prog.AddLinearEqualityConstraint(Eigen::RowVector4d::Ones(), 1, q);
// A valid probability should be non-negative.
prog.AddBoundingBoxConstraint(0, kInf, q);
// prog minimizes the KL divergence KL(p || q) = ∑ₓ p(x) * log(p(x) / q(x)).
// Equivalently, the KL divergence is ∑ₓ -p(x) * log(q(x) / p(x)).
// We introduce a slack variable t(x), such that t(x) >= -p(x)* log(q(x) /
// p(x)) namely (q(x), p(x), -t(x)) is in the exponential cone, and we
// minimize ∑ₓ t(x).
const auto t = prog.NewContinuousVariables<4>();
for (int i = 0; i < 4; ++i) {
prog.AddExponentialConeConstraint(
Vector3<symbolic::Expression>(q(i), p(i), -t(i)));
}
prog.AddLinearCost(t.cast<symbolic::Expression>().sum());
MathematicalProgramResult result;
solver.Solve(prog, {}, {}, &result);
EXPECT_TRUE(result.is_success());
EXPECT_TRUE(CompareMatrices(result.GetSolution(q), p, tol));
EXPECT_TRUE(
CompareMatrices(result.GetSolution(t), Eigen::Vector4d::Zero(), tol));
}
void MinimalEllipsoidCoveringPoints(const SolverInterface& solver, double tol) {
// We choose 4 special points as the vertices of a box in 2D. The minimal
// ellipsoid must have all these 4 points on the ellipsoid boundary.
Eigen::Matrix<double, 2, 4> pts;
pts << 1, 1, -1, -1, 1, -1, 1, -1;
// Arbitrarily scale, rotate, and translate the box.
const double theta = M_PI / 7;
Eigen::Matrix2d R;
R << std::cos(theta), -std::sin(theta), std::sin(theta), std::cos(theta);
const Eigen::Vector2d scaling_factor(0.3, 0.5);
pts = R * scaling_factor.asDiagonal() * pts;
// pts += Eigen::Vector2d(0.2, 0.5) * Eigen::RowVector4d::Ones();
// Create the MathematicalProgram, such that the ellipsoid covers pts.
MathematicalProgram prog;
auto S = prog.NewSymmetricContinuousVariables<2>();
auto b = prog.NewContinuousVariables<2>();
auto c = prog.NewContinuousVariables<1>()(0);
Matrix3<symbolic::Expression> ellipsoid_psd;
ellipsoid_psd << S, b.cast<symbolic::Expression>() / 2,
b.cast<symbolic::Expression>().transpose() / 2, c;
prog.AddPositiveSemidefiniteConstraint(ellipsoid_psd);
const auto [linear_cost, log_det_t, log_det_Z] =
prog.AddMaximizeLogDeterminantCost(S.cast<symbolic::Expression>());
for (int i = 0; i < 4; ++i) {
prog.AddLinearConstraint(
pts.col(i).dot(S.cast<symbolic::Expression>() * pts.col(i)) +
pts.col(i).dot(b.cast<symbolic::Expression>()) + c <=
1);
}
MathematicalProgramResult result;
solver.Solve(prog, {}, {}, &result);
EXPECT_TRUE(result.is_success());
auto S_sol = result.GetSolution(S);
auto b_sol = result.GetSolution(b);
auto c_sol = result.GetSolution(c);
for (int i = 0; i < 4; ++i) {
EXPECT_NEAR(
pts.col(i).dot(S_sol * pts.col(i)) + b_sol.dot(pts.col(i)) + c_sol, 1,
tol);
}
// Check the volume and the cost matches with the expected minimal volume.
// We know that for the smallest ellipsoid, S* has eigen values
// (0.5 / scaling_factor(0)², 0.5 / scaling_factor(1)²). det(S) is just
// (0.25 / (scaling_factor(0)² * scaling_factor(1)²));
const double expected_cost =
-std::log(0.25 / std::pow(scaling_factor(0) * scaling_factor(1), 2));
EXPECT_NEAR(result.get_optimal_cost(), expected_cost, tol);
EXPECT_NEAR(result.EvalBinding(linear_cost)(0), expected_cost, tol);
const Eigen::VectorXd log_det_t_sol = result.GetSolution(log_det_t);
EXPECT_NEAR(log_det_t_sol.sum(), -expected_cost, tol);
Eigen::MatrixXd log_det_Z_sol =
ExtractDoubleOrThrow(result.GetSolution(log_det_Z));
EXPECT_TRUE(
(log_det_Z_sol.diagonal().array().log() >= log_det_t_sol.array() - tol)
.all());
EXPECT_TRUE(CompareMatrices(
Eigen::TriangularView<Eigen::MatrixXd, Eigen::StrictlyUpper>(
log_det_Z_sol)
.toDenseMatrix(),
Eigen::MatrixXd::Zero(log_det_Z_sol.rows(), log_det_Z_sol.cols())));
EXPECT_NEAR(-std::log(S_sol.determinant()), expected_cost, tol);
}
void MatrixLogDeterminantLower(const SolverInterface& solver, double tol) {
MathematicalProgram prog;
auto X = prog.NewSymmetricContinuousVariables<3>();
// Push log(det(X)) downward.
prog.AddLinearCost(X.cast<symbolic::Expression>().trace());
const double lower = 1;
const auto ret = prog.AddLogDeterminantLowerBoundConstraint(
X.cast<symbolic::Expression>(), lower);
if (solver.available()) {
MathematicalProgramResult result;
solver.Solve(prog, std::nullopt, std::nullopt, &result);
EXPECT_TRUE(result.is_success());
const auto X_sol = result.GetSolution(X);
EXPECT_GE(std::log(X_sol.determinant()), lower - tol);
// Now remove the returned constraint, solve the problem again with an X not
// satisfying log(det(X)) >= 1. The problem should be feasible.
prog.RemoveConstraint(std::get<0>(ret));
prog.AddBoundingBoxConstraint(0.01 * Eigen::Matrix3d::Identity(),
0.01 * Eigen::Matrix3d::Identity(), X);
solver.Solve(prog, std::nullopt, std::nullopt, &result);
EXPECT_TRUE(result.is_success());
}
}
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/add_solver_util.h | // TODO(hongkai.dai) : delete this file when
// mixed_integer_optimization_test.cc and convex_optimization_test.cc are
// refactored.
#pragma once
#include <list>
#include <memory>
#include <utility>
#include "drake/solvers/solver_interface.h"
namespace drake {
namespace solvers {
namespace test {
template <typename Solver>
void AddSolverIfAvailable(
std::list<std::unique_ptr<SolverInterface>>* solver_list) {
auto solver = std::make_unique<Solver>();
if (solver->available()) {
solver_list->push_back(std::move(solver));
}
}
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/quadratic_constrained_program_examples.cc | #include "drake/solvers/test/quadratic_constrained_program_examples.h"
#include <limits>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace solvers {
namespace test {
const double kInf = std::numeric_limits<double>::infinity();
void TestEllipsoid1(const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options,
double tol) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>("x");
const Eigen::Matrix2d Q = Eigen::Vector2d(8, 18).asDiagonal();
auto quadratic_con =
prog.AddQuadraticConstraint(Q, Eigen::Vector2d::Zero(), -kInf, 1, x);
prog.AddLinearCost(Eigen::Vector2d(1, 1), x);
MathematicalProgramResult result;
solver.Solve(prog, std::nullopt, solver_options, &result);
EXPECT_TRUE(result.is_success());
const Eigen::Vector2d x_sol = result.GetSolution(x);
EXPECT_NEAR(result.get_optimal_cost(), -std::sqrt(13) / 6, tol);
const Eigen::Vector2d x_expected(-3 * std::sqrt(13) / 26,
-4 * std::sqrt(13) / 78);
EXPECT_TRUE(CompareMatrices(x_sol, x_expected, tol));
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(quadratic_con),
-Vector1d(std::sqrt(13) / 12), tol));
}
void TestEllipsoid2(const SolverInterface& solver,
const std::optional<SolverOptions>& solver_options,
double tol) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
// We intentially wirte this constraint as -x0² - x0*x1 - x1² >= -1 to test
// the quadratic constraint with a lower bound.
const auto quadratic_constraint1 = prog.AddQuadraticConstraint(
-x(0) * x(0) - x(0) * x(1) - x(1) * x(1), -1, kInf);
const auto quadratic_constraint2 = prog.AddQuadraticConstraint(
x(0) * x(0) + 2 * x(0) * x(1) + 4 * x(1) * x(1), -kInf, 9);
const auto linear_constraint = prog.AddLinearConstraint(x(0) + x(1) <= 0);
prog.AddLinearCost(x(0) + x(1));
MathematicalProgramResult result;
solver.Solve(prog, std::nullopt, solver_options, &result);
EXPECT_TRUE(result.is_success());
const Eigen::Vector2d x_sol = result.GetSolution(x);
EXPECT_TRUE(CompareMatrices(
x_sol, Eigen::Vector2d(-std::sqrt(3) / 3, -std::sqrt(3) / 3), tol));
EXPECT_NEAR(result.get_optimal_cost(), -2 * std::sqrt(3) / 3, tol);
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(quadratic_constraint1),
Vector1d(std::sqrt(3) / 3), tol));
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(quadratic_constraint2),
Vector1d(0), tol));
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(linear_constraint),
Vector1d(0), tol));
}
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/mathematical_program_test_util.cc | #include "drake/solvers/test/mathematical_program_test_util.h"
#include <stdexcept>
namespace drake {
namespace solvers {
namespace test {
MathematicalProgramResult RunSolver(
const MathematicalProgram& prog, const SolverInterface& solver,
const std::optional<Eigen::VectorXd>& initial_guess,
const std::optional<SolverOptions>& solver_options) {
if (!solver.available()) {
throw std::runtime_error("Solver " + solver.solver_id().name() +
" is not available");
}
MathematicalProgramResult result{};
solver.Solve(prog, initial_guess, solver_options, &result);
EXPECT_TRUE(result.is_success());
if (!result.is_success()) {
throw std::runtime_error("Solver " + solver.solver_id().name() +
" fails to find the solution");
}
return result;
}
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/add_solver_util.cc | #include "drake/solvers/test/add_solver_util.h"
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/osqp_solver_test.cc | #include "drake/solvers/osqp_solver.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/test/quadratic_program_examples.h"
using ::testing::HasSubstr;
namespace drake {
namespace solvers {
namespace test {
GTEST_TEST(QPtest, TestUnconstrainedQP) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<3>("x");
prog.AddQuadraticCost(x(0) * x(0));
OsqpSolver solver;
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
const double tol = 1E-10;
EXPECT_NEAR(result.GetSolution(x(0)), 0, tol);
EXPECT_NEAR(result.get_optimal_cost(), 0, tol);
EXPECT_EQ(result.get_solver_details<OsqpSolver>().y.rows(), 0);
}
// Add additional quadratic costs
prog.AddQuadraticCost((x(1) + x(2) - 2) * (x(1) + x(2) - 2));
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
const double tol = 1E-10;
EXPECT_NEAR(result.GetSolution(x(0)), 0, tol);
EXPECT_NEAR(result.GetSolution(x(1)) + result.GetSolution(x(2)), 2, tol);
EXPECT_NEAR(result.get_optimal_cost(), 0, tol);
EXPECT_EQ(result.get_solver_details<OsqpSolver>().y.rows(), 0);
}
// Add linear costs.
prog.AddLinearCost(4 * x(0) + 5);
// Now the cost is (x₀ + 2)² + (x₁ + x₂-2)² + 1
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
const double tol = 1E-10;
EXPECT_NEAR(result.GetSolution(x(0)), -2, tol);
EXPECT_NEAR(result.GetSolution(x(1)) + result.GetSolution(x(2)), 2, tol);
EXPECT_NEAR(result.get_optimal_cost(), 1, tol);
EXPECT_EQ(result.get_solver_details<OsqpSolver>().y.rows(), 0);
}
}
TEST_P(QuadraticProgramTest, TestQP) {
OsqpSolver solver;
prob()->RunProblem(&solver);
}
INSTANTIATE_TEST_SUITE_P(
OsqpTest, QuadraticProgramTest,
::testing::Combine(::testing::ValuesIn(quadratic_cost_form()),
::testing::ValuesIn(linear_constraint_form()),
::testing::ValuesIn(quadratic_problems())));
GTEST_TEST(QPtest, TestUnitBallExample) {
OsqpSolver solver;
if (solver.available()) {
TestQPonUnitBallExample(solver);
}
}
GTEST_TEST(QPtest, TestUnbounded) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<3>();
prog.AddQuadraticCost(x(0) * x(0) + x(1));
OsqpSolver solver;
// The program is unbounded.
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_EQ(result.get_solution_result(), SolutionResult::kDualInfeasible);
}
// Add a constraint
prog.AddLinearConstraint(x(0) + 2 * x(2) == 2);
prog.AddLinearConstraint(x(0) >= 0);
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_EQ(result.get_solution_result(), SolutionResult::kDualInfeasible);
}
}
GTEST_TEST(QPtest, TestInfeasible) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
prog.AddQuadraticCost(x(0) * x(0) + 2 * x(1) * x(1));
prog.AddLinearConstraint(x(0) + 2 * x(1) == 2);
prog.AddLinearConstraint(x(0) >= 1);
prog.AddLinearConstraint(x(1) >= 2);
OsqpSolver solver;
// The program is infeasible.
if (solver.available()) {
auto result = solver.Solve(prog, {}, {});
EXPECT_EQ(result.get_solution_result(),
SolutionResult::kInfeasibleConstraints);
EXPECT_EQ(result.get_optimal_cost(),
MathematicalProgram::kGlobalInfeasibleCost);
EXPECT_EQ(result.get_solver_details<OsqpSolver>().y.rows(), 0);
// In OSQP's default upstream settings, time-based adaptive rho is enabled
// by default (i.e., adaptive_rho_interval=0). However, in our OsqpSolver
// wrapper, we've changed the default to be non-zero so that solver results
// are deterministic. The following check proves that our custom default is
// effective: with time-based adaptive rho there would be one rho_update,
// but with our custom default value there will be no updates (since the
// iteration count never reaches the scheduled iteration step of an update).
EXPECT_EQ(result.get_solver_details<OsqpSolver>().rho_updates, 0);
}
}
GTEST_TEST(OsqpSolverTest, DuplicatedVariable) {
OsqpSolver solver;
if (solver.available()) {
TestDuplicatedVariableQuadraticProgram(solver, 1E-5);
}
}
GTEST_TEST(OsqpSolverTest, DualSolution1) {
// Test GetDualSolution().
OsqpSolver solver;
TestQPDualSolution1(solver);
}
GTEST_TEST(OsqpSolverTest, DualSolution2) {
// Test GetDualSolution().
// This QP has non-zero dual solution for linear inequality constraint.
OsqpSolver solver;
TestQPDualSolution2(solver);
}
GTEST_TEST(OsqpSolverTest, DualSolution3) {
// Test GetDualSolution().
// This QP has non-zero dual solution for the bounding box constraint.
OsqpSolver solver;
TestQPDualSolution3(solver);
}
GTEST_TEST(OsqpSolverTest, EqualityConstrainedQPDualSolution1) {
OsqpSolver solver;
TestEqualityConstrainedQPDualSolution1(solver);
}
GTEST_TEST(OsqpSolverTest, EqualityConstrainedQPDualSolution2) {
OsqpSolver solver;
TestEqualityConstrainedQPDualSolution2(solver);
}
void AddTestProgram(
MathematicalProgram* prog,
const MatrixDecisionVariable<3, 1>& x) {
prog->AddLinearConstraint(x(0) + 2 * x(1) - 3 * x(2) <= 3);
prog->AddLinearConstraint(4 * x(0) - 2 * x(1) - 6 * x(2) >= -3);
prog->AddQuadraticCost(x(0) * x(0) + 2 * x(1) * x(1) + 5 * x(2) * x(2) +
2 * x(1) * x(2));
prog->AddLinearConstraint(8 * x(0) - x(1) == 2);
}
// This is a regression test for #18711. To reproduce that issue, we need to
// solve a sufficiently complicated QP so that OSQP will iterate internally
// enough to engage its wall-clock timing heuristics. We'll set up some very
// specific costs and constraints (captured from a real world example) and
// then repeatedly solve the same program over and over again, checking that
// the solution is bit-exact each time. Note that this is a probabilistic test:
// even if we revert the fix for #18711, this only fails ~40% of the time.
GTEST_TEST(OsqpSolverTest, ComplicatedExampleForAdaptiveRhoTiming) {
MathematicalProgram prog;
const int num_v = 7;
const int num_u = 7;
Eigen::MatrixXd M(num_v, num_v);
M << 1.5265000092743219, 1.3567292738062303e-01, 1.0509980442610054,
1.0593165893494538e-01, 5.2550137200876458e-02, 1.4695302469350939e-02,
-5.6634685479957378e-03,
//
1.3567292738062303e-01, 2.6582813453131502, 1.8437561004161429e-01,
-1.1606165163872926, -6.7115703782523864e-02, -6.8744248816288878e-02,
-2.3803654356554906e-03,
//
1.0509980442610054, 1.8437561004161429e-01, 7.5578462775698307e-01,
2.9778874473806963e-02, 4.2191302344065193e-02, 6.9686779847817938e-03,
-4.7168273440004261e-03,
//
1.0593165893494538e-01, -1.1606165163872926, 2.9778874473806963e-02,
7.0143698885704575e-01, 4.3907540905320175e-02, 6.0704344118780576e-02,
6.2450624459637065e-04,
//
5.2550137200876458e-02, -6.7115703782523864e-02, 4.2191302344065193e-02,
4.3907540905320175e-02, 2.3108956248772367e-02, -4.0027553954531062e-04,
-9.6135531130737148e-04,
//
1.4695302469350939e-02, -6.8744248816288878e-02, 6.9686779847817938e-03,
6.0704344118780576e-02, -4.0027553954531062e-04, 1.8750100174003432e-02,
-2.3318254131776553e-04,
//
-5.6634685479957378e-03, -2.3803654356554906e-03, -4.7168273440004261e-03,
6.2450624459637065e-04, -9.6135531130737148e-04, -2.3318254131776553e-04,
8.4560640585000036e-04;
Eigen::VectorXd C(num_v);
C << 0.12534316615346058, -4.262437098995484, -0.1292406593401465,
1.2824026531372175, 0.057990230523857114, -0.11631318722553598,
0.008118721429606525;
Eigen::VectorXd tau_g(num_v);
tau_g << 0.0, 3.2520059971872882e+01, 1.1056387788047277,
-1.6455090196304102e+01, -1.3129246602609450, -1.2645040362872129,
-1.6577819002396472e-02;
auto vd_star = prog.NewContinuousVariables(num_v, "vd_star");
auto u_star = prog.NewContinuousVariables(num_u, "u_star");
Eigen::MatrixXd Aeq(num_v, num_v + num_v);
Aeq.block(0, 0, num_v, num_v) = M;
Aeq.block(0, num_v, num_v, num_v) = Eigen::MatrixXd::Identity(num_v, num_v);
Eigen::VectorXd beq = -C + tau_g;
prog.AddLinearEqualityConstraint(Aeq, beq, {vd_star, u_star});
Eigen::MatrixXd task_cost_A(6, num_v);
task_cost_A << 0.0, 2.6276770346517636e-01, 3.0114875389439555e-01,
-4.7285620522256971e-01, 8.7440544000403608e-01, -4.8174857078266453e-01,
-1.9618608268142981e-01,
//
0.0, 9.6485912651310768e-01, -8.2014217710682832e-02,
-8.7801906757823511e-01, -4.5720465227404666e-01, -8.5793882676911759e-01,
-9.2923842949070412e-02,
//
1.0, 4.8965888601467475e-12, 9.5004373379395413e-01,
7.4091336548597356e-02, 1.6241623204075539e-01, 1.7849169188197500e-01,
-9.7615376881600568e-01,
//
2.8311221691848737e-01, 2.9275947741254926e-01, 2.4408407039656915e-01,
-8.6056328493326305e-03, 6.1561854687226442e-02, 1.0864947505835820e-01,
-1.2143064331837650e-17,
//
5.4444702526853128e-01, -7.9729499810435950e-02, 4.2587333018015111e-01,
4.1571230146216887e-02, 1.0963458655960948e-01, -4.5887476583813355e-02,
-1.3877787807814457e-17,
//
0.0, -5.9970742829586077e-01, -4.0606494474492376e-02,
4.3771792154289879e-01, -2.2809158687563048e-02, 7.2681710645204109e-02,
3.6862873864507151e-18;
Eigen::VectorXd task_cost_b(6);
task_cost_b << -24.566247201232553, -0.3677519895564192, -44.03725978974725,
34.38537004440926, 45.39628041050313, -42.53770459411413;
Eigen::MatrixXd task_cost_proj(num_v, 6);
task_cost_proj << 0.0, 0.0, 1.0, 2.8311221691848737e-01,
5.4444702526853128e-01, 0.0,
//
2.6276770346517636e-01, 9.6485912651310768e-01, 4.8965888601467475e-12,
2.9275947741254926e-01, -7.9729499810435950e-02, -5.9970742829586077e-01,
//
3.0114875389439555e-01, -8.2014217710682832e-02, 9.5004373379395413e-01,
2.4408407039656915e-01, 4.2587333018015111e-01, -4.0606494474492376e-02,
//
-4.7285620522256971e-01, -8.7801906757823511e-01, 7.4091336548597356e-02,
-8.6056328493326305e-03, 4.1571230146216887e-02, 4.3771792154289879e-01,
//
8.7440544000403608e-01, -4.5720465227404666e-01, 1.6241623204075539e-01,
6.1561854687226442e-02, 1.0963458655960948e-01, -2.2809158687563048e-02,
//
-4.8174857078266453e-01, -8.5793882676911759e-01, 1.7849169188197500e-01,
1.0864947505835820e-01, -4.5887476583813355e-02, 7.2681710645204109e-02,
//
-1.9618608268142981e-01, -9.2923842949070412e-02, -9.7615376881600568e-01,
-1.2143064331837650e-17, -1.3877787807814457e-17, 3.6862873864507151e-18;
prog.Add2NormSquaredCost(task_cost_proj * task_cost_A,
task_cost_proj * task_cost_b, vd_star);
if (!OsqpSolver::is_available()) {
return;
}
// Run one solve to get a specific answer.
auto run_one_solve = [&prog, &u_star]() {
const OsqpSolver dut;
const MathematicalProgramResult result = dut.Solve(prog);
EXPECT_TRUE(result.is_success());
return result.GetSolution(u_star);
};
const Eigen::VectorXd first_answer = run_one_solve();
// Run the same thing over and over again, to "prove" that it's deterministic.
for (int i = 0; i < 100; ++i) {
SCOPED_TRACE(fmt::format("i = {}", i));
const Eigen::VectorXd new_answer = run_one_solve();
ASSERT_EQ(new_answer, first_answer);
}
}
GTEST_TEST(OsqpSolverTest, SolverOptionsTest) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<3>();
AddTestProgram(&prog, x);
MathematicalProgramResult result;
OsqpSolver osqp_solver;
if (osqp_solver.available()) {
osqp_solver.Solve(prog, {}, {}, &result);
const int OSQP_SOLVED = 1;
EXPECT_EQ(result.get_solver_details<OsqpSolver>().status_val, OSQP_SOLVED);
// OSQP is not very accurate, use a loose tolerance.
EXPECT_TRUE(CompareMatrices(result.get_solver_details<OsqpSolver>().y,
Eigen::Vector3d(0, 0, -0.0619621), 1E-5));
// Now only allow half the iterations in the OSQP solver. The solver should
// not be able to solve the problem accurately.
const int half_iterations =
result.get_solver_details<OsqpSolver>().iter / 2;
SolverOptions solver_options;
solver_options.SetOption(osqp_solver.solver_id(), "max_iter",
half_iterations);
osqp_solver.Solve(prog, {}, solver_options, &result);
EXPECT_NE(result.get_solver_details<OsqpSolver>().status_val, OSQP_SOLVED);
// Now set the options in prog.
prog.SetSolverOption(osqp_solver.solver_id(), "max_iter", half_iterations);
osqp_solver.Solve(prog, {}, {}, &result);
EXPECT_NE(result.get_solver_details<OsqpSolver>().status_val, OSQP_SOLVED);
}
}
GTEST_TEST(OsqpSolverTest, WarmStartPrimalOnly) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<3>();
AddTestProgram(&prog, x);
MathematicalProgramResult result;
OsqpSolver osqp_solver;
if (osqp_solver.available()) {
// Solve with no prior solution; should be same as above test case.
osqp_solver.Solve(prog, {}, {}, &result);
const int OSQP_SOLVED = 1;
EXPECT_EQ(result.get_solver_details<OsqpSolver>().status_val, OSQP_SOLVED);
// Solve with primal-only warm-start, restricting the iterations as above,
// but showing that we now have a solution.
const int half_iterations =
result.get_solver_details<OsqpSolver>().iter / 2;
SolverOptions solver_options;
solver_options.SetOption(
osqp_solver.solver_id(), "max_iter", half_iterations);
const Eigen::VectorXd x_sol = result.get_x_val();
osqp_solver.Solve(prog, x_sol, solver_options, &result);
EXPECT_EQ(result.get_solver_details<OsqpSolver>().status_val, OSQP_SOLVED);
}
}
/* Tests the solver's processing of the verbosity options. With multiple ways
to request verbosity (common options and solver-specific options), we simply
apply a smoke test that none of the means causes runtime errors. Note, we
don't test the case where we configure the mathematical program itself; that
is resolved in SolverBase. We only need to test the options passed into
Solve(). The possible configurations are:
- No verbosity set at all (this is implicitly tested in all other tests).
- Common option explicitly set (on & off)
- Solver option explicitly set (on & off)
- Both options explicitly set (with all permutations of (on, on), etc.) */
GTEST_TEST(OsqpSolverTest, SolverOptionsVerbosity) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
prog.AddLinearConstraint(x(0) + x(1) <= 3);
prog.AddLinearConstraint(4 * x(0) - 2 * x(1) >= -3);
prog.AddQuadraticCost(x(0) * x(0) + 2 * x(1) * x(1) + 2 * x(0) * x(1));
OsqpSolver osqp_solver;
if (osqp_solver.is_available()) {
// Setting common options.
for (int print_to_console : {0, 1}) {
SolverOptions options;
options.SetOption(CommonSolverOption::kPrintToConsole, print_to_console);
osqp_solver.Solve(prog, {}, options);
}
// Setting solver options.
for (int print_to_console : {0, 1}) {
SolverOptions options;
options.SetOption(OsqpSolver::id(), "verbose", print_to_console);
osqp_solver.Solve(prog, {}, options);
}
// Setting both.
for (int common_print_to_console : {0, 1}) {
for (int solver_print_to_console : {0, 1}) {
SolverOptions options;
options.SetOption(CommonSolverOption::kPrintToConsole,
common_print_to_console);
options.SetOption(OsqpSolver::id(), "verbose", solver_print_to_console);
osqp_solver.Solve(prog, {}, options);
}
}
}
}
GTEST_TEST(OsqpSolverTest, TimeLimitTest) {
// Intentionally create a slightly big problem to get a longer solve time.
int n_x = 200;
MathematicalProgram prog;
auto x = prog.NewContinuousVariables(n_x);
Eigen::MatrixXd A = Eigen::MatrixXd::Identity(n_x, n_x);
Eigen::VectorXd b = Eigen::VectorXd::Ones(n_x);
prog.AddLinearConstraint(A, -b, b, x);
prog.AddQuadraticErrorCost(A, -1.1 * b, x);
MathematicalProgramResult result;
OsqpSolver osqp_solver;
if (osqp_solver.available()) {
osqp_solver.Solve(prog, {}, {}, &result);
// Status codes listed in
// https://osqp.org/docs/interfaces/status_values.html
const int OSQP_SOLVED = 1;
const int OSQP_TIME_LIMIT_REACHED = -6;
EXPECT_EQ(result.get_solver_details<OsqpSolver>().status_val, OSQP_SOLVED);
// OSQP is not very accurate, use a loose tolerance.
EXPECT_TRUE(CompareMatrices(result.GetSolution(x), -b, 1E-5));
// Now only allow one hundredth of the solve time in the OSQP solver. The
// solver should not be able to solve the problem in time.
const double one_hundredth_solve_time =
result.get_solver_details<OsqpSolver>().solve_time / 100.0;
SolverOptions solver_options;
solver_options.SetOption(osqp_solver.solver_id(), "time_limit",
one_hundredth_solve_time);
osqp_solver.Solve(prog, {}, solver_options, &result);
EXPECT_EQ(result.get_solver_details<OsqpSolver>().status_val,
OSQP_TIME_LIMIT_REACHED);
// Now set the options in prog.
prog.SetSolverOption(osqp_solver.solver_id(), "time_limit",
one_hundredth_solve_time);
osqp_solver.Solve(prog, {}, {}, &result);
EXPECT_EQ(result.get_solver_details<OsqpSolver>().status_val,
OSQP_TIME_LIMIT_REACHED);
}
}
GTEST_TEST(OsqpSolverTest, ProgramAttributesGood) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>("x");
prog.AddQuadraticCost(x(0) * x(0));
EXPECT_TRUE(OsqpSolver::ProgramAttributesSatisfied(prog));
EXPECT_EQ(OsqpSolver::UnsatisfiedProgramAttributes(prog), "");
}
GTEST_TEST(OsqpSolverTest, ProgramAttributesBad) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>("x");
prog.AddCost(x(0) * x(0) * x(0));
EXPECT_FALSE(OsqpSolver::ProgramAttributesSatisfied(prog));
EXPECT_THAT(OsqpSolver::UnsatisfiedProgramAttributes(prog),
HasSubstr("GenericCost was declared"));
}
GTEST_TEST(OsqpSolverTest, ProgramAttributesMisfit) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>("x");
prog.AddLinearCost(4 * x(0) + 5);
EXPECT_FALSE(OsqpSolver::ProgramAttributesSatisfied(prog));
EXPECT_THAT(OsqpSolver::UnsatisfiedProgramAttributes(prog),
HasSubstr("QuadraticCost is required"));
}
GTEST_TEST(OsqpSolverTest, TestNonconvexQP) {
OsqpSolver solver;
if (solver.available()) {
TestNonconvexQP(solver, true);
}
}
GTEST_TEST(OsqpSolverTest, VariableScaling1) {
// Quadractic cost and linear inequality constraints.
double s = 100;
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
prog.AddLinearConstraint(2 * x(0) / s - 2 * x(1) == 2);
prog.AddQuadraticCost((x(0) / s + 1) * (x(0) / s + 1));
prog.AddQuadraticCost((x(1) + 1) * (x(1) + 1));
prog.SetVariableScaling(x(0), s);
OsqpSolver solver;
if (solver.available()) {
auto result = solver.Solve(prog);
EXPECT_TRUE(result.is_success());
const double tol = 1E-6;
EXPECT_NEAR(result.get_optimal_cost(), 0.5, tol);
EXPECT_TRUE(CompareMatrices(result.GetSolution(x),
Eigen::Vector2d((-0.5) * s, -1.5), tol));
}
}
GTEST_TEST(OsqpSolverTest, VariableScaling2) {
// Quadratic and linear cost, together with bounding box constraints.
double s = 100;
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
prog.AddBoundingBoxConstraint(0.5 * s,
std::numeric_limits<double>::infinity(), x(0));
prog.AddQuadraticCost((x(0) / s + 1) * (x(0) / s + 1));
prog.AddQuadraticCost(x(1) * x(1));
prog.AddLinearCost(2 * x(1) + 1);
prog.SetVariableScaling(x(0), s);
OsqpSolver solver;
if (solver.available()) {
auto result = solver.Solve(prog);
EXPECT_TRUE(result.is_success());
const double tol = 1E-6;
EXPECT_NEAR(result.get_optimal_cost(), 2.25, tol);
EXPECT_TRUE(CompareMatrices(result.GetSolution(x),
Eigen::Vector2d((0.5) * s, -1), tol));
}
}
} // namespace test
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/mosek_solver_moseklm_license_file_test.cc | #include <cstdlib>
#include <optional>
#include <stdexcept>
#include <string>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mosek_solver.h"
namespace drake {
namespace solvers {
namespace {
// These tests are deliberately not in mosek_solver_test.cc to avoid causing
// license issues during tests in that file.
std::optional<std::string> GetEnvStr(const char* name) {
const char* const value = std::getenv(name);
if (!value) {
return std::nullopt;
}
return std::string(value);
}
class MoseklmLicenseFileTest : public ::testing::Test {
protected:
MoseklmLicenseFileTest()
: orig_moseklm_license_file_(GetEnvStr("MOSEKLM_LICENSE_FILE")) {}
void SetUp() override {
ASSERT_EQ(solver_.available(), true);
ASSERT_TRUE(orig_moseklm_license_file_);
// Add a variable to avoid the "Solve" function terminating without calling
// the external MOSEK solver.
prog_.NewContinuousVariables<1>();
}
void TearDown() override {
if (orig_moseklm_license_file_) {
const int setenv_result = ::setenv(
"MOSEKLM_LICENSE_FILE", orig_moseklm_license_file_->c_str(), 1);
EXPECT_EQ(setenv_result, 0);
}
}
const std::optional<std::string> orig_moseklm_license_file_;
MathematicalProgram prog_;
MosekSolver solver_;
};
TEST_F(MoseklmLicenseFileTest, MoseklmLicenseFileSet) {
EXPECT_EQ(solver_.enabled(), true);
DRAKE_EXPECT_NO_THROW(solver_.Solve(prog_));
}
TEST_F(MoseklmLicenseFileTest, MoseklmLicenseFileUnset) {
EXPECT_EQ(solver_.enabled(), true);
const int unsetenv_result = ::unsetenv("MOSEKLM_LICENSE_FILE");
ASSERT_EQ(unsetenv_result, 0);
EXPECT_EQ(solver_.enabled(), false);
DRAKE_EXPECT_THROWS_MESSAGE(
solver_.Solve(prog_), ".*MosekSolver has not been properly configured.*");
}
} // namespace
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/test/gurobi_solver_test.cc | #include "drake/solvers/gurobi_solver.h"
#include <filesystem>
#include <limits>
#include <thread>
#include <gtest/gtest.h>
#include "drake/common/temp_directory.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/solvers/mixed_integer_optimization_util.h"
#include "drake/solvers/test/l2norm_cost_examples.h"
#include "drake/solvers/test/linear_program_examples.h"
#include "drake/solvers/test/quadratic_program_examples.h"
#include "drake/solvers/test/second_order_cone_program_examples.h"
namespace drake {
namespace solvers {
namespace test {
const double kInf = std::numeric_limits<double>::infinity();
TEST_P(LinearProgramTest, TestLP) {
GurobiSolver solver;
prob()->RunProblem(&solver);
}
INSTANTIATE_TEST_SUITE_P(
GurobiTest, LinearProgramTest,
::testing::Combine(::testing::ValuesIn(linear_cost_form()),
::testing::ValuesIn(linear_constraint_form()),
::testing::ValuesIn(linear_problems())));
TEST_F(InfeasibleLinearProgramTest0, TestGurobiInfeasible) {
GurobiSolver solver;
if (solver.available()) {
// With dual reductions, Gurobi may not be able to differentiate between
// infeasible and unbounded.
prog_->SetSolverOption(GurobiSolver::id(), "DualReductions", 1);
auto result = solver.Solve(*prog_, {}, {});
EXPECT_EQ(result.get_solution_result(),
SolutionResult::kInfeasibleOrUnbounded);
EXPECT_TRUE(std::isnan(result.get_optimal_cost()));
prog_->SetSolverOption(GurobiSolver::id(), "DualReductions", 0);
result = solver.Solve(*prog_, {}, {});
EXPECT_EQ(result.get_solution_result(),
SolutionResult::kInfeasibleConstraints);
EXPECT_TRUE(std::isinf(result.get_optimal_cost()));
EXPECT_GE(result.get_optimal_cost(), 0);
}
}
TEST_F(UnboundedLinearProgramTest0, TestGurobiUnbounded) {
GurobiSolver solver;
if (solver.available()) {
// With dual reductions, Gurobi may not be able to differentiate between
// infeasible and unbounded.
SolverOptions solver_options;
solver_options.SetOption(GurobiSolver::id(), "DualReductions", 1);
auto result = solver.Solve(*prog_, {}, solver_options);
EXPECT_FALSE(result.is_success());
EXPECT_EQ(result.get_solution_result(),
SolutionResult::kInfeasibleOrUnbounded);
// This code is defined in
// https://www.gurobi.com/documentation/10.0/refman/optimization_status_codes.html
const int GRB_INF_OR_UNBD = 4;
EXPECT_EQ(result.get_solver_details<GurobiSolver>().optimization_status,
GRB_INF_OR_UNBD);
solver_options.SetOption(GurobiSolver::id(), "DualReductions", 0);
result = solver.Solve(*prog_, {}, solver_options);
EXPECT_FALSE(result.is_success());
EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded);
// This code is defined in
// https://www.gurobi.com/documentation/10.0/refman/optimization_status_codes.html
const int GRB_UNBOUNDED = 5;
EXPECT_EQ(result.get_solver_details<GurobiSolver>().optimization_status,
GRB_UNBOUNDED);
EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kUnboundedCost);
}
}
TEST_F(DuplicatedVariableLinearProgramTest1, Test) {
GurobiSolver solver;
if (solver.is_available()) {
CheckSolution(solver);
}
}
TEST_P(QuadraticProgramTest, TestQP) {
GurobiSolver solver;
prob()->RunProblem(&solver);
}
INSTANTIATE_TEST_SUITE_P(
GurobiTest, QuadraticProgramTest,
::testing::Combine(::testing::ValuesIn(quadratic_cost_form()),
::testing::ValuesIn(linear_constraint_form()),
::testing::ValuesIn(quadratic_problems())));
GTEST_TEST(QPtest, TestUnitBallExample) {
GurobiSolver solver;
if (solver.available()) {
TestQPonUnitBallExample(solver);
}
}
GTEST_TEST(GurobiTest, TestInitialGuess) {
GurobiSolver solver;
if (solver.available()) {
// Formulate a simple problem with multiple optimal
// solutions, and solve it twice with two different
// initial conditions. The resulting solutions should
// match the initial conditions supplied. Doing two
// solves from different initial positions ensures the
// test doesn't pass by chance.
MathematicalProgram prog;
auto x = prog.NewBinaryVariables<1>("x");
// Presolve and Heuristics would each independently solve
// this problem inside of the Gurobi solver, but without
// consulting the initial guess.
prog.SetSolverOption(GurobiSolver::id(), "Presolve", 0);
prog.SetSolverOption(GurobiSolver::id(), "Heuristics", 0.0);
double x_expected0_to_test[] = {0.0, 1.0};
for (int i = 0; i < 2; i++) {
Eigen::VectorXd x_expected(1);
x_expected[0] = x_expected0_to_test[i];
prog.SetInitialGuess(x, x_expected);
auto result = solver.Solve(prog, x_expected, {});
EXPECT_TRUE(result.is_success());
const auto& x_value = result.GetSolution(x);
EXPECT_TRUE(CompareMatrices(x_value, x_expected, 1E-6,
MatrixCompareType::absolute));
EXPECT_NEAR(result.get_optimal_cost(), 0, 1E-6);
}
}
}
GTEST_TEST(TestDuplicatedVariableQuadraticProgram, Test) {
GurobiSolver solver;
if (solver.available()) {
TestDuplicatedVariableQuadraticProgram(solver);
}
}
namespace TestCallbacks {
struct TestCallbackInfo {
Eigen::VectorXd x_vals;
VectorXDecisionVariable x_vars;
bool mip_sol_callback_called = false;
bool mip_node_callback_called = false;
};
static void MipSolCallbackFunctionTest(
const MathematicalProgram& prog,
const drake::solvers::GurobiSolver::SolveStatusInfo& solve_info,
TestCallbackInfo* cb_info) {
cb_info->mip_sol_callback_called = true;
}
static void MipNodeCallbackFunctionTest(
const MathematicalProgram& prog,
const GurobiSolver::SolveStatusInfo& solve_info, Eigen::VectorXd* vals,
VectorXDecisionVariable* vars, TestCallbackInfo* cb_info) {
cb_info->mip_node_callback_called = true;
*vals = cb_info->x_vals;
*vars = cb_info->x_vars;
}
GTEST_TEST(GurobiTest, TestCallbacks) {
GurobiSolver solver;
if (solver.available()) {
// Formulate a problem with multiple feasible
// solutions and multiple clear optimal solutions.
MathematicalProgram prog;
auto x = prog.NewBinaryVariables<4>("x");
// Constraint such that x_0 and x_1 can't both be
// 1, but leave a feasible vertex at (2/3, 2/3)
// that is optimal in the continuous relaxation.
prog.AddLinearConstraint(x[0] <= 1. - 0.5 * x[1]);
prog.AddLinearConstraint(x[1] <= 1. - 0.5 * x[0]);
prog.AddLinearCost(-x[0] - x[1]);
// Each of these options would short-circuit the solver
// from entering a full solve and generating both
// feasible solution callbacks (mipSol) and intermediate
// node callbacks (mipNode).
// Prevents the problem from being simplified, making the
// solution potentially trivial:
prog.SetSolverOption(GurobiSolver::id(), "Presolve", 0);
// Prevents the optimal solution from being generated without
// doing a full solve:
prog.SetSolverOption(GurobiSolver::id(), "Heuristics", 0.0);
// Similarly, prevents trivialization of the problem via
// clever new cuts:
prog.SetSolverOption(GurobiSolver::id(), "Cuts", 0);
// Prevents the root node from finding the optimal feasible
// solution via simplex, by switching to a barrier method:
prog.SetSolverOption(GurobiSolver::id(), "NodeMethod", 2);
// Force us to start at a known-suboptimal sol.
Eigen::VectorXd x_init(4);
x_init << 0.0, 0.0, 0.0, 0.0;
prog.SetInitialGuess(x, x_init);
// Enumerate a few different optimal solutions and try
// injecting each of them to make sure the solver
// is receiving these injections and listening to them.
std::vector<Eigen::VectorXd> optimal_sols(3, Eigen::VectorXd(4));
optimal_sols[0] << 1.0, 0.0, 0.0, 1.0;
optimal_sols[1] << 1.0, 0.0, 1.0, 0.0;
optimal_sols[2] << 0.0, 1.0, 1.0, 1.0;
for (const auto& x_expected : optimal_sols) {
TestCallbackInfo cb_info;
cb_info.x_vals = x_expected;
cb_info.x_vars = x;
GurobiSolver::MipNodeCallbackFunction mip_node_callback_function_wrapper =
std::bind(MipNodeCallbackFunctionTest, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3,
std::placeholders::_4, &cb_info);
GurobiSolver::MipSolCallbackFunction mip_sol_callback_function_wrapper =
std::bind(MipSolCallbackFunctionTest, std::placeholders::_1,
std::placeholders::_2, &cb_info);
solver.AddMipNodeCallback(mip_node_callback_function_wrapper);
solver.AddMipSolCallback(mip_sol_callback_function_wrapper);
auto result = solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
const auto& x_value = result.GetSolution(x);
EXPECT_TRUE(CompareMatrices(x_value, x_expected, 1E-6,
MatrixCompareType::absolute));
ExpectSolutionCostAccurate(prog, result, 1E-6);
EXPECT_TRUE(cb_info.mip_sol_callback_called);
EXPECT_TRUE(cb_info.mip_node_callback_called);
}
}
}
} // namespace TestCallbacks
TEST_P(TestEllipsoidsSeparation, TestSOCP) {
GurobiSolver gurobi_solver;
if (gurobi_solver.available()) {
SolveAndCheckSolution(gurobi_solver, {}, 1.1E-8);
}
}
INSTANTIATE_TEST_SUITE_P(
GurobiTest, TestEllipsoidsSeparation,
::testing::ValuesIn(GetEllipsoidsSeparationProblems()));
TEST_P(TestQPasSOCP, TestSOCP) {
GurobiSolver gurobi_solver;
if (gurobi_solver.available()) {
SolveAndCheckSolution(gurobi_solver);
}
}
INSTANTIATE_TEST_SUITE_P(GurobiTest, TestQPasSOCP,
::testing::ValuesIn(GetQPasSOCPProblems()));
TEST_P(TestFindSpringEquilibrium, TestSOCP) {
GurobiSolver gurobi_solver;
if (gurobi_solver.available()) {
SolveAndCheckSolution(gurobi_solver, {}, 2E-2);
}
}
INSTANTIATE_TEST_SUITE_P(
GurobiTest, TestFindSpringEquilibrium,
::testing::ValuesIn(GetFindSpringEquilibriumProblems()));
GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem1) {
MaximizeGeometricMeanTrivialProblem1 prob;
GurobiSolver solver;
if (solver.available()) {
const auto result = solver.Solve(prob.prog(), {}, {});
prob.CheckSolution(result, 4E-6);
}
}
GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem2) {
MaximizeGeometricMeanTrivialProblem2 prob;
GurobiSolver solver;
if (solver.available()) {
const auto result = solver.Solve(prob.prog(), {}, {});
// Gurobi 9.0.0 returns a solution that is accurate up to 1.4E-6 for this
// specific problem. Might need to change the tolerance when we upgrade
// Gurobi.
prob.CheckSolution(result, 1.4E-6);
}
}
GTEST_TEST(TestSOCP, SmallestEllipsoidCoveringProblem) {
GurobiSolver solver;
SolveAndCheckSmallestEllipsoidCoveringProblems(solver, {}, 1E-6);
}
GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable1) {
GurobiSolver solver;
TestSocpDuplicatedVariable1(solver, std::nullopt, 1E-6);
}
GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable2) {
GurobiSolver solver;
TestSocpDuplicatedVariable2(solver, std::nullopt, 1E-6);
}
GTEST_TEST(L2NormCost, ShortestDistanceToThreePoints) {
GurobiSolver solver;
ShortestDistanceToThreePoints tester{};
tester.CheckSolution(solver);
}
GTEST_TEST(L2NormCost, ShortestDistanceFromCylinderToPoint) {
GurobiSolver solver;
ShortestDistanceFromCylinderToPoint tester{};
tester.CheckSolution(solver);
}
GTEST_TEST(L2NormCost, ShortestDistanceFromPlaneToTwoPoints) {
GurobiSolver solver;
ShortestDistanceFromPlaneToTwoPoints tester{};
SolverOptions solver_options{};
// Gurobi's default QCP tolerance result in very low precision sub-optimal
// solution. We use a tighter tolerance to make sure the Gurobi solution is
// close to optimal.
solver_options.SetOption(solver.id(), "BarQCPConvTol", 1E-9);
tester.CheckSolution(solver, solver_options, 5E-4);
}
GTEST_TEST(GurobiTest, MultipleThreadsSharingEnvironment) {
// Running multiple threads of GurobiSolver, they share the same GRBenv
// which is created when acquiring the Gurobi license in the main function.
auto solve_program = [](int i, int N) {
// We want to solve a complicated program in each thread, so that multiple
// programs will run concurrently. To this end, in each thread, we solve
// the following mixed-integer program
// min (x - i)² + (y - 1)²
// s.t Point (x, y) are on the line segments A₁A₂, A₂A₃, ..., Aₙ₋₁Aₙ,
// where A₂ⱼ= (2j, 1), A₂ⱼ₊₁ = (2j+1, 0)
// When i is an even number, the optimal solution is (i, 1), with optimal
// cost equals to 0. When i is an odd number, the optimal solution is either
// (i - 0.5, 0.5) or (i + 0.5, 0.5), with the optimal cost being 0.5
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>()(0);
auto y = prog.NewContinuousVariables<1>()(0);
// To constrain the point (x, y) on the line segment, we introduce a SOS2
// constraint with auxiliary variable lambda.
auto lambda = prog.NewContinuousVariables(N + 1);
// TODO(hongkai.dai): there is a bug in AddSos2Constraint, that it didn't
// add lambda(N) >= 0. After I resolve that bug, the next line could be
// removed.
prog.AddBoundingBoxConstraint(0, 1, lambda);
auto z = prog.NewBinaryVariables(N);
AddSos2Constraint(&prog, lambda.cast<symbolic::Expression>(),
z.cast<symbolic::Expression>());
Vector2<symbolic::Expression> line_segment(0, 0);
for (int j = 0; j <= N; ++j) {
line_segment(0) += j * lambda(j);
line_segment(1) += j % 2 == 0 ? symbolic::Expression(lambda(j))
: symbolic::Expression(0);
}
prog.AddLinearConstraint(line_segment(0) == x);
prog.AddLinearConstraint(line_segment(1) == y);
prog.AddQuadraticCost((x - i) * (x - i) + (y - 1) * (y - 1));
GurobiSolver gurobi_solver;
auto result = gurobi_solver.Solve(prog, {}, {});
EXPECT_TRUE(result.is_success());
const double tol = 1E-6;
if (i % 2 == 0) {
EXPECT_NEAR(result.get_optimal_cost(), 0, tol);
EXPECT_NEAR(result.GetSolution(x), i, tol);
EXPECT_NEAR(result.GetSolution(y), 1, tol);
} else {
EXPECT_NEAR(result.get_optimal_cost(), 0.5, tol);
EXPECT_NEAR(result.GetSolution(y), 0.5, tol);
const double x_val = result.GetSolution(x);
EXPECT_TRUE(std::abs(x_val - (i - 0.5)) < tol ||
std::abs(x_val - (i + 0.5)) < tol);
}
};
std::vector<std::thread> test_threads;
const int num_threads = 20;
for (int i = 0; i < num_threads; ++i) {
test_threads.emplace_back(solve_program, i, num_threads);
}
for (int i = 0; i < num_threads; ++i) {
test_threads[i].join();
}
}
GTEST_TEST(GurobiTest, GurobiErrorCode) {
// This test verifies that we can return the error code reported by Gurobi.
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
prog.AddLinearConstraint(x(0) + x(1) <= 1);
GurobiSolver solver;
if (solver.available()) {
// Report error when we set an unknown attribute to Gurobi.
SolverOptions solver_options1;
solver_options1.SetOption(solver.solver_id(), "Foo", 1);
DRAKE_EXPECT_THROWS_MESSAGE(solver.Solve(prog, {}, solver_options1),
".* 'Foo' is an unknown parameter in Gurobi.*");
// Report error when we pass an incorrect value to a valid Gurobi parameter
SolverOptions solver_options2;
solver_options2.SetOption(solver.solver_id(), "FeasibilityTol", 1E10);
DRAKE_EXPECT_THROWS_MESSAGE(solver.Solve(prog, {}, solver_options2),
".* is outside the parameter Feasibility.*");
// It is NOT an error to pass a float option using an int.
// Drake will promote the int to a float automatically.
SolverOptions solver_options3;
solver_options3.SetOption(solver.solver_id(), "TimeLimit", 3);
EXPECT_NO_THROW(solver.Solve(prog, {}, solver_options3));
// But it IS an error to pass a numeric option using a string.
SolverOptions solver_options4;
solver_options4.SetOption(solver.solver_id(), "Quad", "0");
DRAKE_EXPECT_THROWS_MESSAGE(solver.Solve(prog, {}, solver_options4),
".*Quad.*integer.*not.*string.*");
}
}
GTEST_TEST(GurobiTest, LogFile) {
// Test setting gurobi log file.
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<3>();
prog.AddQuadraticCost(x[0] * x[0] + 2 * x[1] * x[1]);
prog.AddBoundingBoxConstraint(0, 1, x);
prog.AddLinearEqualityConstraint(x[0] + x[1] + 2 * x[2] == 1);
prog.NewBinaryVariables<2>();
GurobiSolver solver;
if (solver.available()) {
{
SolverOptions solver_options;
const std::string log_file = temp_directory() + "/gurobi.log";
EXPECT_FALSE(std::filesystem::exists({log_file}));
solver_options.SetOption(solver.id(), "LogFile", log_file);
auto result = solver.Solve(prog, {}, solver_options);
EXPECT_TRUE(std::filesystem::exists({log_file}));
}
// Set log file through CommonSolverOptions.
{
SolverOptions solver_options;
const std::string log_file_common =
temp_directory() + "/gurobi_common.log";
EXPECT_FALSE(std::filesystem::exists({log_file_common}));
solver_options.SetOption(CommonSolverOption::kPrintFileName,
log_file_common);
solver.Solve(prog, {}, solver_options);
EXPECT_TRUE(std::filesystem::exists({log_file_common}));
}
// Also set to log to console. We can't test the console output but this
// test verifies no error thrown.
{
SolverOptions solver_options;
solver_options.SetOption(CommonSolverOption::kPrintToConsole, 1);
solver_options.SetOption(CommonSolverOption::kPrintFileName, "");
auto result = solver.Solve(prog, {}, solver_options);
EXPECT_TRUE(result.is_success());
}
// Set the option through both CommonSolverOption and solver-specific
// option. The common solver option should win.
{
SolverOptions solver_options;
const std::string log_file_common =
temp_directory() + "/gurobi_common2.log";
solver_options.SetOption(CommonSolverOption::kPrintFileName,
log_file_common);
const std::string log_file = temp_directory() + "/gurobi2.log";
solver_options.SetOption(solver.id(), "LogFile", log_file);
EXPECT_FALSE(std::filesystem::exists({log_file}));
EXPECT_FALSE(std::filesystem::exists({log_file_common}));
auto result = solver.Solve(prog, {}, solver_options);
EXPECT_TRUE(std::filesystem::exists({log_file}));
EXPECT_FALSE(std::filesystem::exists({log_file_common}));
}
}
}
GTEST_TEST(GurobiTest, WriteModel) {
// Test writing Gurobi model to a file.
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
prog.AddLinearConstraint(x[0] + x[1] == 1);
prog.AddQuadraticCost(x[0] * x[0] + x[1] * x[1]);
GurobiSolver solver;
if (solver.available()) {
const std::string model_file = temp_directory() + "/gurobi_model.mps";
SolverOptions options;
options.SetOption(solver.id(), "GRBwrite", "");
// Setting GRBwrite to "" and make sure calling Solve doesn't cause error.
solver.Solve(prog, {}, options);
options.SetOption(solver.id(), "GRBwrite", model_file);
EXPECT_FALSE(std::filesystem::exists({model_file}));
const auto result = solver.Solve(prog, {}, options);
EXPECT_TRUE(std::filesystem::exists({model_file}));
options.SetOption(solver.id(), "GRBwrite", "foo.wrong_extension");
DRAKE_EXPECT_THROWS_MESSAGE(solver.Solve(prog, {}, options),
".* setting GRBwrite to foo.wrong_extension.*");
}
}
GTEST_TEST(GurobiTest, ComputeIIS) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
prog.AddLinearConstraint(x[0] + x[1] == 2);
prog.AddLinearConstraint(x[0] - x[1] == 0);
auto bb_con = prog.AddBoundingBoxConstraint(2, 10, x[0]);
GurobiSolver solver;
if (solver.available()) {
SolverOptions options;
options.SetOption(solver.id(), "GRBcomputeIIS", 1);
const std::string ilp_file = temp_directory() + "/gurobi_model.ilp";
options.SetOption(solver.id(), "GRBwrite", ilp_file);
EXPECT_FALSE(std::filesystem::exists({ilp_file}));
auto result = solver.Solve(prog, {}, options);
EXPECT_TRUE(std::filesystem::exists({ilp_file}));
// Set GRBcomputeIIS to a wrong value.
options.SetOption(solver.id(), "GRBcomputeIIS", 100);
DRAKE_EXPECT_THROWS_MESSAGE(
solver.Solve(prog, {}, options),
".*option GRBcomputeIIS should be either 0 or 1.*");
// Reset GRBcomputeIIS to the right value.
options.SetOption(solver.id(), "GRBcomputeIIS", 1);
// Now remove bb_con. The problem should be feasible.
prog.RemoveConstraint(bb_con);
options.SetOption(solver.id(), "GRBwrite", "");
result = solver.Solve(prog, {}, options);
EXPECT_TRUE(result.is_success());
EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector2d(1, 1)));
}
}
GTEST_TEST(GurobiTest, SolutionPool) {
// For mixed-integer program, Gurobi can find a pool of suboptimal solutions.
MathematicalProgram prog;
auto b = prog.NewBinaryVariables<2>();
prog.AddLinearEqualityConstraint(b(0) + b(1) == 1);
prog.AddLinearCost(b(0));
GurobiSolver solver;
if (solver.is_available()) {
SolverOptions solver_options;
// Find at most 3 suboptimal solutions. Note that the problem only has 2
// solutions. This is to make sure that the user can set the size of the
// pool as large as he wants, and the solver will try to find all possible
// solutions.
solver_options.SetOption(solver.id(), "PoolSolutions", 3);
MathematicalProgramResult result;
solver.Solve(prog, {}, solver_options, &result);
// The problem has only two set of solutions, either b = [0, 1] and b = [1,
// 0].
EXPECT_EQ(result.num_suboptimal_solution(), 2);
const double tol = 1E-8;
EXPECT_TRUE(
CompareMatrices(result.GetSolution(b), Eigen::Vector2d(0, 1), tol));
EXPECT_TRUE(CompareMatrices(result.GetSuboptimalSolution(b, 0),
Eigen::Vector2d(0, 1), tol));
EXPECT_TRUE(CompareMatrices(result.GetSuboptimalSolution(b, 1),
Eigen::Vector2d(1, 0), tol));
EXPECT_NEAR(result.get_optimal_cost(), 0, tol);
EXPECT_NEAR(result.get_suboptimal_objective(0), 0, tol);
EXPECT_NEAR(result.get_suboptimal_objective(1), 1, tol);
}
}
GTEST_TEST(GurobiTest, QPDualSolution1) {
GurobiSolver solver;
TestQPDualSolution1(solver, {} /* solver_options */, 1e-6);
}
GTEST_TEST(GurobiTest, QPDualSolution2) {
GurobiSolver solver;
TestQPDualSolution2(solver);
}
GTEST_TEST(GurobiTest, QPDualSolution3) {
GurobiSolver solver;
TestQPDualSolution3(solver);
}
GTEST_TEST(GurobiTest, TestEqualityConstrainedQP1) {
GurobiSolver solver;
TestEqualityConstrainedQP1(solver);
}
GTEST_TEST(GurobiTest, EqualityConstrainedQPDualSolution1) {
GurobiSolver solver;
TestEqualityConstrainedQPDualSolution1(solver);
}
GTEST_TEST(GurobiTest, EqualityConstrainedQPDualSolution2) {
GurobiSolver solver;
TestEqualityConstrainedQPDualSolution2(solver);
}
GTEST_TEST(GurobiTest, LPDualSolution1) {
GurobiSolver solver;
TestLPDualSolution1(solver);
}
GTEST_TEST(GurobiTest, LPDualSolution2) {
GurobiSolver solver;
TestLPDualSolution2(solver);
}
GTEST_TEST(GurobiTest, LPDualSolution3) {
GurobiSolver solver;
TestLPDualSolution3(solver);
}
GTEST_TEST(GurobiTest, LPDualSolution4) {
GurobiSolver solver;
TestLPDualSolution4(solver);
}
GTEST_TEST(GurobiTest, LPDualSolution5) {
GurobiSolver solver;
TestLPDualSolution5(solver);
}
GTEST_TEST(GurobiTest, SOCPDualSolution1) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<2>();
auto constraint1 = prog.AddLorentzConeConstraint(
Vector3<symbolic::Expression>(2., 2 * x(0), 3 * x(1) + 1));
GurobiSolver solver;
prog.AddLinearCost(x(1));
if (solver.is_available()) {
// By default the dual solution for second order cone is not computed.
MathematicalProgramResult result = solver.Solve(prog);
DRAKE_EXPECT_THROWS_MESSAGE(
result.GetDualSolution(constraint1),
"You used Gurobi to solve this optimization problem.*");
SolverOptions options;
options.SetOption(solver.id(), "QCPDual", 1);
result = solver.Solve(prog, std::nullopt, options);
// The shadow price can be computed analytically, since the optimal cost
// is (-sqrt(4 + eps) - 1)/3, when the Lorentz cone constraint is perturbed
// by eps as 2*x(0)² + (3*x(1)+1)² <= 4 + eps. The gradient of the optimal
// cost (-sqrt(4 + eps) - 1)/3 w.r.t eps is -1/12.
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1),
Vector1d(-1. / 12), 1e-7));
// Now add a bounding box constraint to the program. By setting QCPDual to
// 0, the program should throw an error.
auto bb_con = prog.AddBoundingBoxConstraint(0, kInf, x(1));
options.SetOption(solver.id(), "QCPDual", 0);
result = solver.Solve(prog, std::nullopt, options);
DRAKE_EXPECT_THROWS_MESSAGE(
result.GetDualSolution(bb_con),
"You used Gurobi to solve this optimization problem.*");
// Now set QCPDual = 1, we should be able to retrieve the dual solution to
// the bounding box constraint.
options.SetOption(solver.id(), "QCPDual", 1);
result = solver.Solve(prog, std::nullopt, options);
// The cost is x(1), hence the shadow price for the constraint x(1) >= 0
// should be 1.
EXPECT_TRUE(
CompareMatrices(result.GetDualSolution(bb_con), Vector1d(1.), 1E-8));
}
}
GTEST_TEST(GurobiTest, SOCPDualSolution2) {
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<1>()(0);
auto constraint1 = prog.AddRotatedLorentzConeConstraint(
Vector3<symbolic::Expression>(2., x + 1.5, x));
auto constraint2 =
prog.AddLorentzConeConstraint(Vector2<symbolic::Expression>(1, x + 1));
prog.AddLinearCost(x);
GurobiSolver solver;
if (solver.is_available()) {
SolverOptions options;
options.SetOption(GurobiSolver::id(), "QCPDual", 1);
const auto result = solver.Solve(prog, {}, options);
// By perturbing the constraint1 as x^2 <= 2x + 3 + eps, the optimal cost
// becomes -1 - sqrt(4+eps). The gradient of the cost w.r.t eps is -1/4.
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1),
Vector1d(-1.0 / 4), 1e-8));
// constraint 2 is not active at the optimal solution, hence the shadow
// price is 0.
EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint2),
Vector1d(0), 1e-8));
}
}
GTEST_TEST(GurobiTest, TestDegenerateSOCP) {
GurobiSolver solver;
if (solver.is_available()) {
TestDegenerateSOCP(solver);
}
}
GTEST_TEST(GurobiTest, TestNonconvexQP) {
GurobiSolver solver;
if (solver.available()) {
TestNonconvexQP(solver, true);
}
}
GTEST_TEST(GurobiTest, TestIterationLimit) {
// Make sure that when the solver hits the iteration limit, it still reports
// the best-effort solution.
MathematicalProgram prog;
auto x = prog.NewContinuousVariables<4>();
prog.AddLorentzConeConstraint(x);
auto constraint2 = prog.AddLinearConstraint(x(0) + x(1) + x(2) + x(3) == 2);
prog.AddRotatedLorentzConeConstraint(x);
prog.AddLinearCost(x(0) + 2 * x(1));
GurobiSolver solver;
if (solver.available()) {
SolverOptions solver_options;
solver_options.SetOption(solver.id(), "IterationLimit", 1);
solver_options.SetOption(solver.id(), "BarIterLimit", 1);
solver_options.SetOption(solver.id(), "QCPDual", 1);
const auto result = solver.Solve(prog, std::nullopt, solver_options);
const auto solver_details = result.get_solver_details<GurobiSolver>();
// This code is defined in
// https://www.gurobi.com/documentation/10.0/refman/optimization_status_codes.html
const int ITERATION_LIMIT = 7;
EXPECT_EQ(solver_details.optimization_status, ITERATION_LIMIT);
EXPECT_TRUE(std::isfinite(result.get_optimal_cost()));
EXPECT_TRUE(result.GetSolution(x).array().isFinite().all());
EXPECT_TRUE(result.GetDualSolution(constraint2).array().isFinite().all());
}
}
} // namespace test
} // namespace solvers
} // namespace drake
int main(int argc, char** argv) {
// Ensure that we have the Gurobi license for the entire duration of this
// test, so that we do not have to release and re-acquire the license for
// every test.
auto gurobi_license = drake::solvers::GurobiSolver::AcquireLicense();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/benchmarking/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/performance:defs.bzl",
"drake_cc_googlebench_binary",
"drake_py_experiment_binary",
)
package(default_visibility = ["//visibility:public"])
drake_cc_googlebench_binary(
name = "benchmark_mathematical_program",
srcs = ["benchmark_mathematical_program.cc"],
add_test_rule = True,
test_timeout = "moderate",
deps = [
"//common:add_text_logging_gflags",
"//solvers:mathematical_program",
"//tools/performance:fixture_common",
"//tools/performance:gflags_main",
],
)
drake_py_experiment_binary(
name = "mathematical_program_experiment",
googlebench_binary = ":benchmark_mathematical_program",
)
drake_cc_googlebench_binary(
name = "benchmark_ipopt_solver",
srcs = ["benchmark_ipopt_solver.cc"],
add_test_rule = True,
test_timeout = "moderate",
deps = [
"//common:add_text_logging_gflags",
"//solvers:ipopt_solver",
"//solvers:mathematical_program",
"//tools/performance:fixture_common",
"//tools/performance:gflags_main",
],
)
drake_py_experiment_binary(
name = "ipopt_solver_experiment",
googlebench_binary = ":benchmark_ipopt_solver",
)
add_lint_tests()
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/benchmarking/benchmark_mathematical_program.cc | #include "drake/common/symbolic/monomial_util.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/tools/performance/fixture_common.h"
namespace drake {
namespace solvers {
namespace {
static void BenchmarkSosProgram1(benchmark::State& state) { // NOLINT
// Formulate a mathematical program with sum-of-squares constraints. This
// will involve a lot of computation on symbolic::Polynomial and imposing
// linear constraints.
// We construct symbolic::Polynomial directly from a Monomial map instead of
// parsing a symbolic::Expression.
for (auto _ : state) {
MathematicalProgram prog;
// Impose a constraint p_i(x).dot(q_i(x)) is sos, where both p_i(x) and
// q_i(x) are vectors of polynomials.
const auto x = prog.NewIndeterminates<7>();
const symbolic::Variables x_vars(x);
const auto monomial_basis = symbolic::MonomialBasis(x_vars, 3);
for (int i = 0; i < 10; ++i) {
VectorX<symbolic::Polynomial> p_i(15);
VectorX<symbolic::Polynomial> q_i(p_i.rows());
for (int j = 0; j < p_i.rows(); ++j) {
symbolic::Polynomial::MapType p_map;
for (int k = 0; k < monomial_basis.rows(); ++k) {
p_map.emplace(monomial_basis(k),
static_cast<double>(i * j) / 100.0 + k / 10.0 + 1);
}
p_i(j) = symbolic::Polynomial(std::move(p_map));
q_i(j) = prog.NewFreePolynomial(x_vars, 2);
}
prog.AddSosConstraint(p_i.dot(q_i));
}
}
}
static void BenchmarkSosProgram2(benchmark::State& state) { // NOLINT
// Formulate a mathematical program with sum-of-squares constraints. This
// will involve a lot of computation on symbolic::Polynomial and imposing
// linear constraints. Specifically it would involve the multiplication
// between two polynomials, one of the polynomial has all the coefficients as
// double constants, and the other polynomial coefficients are linear
// expressions, constructed using symbolic polynomial operations. This is
// different from BenchmarkSosProgram1 where the second polynomial
// coefficients are symbolic variables. We construct symbolic::Polynomial
// directly from a Monomial map instead of parsing a symbolic::Expression.
for (auto _ : state) {
MathematicalProgram prog;
// Impose a constraint p(x).dot(q(x)) is sos, where both p(x) and
// q(x) are both polynomials.
// where q(x) = ∂V/∂x * f(x)
// This ∂V/∂x * f(x) is often found in Lyapunov stability analysis.
const auto x = prog.NewIndeterminates<5>();
const symbolic::Variables x_vars(x);
const VectorX<symbolic::Monomial> monomial_basis =
symbolic::MonomialBasis(x_vars, 3);
const symbolic::Polynomial V = prog.NewFreePolynomial(x_vars, 4);
const Eigen::Matrix<symbolic::Polynomial, 1, 5> dVdx = V.Jacobian(x);
symbolic::Polynomial::MapType p_map;
for (int k = 0; k < monomial_basis.rows(); ++k) {
p_map.emplace(monomial_basis(k), static_cast<double>(k) / 10.0 + 1);
}
const symbolic::Polynomial p = symbolic::Polynomial(std::move(p_map));
// Construct f(x) ∈ ℝⁿ[x] where n = x.rows()
VectorX<symbolic::Polynomial> f(x.rows());
for (int i = 0; i < x.rows(); ++i) {
symbolic::Polynomial::MapType f_map;
for (int k = 0; k < monomial_basis.rows(); ++k) {
f_map.emplace(monomial_basis(k), static_cast<double>(k) * 2.0 + 1);
}
f(i) = symbolic::Polynomial(std::move(f_map));
}
const symbolic::Polynomial q = dVdx.dot(f);
prog.AddSosConstraint(p * q);
}
}
/**
* This program is reported in github issue
* https://github.com/RobotLocomotion/drake/issues/17160
* This program tries to find a lower bound for the cost-to-go that satisfies
* HJB inequality. Note that we create the right-hand side polynomial of the HJB
* inequality but don't impose any non-negative constraint on this polynomial.
* The reason is that this polynomial's coefficient isn't a linear expression of
* our decision variables. This benchmark program tests parsing a symbolic
* expression to a polynomial, but not imposing constraint on the polynomial.
*/
static void BenchmarkSosProgram3(benchmark::State& state) { // NOLINT
for (auto _ : state) {
MathematicalProgram prog;
const int nz = 3;
const int degree = 8;
const auto z = prog.NewIndeterminates(nz, "z");
const symbolic::Polynomial J =
prog.NewFreePolynomial(symbolic::Variables(z), degree);
const symbolic::Expression J_expr = J.ToExpression();
const RowVectorX<symbolic::Expression> dJdz = J_expr.Jacobian(z);
const Eigen::Vector3d f2(0, 0, 1);
const symbolic::Expression u_opt = -0.5 * dJdz.dot(f2);
const Eigen::Vector3d z0(0, 1, 0);
using std::pow;
const symbolic::Expression one_step_cost =
(z - z0).dot(z - z0) + pow(u_opt, 2);
const Vector3<symbolic::Expression> f(z(1) + z(2), -z(0) + z(2),
(z(0) + u_opt - z(2)));
const symbolic::Expression rhs = one_step_cost + dJdz.dot(f);
const symbolic::Polynomial rhs_poly(rhs, symbolic::Variables(z));
}
}
BENCHMARK(BenchmarkSosProgram1);
BENCHMARK(BenchmarkSosProgram2);
BENCHMARK(BenchmarkSosProgram3);
} // namespace
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake/solvers | /home/johnshepherd/drake/solvers/benchmarking/benchmark_ipopt_solver.cc | #include "drake/solvers/ipopt_solver.h"
#include "drake/solvers/mathematical_program.h"
#include "drake/tools/performance/fixture_common.h"
namespace drake {
namespace solvers {
namespace {
static void BenchmarkIpoptSolver(benchmark::State& state) { // NOLINT
// Number of decision variables.
const int nx = 1000;
// Create the mathematical program and the solver.
MathematicalProgram prog;
IpoptSolver solver;
// Create decision variables.
auto x = prog.NewContinuousVariables<nx>();
// Add bounding box constraints.
auto lbx = -1e0 * Eigen::VectorXd::Ones(nx);
auto ubx = +1e0 * Eigen::VectorXd::Ones(nx);
prog.AddBoundingBoxConstraint(lbx, ubx, x);
// Add random linear constraints.
auto A = Eigen::MatrixXd::Random(nx, nx);
auto lb = Eigen::VectorXd::Zero(nx);
auto ub = 1e20 * Eigen::VectorXd::Ones(nx);
prog.AddLinearConstraint(A, lb, ub, x);
// Add linear equality constraints.
auto Aeq = Eigen::MatrixXd::Identity(nx, nx);
auto beq = Eigen::VectorXd::Zero(nx);
prog.AddLinearEqualityConstraint(Aeq, beq, x);
// Add a nonlinear constraint: closed unit disk.
prog.AddConstraint(x.transpose() * x <= 1e0);
// Add a quadratic cost.
prog.AddQuadraticCost(Eigen::MatrixXd::Identity(nx, nx),
Eigen::VectorXd::Zero(nx), x);
// Run the solver and measure the performance.
MathematicalProgramResult result;
for (auto _ : state) {
result = solver.Solve(prog);
}
// Verify the success of the solver.
DRAKE_DEMAND(result.is_success());
}
BENCHMARK(BenchmarkIpoptSolver);
} // namespace
} // namespace solvers
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/setup/BUILD.bazel | load("//tools/install:install.bzl", "install_files")
load("//tools/lint:lint.bzl", "add_lint_tests")
package(default_visibility = ["//visibility:public"])
# Make our package requirements (but not manual scripts) available to
# downstream projects.
exports_files([
"mac/binary_distribution/Brewfile",
"mac/binary_distribution/requirements.txt",
"mac/source_distribution/Brewfile",
"mac/source_distribution/Brewfile-doc-only",
"mac/source_distribution/Brewfile-maintainer-only",
"mac/source_distribution/requirements.txt",
"mac/source_distribution/requirements-maintainer-only.txt",
"mac/source_distribution/requirements-test-only.txt",
"ubuntu/binary_distribution/packages-jammy.txt",
"ubuntu/source_distribution/packages-jammy.txt",
"ubuntu/source_distribution/packages-jammy-clang.txt",
"ubuntu/source_distribution/packages-jammy-doc-only.txt",
"ubuntu/source_distribution/packages-jammy-maintainer-only.txt",
"ubuntu/source_distribution/packages-jammy-test-only.txt",
"ubuntu/binary_distribution/packages-noble.txt",
"ubuntu/source_distribution/packages-noble.txt",
"ubuntu/source_distribution/packages-noble-clang.txt",
"ubuntu/source_distribution/packages-noble-doc-only.txt",
"ubuntu/source_distribution/packages-noble-maintainer-only.txt",
"ubuntu/source_distribution/packages-noble-test-only.txt",
])
filegroup(
name = "deepnote",
srcs = [
"deepnote/install_nginx",
"deepnote/nginx-meshcat-proxy.conf",
],
visibility = ["//bindings/pydrake:__subpackages__"],
)
install_files(
name = "install",
dest = "share/drake/setup",
files = select({
"//tools/cc_toolchain:apple": [
"mac/binary_distribution/Brewfile",
"mac/binary_distribution/install_prereqs.sh",
"mac/binary_distribution/requirements.txt",
],
"//tools/cc_toolchain:linux": [
"deepnote/install_nginx",
"deepnote/install_xvfb",
"deepnote/nginx-meshcat-proxy.conf",
"deepnote/xvfb",
"ubuntu/binary_distribution/install_prereqs.sh",
"ubuntu/binary_distribution/packages-jammy.txt",
"ubuntu/binary_distribution/packages-noble.txt",
],
"//conditions:default": [],
}),
strip_prefix = [
"mac/binary_distribution",
"ubuntu/binary_distribution",
],
rename = {
"share/drake/setup/install_prereqs.sh": "install_prereqs",
},
)
add_lint_tests()
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/setup/README.md | # Installation Prerequisites
These are dependencies that are not pulled in via Bazel and must be installed
on the OS itself.
For how to install Drake on your system, please see the
[Installation and Quickstart](https://drake.mit.edu/installation.html)
documentation.
If you are a developer wishing to add dependencies, please see the
[Jenkins pages for Updating Installation Prerequisites](
https://drake.mit.edu/jenkins.html#updating-installation-prerequisites).
| 0 |
/home/johnshepherd/drake/setup | /home/johnshepherd/drake/setup/deepnote/xvfb | #!/bin/sh
### BEGIN INIT INFO
# Provides: Xvfb
# Required-Start: $local_fs $remote_fs
# Required-Stop:
# X-Start-Before:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Loads X Virtual Frame Buffer
### END INIT INFO
XVFB=/usr/bin/Xvfb
XVFBARGS=":1 -screen 0 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
PIDFILE=/var/run/xvfb.pid
case "$1" in
start)
echo -n "Starting virtual X frame buffer: Xvfb"
start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS
echo "."
;;
stop)
echo -n "Stopping virtual X frame buffer: Xvfb"
start-stop-daemon --stop --quiet --pidfile $PIDFILE
echo "."
;;
restart)
$0 stop
$0 start
;;
*)
echo "Usage: /etc/init.d/xvfb {start|stop|restart}"
exit 1
esac
exit 0
| 0 |
/home/johnshepherd/drake/setup | /home/johnshepherd/drake/setup/deepnote/nginx-meshcat-proxy.conf | # Deepnote- and MeshCat- specific NginX proxy server configuration.
#
# Proxy https://DEEPNOTE_PROJECT_ID:8080/PORT/ to http://127.0.0.1:PORT/ so
# that multiple notebooks can all be served via Deepnote's only open port.
#
# For conf documentation, see https://www.nginx.com/resources/wiki/start/.
server {
listen 8080 default_server;
listen [::]:8080 default_server;
root /var/www/html;
server_name _;
location ~ /(7[0-9][0-9][0-9])/(.*) {
proxy_pass http://127.0.0.1:$1/$2;
}
proxy_read_timeout 600;
proxy_connect_timeout 600;
proxy_send_timeout 600;
send_timeout 600;
}
| 0 |
/home/johnshepherd/drake/setup | /home/johnshepherd/drake/setup/deepnote/install_nginx | #!/bin/bash
#
# Installs and runs nginx as an Ubuntu (or Debian) system daemon, and adds our
# nginx-meshcat-proxy.conf as a site to be served.
#
# This is intended for use by pydrake.geometry.SetupMeshcat() to configure a
# Deepnote notebook to allow for MeshCat traffic to flow. Refer to the
# implementation in bindings/pydrake/_geometry_extra.py for details.
set -euo pipefail
# Install nginx; disable its default site.
if [[ $(dpkg-query -W -f'${db:Status-Abbrev}' nginx-light) != "ii " ]]; then
apt-get update
apt-get install -y --no-install-recommends nginx-light
fi
rm -f /etc/nginx/sites-enabled/default
# Enable our meshcat site.
my_dir="$(cd "$(dirname "${BASH_SOURCE}")" && pwd)"
site="/etc/nginx/sites-available/deepnote-meshcat-proxy"
cp "${my_dir}/nginx-meshcat-proxy.conf" "${site}"
ln -sf "${site}" /etc/nginx/sites-enabled/
service nginx start
| 0 |
/home/johnshepherd/drake/setup | /home/johnshepherd/drake/setup/deepnote/README.md | The nginx-related files are used by pydrake.geometry.SetupMeshcat() to
configure a Deepnote notebook to allow for MeshCat traffic to flow. Refer
to the implementation in bindings/pydrake/_geometry_extra.py for details.
The xvfb-related files are used to launch an X display suitable for Drake's
image rendering simulations.
Even though these files are used on Ubuntu- or Debian-based systems,
we don't place them under drake/setup/ubuntu/... because they are not
relevant to most Drake users on Ubuntu -- they are only useful for the
Deepnote cloud hosting platform.
| 0 |
/home/johnshepherd/drake/setup | /home/johnshepherd/drake/setup/deepnote/install_xvfb | #!/bin/bash
#
# Installs and runs Xvfb as an Ubuntu system daemon at DISPLAY=:1.
#
# This is intended for use only on Deepnote, to allow VTK and GL rendering.
set -euo pipefail
# Install Xvfb.
if [[ $(dpkg-query -W -f'${db:Status-Abbrev}' xvfb) != "ii " ]]; then
apt-get update
apt-get install -y --no-install-recommends xvfb
fi
# Run it as a service.
ln -sf /opt/drake/share/drake/setup/deepnote/xvfb /etc/init.d/
service xvfb start
| 0 |
/home/johnshepherd/drake/setup | /home/johnshepherd/drake/setup/mac/install_prereqs.sh | #!/bin/bash
#
# Install development and runtime prerequisites for both binary and source
# distributions of Drake on macOS.
set -euxo pipefail
binary_distribution_args=()
source_distribution_args=()
while [ "${1:-}" != "" ]; do
case "$1" in
# Do NOT install prerequisites that are only needed to build and/or run
# unit tests, i.e., those prerequisites that are not dependencies of
# bazel { build, run } //:install.
--without-test-only)
source_distribution_args+=(--without-test-only)
;;
# Do NOT call brew update during execution of this script.
--without-update)
binary_distribution_args+=(--without-update)
source_distribution_args+=(--without-update)
;;
*)
echo 'Invalid command line argument' >&2
exit 1
esac
shift
done
# Dependencies that are installed by the following sourced script that are
# needed when developing with binary distributions are also needed when
# developing with source distributions.
# N.B. We need `${var:-}` here because mac's older version of bash does
# not seem to be able to cope with an empty array.
source "${BASH_SOURCE%/*}/binary_distribution/install_prereqs.sh" \
"${binary_distribution_args[@]:-}"
# The following additional dependencies are only needed when developing with
# source distributions.
source "${BASH_SOURCE%/*}/source_distribution/install_prereqs.sh" \
"${source_distribution_args[@]:-}"
# The preceding only needs to be run once per machine. The following sourced
# script should be run once per user who develops with source distributions.
source "${BASH_SOURCE%/*}/source_distribution/install_prereqs_user_environment.sh"
| 0 |
/home/johnshepherd/drake/setup/mac | /home/johnshepherd/drake/setup/mac/binary_distribution/requirements.txt | ipywidgets
matplotlib
notebook
Pillow
pydot
PyYAML
| 0 |
/home/johnshepherd/drake/setup/mac | /home/johnshepherd/drake/setup/mac/binary_distribution/Brewfile | # -*- mode: ruby -*-
# vi: set ft=ruby :
cask 'adoptopenjdk' unless system '/usr/libexec/java_home --version 1.8+ --failfast &> /dev/null'
brew 'eigen'
brew 'gcc'
brew 'fmt'
brew 'glib'
brew 'graphviz'
brew 'ipopt'
brew 'numpy'
brew 'pkg-config'
brew '[email protected]'
brew 'spdlog'
mas 'Xcode', id: 497799835 unless File.exist? '/Applications/Xcode.app'
| 0 |
/home/johnshepherd/drake/setup/mac | /home/johnshepherd/drake/setup/mac/binary_distribution/install_prereqs.sh | #!/bin/bash
#
# Install development and runtime prerequisites for binary distributions of
# Drake on macOS.
set -euxo pipefail
with_update=1
while [ "${1:-}" != "" ]; do
case "$1" in
# Do NOT call brew update during execution of this script.
--without-update)
with_update=0
;;
*)
echo 'Invalid command line argument' >&2
exit 5
esac
shift
done
if [[ "${EUID}" -eq 0 ]]; then
echo 'ERROR: This script must NOT be run as root' >&2
exit 1
fi
if command -v conda &>/dev/null; then
echo 'NOTE: Drake is not tested regularly with Anaconda, so you may experience compatibility hiccups; when asking for help, be sure to mention that Conda is involved.' >&2
fi
if ! command -v brew &>/dev/null; then
/bin/bash -c \
"$(/usr/bin/curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi
# Pass --retry 2 when invoking the curl command line tool during execution of
# this script to retry twice the download of a bottle.
[[ -z "${HOMEBREW_CURL_RETRIES:-}" ]] || export HOMEBREW_CURL_RETRIES=2
# Do not automatically update before running brew install, brew upgrade, or brew
# tap during execution of this script. We manually update where necessary and
# retry if the update fails.
export HOMEBREW_NO_AUTO_UPDATE=1
# Do not automatically cleanup installed, upgraded, and/or reinstalled formulae
# during execution of this script. Manually run brew cleanup after the script
# completes or wait for the next automatic cleanup if necessary.
export HOMEBREW_NO_INSTALL_CLEANUP=1
binary_distribution_called_update=0
if [[ "${with_update}" -eq 1 ]]; then
# Note that brew update uses git, so HOMEBREW_CURL_RETRIES does not take
# effect.
brew update || (sleep 30; brew update)
# Do NOT call brew update again when installing prerequisites for source
# distributions.
binary_distribution_called_update=1
fi
brew bundle --file="${BASH_SOURCE%/*}/Brewfile" --no-lock
if ! command -v pip3.12 &>/dev/null; then
echo 'ERROR: pip3.12 is NOT installed. The post-install step for the [email protected] formula may have failed.' >&2
exit 2
fi
pip3.12 install --break-system-packages -r "${BASH_SOURCE%/*}/requirements.txt"
| 0 |
/home/johnshepherd/drake/setup/mac | /home/johnshepherd/drake/setup/mac/source_distribution/Brewfile | # -*- mode: ruby -*-
# vi: set ft=ruby :
brew 'bazelisk'
brew 'cmake'
brew 'nasm'
| 0 |
/home/johnshepherd/drake/setup/mac | /home/johnshepherd/drake/setup/mac/source_distribution/Brewfile-test-only | # -*- mode: ruby -*-
# vi: set ft=ruby :
brew 'llvm@15'
| 0 |
/home/johnshepherd/drake/setup/mac | /home/johnshepherd/drake/setup/mac/source_distribution/requirements-test-only.txt | flask
six
u-msgpack-python
websockets
| 0 |
/home/johnshepherd/drake/setup/mac | /home/johnshepherd/drake/setup/mac/source_distribution/install_prereqs_user_environment.sh | #!/bin/bash
#
# Write user environment prerequisites for source distributions of Drake on
# macOS.
# N.B. Ensure that this is synchronized with the install instructions regarding
# Homebrew Python in `doc/python_bindings.rst`.
set -euo pipefail
if [[ "${EUID}" -eq 0 ]]; then
echo 'ERROR: This script must NOT be run as root' >&2
exit 1
fi
workspace_dir="$(cd "$(dirname "${BASH_SOURCE}")/../../.." && pwd)"
bazelrc="${workspace_dir}/gen/environment.bazelrc"
arch="$(/usr/bin/arch)"
mkdir -p "$(dirname "${bazelrc}")"
cat > "${bazelrc}" <<EOF
import %workspace%/tools/macos.bazelrc
import %workspace%/tools/macos-arch-${arch}.bazelrc
EOF
# Prefetch the bazelisk download of bazel.
# This is especially helpful for the "Provisioned" images in CI.
(cd "${workspace_dir}" && bazelisk version) > /dev/null
| 0 |
/home/johnshepherd/drake/setup/mac | /home/johnshepherd/drake/setup/mac/source_distribution/install_prereqs.sh | #!/bin/bash
#
# Install development prerequisites for source distributions of Drake on macOS.
#
# The development and runtime prerequisites for binary distributions should be
# installed before running this script.
set -euxo pipefail
with_test_only=1
with_update=1
while [ "${1:-}" != "" ]; do
case "$1" in
# Do NOT install prerequisites that are only needed to build and/or run
# unit tests, i.e., those prerequisites that are not dependencies of
# bazel { build, run } //:install.
--without-test-only)
with_test_only=0
;;
# Do NOT call brew update during execution of this script.
--without-update)
with_update=0
;;
*)
echo 'Invalid command line argument' >&2
exit 5
esac
shift
done
if [[ "${EUID}" -eq 0 ]]; then
echo 'ERROR: This script must NOT be run as root' >&2
exit 1
fi
if ! command -v brew &>/dev/null; then
echo 'ERROR: brew is NOT installed. Please ensure that the prerequisites for binary distributions have been installed.' >&2
exit 4
fi
if [[ "${with_update}" -eq 1 && "${binary_distribution_called_update:-0}" -ne 1 ]]; then
brew update || (sleep 30; brew update)
fi
brew bundle --file="${BASH_SOURCE%/*}/Brewfile" --no-lock
if [[ "${with_test_only}" -eq 1 ]]; then
brew bundle --file="${BASH_SOURCE%/*}/Brewfile-test-only" --no-lock
fi
if ! command -v pip3.12 &>/dev/null; then
echo 'ERROR: pip3.12 is NOT installed. The post-install step for the [email protected] formula may have failed.' >&2
exit 2
fi
pip3.12 install --break-system-packages -r "${BASH_SOURCE%/*}/requirements.txt"
if [[ "${with_test_only}" -eq 1 ]]; then
pip3.12 install --break-system-packages -r "${BASH_SOURCE%/*}/requirements-test-only.txt"
fi
| 0 |
/home/johnshepherd/drake/setup | /home/johnshepherd/drake/setup/ubuntu/install_prereqs.sh | #!/bin/bash
#
# Install development and runtime prerequisites for both binary and source
# distributions of Drake on Ubuntu.
set -euo pipefail
# Check for existence of `SUDO_USER` so that this may be used in Docker
# environments.
if [[ -n "${SUDO_USER:+D}" && $(id -u ${SUDO_USER}) -eq 0 ]]; then
cat <<eof >&2
It appears that this script is running under sudo, but it was the root user
who ran sudo. That use is not supported; when already running as root, do not
use sudo when calling this script.
eof
exit 1
fi
at_exit () {
echo "${me} has experienced an error on line ${LINENO}" \
"while running the command ${BASH_COMMAND}"
}
me='The Drake source distribution prerequisite setup script'
trap at_exit EXIT
binary_distribution_args=()
source_distribution_args=()
while [ "${1:-}" != "" ]; do
case "$1" in
# Install prerequisites that are only needed to build documentation,
# i.e., those prerequisites that are dependencies of bazel run //doc:build.
--with-doc-only)
source_distribution_args+=(--with-doc-only)
;;
# Install bazelisk from a deb package.
--with-bazel)
source_distribution_args+=(--with-bazel)
;;
# Do NOT install bazelisk.
--without-bazel)
source_distribution_args+=(--without-bazel)
;;
# Install prerequisites that are only needed for --config clang, i.e.,
# opts-in to the ability to compile Drake's C++ code using Clang.
--with-clang)
source_distribution_args+=(--with-clang)
;;
# Do NOT install prerequisites that are only needed for --config clang,
# i.e., opts-out of the ability to compile Drake's C++ code using Clang.
--without-clang)
source_distribution_args+=(--without-clang)
;;
# Install prerequisites that are only needed to run select maintainer
# scripts. Most developers will not need to install these dependencies.
--with-maintainer-only)
source_distribution_args+=(--with-maintainer-only)
;;
# Do NOT install prerequisites that are only needed to build and/or run
# unit tests, i.e., those prerequisites that are not dependencies of
# bazel { build, run } //:install.
--without-test-only)
source_distribution_args+=(--without-test-only)
;;
# Do NOT call apt-get update during execution of this script.
--without-update)
binary_distribution_args+=(--without-update)
source_distribution_args+=(--without-update)
;;
-y)
binary_distribution_args+=(-y)
source_distribution_args+=(-y)
;;
*)
echo 'Invalid command line argument' >&2
exit 1
esac
shift
done
# Dependencies that are installed by the following sourced script that are
# needed when developing with binary distributions are also needed when
# developing with source distributions.
#
# Note that the list of packages in binary_distribution/packages.txt is used to
# generate the dependencies of the drake .deb package, so does not include
# development dependencies such as build-essential and cmake.
source "${BASH_SOURCE%/*}/binary_distribution/install_prereqs.sh" \
"${binary_distribution_args[@]}"
# The following additional dependencies are only needed when developing with
# source distributions.
source "${BASH_SOURCE%/*}/source_distribution/install_prereqs.sh" \
"${source_distribution_args[@]}"
# Configure user environment, executing as user if we're under `sudo`.
user_env_script="${BASH_SOURCE%/*}/source_distribution/install_prereqs_user_environment.sh"
if [[ -n "${SUDO_USER:+D}" ]]; then
sudo -u "${SUDO_USER}" bash "${user_env_script}"
else
source "${user_env_script}"
fi
trap : EXIT # Disable exit reporting.
echo 'install_prereqs: success'
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/binary_distribution/packages-jammy.txt | default-jre
jupyter-notebook
libblas-dev
libeigen3-dev
libgfortran5
libglib2.0-0
libglx0
libgomp1
libjchart2d-java
liblapack3
libmumps-seq-5.4
libopengl0
libpython3.10
libspdlog-dev
libx11-6
ocl-icd-libopencl1
python3
python3-ipywidgets
python3-matplotlib
python3-munkres
python3-numpy
python3-pil
python3-pydot
python3-yaml
zlib1g
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/binary_distribution/packages-noble.txt | default-jre
jupyter-notebook
libblas-dev
libeigen3-dev
libgfortran5
libglib2.0-0
libglx0
libgomp1
libjchart2d-java
liblapack3
libmumps-seq-5.6
libopengl0
libquadmath0
libpython3.12
libspdlog-dev
libx11-6
ocl-icd-libopencl1
python3
python3-ipywidgets
python3-matplotlib
python3-munkres
python3-numpy
python3-pil
python3-pydot
python3-yaml
zlib1g
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/binary_distribution/install_prereqs.sh | #!/bin/bash
#
# Install development and runtime prerequisites for binary distributions of
# Drake on Ubuntu.
set -euo pipefail
with_update=1
with_asking=1
while [ "${1:-}" != "" ]; do
case "$1" in
# Do NOT call apt-get update during execution of this script.
--without-update)
with_update=0
;;
# Pass -y along to apt-get.
-y)
with_asking=0
;;
*)
echo 'Invalid command line argument' >&2
exit 3
esac
shift
done
if [[ "${EUID}" -ne 0 ]]; then
echo 'ERROR: This script must be run as root' >&2
exit 1
fi
if [[ "${with_asking}" -eq 0 ]]; then
maybe_yes='-y'
else
maybe_yes=''
fi
if command -v conda &>/dev/null; then
echo 'NOTE: Drake is not tested regularly with Anaconda, so you may experience compatibility hiccups; when asking for help, be sure to mention that Conda is involved.' >&2
fi
binary_distribution_called_update=0
if [[ "${with_update}" -eq 1 ]]; then
apt-get update || (sleep 30; apt-get update) || (cat <<EOF && false)
****************************************************************************
Drake is unable to run 'sudo apt-get update', probably because this computer
contains incorrect entries in its sources.list files, or possibly because an
internet service is down.
Run 'sudo apt-get update' and try to resolve whatever problems it reports.
Do not try to set up Drake until that command succeeds.
This is not a bug in Drake. Do not contact the Drake team for help.
****************************************************************************
EOF
# Do NOT call apt-get update again when installing prerequisites for source
# distributions.
binary_distribution_called_update=1
fi
apt-get install ${maybe_yes} --no-install-recommends lsb-release
codename=$(lsb_release -sc)
if ! [[ "${codename}" =~ (jammy|noble) ]]; then
echo 'ERROR: This script requires Ubuntu 22.04 (Jammy) or 24.04 (Noble)' >&2
exit 2
fi
apt-get install ${maybe_yes} --no-install-recommends $(cat <<EOF
build-essential
cmake
pkg-config
EOF
)
packages=$(cat "${BASH_SOURCE%/*}/packages-${codename}.txt")
apt-get install ${maybe_yes} --no-install-recommends ${packages}
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-noble-maintainer-only.txt | alien
diffstat
fakeroot
patchutils
python3-boto3
python3-git
python3-jwcrypto
python3-jwt
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-noble-doc-only.txt | fonts-dejavu-core
fonts-dejavu-extra
graphviz
jekyll
node-uglify
python3-docutils
python3-sphinx
python3-sphinx-rtd-theme
ruby
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-noble-test-only.txt | clang-format-15
curl
libstdc++6-10-dbg
python3-dateutil
python3-dbg
python3-flask
python3-nbconvert
python3-nbformat
python3-opencv
python3-psutil
python3-requests
python3-six
python3-u-msgpack
python3-uritemplate
python3-websockets
valgrind
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-jammy-maintainer-only.txt | alien
diffstat
fakeroot
patchutils
python3-boto3
python3-git
python3-jwcrypto
python3-jwt
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-jammy-doc-only.txt | fonts-dejavu-core
fonts-dejavu-extra
graphviz
jekyll
node-uglify
python3-docutils
python3-sphinx
python3-sphinx-rtd-theme
ruby
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-jammy.txt | default-jdk
file
gfortran
libclang-15-dev
libgl-dev
libglib2.0-dev
libglx-dev
liblapack-dev
libmumps-seq-dev
libopengl-dev
libx11-dev
nasm
ocl-icd-opencl-dev
opencl-headers
patch
patchelf
pkg-config
python3-all-dev
python3-pygame
zlib1g-dev
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-jammy-test-only.txt | clang-format-15
curl
kcov
libstdc++6-10-dbg
python3-dateutil
python3-dbg
python3-flask
python3-nbconvert
python3-nbformat
python3-opencv
python3-psutil
python3-requests
python3-six
python3-u-msgpack
python3-uritemplate
python3-websockets
valgrind
valgrind-dbg
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/install_bazelisk.sh | #!/bin/bash
#
# On Ubuntu, installs bazelisk at /usr/bin/bazel{,isk}.
#
# This script does not accept any command line arguments.
set -euo pipefail
dpkg_install_from_wget() {
package="$1"
version="$2"
url="$3"
checksum="$4"
# Skip the install if we're already at the exact version.
installed=$(dpkg-query --showformat='${Version}\n' --show "${package}" 2>/dev/null || true)
if [[ "${installed}" == "${version}" ]]; then
echo "${package} is already at the desired version ${version}"
return
fi
# If installing our desired version would be a downgrade, ask the user first.
if dpkg --compare-versions "${installed}" gt "${version}"; then
echo "This system has ${package} version ${installed} installed."
echo "Drake suggests downgrading to version ${version}, our supported version."
read -r -p 'Do you want to downgrade? [Y/n] ' reply
if [[ ! "${reply}" =~ ^([yY][eE][sS]|[yY])*$ ]]; then
echo "Skipping ${package} ${version} installation."
return
fi
fi
# Download and verify.
tmpdeb="/tmp/${package}_${version}-amd64.deb"
wget -O "${tmpdeb}" "${url}"
if echo "${checksum} ${tmpdeb}" | sha256sum -c -; then
echo # Blank line between checkout output and dpkg output.
else
echo "ERROR: The ${package} deb does NOT have the expected SHA256. Not installing." >&2
exit 2
fi
# Install.
dpkg -i "${tmpdeb}"
rm "${tmpdeb}"
}
# If bazel.deb is already installed, we'll need to remove it first because
# the Debian package of bazelisk will take over the `/usr/bin/bazel` path.
apt-get remove bazel || true
# Install bazelisk.
#
# TODO(jeremy.nimmer) Once there's a bazelisk >= 1.20 that incorporates
# https://github.com/bazelbuild/bazelisk/pull/563, we should switch to
# official release downloads instead of our Drake-custom Debian packages.
if [[ $(arch) = "aarch64" ]]; then
dpkg_install_from_wget \
bazelisk 1.19.0-9-g58a850f \
https://drake-mirror.csail.mit.edu/github/bazelbuild/bazelisk/pr563/bazelisk_1.19.0-9-g58a850f_arm64.deb \
5501a44ba1f51298d186e4e66966b0556d03524381a967667696f032e292d719
else
dpkg_install_from_wget \
bazelisk 1.19.0-9-g58a850f \
https://drake-mirror.csail.mit.edu/github/bazelbuild/bazelisk/pr563/bazelisk_1.19.0-9-g58a850f_amd64.deb \
c2bfd15d6c3422ae540cda9facc0ac395005e2701c09dbb15d40447b53e831d4
fi
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-noble-clang.txt | clang-15
libomp-15-dev
llvm-15
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-noble.txt | default-jdk
file
gfortran
libclang-15-dev
libgl-dev
libglib2.0-dev
libglx-dev
liblapack-dev
libmumps-seq-dev
libopengl-dev
libx11-dev
nasm
ocl-icd-opencl-dev
opencl-headers
patch
patchelf
pkg-config
python3-all-dev
python3-pygame
zlib1g-dev
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/install_prereqs_user_environment.sh | #!/bin/bash
#
# Write user environment prerequisites for source distributions of Drake on
# Ubuntu.
set -euo pipefail
# Check for existence of `SUDO_USER` so that this may be used in Docker
# environments.
if [[ "${EUID}" -eq 0 && -n "${SUDO_USER:+D}" ]]; then
echo 'This script must NOT be run through sudo as root' >&2
exit 1
fi
workspace_dir="$(cd "$(dirname "${BASH_SOURCE}")/../../.." && pwd)"
bazelrc="${workspace_dir}/gen/environment.bazelrc"
codename=$(lsb_release -sc)
mkdir -p "$(dirname "${bazelrc}")"
cat > "${bazelrc}" <<EOF
import %workspace%/tools/ubuntu.bazelrc
import %workspace%/tools/ubuntu-${codename}.bazelrc
EOF
# Prefetch the bazelisk download of bazel.
# This is especially helpful for the "Provisioned" images in CI.
(cd "${workspace_dir}" && bazel version)
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/packages-jammy-clang.txt | clang-15
libomp-15-dev
llvm-15
| 0 |
/home/johnshepherd/drake/setup/ubuntu | /home/johnshepherd/drake/setup/ubuntu/source_distribution/install_prereqs.sh | #!/bin/bash
#
# Install development prerequisites for source distributions of Drake on
# Ubuntu.
#
# The development and runtime prerequisites for binary distributions should be
# installed before running this script.
set -euo pipefail
with_doc_only=0
with_maintainer_only=0
with_bazel=1
with_clang=1
with_test_only=1
with_update=1
with_asking=1
# TODO(jwnimmer-tri) Eventually we should default to with_clang=0.
while [ "${1:-}" != "" ]; do
case "$1" in
# Install prerequisites that are only needed to build documentation,
# i.e., those prerequisites that are dependencies of bazel run //doc:build.
--with-doc-only)
with_doc_only=1
;;
# Install bazelisk from a deb package.
--with-bazel)
with_bazel=1
;;
# Do NOT install bazelisk.
--without-bazel)
with_bazel=0
;;
# Install prerequisites that are only needed for --config clang, i.e.,
# opts-in to the ability to compile Drake's C++ code using Clang.
--with-clang)
with_clang=1
;;
# Do NOT install prerequisites that are only needed for --config clang,
# i.e., opts-out of the ability to compile Drake's C++ code using Clang.
--without-clang)
with_clang=0
;;
# Install prerequisites that are only needed to run select maintainer
# scripts. Most developers will not need to install these dependencies.
--with-maintainer-only)
with_maintainer_only=1
;;
# Do NOT install prerequisites that are only needed to build and/or run
# unit tests, i.e., those prerequisites that are not dependencies of
# bazel { build, run } //:install.
--without-test-only)
with_test_only=0
;;
# Do NOT call apt-get update during execution of this script.
--without-update)
with_update=0
;;
# Pass -y along to apt-get.
-y)
with_asking=0
;;
*)
echo 'Invalid command line argument' >&2
exit 3
esac
shift
done
if [[ "${EUID}" -ne 0 ]]; then
echo 'ERROR: This script must be run as root' >&2
exit 1
fi
if [[ "${with_asking}" -eq 0 ]]; then
maybe_yes='-y'
else
maybe_yes=''
fi
if [[ "${with_update}" -eq 1 && "${binary_distribution_called_update:-0}" -ne 1 ]]; then
apt-get update || (sleep 30; apt-get update)
fi
apt-get install ${maybe_yes} --no-install-recommends $(cat <<EOF
ca-certificates
wget
EOF
)
codename=$(lsb_release -sc)
packages=$(cat "${BASH_SOURCE%/*}/packages-${codename}.txt")
apt-get install ${maybe_yes} --no-install-recommends ${packages}
# Ensure that we have available a locale that supports UTF-8 for generating a
# C++ header containing Python API documentation during the build.
apt-get install ${maybe_yes} --no-install-recommends locales
locale-gen en_US.UTF-8
# We need a working /usr/bin/python (of any version).
if [[ ! -e /usr/bin/python ]]; then
apt-get install ${maybe_yes} --no-install-recommends python-is-python3
else
echo "/usr/bin/python is already installed"
fi
if [[ "${with_doc_only}" -eq 1 ]]; then
packages=$(cat "${BASH_SOURCE%/*}/packages-${codename}-doc-only.txt")
apt-get install ${maybe_yes} --no-install-recommends ${packages}
fi
if [[ "${with_bazel}" -eq 1 ]]; then
source "${BASH_SOURCE%/*}/install_bazelisk.sh"
fi
if [[ "${with_clang}" -eq 1 ]]; then
packages=$(cat "${BASH_SOURCE%/*}/packages-${codename}-clang.txt")
apt-get install ${maybe_yes} --no-install-recommends ${packages}
fi
if [[ "${with_test_only}" -eq 1 ]]; then
packages=$(cat "${BASH_SOURCE%/*}/packages-${codename}-test-only.txt")
apt-get install ${maybe_yes} --no-install-recommends ${packages}
fi
if [[ "${with_maintainer_only}" -eq 1 ]]; then
packages=$(cat "${BASH_SOURCE%/*}/packages-${codename}-maintainer-only.txt")
apt-get install ${maybe_yes} --no-install-recommends ${packages}
fi
# On Jammy, Drake doesn't install anything related to GCC 12, but if the user
# has chosen to install some GCC 12 libraries but has failed to install all of
# them correctly as a group, Drake's documentation header file parser will fail
# with a libclang-related complaint. Therefore, we'll help the user clean up
# their mess, to avoid apparent Drake build errors.
if [[ "${codename}" == "jammy" ]]; then
status=$(dpkg-query --show --showformat='${db:Status-Abbrev}' libgcc-12-dev 2>/dev/null || true)
if [[ "${status}" == "ii " ]]; then
status_stdcxx=$(dpkg-query --show --showformat='${db:Status-Abbrev}' libstdc++-12-dev 2>/dev/null || true)
status_fortran=$(dpkg-query --show --showformat='${db:Status-Abbrev}' libgfortran-12-dev 2>/dev/null || true)
if [[ "${status_stdcxx}" != "ii " || "${status_fortran}" != "ii " ]]; then
apt-get install ${maybe_yes} --no-install-recommends libgcc-12-dev libstdc++-12-dev libgfortran-12-dev
fi
fi
fi
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_position_controller.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_position_controller.h"
#include <algorithm>
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
using Eigen::Vector2d;
using systems::BasicVector;
const int kNumJoints = 2;
SchunkWsgPdController::SchunkWsgPdController(double kp_command,
double kd_command,
double kp_constraint,
double kd_constraint,
double default_force_limit)
: kp_command_(kp_command),
kd_command_(kd_command),
kp_constraint_(kp_constraint),
kd_constraint_(kd_constraint),
default_force_limit_(default_force_limit) {
DRAKE_DEMAND(kp_command >= 0);
DRAKE_DEMAND(kd_command >= 0);
DRAKE_DEMAND(kp_constraint >= 0);
DRAKE_DEMAND(kd_constraint >= 0);
desired_state_input_port_ =
this->DeclareVectorInputPort("desired_state", 2).get_index();
force_limit_input_port_ =
this->DeclareVectorInputPort("force_limit", 1).get_index();
state_input_port_ =
this->DeclareVectorInputPort("state", 2 * kNumJoints).get_index();
generalized_force_output_port_ =
this->DeclareVectorOutputPort(
"generalized_force", kNumJoints,
&SchunkWsgPdController::CalcGeneralizedForceOutput)
.get_index();
grip_force_output_port_ =
this->DeclareVectorOutputPort("grip_force", 1,
&SchunkWsgPdController::CalcGripForceOutput)
.get_index();
this->set_name("wsg_controller");
}
Vector2d SchunkWsgPdController::CalcGeneralizedForce(
const drake::systems::Context<double>& context) const {
// Read the input ports.
const auto& desired_state = get_desired_state_input_port().Eval(context);
const double force_limit = get_force_limit_input_port().HasValue(context)
? get_force_limit_input_port().Eval(context)[0]
: default_force_limit_;
// TODO(russt): Declare a proper input constraint.
DRAKE_DEMAND(force_limit > 0);
const auto& state = get_state_input_port().Eval(context);
// f₀+f₁ = -kp_constraint*(q₀+q₁) - kd_constraint*(v₀+v₁).
const double f0_plus_f1 = -kp_constraint_ * (state[0] + state[1]) -
kd_constraint_ * (state[2] + state[3]);
// -f₀+f₁ = sat(kp_command*(q_d + q₀ - q₁) + kd_command*(v_d + v₀ - v₁)).
using std::clamp;
const double neg_f0_plus_f1 =
clamp(kp_command_ * (desired_state[0] + state[0] - state[1]) +
kd_command_ * (desired_state[1] + state[2] - state[3]),
-force_limit, force_limit);
// f₀ = (f₀+f₁)/2 - (-f₀+f₁)/2,
// f₁ = (f₀+f₁)/2 + (-f₀+f₁)/2.
return Vector2d(0.5 * f0_plus_f1 - 0.5 * neg_f0_plus_f1,
0.5 * f0_plus_f1 + 0.5 * neg_f0_plus_f1);
}
void SchunkWsgPdController::CalcGeneralizedForceOutput(
const drake::systems::Context<double>& context,
drake::systems::BasicVector<double>* output_vector) const {
output_vector->SetFromVector(CalcGeneralizedForce(context));
}
void SchunkWsgPdController::CalcGripForceOutput(
const drake::systems::Context<double>& context,
drake::systems::BasicVector<double>* output_vector) const {
Vector2d force = CalcGeneralizedForce(context);
output_vector->SetAtIndex(0, std::abs(force[0] - force[1]));
}
SchunkWsgPositionController::SchunkWsgPositionController(
double time_step, double kp_command, double kd_command,
double kp_constraint, double kd_constraint, double default_force_limit) {
systems::DiagramBuilder<double> builder;
auto pd_controller = builder.AddSystem<SchunkWsgPdController>(
kp_command, kd_command, kp_constraint, kd_constraint,
default_force_limit);
state_interpolator_ =
builder.AddSystem<systems::StateInterpolatorWithDiscreteDerivative>(
1, time_step, true /* suppress_initial_transient */);
builder.Connect(state_interpolator_->get_output_port(),
pd_controller->get_desired_state_input_port());
desired_position_input_port_ = builder.ExportInput(
state_interpolator_->get_input_port(), "desired_position");
force_limit_input_port_ = builder.ExportInput(
pd_controller->get_force_limit_input_port(), "force_limit");
state_input_port_ =
builder.ExportInput(pd_controller->get_state_input_port(), "state");
generalized_force_output_port_ = builder.ExportOutput(
pd_controller->get_generalized_force_output_port(), "generalized_force");
grip_force_output_port_ = builder.ExportOutput(
pd_controller->get_grip_force_output_port(), "grip_force");
builder.BuildInto(this);
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/build_schunk_wsg_control.cc | #include "drake/manipulation/schunk_wsg/build_schunk_wsg_control.h"
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/lcmt_schunk_wsg_status.hpp"
#include "drake/manipulation/schunk_wsg/schunk_wsg_constants.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_controller.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"
#include "drake/systems/lcm/lcm_publisher_system.h"
#include "drake/systems/lcm/lcm_subscriber_system.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
using lcm::DrakeLcmInterface;
using multibody::ModelInstanceIndex;
using multibody::MultibodyPlant;
using systems::lcm::LcmPublisherSystem;
using systems::lcm::LcmSubscriberSystem;
void BuildSchunkWsgControl(const MultibodyPlant<double>& plant,
const ModelInstanceIndex wsg_instance,
DrakeLcmInterface* lcm,
systems::DiagramBuilder<double>* builder,
const std::optional<Eigen::Vector3d>& pid_gains) {
// Create gripper command subscriber.
auto wsg_command_sub =
builder->AddSystem(LcmSubscriberSystem::Make<lcmt_schunk_wsg_command>(
"SCHUNK_WSG_COMMAND", lcm));
wsg_command_sub->set_name(plant.GetModelInstanceName(wsg_instance) +
"_wsg_command_subscriber");
Eigen::Vector3d desired_pid_gains =
pid_gains.value_or(Eigen::Vector3d(7200.0, 0.0, 5.0));
auto wsg_controller = builder->AddSystem<SchunkWsgController>(
desired_pid_gains(0), desired_pid_gains(1), desired_pid_gains(2));
builder->Connect(wsg_command_sub->get_output_port(),
wsg_controller->GetInputPort("command_message"));
builder->Connect(wsg_controller->GetOutputPort("force"),
plant.get_actuation_input_port(wsg_instance));
// Create gripper status publisher.
auto wsg_status_pub =
builder->AddSystem(LcmPublisherSystem::Make<lcmt_schunk_wsg_status>(
"SCHUNK_WSG_STATUS", lcm, kSchunkWsgLcmStatusPeriod));
wsg_status_pub->set_name(plant.GetModelInstanceName(wsg_instance) +
"_wsg_status_publisher");
auto wsg_status_sender = builder->AddSystem<SchunkWsgStatusSender>();
builder->Connect(*wsg_status_sender, *wsg_status_pub);
auto wsg_mbp_state_to_wsg_state =
builder->template AddSystem(MakeMultibodyStateToWsgStateSystem<double>());
builder->Connect(plant.get_state_output_port(wsg_instance),
wsg_mbp_state_to_wsg_state->get_input_port());
builder->Connect(wsg_mbp_state_to_wsg_state->get_output_port(),
wsg_status_sender->get_state_input_port());
// TODO(sam.creasey) This should be the measured joint torque according to
// the plant.
auto mbp_force_to_wsg_force =
builder->AddSystem(MakeMultibodyForceToWsgForceSystem<double>());
builder->Connect(
plant.get_generalized_contact_forces_output_port(wsg_instance),
mbp_force_to_wsg_force->get_input_port());
builder->Connect(mbp_force_to_wsg_force->get_output_port(),
wsg_status_sender->get_force_input_port());
builder->Connect(plant.get_state_output_port(wsg_instance),
wsg_controller->GetInputPort("state"));
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_position_controller.h | #pragma once
#include <vector>
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/primitives/discrete_derivative.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
/// This class implements a controller for a Schunk WSG gripper in position
/// control mode. It assumes that the gripper is modeled in the plant as two
/// independent prismatic joints for the fingers.
///
/// Note: This is intended as a simpler single-system implementation that can
/// replace the SchunkWsgController when using position control mode. We
/// anticipate a single-system SchunkWsgForceController implementation to
/// (soon) replace the other mode, and then will deprecate SchunkWsgController.
///
/// Call the positions of the prismatic joints q₀ and q₁. q₀ = q₁ = 0 is
/// the configuration where the fingers are touching in the center. When the
/// gripper is open, q₀ < 0 and q₁ > 0.
///
/// The physical gripper mechanically imposes that -q₀ = q₁, and implements a
/// controller to track -q₀ = q₁ = q_d/2 (q_d is the desired position, which
/// is the signed distance between the two fingers). We model that here with
/// two PD controllers -- one that implements the physical constraint
/// (keeping the fingers centered):
/// f₀+f₁ = -kp_constraint*(q₀+q₁) - kd_constraint*(v₀+v₁),
/// and another to implement the controller (opening/closing the fingers):
/// -f₀+f₁ = sat(kp_command*(q_d + q₀ - q₁) + kd_command*(v_d + v₀ - v₁)),
/// where sat() saturates the command to be in the range [-force_limit,
/// force_limit]. The expectation is that
/// kp_constraint ≫ kp_command.
///
/// @system
/// name: SchunkWSGPdController
/// input_ports:
/// - desired_state
/// - force_limit
/// - state
/// output_ports:
/// - generalized_force
/// - grip_force
/// @endsystem
///
/// The `force_limit` input port can be left unconnected; in this case, the
/// `default_force_limit` value given at construction time will be used.
///
/// The desired_state is a BasicVector<double> of size 2 (position and
/// velocity of the distance between the fingers). The force_limit is a
/// scalar (BasicVector<double> of size 1) and is optional; if the input port is
/// not connected then the constant value passed into the constructor is used.
/// The state is a BasicVector<double> of size 4 (positions and velocities of
/// the two fingers). The output generalized_force is a BasicVector<double> of
/// size 2 (generalized force inputs to the two fingers). The output grip_force
/// is a scalar surrogate for the force measurement from the driver, f =
/// abs(f₀-f₁) which, like the gripper itself, only reports a positive force.
///
/// @ingroup manipulation_systems
class SchunkWsgPdController : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SchunkWsgPdController)
/// Initialize the controller. The gain parameters are set based
/// limited tuning in simulation with a kuka picking up small objects.
// Note: These default parameter values came from the previous version of
// the controller, except that kp_command is decreased by 10x. Setting
// kd_constraint = 50.0 resulted in some numerical instability in existing
// kuka tests. They could be tuned in better with more simulation effort.
SchunkWsgPdController(double kp_command = 200.0, double kd_command = 5.0,
double kp_constraint = 2000.0,
double kd_constraint = 5.0,
double default_force_limit = 40.0);
const systems::InputPort<double>& get_desired_state_input_port() const {
return get_input_port(desired_state_input_port_);
}
const systems::InputPort<double>& get_force_limit_input_port() const {
return get_input_port(force_limit_input_port_);
}
const systems::InputPort<double>& get_state_input_port() const {
return get_input_port(state_input_port_);
}
const systems::OutputPort<double>& get_generalized_force_output_port() const {
return get_output_port(generalized_force_output_port_);
}
const systems::OutputPort<double>& get_grip_force_output_port() const {
return get_output_port(grip_force_output_port_);
}
private:
Eigen::Vector2d CalcGeneralizedForce(
const systems::Context<double>& context) const;
void CalcGeneralizedForceOutput(
const systems::Context<double>& context,
systems::BasicVector<double>* output_vector) const;
void CalcGripForceOutput(const systems::Context<double>& context,
systems::BasicVector<double>* output_vector) const;
const double kp_command_;
const double kd_command_;
const double kp_constraint_;
const double kd_constraint_;
const double default_force_limit_;
systems::InputPortIndex desired_state_input_port_{};
systems::InputPortIndex force_limit_input_port_{};
systems::InputPortIndex state_input_port_{};
systems::OutputPortIndex generalized_force_output_port_{};
systems::OutputPortIndex grip_force_output_port_{};
};
/// This class implements a controller for a Schunk WSG gripper in position
/// control mode adding a discrete-derivative to estimate the desired
/// velocity from the desired position commands. It is a thin wrapper
/// around SchunkWsgPdController.
///
/// @system
/// name: SchunkWSGPositionController
/// input_ports:
/// - desired_position
/// - force_limit
/// - state
/// output_ports:
/// - generalized_force
/// - grip_force
/// @endsystem
///
/// The `force_limit` input port can be left unconnected; in this case, the
/// `default_force_limit` value given at construction time will be used.
///
/// @see SchunkWsgPdController
/// @ingroup manipulation_systems
class SchunkWsgPositionController : public systems::Diagram<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SchunkWsgPositionController)
/// Initialize the controller. The default @p time_step is set to match
/// the update rate of the wsg firmware. The gain parameters are set based
/// limited tuning in simulation with a kuka picking up small objects.
/// @see SchunkWsgPdController::SchunkWsgPdController()
SchunkWsgPositionController(double time_step = 0.05,
double kp_command = 200.0,
double kd_command = 5.0,
double kp_constraint = 2000.0,
double kd_constraint = 5.0,
double default_force_limit = 40.0);
const systems::InputPort<double>& get_desired_position_input_port() const {
return get_input_port(desired_position_input_port_);
}
const systems::InputPort<double>& get_force_limit_input_port() const {
return get_input_port(force_limit_input_port_);
}
const systems::InputPort<double>& get_state_input_port() const {
return get_input_port(state_input_port_);
}
const systems::OutputPort<double>& get_generalized_force_output_port() const {
return get_output_port(generalized_force_output_port_);
}
const systems::OutputPort<double>& get_grip_force_output_port() const {
return get_output_port(grip_force_output_port_);
}
private:
systems::StateInterpolatorWithDiscreteDerivative<double>* state_interpolator_;
systems::InputPortIndex desired_position_input_port_{};
systems::InputPortIndex force_limit_input_port_{};
systems::InputPortIndex state_input_port_{};
systems::OutputPortIndex generalized_force_output_port_{};
systems::OutputPortIndex grip_force_output_port_{};
};
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_googletest",
"drake_cc_library",
"drake_cc_package_library",
)
package(
default_visibility = ["//visibility:public"],
)
drake_cc_package_library(
name = "schunk_wsg",
visibility = ["//visibility:public"],
deps = [
":build_schunk_wsg_control",
":schunk_wsg_constants",
":schunk_wsg_controller",
":schunk_wsg_driver",
":schunk_wsg_driver_functions",
":schunk_wsg_lcm",
":schunk_wsg_plain_controller",
":schunk_wsg_position_controller",
":schunk_wsg_trajectory_generator",
":schunk_wsg_trajectory_generator_state_vector",
],
)
drake_cc_library(
name = "schunk_wsg_constants",
hdrs = ["schunk_wsg_constants.h"],
deps = [
"//common:essential",
"//systems/primitives:matrix_gain",
],
)
drake_cc_library(
name = "schunk_wsg_lcm",
srcs = ["schunk_wsg_lcm.cc"],
hdrs = ["schunk_wsg_lcm.h"],
deps = [
"//lcm:lcm_messages",
"//lcmtypes:schunk",
"//systems/framework:leaf_system",
"//systems/primitives:matrix_gain",
],
)
drake_cc_library(
name = "schunk_wsg_trajectory_generator_state_vector",
srcs = [
"schunk_wsg_trajectory_generator_state_vector.cc",
],
hdrs = [
"gen/schunk_wsg_trajectory_generator_state_vector.h",
"schunk_wsg_trajectory_generator_state_vector.h",
],
visibility = [":__subpackages__"],
deps = [
"//common:dummy_value",
"//common:essential",
"//common:name_value",
"//common/symbolic:expression",
"//systems/framework:vector",
],
)
drake_cc_library(
name = "schunk_wsg_trajectory_generator",
srcs = ["schunk_wsg_trajectory_generator.cc"],
hdrs = ["schunk_wsg_trajectory_generator.h"],
deps = [
":schunk_wsg_trajectory_generator_state_vector",
"//common/trajectories:piecewise_polynomial",
"//common/trajectories:trajectory",
"//systems/framework:leaf_system",
],
)
drake_cc_library(
name = "schunk_wsg_plain_controller",
srcs = ["schunk_wsg_plain_controller.cc"],
hdrs = ["schunk_wsg_plain_controller.h"],
deps = [
":schunk_wsg_constants",
":schunk_wsg_lcm",
"//common:essential",
"//systems/controllers:pid_controller",
"//systems/framework:diagram",
"//systems/framework:diagram_builder",
"//systems/primitives",
],
)
drake_cc_library(
name = "schunk_wsg_position_controller",
srcs = ["schunk_wsg_position_controller.cc"],
hdrs = ["schunk_wsg_position_controller.h"],
deps = [
"//systems/framework:leaf_system",
"//systems/primitives:discrete_derivative",
],
)
drake_cc_library(
name = "schunk_wsg_controller",
srcs = ["schunk_wsg_controller.cc"],
hdrs = ["schunk_wsg_controller.h"],
deps = [
":schunk_wsg_constants",
":schunk_wsg_lcm",
":schunk_wsg_plain_controller",
":schunk_wsg_trajectory_generator",
"//common:essential",
"//systems/framework:diagram",
"//systems/framework:diagram_builder",
],
)
drake_cc_library(
name = "build_schunk_wsg_control",
srcs = ["build_schunk_wsg_control.cc"],
hdrs = ["build_schunk_wsg_control.h"],
deps = [
":schunk_wsg_constants",
":schunk_wsg_controller",
":schunk_wsg_lcm",
"//common:essential",
"//multibody/plant",
"//systems/framework:diagram_builder",
"//systems/lcm",
"@eigen",
],
)
drake_cc_library(
name = "schunk_wsg_driver",
hdrs = ["schunk_wsg_driver.h"],
deps = [
"//common:name_value",
],
)
drake_cc_library(
name = "schunk_wsg_driver_functions",
srcs = ["schunk_wsg_driver_functions.cc"],
hdrs = ["schunk_wsg_driver_functions.h"],
deps = [
":build_schunk_wsg_control",
":schunk_wsg_driver",
"//common:essential",
"//multibody/parsing:model_instance_info",
"//multibody/plant",
"//systems/framework:diagram_builder",
"//systems/lcm:lcm_buses",
],
)
# === test/ ===
drake_cc_googletest(
name = "schunk_wsg_constants_test",
data = [
"@drake_models//:wsg_50_description",
],
deps = [
":schunk_wsg_constants",
"//multibody/parsing",
"//multibody/plant",
],
)
drake_cc_googletest(
name = "schunk_wsg_controller_test",
deps = [
":schunk_wsg_constants",
":schunk_wsg_controller",
"//systems/analysis:simulator",
],
)
drake_cc_googletest(
name = "schunk_wsg_position_controller_test",
data = [
"@drake_models//:wsg_50_description",
],
deps = [
":schunk_wsg_position_controller",
"//common/test_utilities:eigen_matrix_compare",
"//multibody/parsing",
"//multibody/plant",
"//systems/analysis:simulator",
],
)
drake_cc_googletest(
name = "schunk_wsg_lcm_test",
data = [
"@drake_models//:wsg_50_description",
],
deps = [
":schunk_wsg_lcm",
"//common/test_utilities:eigen_matrix_compare",
"//systems/analysis:simulator",
],
)
drake_cc_googletest(
name = "schunk_wsg_trajectory_generator_test",
data = [
"@drake_models//:wsg_50_description",
],
deps = [
":schunk_wsg_trajectory_generator",
"//systems/analysis:simulator",
],
)
drake_cc_googletest(
name = "build_schunk_wsg_control_test",
data = [
"@drake_models//:wsg_50_description",
],
deps = [
":build_schunk_wsg_control",
":schunk_wsg_lcm",
"//lcm",
"//multibody/parsing:parser",
"//multibody/plant",
"//systems/analysis:simulator",
"//systems/framework:diagram_builder",
"//systems/lcm",
],
)
drake_cc_googletest(
name = "schunk_wsg_driver_functions_test",
data = [
"@drake_models//:wsg_50_description",
],
deps = [
":schunk_wsg_driver_functions",
"//lcm:drake_lcm_params",
"//multibody/parsing:parser",
"//multibody/plant",
"//systems/analysis:simulator",
"//systems/framework:diagram_builder",
"//systems/lcm:lcm_config_functions",
],
)
add_lint_tests()
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator.h | #pragma once
#include <memory>
#include <vector>
#include "drake/common/trajectories/trajectory.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
// TODO(sam.creasey) Right now this class just outputs a position
// which is not going to be sufficient to capture the entire control
// state of the gripper (particularly the maximum force).
/// This system defines input ports for the desired finger position
/// represented as the desired distance between the fingers in
/// meters and the desired force limit in newtons, and emits target
/// position/velocity for the actuated finger to reach the commanded target,
/// expressed as the negative of the distance between the two fingers in
/// meters. The force portion of the command message is passed through this
/// system, but does not affect the generated trajectory. The
/// desired_position and force_limit are scalars (BasicVector<double> of size
/// 1).
///
/// @system
/// name: SchunkWsgTrajectoryGenerator
/// input_ports:
/// - desired_position
/// - force_limit
/// - u0
/// output_ports:
/// - y0
/// - y1
/// @endsystem
///
/// Port `u0` accepts state. Port `y0` emits target position/velocity. Port
/// `y1` emits max force.
///
/// @ingroup manipulation_systems
class SchunkWsgTrajectoryGenerator : public systems::LeafSystem<double> {
public:
/// @param input_size The size of the state input port to create
/// (one reason this may vary is passing in the entire state of a
/// rigid body tree vs. having already demultiplexed the actuated
/// finger).
/// @param position_index The index in the state input vector
/// which contains the position of the actuated finger.
SchunkWsgTrajectoryGenerator(int input_size, int position_index);
const systems::InputPort<double>& get_desired_position_input_port() const {
return get_input_port(desired_position_input_port_);
}
const systems::InputPort<double>& get_force_limit_input_port() const {
return get_input_port(force_limit_input_port_);
}
const systems::InputPort<double>& get_state_input_port() const {
return get_input_port(state_input_port_);
}
const systems::OutputPort<double>& get_target_output_port() const {
return this->get_output_port(target_output_port_);
}
const systems::OutputPort<double>& get_max_force_output_port() const {
return this->get_output_port(max_force_output_port_);
}
private:
void OutputTarget(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
void OutputForce(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
/// Latches the input port into the discrete state.
systems::EventStatus CalcDiscreteUpdate(
const systems::Context<double>& context,
systems::DiscreteValues<double>* discrete_state) const;
void UpdateTrajectory(double cur_position, double target_position) const;
/// The minimum change between the last received command and the
/// current command to trigger a trajectory update. Based on
/// manually driving the actual gripper using the web interface, it
/// appears that it will at least attempt to respond to commands as
/// small as 0.1mm.
const double kTargetEpsilon = 0.0001;
const int position_index_{};
const systems::InputPortIndex desired_position_input_port_{};
const systems::InputPortIndex force_limit_input_port_{};
const systems::InputPortIndex state_input_port_{};
const systems::OutputPortIndex target_output_port_{};
const systems::OutputPortIndex max_force_output_port_{};
// TODO(sam.creasey) I'd prefer to store the trajectory as
// discrete state, but unfortunately that's not currently possible
// as DiscreteValues may only contain BasicVector.
mutable std::unique_ptr<trajectories::Trajectory<double>> trajectory_;
};
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator_state_vector.h | #pragma once
// This file was previously auto-generated, but now is just a normal source
// file in git. However, it still retains some historical oddities from its
// heritage. In general, we do recommend against subclassing BasicVector in
// new code.
#include <cmath>
#include <limits>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <Eigen/Core>
#include "drake/common/drake_bool.h"
#include "drake/common/dummy_value.h"
#include "drake/common/name_value.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/symbolic/expression.h"
#include "drake/systems/framework/basic_vector.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
/// Describes the row indices of a SchunkWsgTrajectoryGeneratorStateVector.
struct SchunkWsgTrajectoryGeneratorStateVectorIndices {
/// The total number of rows (coordinates).
static const int kNumCoordinates = 4;
// The index of each individual coordinate.
static const int kLastTargetPosition = 0;
static const int kTrajectoryStartTime = 1;
static const int kLastPosition = 2;
static const int kMaxForce = 3;
/// Returns a vector containing the names of each coordinate within this
/// class. The indices within the returned vector matches that of this class.
/// In other words,
/// `SchunkWsgTrajectoryGeneratorStateVectorIndices::GetCoordinateNames()[i]`
/// is the name for `BasicVector::GetAtIndex(i)`.
static const std::vector<std::string>& GetCoordinateNames();
};
/// Specializes BasicVector with specific getters and setters.
template <typename T>
class SchunkWsgTrajectoryGeneratorStateVector final
: public drake::systems::BasicVector<T> {
public:
/// An abbreviation for our row index constants.
typedef SchunkWsgTrajectoryGeneratorStateVectorIndices K;
/// Default constructor. Sets all rows to their default value:
/// @arg @c last_target_position defaults to 0.0 with unknown units.
/// @arg @c trajectory_start_time defaults to 0.0 with unknown units.
/// @arg @c last_position defaults to 0.0 with unknown units.
/// @arg @c max_force defaults to 0.0 with unknown units.
SchunkWsgTrajectoryGeneratorStateVector()
: drake::systems::BasicVector<T>(K::kNumCoordinates) {
this->set_last_target_position(0.0);
this->set_trajectory_start_time(0.0);
this->set_last_position(0.0);
this->set_max_force(0.0);
}
// Note: It's safe to implement copy and move because this class is final.
/// @name Implements CopyConstructible, CopyAssignable, MoveConstructible,
/// MoveAssignable
//@{
SchunkWsgTrajectoryGeneratorStateVector(
const SchunkWsgTrajectoryGeneratorStateVector& other)
: drake::systems::BasicVector<T>(other.values()) {}
SchunkWsgTrajectoryGeneratorStateVector(
SchunkWsgTrajectoryGeneratorStateVector&& other) noexcept
: drake::systems::BasicVector<T>(std::move(other.values())) {}
SchunkWsgTrajectoryGeneratorStateVector& operator=(
const SchunkWsgTrajectoryGeneratorStateVector& other) {
this->values() = other.values();
return *this;
}
SchunkWsgTrajectoryGeneratorStateVector& operator=(
SchunkWsgTrajectoryGeneratorStateVector&& other) noexcept {
this->values() = std::move(other.values());
other.values().resize(0);
return *this;
}
//@}
/// Create a symbolic::Variable for each element with the known variable
/// name. This is only available for T == symbolic::Expression.
template <typename U = T>
typename std::enable_if_t<std::is_same_v<U, symbolic::Expression>>
SetToNamedVariables() {
this->set_last_target_position(symbolic::Variable("last_target_position"));
this->set_trajectory_start_time(
symbolic::Variable("trajectory_start_time"));
this->set_last_position(symbolic::Variable("last_position"));
this->set_max_force(symbolic::Variable("max_force"));
}
[[nodiscard]] SchunkWsgTrajectoryGeneratorStateVector<T>* DoClone()
const final {
return new SchunkWsgTrajectoryGeneratorStateVector;
}
/// @name Getters and Setters
//@{
/// last_target_position
const T& last_target_position() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kLastTargetPosition);
}
/// Setter that matches last_target_position().
void set_last_target_position(const T& last_target_position) {
ThrowIfEmpty();
this->SetAtIndex(K::kLastTargetPosition, last_target_position);
}
/// Fluent setter that matches last_target_position().
/// Returns a copy of `this` with last_target_position set to a new value.
[[nodiscard]] SchunkWsgTrajectoryGeneratorStateVector<T>
with_last_target_position(const T& last_target_position) const {
SchunkWsgTrajectoryGeneratorStateVector<T> result(*this);
result.set_last_target_position(last_target_position);
return result;
}
/// trajectory_start_time
const T& trajectory_start_time() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kTrajectoryStartTime);
}
/// Setter that matches trajectory_start_time().
void set_trajectory_start_time(const T& trajectory_start_time) {
ThrowIfEmpty();
this->SetAtIndex(K::kTrajectoryStartTime, trajectory_start_time);
}
/// Fluent setter that matches trajectory_start_time().
/// Returns a copy of `this` with trajectory_start_time set to a new value.
[[nodiscard]] SchunkWsgTrajectoryGeneratorStateVector<T>
with_trajectory_start_time(const T& trajectory_start_time) const {
SchunkWsgTrajectoryGeneratorStateVector<T> result(*this);
result.set_trajectory_start_time(trajectory_start_time);
return result;
}
/// last_position
const T& last_position() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kLastPosition);
}
/// Setter that matches last_position().
void set_last_position(const T& last_position) {
ThrowIfEmpty();
this->SetAtIndex(K::kLastPosition, last_position);
}
/// Fluent setter that matches last_position().
/// Returns a copy of `this` with last_position set to a new value.
[[nodiscard]] SchunkWsgTrajectoryGeneratorStateVector<T> with_last_position(
const T& last_position) const {
SchunkWsgTrajectoryGeneratorStateVector<T> result(*this);
result.set_last_position(last_position);
return result;
}
/// max_force
const T& max_force() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kMaxForce);
}
/// Setter that matches max_force().
void set_max_force(const T& max_force) {
ThrowIfEmpty();
this->SetAtIndex(K::kMaxForce, max_force);
}
/// Fluent setter that matches max_force().
/// Returns a copy of `this` with max_force set to a new value.
[[nodiscard]] SchunkWsgTrajectoryGeneratorStateVector<T> with_max_force(
const T& max_force) const {
SchunkWsgTrajectoryGeneratorStateVector<T> result(*this);
result.set_max_force(max_force);
return result;
}
//@}
/// Visit each field of this named vector, passing them (in order) to the
/// given Archive. The archive can read and/or write to the vector values.
/// One common use of Serialize is the //common/yaml tools.
template <typename Archive>
void Serialize(Archive* a) {
T& last_target_position_ref = this->GetAtIndex(K::kLastTargetPosition);
a->Visit(drake::MakeNameValue("last_target_position",
&last_target_position_ref));
T& trajectory_start_time_ref = this->GetAtIndex(K::kTrajectoryStartTime);
a->Visit(drake::MakeNameValue("trajectory_start_time",
&trajectory_start_time_ref));
T& last_position_ref = this->GetAtIndex(K::kLastPosition);
a->Visit(drake::MakeNameValue("last_position", &last_position_ref));
T& max_force_ref = this->GetAtIndex(K::kMaxForce);
a->Visit(drake::MakeNameValue("max_force", &max_force_ref));
}
/// See SchunkWsgTrajectoryGeneratorStateVectorIndices::GetCoordinateNames().
static const std::vector<std::string>& GetCoordinateNames() {
return SchunkWsgTrajectoryGeneratorStateVectorIndices::GetCoordinateNames();
}
/// Returns whether the current values of this vector are well-formed.
drake::boolean<T> IsValid() const {
using std::isnan;
drake::boolean<T> result{true};
result = result && !isnan(last_target_position());
result = result && !isnan(trajectory_start_time());
result = result && !isnan(last_position());
result = result && !isnan(max_force());
return result;
}
private:
void ThrowIfEmpty() const {
if (this->values().size() == 0) {
throw std::out_of_range(
"The SchunkWsgTrajectoryGeneratorStateVector vector has been "
"moved-from; "
"accessor methods may no longer be used");
}
}
};
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_lcm.h | #pragma once
/// @file
/// This file contains classes dealing with sending/receiving LCM messages
/// related to the Schunk WSG gripper.
#include <memory>
#include <vector>
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/lcmt_schunk_wsg_status.hpp"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
/// Handles the command for the Schunk WSG gripper from a LcmSubscriberSystem.
///
/// It has one input port: "command_message" for lcmt_schunk_wsg_command
/// abstract values.
///
/// It has two output ports: one for the commanded finger position represented
/// as the desired distance between the fingers in meters, and one for the
/// commanded force limit. The commanded position and force limit are scalars
/// (BasicVector<double> of size 1).
///
/// @system
/// name: SchunkWsgCommandReceiver
/// input_ports:
/// - command_message
/// output_ports:
/// - position
/// - force_limit
/// @endsystem
///
/// @ingroup manipulation_systems
class SchunkWsgCommandReceiver : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SchunkWsgCommandReceiver)
/// @param initial_position the commanded position to output if no LCM
/// message has been received yet.
///
/// @param initial_force the commanded force limit to output if no LCM
/// message has been received yet.
SchunkWsgCommandReceiver(double initial_position = 0.02,
double initial_force = 40);
const systems::OutputPort<double>& get_position_output_port() const {
return this->GetOutputPort("position");
}
const systems::OutputPort<double>& get_force_limit_output_port() const {
return this->GetOutputPort("force_limit");
}
private:
void CalcPositionOutput(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
void CalcForceLimitOutput(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
const double initial_position_{};
const double initial_force_{};
};
/// Send lcmt_schunk_wsg_command messages for a Schunk WSG gripper. Has
/// two input ports: one for the commanded finger position represented as the
/// desired signed distance between the fingers in meters, and one for the
/// commanded force limit. The commanded position and force limit are
/// scalars (BasicVector<double> of size 1).
///
/// @system
/// name: SchunkWsgCommandSender
/// input_ports:
/// - position
/// - force_limit
/// output_ports:
/// - lcmt_schunk_wsg_command
/// @endsystem
///
/// The `force_limit` input port can be left unconnected; in this case, the
/// `default_force_limit` value given at construction time will be used.
///
/// @ingroup manipulation_systems
class SchunkWsgCommandSender : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SchunkWsgCommandSender)
explicit SchunkWsgCommandSender(double default_force_limit = 40.0);
const systems::InputPort<double>& get_position_input_port() const {
return this->get_input_port(position_input_port_);
}
const systems::InputPort<double>& get_force_limit_input_port() const {
return this->get_input_port(force_limit_input_port_);
}
const systems::OutputPort<double>& get_command_output_port() const {
return this->get_output_port(0);
}
private:
void CalcCommandOutput(const systems::Context<double>& context,
lcmt_schunk_wsg_command* output) const;
private:
const systems::InputPortIndex position_input_port_{};
const systems::InputPortIndex force_limit_input_port_{};
const double default_force_limit_;
};
/// Handles lcmt_schunk_wsg_status messages from a LcmSubscriberSystem. Has
/// two output ports: one for the measured state of the gripper, represented as
/// the signed distance between the fingers in meters and its corresponding
/// velocity, and one for the measured force.
///
/// @system
/// name: SchunkWsgStatusReceiver
/// input_ports:
/// - lcmt_schunk_wsg_status
/// output_ports:
/// - state
/// - force
/// @endsystem
///
/// @ingroup manipulation_systems
class SchunkWsgStatusReceiver : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SchunkWsgStatusReceiver)
SchunkWsgStatusReceiver();
const systems::InputPort<double>& get_status_input_port() const {
return this->get_input_port(0);
}
const systems::OutputPort<double>& get_state_output_port() const {
return this->get_output_port(state_output_port_);
}
const systems::OutputPort<double>& get_force_output_port() const {
return this->get_output_port(force_output_port_);
}
private:
void CopyStateOut(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
void CopyForceOut(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
private:
const systems::OutputPortIndex state_output_port_{};
const systems::OutputPortIndex force_output_port_{};
};
/// Sends lcmt_schunk_wsg_status messages for a Schunk WSG. This
/// system has one input port for the current state of the WSG, and one
/// optional input port for the measured gripping force.
///
/// @system
/// name: SchunkStatusSender
/// input_ports:
/// - state
/// - force
/// output_ports:
/// - lcmt_schunk_wsg_status
/// @endsystem
///
/// The state input is a BasicVector<double> of size 2 -- with one position
/// and one velocity -- representing the distance between the fingers (positive
/// implies non-penetration).
///
/// @ingroup manipulation_systems
class SchunkWsgStatusSender : public systems::LeafSystem<double> {
public:
SchunkWsgStatusSender();
const systems::InputPort<double>& get_state_input_port() const {
DRAKE_DEMAND(state_input_port_.is_valid());
return this->get_input_port(state_input_port_);
}
const systems::InputPort<double>& get_force_input_port() const {
return this->get_input_port(force_input_port_);
}
private:
void OutputStatus(const systems::Context<double>& context,
lcmt_schunk_wsg_status* output) const;
systems::InputPortIndex state_input_port_{};
systems::InputPortIndex force_input_port_{};
};
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_lcm.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"
#include <vector>
#include <Eigen/Dense>
#include "drake/common/drake_assert.h"
#include "drake/common/eigen_types.h"
#include "drake/lcm/lcm_messages.h"
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/lcmt_schunk_wsg_status.hpp"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
using systems::BasicVector;
using systems::Context;
SchunkWsgCommandReceiver::SchunkWsgCommandReceiver(double initial_position,
double initial_force)
: initial_position_(initial_position), initial_force_(initial_force) {
this->DeclareVectorOutputPort("position", 1,
&SchunkWsgCommandReceiver::CalcPositionOutput);
this->DeclareVectorOutputPort(
"force_limit", 1, &SchunkWsgCommandReceiver::CalcForceLimitOutput);
lcmt_schunk_wsg_command uninitialized_message{};
this->DeclareAbstractInputPort(
"command_message", Value<lcmt_schunk_wsg_command>(uninitialized_message));
}
void SchunkWsgCommandReceiver::CalcPositionOutput(
const Context<double>& context, BasicVector<double>* output) const {
const auto& message =
this->get_input_port(0).Eval<lcmt_schunk_wsg_command>(context);
double target_position = initial_position_;
// N.B. This works due to lcm::Serializer<>::CreateDefaultValue() using
// value-initialization.
if (!lcm::AreLcmMessagesEqual(message, lcmt_schunk_wsg_command{})) {
target_position = message.target_position_mm / 1e3;
if (std::isnan(target_position)) {
target_position = 0;
}
}
output->SetAtIndex(0, target_position);
}
void SchunkWsgCommandReceiver::CalcForceLimitOutput(
const Context<double>& context, BasicVector<double>* output) const {
const auto& message =
this->get_input_port(0).Eval<lcmt_schunk_wsg_command>(context);
double force_limit = initial_force_;
// N.B. This works due to lcm::Serializer<>::CreateDefaultValue() using
// value-initialization.
if (!lcm::AreLcmMessagesEqual(message, lcmt_schunk_wsg_command{})) {
force_limit = message.force;
}
output->SetAtIndex(0, force_limit);
}
SchunkWsgCommandSender::SchunkWsgCommandSender(double default_force_limit)
: position_input_port_(
this->DeclareVectorInputPort("position", 1).get_index()),
force_limit_input_port_(
this->DeclareVectorInputPort("force_limit", 1).get_index()),
default_force_limit_(default_force_limit) {
this->DeclareAbstractOutputPort("lcmt_schunk_wsg_command",
&SchunkWsgCommandSender::CalcCommandOutput);
}
void SchunkWsgCommandSender::CalcCommandOutput(
const drake::systems::Context<double>& context,
drake::lcmt_schunk_wsg_command* output) const {
lcmt_schunk_wsg_command& command = *output;
command.utime = context.get_time() * 1e6;
command.target_position_mm = get_position_input_port().Eval(context)[0] * 1e3;
if (get_force_limit_input_port().HasValue(context)) {
command.force = get_force_limit_input_port().Eval(context)[0];
} else {
command.force = default_force_limit_;
}
}
SchunkWsgStatusReceiver::SchunkWsgStatusReceiver()
: state_output_port_(
this->DeclareVectorOutputPort("state", 2,
&SchunkWsgStatusReceiver::CopyStateOut)
.get_index()),
force_output_port_(
this->DeclareVectorOutputPort("force", 1,
&SchunkWsgStatusReceiver::CopyForceOut)
.get_index()) {
this->DeclareAbstractInputPort("lcmt_schunk_wsg_status",
Value<lcmt_schunk_wsg_status>());
}
void SchunkWsgStatusReceiver::CopyStateOut(
const drake::systems::Context<double>& context,
drake::systems::BasicVector<double>* output) const {
const auto& status =
get_status_input_port().Eval<lcmt_schunk_wsg_status>(context);
output->SetAtIndex(0, status.actual_position_mm / 1e3);
output->SetAtIndex(1, status.actual_speed_mm_per_s / 1e3);
}
void SchunkWsgStatusReceiver::CopyForceOut(
const drake::systems::Context<double>& context,
drake::systems::BasicVector<double>* output) const {
const auto& status =
get_status_input_port().Eval<lcmt_schunk_wsg_status>(context);
output->SetAtIndex(0, status.actual_force);
}
SchunkWsgStatusSender::SchunkWsgStatusSender() {
state_input_port_ = this->DeclareInputPort(systems::kUseDefaultName,
systems::kVectorValued, 2)
.get_index();
force_input_port_ = this->DeclareInputPort(systems::kUseDefaultName,
systems::kVectorValued, 1)
.get_index();
this->DeclareAbstractOutputPort(systems::kUseDefaultName,
&SchunkWsgStatusSender::OutputStatus);
}
void SchunkWsgStatusSender::OutputStatus(const Context<double>& context,
lcmt_schunk_wsg_status* output) const {
lcmt_schunk_wsg_status& status = *output;
status.utime = context.get_time() * 1e6;
const auto& state = get_state_input_port().Eval(context);
// The position and speed reported in this message are between the
// two fingers rather than the position/speed of a single finger
// (so effectively doubled).
status.actual_position_mm = state[0] * 1e3;
status.actual_speed_mm_per_s = state[1] * 1e3;
if (get_force_input_port().HasValue(context)) {
// In drake-schunk-driver, the driver attempts to apply a sign to the
// force value based on the last reported direction of gripper movement
// (the gripper always reports positive values). This does not work very
// well, and as a result the sign is almost always negative (when
// non-zero) regardless of which direction the gripper was moving in when
// motion was blocked. As it's not a reliable source of information in
// the driver (and should be removed there at some point), we don't try to
// replicate it here and instead report positive forces.
using std::abs;
status.actual_force = abs(get_force_input_port().Eval(context)[0]);
} else {
status.actual_force = 0;
}
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_constants.h | /**
* @file
*
* Constants defined in this file are for the Schunk WSG gripper modeled in
* models/schunk_wsg_50.sdf.
*/
#pragma once
#include <memory>
#include "drake/common/eigen_types.h"
#include "drake/systems/framework/vector_system.h"
#include "drake/systems/primitives/matrix_gain.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
constexpr int kSchunkWsgNumActuators = 2;
constexpr int kSchunkWsgNumPositions = 2;
constexpr int kSchunkWsgNumVelocities = 2;
// TODO(russt): These constants are predicated on the idea that we can map
// one finger's state => gripper state. We should prefer using
// MakeMultibodyStateToWsgState and MakeMultibodyForceToWsgForce instead.
// But I cannot deprecate them yet without performing surgery on the old
// controller.
constexpr int kSchunkWsgPositionIndex = 0;
constexpr int kSchunkWsgVelocityIndex =
kSchunkWsgNumPositions + kSchunkWsgPositionIndex;
// TODO(sammy): need to double check this.
constexpr double kSchunkWsgLcmStatusPeriod = 0.05;
/**
* Returns the position vector corresponding to the open position of the
* gripper.
*/
template <typename T>
VectorX<T> GetSchunkWsgOpenPosition() {
// clang-format off
return (VectorX<T>(kSchunkWsgNumPositions) <<
-0.0550667,
0.0550667).finished();
// clang-format on
}
/// Extract the distance between the fingers (and its time derivative) out
/// of the plant model which pretends the two fingers are independent.
/// @ingroup manipulation_systems
template <typename T>
std::unique_ptr<systems::MatrixGain<T>> MakeMultibodyStateToWsgStateSystem() {
Eigen::Matrix<double, 2, 4> D;
// clang-format off
D << -1, 1, 0, 0,
0, 0, -1, 1;
// clang-format on
return std::make_unique<systems::MatrixGain<T>>(D);
}
/// Extract the gripper measured force from the generalized forces on the two
/// fingers.
///
/// @system
/// name: MultibodyForceToWsgForceSystem
/// input_ports:
/// - u0
/// output_ports:
/// - y0
/// @endsystem
///
/// @ingroup manipulation_systems
template <typename T>
class MultibodyForceToWsgForceSystem : public systems::VectorSystem<T> {
public:
MultibodyForceToWsgForceSystem()
: systems::VectorSystem<T>(
systems::SystemTypeTag<MultibodyForceToWsgForceSystem>{}, 2, 1) {}
// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit MultibodyForceToWsgForceSystem(
const MultibodyForceToWsgForceSystem<U>&)
: MultibodyForceToWsgForceSystem<T>() {}
void DoCalcVectorOutput(const systems::Context<T>&,
const Eigen::VectorBlock<const VectorX<T>>& input,
const Eigen::VectorBlock<const VectorX<T>>& state,
Eigen::VectorBlock<VectorX<T>>* output) const {
unused(state);
// gripper force = abs(-finger0 + finger1).
using std::abs;
(*output)(0) = abs(input(0) - input(1));
}
};
/// Helper method to create a MultibodyForceToWsgForceSystem.
/// @ingroup manipulation_systems
template <typename T>
std::unique_ptr<systems::VectorSystem<T>> MakeMultibodyForceToWsgForceSystem() {
return std::make_unique<MultibodyForceToWsgForceSystem<T>>();
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator_state_vector.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
using systems::BasicVector;
using systems::Context;
using systems::DiscreteValues;
using systems::EventStatus;
SchunkWsgTrajectoryGenerator::SchunkWsgTrajectoryGenerator(int input_size,
int position_index)
: position_index_(position_index),
desired_position_input_port_(
this->DeclareVectorInputPort("desired_position", 1).get_index()),
force_limit_input_port_(
this->DeclareVectorInputPort("force_limit", 1).get_index()),
state_input_port_(
this->DeclareVectorInputPort(systems::kUseDefaultName, input_size)
.get_index()),
target_output_port_(this->DeclareVectorOutputPort(
systems::kUseDefaultName, 2,
&SchunkWsgTrajectoryGenerator::OutputTarget)
.get_index()),
max_force_output_port_(this->DeclareVectorOutputPort(
systems::kUseDefaultName, 1,
&SchunkWsgTrajectoryGenerator::OutputForce)
.get_index()) {
this->DeclareDiscreteState(SchunkWsgTrajectoryGeneratorStateVector<double>());
// The update period below matches the polling rate from
// drake-schunk-driver.
this->DeclarePeriodicDiscreteUpdateEvent(
0.05, 0.0, &SchunkWsgTrajectoryGenerator::CalcDiscreteUpdate);
this->DeclareForcedDiscreteUpdateEvent(
&SchunkWsgTrajectoryGenerator::CalcDiscreteUpdate);
}
void SchunkWsgTrajectoryGenerator::OutputTarget(
const Context<double>& context, BasicVector<double>* output) const {
const SchunkWsgTrajectoryGeneratorStateVector<double>* traj_state =
dynamic_cast<const SchunkWsgTrajectoryGeneratorStateVector<double>*>(
&context.get_discrete_state(0));
if (trajectory_) {
output->get_mutable_value() = trajectory_->value(
context.get_time() - traj_state->trajectory_start_time());
} else {
output->get_mutable_value() =
Eigen::Vector2d(traj_state->last_position(), 0);
}
}
void SchunkWsgTrajectoryGenerator::OutputForce(
const Context<double>& context, BasicVector<double>* output) const {
const SchunkWsgTrajectoryGeneratorStateVector<double>* traj_state =
dynamic_cast<const SchunkWsgTrajectoryGeneratorStateVector<double>*>(
&context.get_discrete_state(0));
output->get_mutable_value() = Vector1d(traj_state->max_force());
}
EventStatus SchunkWsgTrajectoryGenerator::CalcDiscreteUpdate(
const Context<double>& context,
DiscreteValues<double>* discrete_state) const {
const double desired_position =
get_desired_position_input_port().Eval(context)[0];
// The desired position input is the distance between the fingers in meters.
// This class generates trajectories for the negative of the distance
// between the fingers in meters.
double target_position = -desired_position;
const auto& state = get_state_input_port().Eval(context);
const double cur_position = 2 * state[position_index_];
const SchunkWsgTrajectoryGeneratorStateVector<double>* last_traj_state =
dynamic_cast<const SchunkWsgTrajectoryGeneratorStateVector<double>*>(
&context.get_discrete_state(0));
SchunkWsgTrajectoryGeneratorStateVector<double>* new_traj_state =
dynamic_cast<SchunkWsgTrajectoryGeneratorStateVector<double>*>(
&discrete_state->get_mutable_vector(0));
new_traj_state->set_last_position(cur_position);
const double max_force = get_force_limit_input_port().Eval(context)[0];
new_traj_state->set_max_force(max_force);
if (std::abs(last_traj_state->last_target_position() - target_position) >
kTargetEpsilon) {
UpdateTrajectory(cur_position, target_position);
new_traj_state->set_last_target_position(target_position);
new_traj_state->set_trajectory_start_time(context.get_time());
} else {
new_traj_state->set_last_target_position(
last_traj_state->last_target_position());
new_traj_state->set_trajectory_start_time(
last_traj_state->trajectory_start_time());
}
return EventStatus::Succeeded();
}
void SchunkWsgTrajectoryGenerator::UpdateTrajectory(
double cur_position, double target_position) const {
// The acceleration and velocity limits correspond to the maximum
// values available for manual control through the gripper's web
// interface.
const double kMaxVelocity = 0.42; // m/s
const double kMaxAccel = 5.; // m/s^2
const double kTimeToMaxVelocity = kMaxVelocity / kMaxAccel;
// TODO(sam.creasey) this should probably consider current speed
// if the gripper is already moving.
const double kDistanceToMaxVelocity =
0.5 * kMaxAccel * kTimeToMaxVelocity * kTimeToMaxVelocity;
std::vector<Eigen::MatrixXd> knots;
std::vector<double> times;
knots.push_back(Eigen::Vector2d(cur_position, 0));
times.push_back(0);
const double direction = (cur_position < target_position) ? 1 : -1;
const double delta = std::abs(target_position - cur_position);
if (delta == 0) {
// Create the constant trajectory.
trajectory_.reset(new trajectories::PiecewisePolynomial<double>(knots[0]));
return;
}
// The trajectory creation code below is, to say the best, a bit
// primitive. I (sam.creasey) would not be surprised if it could
// be significantly improved. It's also based only on the
// configurable constants for the WSG 50, not on analysis of the
// actual motion of the gripper.
if (delta < kDistanceToMaxVelocity * 2) {
// If we can't accelerate to our maximum (and decelerate again)
// within the target travel distance, calculate the peak velocity
// we will reach and create a trajectory which ramps to that
// velocity and back down.
const double mid_distance = delta / 2;
const double mid_velocity =
kMaxVelocity * (mid_distance / kDistanceToMaxVelocity);
const double mid_time = mid_velocity / kMaxAccel;
knots.push_back(Eigen::Vector2d(cur_position + mid_distance * direction,
mid_velocity * direction));
times.push_back(mid_time);
knots.push_back(Eigen::Vector2d(target_position, 0));
times.push_back(mid_time * 2);
} else {
knots.push_back(
Eigen::Vector2d(cur_position + (kDistanceToMaxVelocity * direction),
kMaxVelocity * direction));
times.push_back(kTimeToMaxVelocity);
const double time_at_max =
(delta - 2 * kDistanceToMaxVelocity) / kMaxVelocity;
knots.push_back(
Eigen::Vector2d(target_position - (kDistanceToMaxVelocity * direction),
kMaxVelocity * direction));
times.push_back(kTimeToMaxVelocity + time_at_max);
knots.push_back(Eigen::Vector2d(target_position, 0));
times.push_back(kTimeToMaxVelocity + time_at_max + kTimeToMaxVelocity);
}
trajectory_.reset(new trajectories::PiecewisePolynomial<double>(
trajectories::PiecewisePolynomial<double>::FirstOrderHold(times, knots)));
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_plain_controller.h | #pragma once
#include "drake/common/drake_copyable.h"
#include "drake/systems/controllers/state_feedback_controller_interface.h"
#include "drake/systems/framework/diagram.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
enum class ControlMode { kPosition = 0, kForce = 1 };
// N.B. Inheritance order must remain fixed for pydrake (#9243).
/** This class implements a controller for a Schunk WSG gripper as a
* `systems::Diagram`. The composition of this diagram is determined by the
* control mode specified for the controller, which can be either
* ControlMode::kPosition or ControlMode::kForce. In both cases, the overall
* layout of the diagram is:
* ```
* ┌─────────────┐
* joint │Joint State │ ┌──────────┐
* state ─────▶│To Control ├──▶│ │
* │State │ │ │
* └─────────────┘ │PID │ ╔════════════╗
* ╔═════════════╗ │Controller├──▶║ ╟─────┐
* desired ║Generate ║ │ │ ║ ║ │
* grip ──────▶║Desired ╟──▶│ │ ║Handle ║ │
* state ║Control State║ └──────────┘ ║Feed-Forward║ │
* ╚═════════════╝ ║Force ║ │
* feed ║ ║ │
* forward ────────────────────────────────────▶║ ╟──┐ │
* force ╚════════════╝ │ │
* │ │
* ┌──────────────────────────────────┘ │
* │ ┌──────────────────────┘
* │ │
* │ │ ┌───────────┐
* │ │ │Mean Finger│ ┌───┐
* │ └──▶│Force To ├──▶│ │
* │ │Joint Force│ │ │
* │ └───────────┘ │ │
* │ │ + ├──▶ control
* │ ┌──────────┐ ┌───────────┐ │ │
* ┌─────────│──▶│ │ │Grip Force │ │ │
* │ ┌──┐ └──▶│Saturation├──▶│To Joint ├──▶│ │
* max force / 2 ──┴──▶│-1├─────▶│ │ │Force │ └───┘
* └──┘ └──────────┘ └───────────┘
* ```
* The blocks with double outlines (══) differ between the two control modes:
*
* - Generate Desired Control State
* - ControlMode::kPosition
* ```
* ┌───────────┐
* │Desired │
* │Mean Finger├──▶█
* │State │ █ ┌─────────────┐
* └───────────┘ █ │Muxed States │ desired
* █──▶│To Control ├──▶ control
* █ │State │ state
* desired █ └─────────────┘
* grip ───────▶█
* state
*
* ```
* - ControlMode::kForce
* ```
* ┌───────────┐
* │Desired │ desired
* │Mean Finger├────────────────────────▶ control
* │State │ state
* └───────────┘
*
* desired ┌────────┐
* grip ───────▶│IGNORED │
* state └────────┘
* ```
* - Handle Feed-Forward Force
* - ControlMode::kPosition
* ```
* █────▶ mean finger force
* pid █
* controller ────────────────▶█
* output █
* █────▶ grip force
* feed ┌────────┐
* forward ──────▶│IGNORED │
* force └────────┘
* ```
* - ControlMode::kForce
* ```
* pid
* controller ──────────────────────▶ mean finger force
* output
*
* feed
* forward ─────────────────────────▶ grip force
* force
*
* ```
* The remaining blocks differ only in their numerical parameters.
*
* Note that the "feed forward force" input is ignored for
* ControlMode::kPosition and the "desired grip state" input is ignored for
* ControlMode::kPosition.
*
* @system
* name: SchunkWsgPlainController
* input_ports:
* - joint_state
* - max_force
* - <span style="color:gray">desired_grip_state</span>
* - <span style="color:gray">feed_forward_force</span>
* output_ports:
* - control
* @endsystem
*
* The `desired_grip_state` port is present only when the control mode is
* `kPosition`; the `feed_forward_force` port is present only when the control
* mode is `kForce`.
*
* @ingroup manipulation_systems
*/
class SchunkWsgPlainController
: public systems::Diagram<double>,
public systems::controllers::StateFeedbackControllerInterface<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SchunkWsgPlainController)
/** Specify control gains and mode. Mode defaults to position control. */
explicit SchunkWsgPlainController(
ControlMode control_mode = ControlMode::kPosition, double kp = 2000,
double ki = 0, double kd = 5);
/** Returns the feed-forward force input port.
* @pre `this` was constructed with `control_mode` set to
* `ControlMode::kForce`.*/
const systems::InputPort<double>& get_input_port_feed_forward_force() const {
DRAKE_ASSERT(feed_forward_force_input_port_ >= 0);
return this->get_input_port(feed_forward_force_input_port_);
}
const systems::InputPort<double>& get_input_port_max_force() const {
return this->get_input_port(max_force_input_port_);
}
// These methods implement StateFeedbackControllerInterface.
const systems::InputPort<double>& get_input_port_estimated_state()
const override {
return this->get_input_port(state_input_port_);
}
/** Returns the desired grip state input port.
* @pre `this` was constructed with `control_mode` set to
* `ControlMode::kPosition`.*/
const systems::InputPort<double>& get_input_port_desired_state()
const override {
DRAKE_ASSERT(state_input_port_ >= 0);
return this->get_input_port(desired_grip_state_input_port_);
}
const systems::OutputPort<double>& get_output_port_control() const override {
return systems::Diagram<double>::get_output_port(0);
}
private:
systems::InputPortIndex desired_grip_state_input_port_;
systems::InputPortIndex feed_forward_force_input_port_;
systems::InputPortIndex state_input_port_;
systems::InputPortIndex max_force_input_port_;
};
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_plain_controller.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_plain_controller.h"
#include <vector>
#include "drake/systems/controllers/pid_controller.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/primitives/adder.h"
#include "drake/systems/primitives/constant_vector_source.h"
#include "drake/systems/primitives/demultiplexer.h"
#include "drake/systems/primitives/matrix_gain.h"
#include "drake/systems/primitives/multiplexer.h"
#include "drake/systems/primitives/pass_through.h"
#include "drake/systems/primitives/saturation.h"
using Eigen::Matrix;
namespace drake {
namespace manipulation {
namespace schunk_wsg {
SchunkWsgPlainController::SchunkWsgPlainController(ControlMode control_mode,
double kp, double ki,
double kd) {
systems::DiagramBuilder<double> builder;
// Define position and state sizes.
// Size of joint position vector, q. The gripper has two prismatic joints.
// When the gripper is closed, q == 0. When the gripper is open, q[0] < 0 and
// q[1] > 0.
constexpr int nq{2};
// Size of state (joint positions and velocities) vector, x.
constexpr int nx{2 * nq};
// Size of mean finger position representation.
// The mean finger position, m, is a scalar given by
//
// m = 0.5 (q[0] + q[1]).
//
// m == 0 implies that the fingers are centered.
constexpr int nm{1};
// Size of grip position representation.
// The grip position, g, is a scalar given by
//
// g = q[0] - q[1].
//
// g is 0 when the gripper is closed and decreases as the gripper opens. This
// definition is chosen so that a positive grip force corresponds to closing
// the gripper.
constexpr int ng{1};
// Define Jacobians for the mean finger position and the grip position
// Mean finger position Jacobian (nm × nq).
const auto Jm = (Matrix<double, nm, nq>() << 0.5, 0.5).finished();
// Grip position Jacobian (ng × nq).
const auto Jg = (Matrix<double, ng, nq>() << 1, -1).finished();
// Add blocks to convert the estimated joint state to the estimated
// controller state and the controller output to joint force.
// Size of the control position, c. The control position is the quantity
// regulated by the PID controller. The size of the control position vector
// depends on which control mode is used.
int nc{};
// Control position Jacobian (nc × nq).
MatrixX<double> Jc;
switch (control_mode) {
case ControlMode::kPosition: {
nc = nm + ng;
Jc = (MatrixX<double>(nc, nq) << Jm, Jg).finished();
break;
}
case ControlMode::kForce: {
nc = nm;
Jc = (MatrixX<double>(nc, nq) << Jm).finished();
}
}
const auto zero_nc_by_nq = MatrixX<double>::Zero(nc, nq);
// clang-format off
const auto control_state_jacobian =
(MatrixX<double>(2 * nc, nx) <<
Jc, zero_nc_by_nq,
zero_nc_by_nq, Jc)
.finished();
// clang-format on
const auto joint_state_to_control_state =
builder.AddSystem<systems::MatrixGain<double>>(control_state_jacobian);
// Add the PID controller
const auto pid_controller =
builder.AddSystem<systems::controllers::PidController<double>>(
VectorX<double>::Constant(nc, kp), VectorX<double>::Constant(nc, ki),
VectorX<double>::Constant(nc, kd));
// Add the saturation block.
// Create gain blocks to convert the scalar, positive max-force input into
// positive and negative max-joint-force vectors.
const auto positive_gain = builder.AddSystem<systems::MatrixGain<double>>(
0.5 * MatrixX<double>::Ones(ng, 1));
const auto negative_gain = builder.AddSystem<systems::MatrixGain<double>>(
-0.5 * MatrixX<double>::Ones(ng, 1));
const auto saturation = builder.AddSystem<systems::Saturation<double>>(ng);
// Add blocks to generate the desired control state.
const systems::InputPort<double>* desired_grip_state_input_port{};
const systems::OutputPort<double>* desired_control_state_output_port{};
// Add a source for the desired mean finger state. The mean finger
// position and velocity should be zero.
auto desired_mean_finger_state =
builder.AddSystem<systems::ConstantVectorSource<double>>(
Vector2<double>::Zero());
switch (control_mode) {
case ControlMode::kPosition: {
// Add a multiplexer to concatenate the desired grip state and the desired
// mean finger state.
auto concatenate_desired_states =
builder.AddSystem<systems::Multiplexer<double>>(
std::vector<int>({2, 2}));
// The output of concatenate_desired_states has the form
//
// [q_tilde_0, v_tilde_0, q_tilde_1, v_tilde_1].
//
// whereas the PID controller takes
//
// [q_tilde_0, q_tilde_0, v_tilde_0, v_tilde_1]
//
// We now construct a matrix gain block to swap the order of th
// elements.
Matrix4<double> D;
// clang-format off
D << 1, 0, 0, 0,
0, 0, 1, 0,
0, 1, 0, 0,
0, 0, 0, 1;
// clang-format on
auto convert_to_x_tilde_desired =
builder.AddSystem<systems::MatrixGain<double>>(D);
// Get the input port.
desired_grip_state_input_port =
&concatenate_desired_states->get_input_port(1);
// Get the output port.
desired_control_state_output_port =
&convert_to_x_tilde_desired->get_output_port();
// Connect the subsystems.
builder.Connect(desired_mean_finger_state->get_output_port(),
concatenate_desired_states->get_input_port(0));
builder.Connect(concatenate_desired_states->get_output_port(0),
convert_to_x_tilde_desired->get_input_port());
} break;
case ControlMode::kForce: {
// Get the output port.
desired_control_state_output_port =
&desired_mean_finger_state->get_output_port();
} break;
}
// Add blocks to handle the feed-forward force
const systems::InputPort<double>* feed_forward_force_input_port{};
const systems::OutputPort<double>* mean_finger_force_output_port{};
const systems::OutputPort<double>* grip_force_output_port{};
switch (control_mode) {
case ControlMode::kPosition: {
// Add a de-multiplexer to split the PID outputs
auto demux = builder.AddSystem<systems::Demultiplexer<double>>(nc);
// Get the output ports.
mean_finger_force_output_port = &demux->get_output_port(0);
grip_force_output_port = &demux->get_output_port(1);
// Connect the subsystems.
builder.Connect(pid_controller->get_output_port_control(),
demux->get_input_port(0));
break;
}
case ControlMode::kForce: {
// Add a pass-through for the feed-forward force.
auto pass_through = builder.AddSystem<systems::PassThrough<double>>(ng);
// Get the input port.
feed_forward_force_input_port = &pass_through->get_input_port();
// Get the output ports.
mean_finger_force_output_port =
&pid_controller->get_output_port_control();
grip_force_output_port = &pass_through->get_output_port();
break;
}
}
// Add block to convert the grip force to joint force.
auto grip_force_to_joint_force =
builder.AddSystem<systems::MatrixGain<double>>(Jg.transpose());
// Add block to convert the mean_finger force to joint force.
auto mean_finger_force_to_joint_force =
builder.AddSystem<systems::MatrixGain<double>>(Jm.transpose());
// Add a block to sum the joint forces from the mean finger force and grip
// force.
auto adder = builder.AddSystem<systems::Adder<double>>(2 /*num_inputs*/, nq);
// Export the inputs.
state_input_port_ = builder.ExportInput(
joint_state_to_control_state->get_input_port(), "joint_state");
// Max force input -> Saturation
max_force_input_port_ =
builder.ExportInput(positive_gain->get_input_port(), "max_force");
builder.ConnectInput(max_force_input_port_, negative_gain->get_input_port());
if (desired_grip_state_input_port) {
desired_grip_state_input_port_ = builder.ExportInput(
*desired_grip_state_input_port, "desired_grip_state");
}
if (feed_forward_force_input_port) {
feed_forward_force_input_port_ = builder.ExportInput(
*feed_forward_force_input_port, "feed_forward_force");
}
// Export the output.
builder.ExportOutput(adder->get_output_port(), "control");
// Connect the subsystems.
// Upstream subsystems -> PID
builder.Connect(joint_state_to_control_state->get_output_port(),
pid_controller->get_input_port_estimated_state());
builder.Connect(*desired_control_state_output_port,
pid_controller->get_input_port_desired_state());
// Mean finger force -> Mean Finger Force to Joint Force
builder.Connect(*mean_finger_force_output_port,
mean_finger_force_to_joint_force->get_input_port());
// Grip force -> Saturation
builder.Connect(*grip_force_output_port, saturation->get_input_port());
builder.Connect(positive_gain->get_output_port(),
saturation->get_max_value_port());
builder.Connect(negative_gain->get_output_port(),
saturation->get_min_value_port());
// Saturation -> Grip Force To Joint Force
builder.Connect(saturation->get_output_port(),
grip_force_to_joint_force->get_input_port());
// Joint forces -> Adder
builder.Connect(mean_finger_force_to_joint_force->get_output_port(),
adder->get_input_port(0));
builder.Connect(grip_force_to_joint_force->get_output_port(),
adder->get_input_port(1));
builder.BuildInto(this);
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/build_schunk_wsg_control.h | #pragma once
#include <optional>
#include <Eigen/Dense>
#include "drake/lcm/drake_lcm_interface.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
/// Builds (into @p builder) the WSG control and sensing systems for the wsg
/// model in @p plant indicated by @p wsg_instance; hooks those systems up to
/// @p lcm and the relevant MultibodyPlant ports in the diagram. @p pid_gains
/// can be used to override the default sim PID gains.
void BuildSchunkWsgControl(
const multibody::MultibodyPlant<double>& plant,
multibody::ModelInstanceIndex wsg_instance, lcm::DrakeLcmInterface* lcm,
systems::DiagramBuilder<double>* builder,
const std::optional<Eigen::Vector3d>& pid_gains = {});
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator_state_vector.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator_state_vector.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
const int SchunkWsgTrajectoryGeneratorStateVectorIndices::kNumCoordinates;
const int SchunkWsgTrajectoryGeneratorStateVectorIndices::kLastTargetPosition;
const int SchunkWsgTrajectoryGeneratorStateVectorIndices::kTrajectoryStartTime;
const int SchunkWsgTrajectoryGeneratorStateVectorIndices::kLastPosition;
const int SchunkWsgTrajectoryGeneratorStateVectorIndices::kMaxForce;
const std::vector<std::string>&
SchunkWsgTrajectoryGeneratorStateVectorIndices::GetCoordinateNames() {
static const drake::never_destroyed<std::vector<std::string>> coordinates(
std::vector<std::string>{
"last_target_position",
"trajectory_start_time",
"last_position",
"max_force",
});
return coordinates.access();
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_driver_functions.h | #pragma once
#include <map>
#include <string>
#include "drake/manipulation/schunk_wsg/schunk_wsg_driver.h"
#include "drake/multibody/parsing/model_instance_info.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/lcm/lcm_buses.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
/** Wires up Drake systems between an LCM interface and the actuation input
ports of a MultibodyPlant. This simulates the role that driver software and
robot firmware would take in real life. */
void ApplyDriverConfig(
const SchunkWsgDriver& driver_config,
const std::string& model_instance_name,
const multibody::MultibodyPlant<double>& sim_plant,
const std::map<std::string, multibody::parsing::ModelInstanceInfo>&
models_from_directives,
const systems::lcm::LcmBuses& lcms,
systems::DiagramBuilder<double>* builder);
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_driver.h | #pragma once
#include <string>
#include <Eigen/Dense>
#include "drake/common/drake_copyable.h"
#include "drake/common/name_value.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
/** This config struct specifies how to wire up Drake systems between an LCM
interface and the actuation input ports of a MultibodyPlant. This simulates the
role that driver software and control cabinets would take in real life.
It creates an LCM publisher on the `SCHUNK_WSG_STATUS` channel and an LCM
subscriber on the `SCHUNK_WSG_COMMAND` channel. */
struct SchunkWsgDriver {
/** Gains to apply to the the WSG fingers. The p term corresponds
approximately to the elastic modulus of the belt, the d term to the viscous
friction of the geartrain. The i term is nonphysical. */
Eigen::Vector3d pid_gains{7200., 0., 5.};
std::string lcm_bus{"default"};
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(pid_gains));
a->Visit(DRAKE_NVP(lcm_bus));
}
};
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_controller.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_controller.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_constants.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_plain_controller.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator.h"
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
SchunkWsgController::SchunkWsgController(double kp, double ki, double kd) {
systems::DiagramBuilder<double> builder;
auto wsg_trajectory_generator =
builder.AddSystem<SchunkWsgTrajectoryGenerator>(
kSchunkWsgNumPositions + kSchunkWsgNumVelocities,
kSchunkWsgPositionIndex);
const auto state_port_index = builder.ExportInput(
wsg_trajectory_generator->get_state_input_port(), "state");
auto command_receiver = builder.AddSystem<SchunkWsgCommandReceiver>();
builder.ExportInput(command_receiver->GetInputPort("command_message"),
"command_message");
builder.Connect(command_receiver->get_position_output_port(),
wsg_trajectory_generator->get_desired_position_input_port());
builder.Connect(command_receiver->get_force_limit_output_port(),
wsg_trajectory_generator->get_force_limit_input_port());
auto wsg_controller = builder.AddSystem<SchunkWsgPlainController>(
ControlMode::kPosition, kp, ki, kd);
builder.ConnectInput(state_port_index,
wsg_controller->get_input_port_estimated_state());
builder.Connect(wsg_trajectory_generator->get_target_output_port(),
wsg_controller->get_input_port_desired_state());
builder.Connect(wsg_trajectory_generator->get_max_force_output_port(),
wsg_controller->get_input_port_max_force());
builder.ExportOutput(wsg_controller->get_output_port_control(), "force");
builder.BuildInto(this);
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_controller.h | #pragma once
#include "drake/common/drake_copyable.h"
#include "drake/systems/framework/diagram.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
/// This class implements a controller for a Schunk WSG gripper. It
/// has two input ports: lcmt_schunk_wsg_command message and the current
/// state, and an output port which emits the target force for the actuated
/// finger. Note, only one of the command input ports should be connected,
/// However, if both are connected, the message input will be ignored.
/// The internal implementation consists of a PID controller (which controls
/// the target position from the command message) combined with a saturation
/// block (which applies the force control from the command message).
///
/// @system
/// name: SchunkWsgController
/// input_ports:
/// - state
/// - command_message
/// output_ports:
/// - force
/// @endsystem
///
/// @ingroup manipulation_systems
class SchunkWsgController : public systems::Diagram<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SchunkWsgController)
// The gains here are somewhat arbitrary. The goal is to make sure
// that the maximum force is generated except when very close to the
// target.
explicit SchunkWsgController(double kp = 2000.0, double ki = 0.0,
double kd = 5.0);
};
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/schunk_wsg/schunk_wsg_driver_functions.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_driver_functions.h"
#include "drake/manipulation/schunk_wsg/build_schunk_wsg_control.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
using lcm::DrakeLcmInterface;
using multibody::MultibodyPlant;
using multibody::parsing::ModelInstanceInfo;
using systems::DiagramBuilder;
using systems::lcm::LcmBuses;
void ApplyDriverConfig(const SchunkWsgDriver& driver_config,
const std::string& model_instance_name,
const MultibodyPlant<double>& sim_plant,
const std::map<std::string, ModelInstanceInfo>&,
const LcmBuses& lcms, DiagramBuilder<double>* builder) {
DRAKE_THROW_UNLESS(builder != nullptr);
DrakeLcmInterface* lcm =
lcms.Find("Driver for " + model_instance_name, driver_config.lcm_bus);
BuildSchunkWsgControl(sim_plant,
sim_plant.GetModelInstanceByName(model_instance_name),
lcm, builder, driver_config.pid_gains);
}
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/schunk_wsg | /home/johnshepherd/drake/manipulation/schunk_wsg/gen/schunk_wsg_trajectory_generator_state_vector.h | #pragma once
#include "drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator_state_vector.h"
// clang-format off
// NOLINTNEXTLINE
#warning "DRAKE_DEPRECATED: This include path is deprecated and will be removed on or after 2024-09-01. Remove the /gen/ part of your code's include statement."
// clang-format on
| 0 |
/home/johnshepherd/drake/manipulation/schunk_wsg | /home/johnshepherd/drake/manipulation/schunk_wsg/test/schunk_wsg_position_controller_test.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_position_controller.h"
#include <memory>
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
namespace {
using Eigen::Vector4d;
using multibody::MultibodyPlant;
using multibody::Parser;
using systems::BasicVector;
GTEST_TEST(SchunkWsgPdControllerTest, BasicTest) {
// Just check the inputs and outputs; the math is being checked by the
// simulation test below.
SchunkWsgPdController controller;
EXPECT_EQ(&controller.get_desired_state_input_port(),
&controller.GetInputPort("desired_state"));
EXPECT_EQ(&controller.get_force_limit_input_port(),
&controller.GetInputPort("force_limit"));
EXPECT_EQ(&controller.get_state_input_port(),
&controller.GetInputPort("state"));
EXPECT_EQ(&controller.get_generalized_force_output_port(),
&controller.GetOutputPort("generalized_force"));
EXPECT_EQ(&controller.get_grip_force_output_port(),
&controller.GetOutputPort("grip_force"));
}
GTEST_TEST(SchunkWsgPdControllerTest, DefaultForceLimitTest) {
SchunkWsgPdController controller;
auto context = controller.CreateDefaultContext();
controller.get_desired_state_input_port().FixValue(context.get(),
Eigen::Vector2d(0.1, 0));
controller.get_state_input_port().FixValue(
context.get(), Eigen::Vector4d(-0.05, 0.05, 0, 0));
// Do NOT connect the force limit input port.
// Make sure that both output ports still evaluate without error.
controller.get_generalized_force_output_port().Eval(*context);
controller.get_grip_force_output_port().Eval(*context);
}
void FixInputsAndHistory(const SchunkWsgPositionController& controller,
double desired_position, double force_limit,
systems::Context<double>* controller_context) {
controller.get_desired_position_input_port().FixValue(controller_context,
desired_position);
controller.get_force_limit_input_port().FixValue(controller_context,
force_limit);
}
/// Runs the controller for a brief period with the specified initial conditions
/// and returns the commanded forces on the gripper's fingers (left finger
/// first).
GTEST_TEST(SchunkWsgPositionControllerTest, SimTest) {
systems::DiagramBuilder<double> builder;
const double kTimeStep = 0.002;
const auto wsg = builder.AddSystem<MultibodyPlant>(kTimeStep);
// Add the Schunk gripper and weld it to the world.
const std::string wsg_sdf_url =
"package://drake_models/"
"wsg_50_description/sdf/schunk_wsg_50.sdf";
const auto wsg_model = Parser(wsg).AddModelsFromUrl(wsg_sdf_url).at(0);
wsg->WeldFrames(wsg->world_frame(), wsg->GetFrameByName("body", wsg_model),
math::RigidTransformd::Identity());
wsg->Finalize();
const auto controller = builder.AddSystem<SchunkWsgPositionController>();
builder.Connect(wsg->get_state_output_port(wsg_model),
controller->get_state_input_port());
builder.Connect(controller->get_generalized_force_output_port(),
wsg->get_actuation_input_port(wsg_model));
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
auto& context = simulator.get_mutable_context();
auto& wsg_context = diagram->GetMutableSubsystemContext(*wsg, &context);
auto& controller_context =
diagram->GetMutableSubsystemContext(*controller, &context);
// Start off with the gripper closed (zero) and a command to open to
// 100mm.
double desired_position = 0.1;
double force_limit = 40;
FixInputsAndHistory(*controller, desired_position, force_limit,
&controller_context);
EXPECT_LE(
controller->get_grip_force_output_port().Eval(controller_context)[0],
force_limit);
EXPECT_GE(
controller->get_grip_force_output_port().Eval(controller_context)[0],
-force_limit);
wsg->SetPositionsAndVelocities(&wsg_context, Vector4d::Zero());
simulator.AdvanceTo(1.0);
const double kTolerance = 1e-12;
// Check that we achieved the desired position.
EXPECT_TRUE(CompareMatrices(
wsg->GetPositionsAndVelocities(wsg_context),
Vector4d(-desired_position / 2, desired_position / 2, 0.0, 0.0),
kTolerance));
// The steady-state force should be near zero.
EXPECT_NEAR(
controller->get_grip_force_output_port().Eval(controller_context)[0], 0.0,
kTolerance);
// Move in toward the middle of the range with lower force from the outside.
desired_position = 0.05;
force_limit = 20;
FixInputsAndHistory(*controller, desired_position, force_limit,
&controller_context);
simulator.AdvanceTo(2.0);
EXPECT_TRUE(CompareMatrices(
wsg->GetPositionsAndVelocities(wsg_context),
Vector4d(-desired_position / 2, desired_position / 2, 0.0, 0.0),
kTolerance));
// The steady-state force should be near zero.
EXPECT_NEAR(
controller->get_grip_force_output_port().Eval(controller_context)[0], 0.0,
kTolerance);
// Move to more than closed, and see that the force is at the limit.
desired_position = -1.0;
force_limit = 20;
FixInputsAndHistory(*controller, desired_position, force_limit,
&controller_context);
simulator.AdvanceTo(3.0);
EXPECT_NEAR(
controller->get_grip_force_output_port().Eval(controller_context)[0],
force_limit, kTolerance);
// Set the position to the target and observe zero force.
wsg->SetPositionsAndVelocities(
&wsg_context,
Vector4d(-desired_position / 2, desired_position / 2, 0.0, 0.0));
EXPECT_EQ(
controller->get_grip_force_output_port().Eval(controller_context)[0],
0.0);
}
} // namespace
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/schunk_wsg | /home/johnshepherd/drake/manipulation/schunk_wsg/test/schunk_wsg_trajectory_generator_test.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator.h"
#include <memory>
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_trajectory_generator_state_vector.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/fixed_input_port_value.h"
#include "drake/systems/framework/system_output.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
namespace {
GTEST_TEST(SchunkWsgTrajectoryGeneratorTest, BasicTest) {
SchunkWsgTrajectoryGenerator dut(1, 0);
std::unique_ptr<systems::Context<double>> context =
dut.CreateDefaultContext();
std::unique_ptr<systems::SystemOutput<double>> output = dut.AllocateOutput();
// Start off with the gripper closed (zero) and a command to open to
// 100mm.
dut.get_desired_position_input_port().FixValue(context.get(), 0.05);
dut.get_force_limit_input_port().FixValue(context.get(), 40.);
dut.get_state_input_port().FixValue(context.get(), 0.0);
// Step a little bit. We should be commanding a point on the
// trajectory wider than zero, but not to the target yet.
const double expected_target = -0.05; // 50mm
systems::Simulator<double> simulator(dut, std::move(context));
simulator.AdvanceTo(0.1);
dut.CalcOutput(simulator.get_context(), output.get());
EXPECT_LT(output->get_vector_data(0)->GetAtIndex(0), 0);
EXPECT_GT(output->get_vector_data(0)->GetAtIndex(0), expected_target);
// Step quite a bit longer and see that we get there.
simulator.AdvanceTo(2.0);
dut.CalcOutput(simulator.get_context(), output.get());
EXPECT_FLOAT_EQ(output->get_vector_data(0)->GetAtIndex(0), expected_target);
}
// Test the specific case when the last command does not match the current
// command but the difference between the measured position and the desired
// position is zero.
GTEST_TEST(SchunkWsgTrajectoryGeneratorTest, DeltaEqualsZero) {
SchunkWsgTrajectoryGenerator dut(1, 0);
auto context = dut.CreateDefaultContext();
SchunkWsgTrajectoryGeneratorStateVector<double> state;
state.set_last_target_position(0.0);
context->SetDiscreteState(state.value());
const double pos = 0.06;
dut.get_desired_position_input_port().FixValue(context.get(), pos);
dut.get_force_limit_input_port().FixValue(context.get(), 40.0);
dut.get_state_input_port().FixValue(context.get(), -pos / 2.0);
systems::Simulator<double> simulator(dut, std::move(context));
simulator.AdvanceTo(0.1);
Eigen::Vector2d target =
dut.get_target_output_port().Eval(simulator.get_context());
EXPECT_EQ(target[0], -pos);
}
} // namespace
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/schunk_wsg | /home/johnshepherd/drake/manipulation/schunk_wsg/test/schunk_wsg_lcm_test.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"
#include <memory>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/lcmt_schunk_wsg_status.hpp"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/fixed_input_port_value.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
namespace {
using Eigen::Vector2d;
using systems::BasicVector;
GTEST_TEST(SchunkWsgLcmTest, SchunkWsgCommandReceiverTest) {
const double initial_position = 0.03;
const double initial_force = 27;
SchunkWsgCommandReceiver dut(initial_position, initial_force);
std::unique_ptr<systems::Context<double>> context =
dut.CreateDefaultContext();
// Check that we get the initial position and force before receiving a
// command.
lcmt_schunk_wsg_command initial_command{};
const systems::InputPort<double>& message_input_port =
dut.GetInputPort("command_message");
message_input_port.FixValue(context.get(), initial_command);
EXPECT_EQ(dut.get_position_output_port().Eval(*context)[0], initial_position);
EXPECT_EQ(dut.get_force_limit_output_port().Eval(*context)[0], initial_force);
// Start off with the gripper closed (zero) and a command to open to
// 100mm.
initial_command.utime = 0;
initial_command.target_position_mm = 100;
initial_command.force = 40;
message_input_port.FixValue(context.get(), initial_command);
EXPECT_EQ(dut.get_position_output_port().Eval(*context)[0], 0.1);
EXPECT_EQ(dut.get_force_limit_output_port().Eval(*context)[0], 40);
}
GTEST_TEST(SchunkWsgLcmTest, SchunkWsgCommandSenderTest) {
const double default_force_limit = 37.0;
SchunkWsgCommandSender dut(default_force_limit);
std::unique_ptr<systems::Context<double>> context =
dut.CreateDefaultContext();
const double position = 0.0015;
dut.get_position_input_port().FixValue(context.get(), position);
const lcmt_schunk_wsg_command& command =
dut.get_output_port(0).Eval<lcmt_schunk_wsg_command>(*context);
EXPECT_EQ(command.target_position_mm, 1.5);
EXPECT_EQ(command.force, default_force_limit);
const double force_limit = 25.0;
dut.get_force_limit_input_port().FixValue(context.get(), force_limit);
const lcmt_schunk_wsg_command& command_w_force =
dut.get_output_port(0).Eval<lcmt_schunk_wsg_command>(*context);
EXPECT_EQ(command_w_force.target_position_mm, 1.5);
EXPECT_EQ(command_w_force.force, force_limit);
}
GTEST_TEST(SchunkWsgLcmTest, SchunkWsgStatusReceiverTest) {
SchunkWsgStatusReceiver dut;
std::unique_ptr<systems::Context<double>> context =
dut.CreateDefaultContext();
// Check that we get zeros before receiving any messages (using the POD
// initialization via {}, as used in LcmSubscriberSystem).
lcmt_schunk_wsg_status status{};
dut.get_input_port(0).FixValue(context.get(), status);
EXPECT_TRUE(CompareMatrices(dut.get_state_output_port().Eval(*context),
Vector2d::Zero()));
EXPECT_EQ(dut.get_force_output_port().Eval(*context)[0], 0.0);
// Check that we can read out valid input.
status.utime = 0;
status.actual_position_mm = 100;
status.actual_speed_mm_per_s = 324;
status.actual_force = 40;
dut.get_input_port(0).FixValue(context.get(), status);
EXPECT_TRUE(CompareMatrices(dut.get_state_output_port().Eval(*context),
Vector2d(.1, .324)));
EXPECT_EQ(dut.get_force_output_port().Eval(*context)[0], 40.0);
}
GTEST_TEST(SchunkWsgLcmTest, SchunkWsgStatusSenderTest) {
SchunkWsgStatusSender dut;
std::unique_ptr<systems::Context<double>> context =
dut.CreateDefaultContext();
const double position = 0.001;
const double velocity = 0.04;
dut.get_state_input_port().FixValue(context.get(),
Vector2d(position, velocity));
// Check that the force input port is indeed optional.
{
const lcmt_schunk_wsg_status& status =
dut.get_output_port(0).Eval<lcmt_schunk_wsg_status>(*context);
EXPECT_EQ(status.actual_force, 0.0);
EXPECT_EQ(status.actual_position_mm, 1.0);
EXPECT_EQ(status.actual_speed_mm_per_s, 40.0);
}
// Check that we can also set the force.
const double force = 32.0;
dut.get_force_input_port().FixValue(context.get(), force);
EXPECT_EQ(dut.get_output_port(0)
.Eval<lcmt_schunk_wsg_status>(*context)
.actual_force,
force);
}
} // namespace
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/schunk_wsg | /home/johnshepherd/drake/manipulation/schunk_wsg/test/schunk_wsg_controller_test.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_controller.h"
#include <memory>
#include <gtest/gtest.h>
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/manipulation/schunk_wsg/schunk_wsg_constants.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/fixed_input_port_value.h"
#include "drake/systems/framework/system_output.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
namespace {
/// Runs the controller for a brief period with the specified initial conditions
/// and returns the commanded forces on the gripper's fingers (left finger
/// first).
std::pair<double, double> RunWsgControllerTestStep(
const lcmt_schunk_wsg_command& wsg_command, double wsg_position) {
SchunkWsgController dut;
std::unique_ptr<systems::Context<double>> context =
dut.CreateDefaultContext();
std::unique_ptr<systems::SystemOutput<double>> output = dut.AllocateOutput();
dut.GetInputPort("command_message").FixValue(context.get(), wsg_command);
Eigen::VectorXd wsg_state_vec =
Eigen::VectorXd::Zero(kSchunkWsgNumPositions + kSchunkWsgNumVelocities);
wsg_state_vec(0) = -(wsg_position / 1e3) / 2.;
wsg_state_vec(1) = (wsg_position / 1e3) / 2.;
dut.GetInputPort("state").FixValue(context.get(), wsg_state_vec);
systems::Simulator<double> simulator(dut, std::move(context));
simulator.AdvanceTo(1.0);
dut.CalcOutput(simulator.get_context(), output.get());
return {output->get_vector_data(0)->GetAtIndex(0),
output->get_vector_data(0)->GetAtIndex(1)};
}
GTEST_TEST(SchunkWsgControllerTest, SchunkWsgControllerTest) {
// Start off with the gripper closed (zero) and a command to open to
// 100mm.
lcmt_schunk_wsg_command wsg_command{};
wsg_command.utime = 1;
wsg_command.target_position_mm = 100;
wsg_command.force = 40;
std::pair<double, double> commanded_force =
RunWsgControllerTestStep(wsg_command, 0);
EXPECT_FLOAT_EQ(commanded_force.first, -wsg_command.force * 0.5);
EXPECT_FLOAT_EQ(commanded_force.second, wsg_command.force * 0.5);
// Move in toward the middle of the range with lower force from the outside.
wsg_command.target_position_mm = 50;
wsg_command.force = 20;
commanded_force = RunWsgControllerTestStep(wsg_command, 100);
EXPECT_FLOAT_EQ(commanded_force.first, wsg_command.force * 0.5);
EXPECT_FLOAT_EQ(commanded_force.second, -wsg_command.force * 0.5);
// Set the position to something near the target and observe zero force.
commanded_force = RunWsgControllerTestStep(
wsg_command, wsg_command.target_position_mm * 0.999);
EXPECT_NEAR(commanded_force.first, 0, 1);
EXPECT_NEAR(commanded_force.second, 0, 1);
}
} // namespace
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/schunk_wsg | /home/johnshepherd/drake/manipulation/schunk_wsg/test/schunk_wsg_driver_functions_test.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_driver_functions.h"
#include <gtest/gtest.h>
#include "drake/lcm/drake_lcm_params.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_driver.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/multibody/plant/multibody_plant_config_functions.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/lcm/lcm_config_functions.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
namespace {
using lcm::DrakeLcmParams;
using multibody::ModelInstanceIndex;
using multibody::MultibodyPlant;
using multibody::MultibodyPlantConfig;
using multibody::Parser;
using systems::DiagramBuilder;
using systems::Simulator;
using systems::lcm::LcmBuses;
/* A smoke test to apply simulated wsg driver with default driver config. */
GTEST_TEST(SchunkWsgDriverFunctionsTest, ApplyDriverConfig) {
DiagramBuilder<double> builder;
MultibodyPlant<double>& plant =
AddMultibodyPlant(MultibodyPlantConfig{}, &builder);
const std::string url =
"package://drake_models/wsg_50_description/sdf/schunk_wsg_50.sdf";
const ModelInstanceIndex schunk_wsg =
Parser(&plant).AddModelsFromUrl(url).at(0);
plant.WeldFrames(plant.world_frame(),
plant.GetFrameByName("body", schunk_wsg));
plant.Finalize();
const std::map<std::string, DrakeLcmParams> lcm_bus_config = {
{"default", {}}};
const LcmBuses lcm_buses =
systems::lcm::ApplyLcmBusConfig(lcm_bus_config, &builder);
const SchunkWsgDriver schunk_wsg_driver;
const std::string schunk_wsg_name = plant.GetModelInstanceName(schunk_wsg);
ApplyDriverConfig(schunk_wsg_driver, schunk_wsg_name, plant, {}, lcm_buses,
&builder);
// Prove that simulation does not crash.
Simulator<double> simulator(builder.Build());
simulator.AdvanceTo(0.1);
}
} // namespace
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/schunk_wsg | /home/johnshepherd/drake/manipulation/schunk_wsg/test/build_schunk_wsg_control_test.cc | #include "drake/manipulation/schunk_wsg/build_schunk_wsg_control.h"
#include <memory>
#include <utility>
#include <gtest/gtest.h>
#include "drake/lcm/drake_lcm.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
namespace {
using math::RigidTransformd;
using multibody::ModelInstanceIndex;
using multibody::MultibodyPlant;
using multibody::Parser;
constexpr double kTolerance = 1e-3;
class BuildSchunkWsgControlTest : public ::testing::Test {
public:
BuildSchunkWsgControlTest() = default;
protected:
void SetUp() {
sim_plant_ = builder_.AddSystem<MultibodyPlant<double>>(0.001);
Parser parser{sim_plant_};
const std::string wsg_url =
"package://drake_models/wsg_50_description/sdf/schunk_wsg_50.sdf";
wsg_instance_ = parser.AddModelsFromUrl(wsg_url).at(0);
// Weld the gripper to the world frame.
sim_plant_->WeldFrames(sim_plant_->world_frame(),
sim_plant_->GetFrameByName("body", wsg_instance_),
RigidTransformd::Identity());
sim_plant_->Finalize();
}
systems::DiagramBuilder<double> builder_;
MultibodyPlant<double>* sim_plant_{nullptr};
lcm::DrakeLcm lcm_;
ModelInstanceIndex wsg_instance_;
};
TEST_F(BuildSchunkWsgControlTest, BuildSchunkWsgControl) {
BuildSchunkWsgControl(*sim_plant_, wsg_instance_, &lcm_, &builder_);
const auto diagram = builder_.Build();
systems::Simulator<double> simulator(*diagram);
lcm::Subscriber<lcmt_schunk_wsg_status> sub{&lcm_, "SCHUNK_WSG_STATUS"};
// Publish commands and check whether the wsg gripper moves to the correct
// positions.
lcmt_schunk_wsg_command command{};
command.force = 40.0;
command.target_position_mm = 100.0;
Publish(&lcm_, "SCHUNK_WSG_COMMAND", command);
lcm_.HandleSubscriptions(0);
simulator.AdvanceTo(1.0);
lcm_.HandleSubscriptions(0);
EXPECT_NEAR(sub.message().actual_position_mm, 100.0, kTolerance);
command.target_position_mm = 0.0;
Publish(&lcm_, "SCHUNK_WSG_COMMAND", command);
lcm_.HandleSubscriptions(0);
simulator.AdvanceTo(2.0);
lcm_.HandleSubscriptions(0);
EXPECT_NEAR(sub.message().actual_position_mm, 0.0, kTolerance);
}
} // namespace
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/schunk_wsg | /home/johnshepherd/drake/manipulation/schunk_wsg/test/schunk_wsg_constants_test.cc | #include "drake/manipulation/schunk_wsg/schunk_wsg_constants.h"
#include <gtest/gtest.h>
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
namespace drake {
namespace manipulation {
namespace schunk_wsg {
namespace {
// Test that the constants defined in schunk_wsg_constants.h are
// correct wrt `models/schunk_wsg_50.sdf`.
GTEST_TEST(SchunkWsgConstantTest, ConstantTest) {
multibody::MultibodyPlant<double> plant(0.0);
multibody::Parser parser(&plant);
parser.AddModelsFromUrl(
"package://drake_models/wsg_50_description/sdf/schunk_wsg_50.sdf");
plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("body"));
plant.Finalize();
EXPECT_EQ(plant.num_actuators(), kSchunkWsgNumActuators);
EXPECT_EQ(plant.num_positions(), kSchunkWsgNumPositions);
EXPECT_EQ(plant.num_velocities(), kSchunkWsgNumVelocities);
const auto& joint = plant.GetJointByName("left_finger_sliding_joint");
const auto& matrix = plant.MakeStateSelectorMatrix({joint.index()});
EXPECT_EQ(matrix(0, kSchunkWsgPositionIndex), 1.0);
}
} // namespace
} // namespace schunk_wsg
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_googletest",
"drake_cc_library",
"drake_cc_package_library",
)
package(
default_visibility = ["//visibility:public"],
)
drake_cc_package_library(
name = "kinova_jaco",
visibility = ["//visibility:public"],
deps = [
":jaco_command_receiver",
":jaco_command_sender",
":jaco_constants",
":jaco_status_receiver",
":jaco_status_sender",
],
)
drake_cc_library(
name = "jaco_constants",
hdrs = ["jaco_constants.h"],
)
drake_cc_library(
name = "jaco_command_receiver",
srcs = ["jaco_command_receiver.cc"],
hdrs = ["jaco_command_receiver.h"],
deps = [
":jaco_constants",
"//common:essential",
"//lcmtypes:lcmtypes_drake_cc",
"//systems/framework:leaf_system",
"//systems/lcm:lcm_pubsub_system",
],
)
drake_cc_library(
name = "jaco_command_sender",
srcs = ["jaco_command_sender.cc"],
hdrs = ["jaco_command_sender.h"],
deps = [
":jaco_constants",
"//common:essential",
"//lcmtypes:lcmtypes_drake_cc",
"//systems/framework:leaf_system",
],
)
drake_cc_library(
name = "jaco_status_receiver",
srcs = ["jaco_status_receiver.cc"],
hdrs = ["jaco_status_receiver.h"],
deps = [
":jaco_constants",
"//common:essential",
"//lcmtypes:lcmtypes_drake_cc",
"//systems/framework:leaf_system",
],
)
drake_cc_library(
name = "jaco_status_sender",
srcs = ["jaco_status_sender.cc"],
hdrs = ["jaco_status_sender.h"],
deps = [
":jaco_constants",
"//common:essential",
"//lcmtypes:lcmtypes_drake_cc",
"//systems/framework:leaf_system",
],
)
# === test/ ===
drake_cc_googletest(
name = "jaco_command_receiver_test",
deps = [
":jaco_command_receiver",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "jaco_command_sender_test",
deps = [
":jaco_command_sender",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "jaco_status_receiver_test",
deps = [
":jaco_status_receiver",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "jaco_status_sender_test",
deps = [
":jaco_status_sender",
"//common/test_utilities:eigen_matrix_compare",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_status_receiver.h | #pragma once
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/lcmt_jaco_status.hpp"
#include "drake/manipulation/kinova_jaco/jaco_constants.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
/// Handles lcmt_jaco_status messages from a LcmSubscriberSystem.
///
/// Note that this system does not actually subscribe to an LCM channel. To
/// receive the message, the input of this system should be connected to a
/// systems::lcm::LcmSubscriberSystem::Make<lcmt_jaco_status>().
///
/// This system has one abstract-valued input port of type lcmt_jaco_status.
///
/// This system has many vector-valued output ports. All output ports are of
/// size num_joints + num_fingers. The exception is `time_measured`, which
/// has a one-dimensional measured time output in seconds, i.e., the timestamp
/// from the hardware in microseconds converted into seconds. The ports will
/// output zeros until an input message is received. Finger velocities will
/// be translated from the values used by the Kinova SDK to values appropriate
/// for the finger joints in the Jaco description (see jaco_constants.h.)
//
/// @system
/// name: JacoStatusReceiver
/// input_ports:
/// - lcmt_jaco_status
/// output_ports:
/// - position_measured
/// - velocity_measured
/// - torque_measured
/// - torque_external
/// - current
/// - time_measured
/// @endsystem
///
/// @see `lcmt_jaco_status.lcm` for additional documentation.
class JacoStatusReceiver : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(JacoStatusReceiver)
JacoStatusReceiver(int num_joints = kJacoDefaultArmNumJoints,
int num_fingers = kJacoDefaultArmNumFingers);
/// @name Named accessors for this System's input and output ports.
//@{
const systems::OutputPort<double>& get_position_measured_output_port() const {
return *position_measured_output_;
}
const systems::OutputPort<double>& get_velocity_measured_output_port() const {
return *velocity_measured_output_;
}
const systems::OutputPort<double>& get_torque_measured_output_port() const {
return *torque_measured_output_;
}
const systems::OutputPort<double>& get_torque_external_output_port() const {
return *torque_external_output_;
}
const systems::OutputPort<double>& get_current_output_port() const {
return *current_output_;
}
const systems::OutputPort<double>& get_time_measured_output_port() const {
return *time_measured_output_;
}
//@}
private:
template <std::vector<double> drake::lcmt_jaco_status::*,
std::vector<double> drake::lcmt_jaco_status::*,
int>
void CalcJointOutput(const systems::Context<double>&,
systems::BasicVector<double>*) const;
void CalcTimeOutput(const systems::Context<double>&,
systems::BasicVector<double>*) const;
const int num_joints_;
const int num_fingers_;
const systems::OutputPort<double>* time_measured_output_{};
const systems::OutputPort<double>* position_measured_output_{};
const systems::OutputPort<double>* velocity_measured_output_{};
const systems::OutputPort<double>* torque_measured_output_{};
const systems::OutputPort<double>* torque_external_output_{};
const systems::OutputPort<double>* current_output_{};
const systems::InputPort<double>* message_input_{};
};
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_command_sender.cc | #include "drake/manipulation/kinova_jaco/jaco_command_sender.h"
#include "drake/common/drake_assert.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
using drake::systems::kVectorValued;
JacoCommandSender::JacoCommandSender(int num_joints, int num_fingers)
: num_joints_(num_joints),
num_fingers_(num_fingers) {
position_input_ = &DeclareInputPort(
"position", kVectorValued, num_joints_ + num_fingers_);
velocity_input_ = &DeclareInputPort(
"velocity", kVectorValued, num_joints_ + num_fingers_);
time_input_ = &DeclareInputPort("time", kVectorValued, 1);
this->DeclareAbstractOutputPort(
"lcmt_jaco_command", &JacoCommandSender::CalcOutput);
}
void JacoCommandSender::CalcOutput(
const systems::Context<double>& context, lcmt_jaco_command* output) const {
if (time_input_->HasValue(context)) {
output->utime = time_input_->Eval(context)[0] * 1e6;
} else {
output->utime = context.get_time() * 1e6;
}
output->num_joints = num_joints_;
output->joint_position.resize(num_joints_);
output->joint_velocity.resize(num_joints_);
output->num_fingers = num_fingers_;
output->finger_position.resize(num_fingers_);
output->finger_velocity.resize(num_fingers_);
const auto& position = position_input_->Eval(context);
const auto& velocity = velocity_input_->Eval(context);
for (int i = 0; i < num_joints_; ++i) {
output->joint_position[i] = position(i);
output->joint_velocity[i] = velocity(i);
}
for (int i = 0; i < num_fingers_; ++i) {
output->finger_position[i] =
position(num_joints_ + i) * kFingerUrdfToSdk;
output->finger_velocity[i] =
velocity(num_joints_ + i) * kFingerUrdfToSdk;
}
}
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_command_receiver.h | #pragma once
#include <memory>
#include <string>
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/lcmt_jaco_command.hpp"
#include "drake/manipulation/kinova_jaco/jaco_constants.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
/// Handles lcmt_jaco_command message from a LcmSubscriberSystem.
///
/// Note that this system does not actually subscribe to an LCM channel. To
/// receive the message, the input of this system should be connected to a
/// LcmSubscriberSystem::Make<drake::lcmt_jaco_command>().
///
/// It has one required input port, "lcmt_jaco_command".
///
/// This system has three output ports: one each for the commanded position
/// and velocity of the arm+finger joints, and one for the timestamp in the
/// most recently received message. Finger velocities will be translated from
/// the values used by the Kinova SDK to values appropriate for the finger
/// joints in the Jaco description (see jaco_constants.h).
///
/// @system
/// name: JacoCommandReceiver
/// input_ports:
/// - lcmt_jaco_command
/// - position_measured (optional)
/// output_ports:
/// - position
/// - velocity
/// - time
///
/// @par Output prior to receiving a valid lcmt_jaco_command message: The
/// "position" output initially feeds through from the "position_measured"
/// input port -- or if not connected, outputs zero. When discrete update
/// events are enabled (e.g., during a simulation), the system latches the
/// "position_measured" input into state during the first event, and the
/// "position" output comes from the latched state, no longer fed through from
/// the "position" input. Alternatively, the LatchInitialPosition() method is
/// available to achieve the same effect without using events. The "time"
/// output will be a vector of a single zero.
///
/// @endsystem
class JacoCommandReceiver : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(JacoCommandReceiver)
JacoCommandReceiver(int num_joints = kJacoDefaultArmNumJoints,
int num_fingers = kJacoDefaultArmNumFingers);
/// (Advanced) Copies the current "position_measured" input (or zero if not
/// connected) into Context state, and changes the behavior of the "position"
/// output to produce the latched state if no message has been received yet.
/// The latching already happens automatically during the first discrete
/// update event (e.g., when using a Simulator); this method exists for use
/// when not already using a Simulator or other special cases.
void LatchInitialPosition(systems::Context<double>* context) const;
/// @name Named accessors for this System's input and output ports.
//@{
const systems::InputPort<double>& get_message_input_port() const {
return *message_input_;
}
const systems::InputPort<double>& get_position_measured_input_port() const {
return *position_measured_input_;
}
const systems::OutputPort<double>& get_commanded_position_output_port()
const {
return *commanded_position_output_;
}
const systems::OutputPort<double>& get_commanded_velocity_output_port()
const {
return *commanded_velocity_output_;
}
const systems::OutputPort<double>& get_time_output_port() const {
return *time_output_;
}
//@}
private:
void CalcInput(const systems::Context<double>&, lcmt_jaco_command*) const;
void DoCalcNextUpdateTime(
const systems::Context<double>&,
systems::CompositeEventCollection<double>*, double*) const final;
void CalcPositionMeasuredOrZero(
const systems::Context<double>&, systems::BasicVector<double>*) const;
// Copies the current "position measured" input (or zero if not connected)
// into the @p result.
void LatchInitialPosition(
const systems::Context<double>&,
systems::DiscreteValues<double>*) const;
void CalcPositionOutput(
const systems::Context<double>&, systems::BasicVector<double>*) const;
void CalcVelocityOutput(
const systems::Context<double>&, systems::BasicVector<double>*) const;
void CalcTimeOutput(
const systems::Context<double>&, systems::BasicVector<double>*) const;
const int num_joints_;
const int num_fingers_;
const systems::InputPort<double>* message_input_{};
const systems::InputPort<double>* position_measured_input_{};
const systems::CacheEntry* position_measured_or_zero_{};
systems::DiscreteStateIndex latched_position_measured_is_set_;
systems::DiscreteStateIndex latched_position_measured_;
const systems::CacheEntry* groomed_input_{};
const systems::OutputPort<double>* commanded_position_output_{};
const systems::OutputPort<double>* commanded_velocity_output_{};
const systems::OutputPort<double>* time_output_{};
};
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_constants.h | #pragma once
namespace drake {
namespace manipulation {
namespace kinova_jaco {
/// The LCM system classes for the Jaco default to a 7dof model with 3
/// fingers. Different configurations are supported by passing the
/// proper arguments to the system constructors.
constexpr int kJacoDefaultArmNumJoints = 7;
constexpr int kJacoDefaultArmNumFingers = 3;
/// The Jaco URDF models the fingers as having a single revolute joint, but
/// the SDK uses the motor position for the actuator driving the adaptive
/// fingers. This doesn't really convert well, so we use a scaling factor to
/// approximate a reasonable behavior for simulation/visualization.
constexpr double kFingerSdkToUrdf = 1.34 / 118.68;
constexpr double kFingerUrdfToSdk = 1. / kFingerSdkToUrdf;
/// Kinova says 100Hz is the proper frequency for joint velocity
/// updates. See
/// https://github.com/Kinovarobotics/kinova-ros#velocity-control-for-joint-space-and-cartesian-space
constexpr double kJacoLcmStatusPeriod = 0.010;
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_status_sender.cc | #include "drake/manipulation/kinova_jaco/jaco_status_sender.h"
#include "drake/common/text_logging.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
using drake::systems::kVectorValued;
JacoStatusSender::JacoStatusSender(int num_joints, int num_fingers)
: num_joints_(num_joints),
num_fingers_(num_fingers) {
position_input_ = &DeclareInputPort(
"position", kVectorValued, num_joints_ + num_fingers_);
velocity_input_ = &DeclareInputPort(
"velocity", kVectorValued, num_joints_ + num_fingers_);
torque_input_ = &DeclareInputPort(
"torque", kVectorValued, num_joints_ + num_fingers_);
torque_external_input_ = &DeclareInputPort(
"torque_external", kVectorValued, num_joints_ + num_fingers_);
current_input_ = &DeclareInputPort(
"current", kVectorValued, num_joints_ + num_fingers_);
time_measured_input_ = &DeclareInputPort(
"time_measured", kVectorValued, 1);
DeclareAbstractOutputPort(
"lcmt_jaco_status", &JacoStatusSender::CalcOutput);
}
void JacoStatusSender::CalcOutput(
const systems::Context<double>& context, lcmt_jaco_status* output) const {
const double time_measured =
get_time_measured_input_port().HasValue(context)
? get_time_measured_input_port().Eval(context)[0]
: context.get_time();
const Eigen::VectorXd zero_state =
Eigen::VectorXd::Zero(num_joints_ + num_fingers_);
const auto& torque =
get_torque_input_port().HasValue(context) ?
get_torque_input_port().Eval(context) :
zero_state;
const auto& torque_external =
get_torque_external_input_port().HasValue(context) ?
get_torque_external_input_port().Eval(context) :
zero_state;
const auto& current =
get_current_input_port().HasValue(context) ?
get_current_input_port().Eval(context) :
zero_state;
lcmt_jaco_status& status = *output;
status.utime = time_measured * 1e6;
status.num_joints = num_joints_;
status.joint_position.resize(num_joints_, 0);
status.joint_velocity.resize(num_joints_, 0);
status.joint_torque.resize(num_joints_, 0);
status.joint_torque_external.resize(num_joints_, 0);
status.joint_current.resize(num_joints_, 0);
status.num_fingers = num_fingers_;
status.finger_position.resize(num_fingers_, 0);
status.finger_velocity.resize(num_fingers_, 0);
status.finger_torque.resize(num_fingers_, 0);
status.finger_torque_external.resize(num_fingers_, 0);
status.finger_current.resize(num_fingers_, 0);
const auto& position = position_input_->Eval(context);
const auto& velocity = velocity_input_->Eval(context);
for (int i = 0; i < num_joints_; ++i) {
status.joint_position[i] = position(i);
// It seems like the Jaco (at least for some models/firmwares) reports
// half of the actual angular velocity. Fix that up here. Note
// bug-for-bug compatibility implemented in JacoStatusReceiver.
status.joint_velocity[i] = velocity(i) / 2;
status.joint_torque[i] = torque(i);
status.joint_torque_external[i] = torque_external(i);
status.joint_current[i] = current(i);
}
for (int i = 0; i < num_fingers_; ++i) {
status.finger_position[i] = position(num_joints_ + i) * kFingerUrdfToSdk;
status.finger_velocity[i] = velocity(num_joints_ + i) * kFingerUrdfToSdk;
status.finger_torque[i] = torque(num_joints_ + i);
status.finger_torque_external[i] = torque_external(num_joints_ + i);
status.finger_current[i] = current(num_joints_ + i);
}
}
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_status_sender.h | #pragma once
#include "drake/common/drake_copyable.h"
#include "drake/lcmt_jaco_status.hpp"
#include "drake/manipulation/kinova_jaco/jaco_constants.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
/// Creates and outputs lcmt_jaco_status messages.
///
/// Note that this system does not actually send the message to an LCM
/// channel. To send the message, the output of this system should be
/// connected to a systems::lcm::LcmPublisherSystem::Make<lcmt_jaco_status>().
///
/// This system has many vector-valued input ports. Most input ports are of
/// size num_joints + num_fingers. The exception is `time_measured` which is
/// the one-dimensional time in seconds to set as the message timestamp
/// (i.e. the time inputted will be converted to microseconds and sent to the
/// hardware). It is optional and if unset, the context time is used. The
/// elements in the ports are the joints of the arm from the base to the tip,
/// followed by the fingers in the same order as used by the Kinova SDK
/// (consult the URDF model for a visual example). If the torque,
/// torque_external, or current input ports are not connected, the output
/// message will use zeros. Finger velocities will be translated to the
/// values used by the Kinova SDK from values appropriate for the finger
/// joints in the Jaco description (see jaco_constants.h).
///
/// This system has one abstract-valued output port of type lcmt_jaco_status.
///
/// This system is presently only used in simulation. The robot hardware drivers
/// publish directly to LCM and do not make use of this system.
///
/// @system
/// name: JacoStatusSender
/// input_ports:
/// - position
/// - velocity
/// - torque (optional)
/// - torque_external (optional)
/// - current (optional)
/// - time_measured (optional)
/// output_ports:
/// - lcmt_jaco_status
/// @endsystem
///
/// @see `lcmt_jaco_status.lcm` for additional documentation.
class JacoStatusSender : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(JacoStatusSender)
JacoStatusSender(int num_joints = kJacoDefaultArmNumJoints,
int num_fingers = kJacoDefaultArmNumFingers);
/// @name Named accessors for this System's input and output ports.
//@{
const systems::InputPort<double>& get_time_measured_input_port() const {
return *time_measured_input_;
}
const systems::InputPort<double>& get_position_input_port() const {
return *position_input_;
}
const systems::InputPort<double>& get_velocity_input_port() const {
return *velocity_input_;
}
const systems::InputPort<double>& get_torque_input_port() const {
return *torque_input_;
}
const systems::InputPort<double>& get_torque_external_input_port() const {
return *torque_external_input_;
}
const systems::InputPort<double>& get_current_input_port() const {
return *current_input_;
}
//@}
private:
void CalcOutput(const systems::Context<double>&, lcmt_jaco_status*) const;
const int num_joints_;
const int num_fingers_;
const systems::InputPort<double>* time_measured_input_{};
const systems::InputPort<double>* position_input_{};
const systems::InputPort<double>* velocity_input_{};
const systems::InputPort<double>* torque_input_{};
const systems::InputPort<double>* torque_external_input_{};
const systems::InputPort<double>* current_input_{};
};
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_command_receiver.cc | #include "drake/manipulation/kinova_jaco/jaco_command_receiver.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
#include "drake/common/text_logging.h"
#include "drake/lcm/lcm_messages.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
using Eigen::VectorXd;
using systems::BasicVector;
using systems::CompositeEventCollection;
using systems::Context;
using systems::DiscreteValues;
using systems::DiscreteUpdateEvent;
using systems::kVectorValued;
JacoCommandReceiver::JacoCommandReceiver(int num_joints, int num_fingers)
: num_joints_(num_joints),
num_fingers_(num_fingers) {
message_input_ = &DeclareAbstractInputPort(
"lcmt_jaco_command", Value<lcmt_jaco_command>());
position_measured_input_ = &DeclareInputPort(
"position_measured", kVectorValued, num_joints + num_fingers);
// This cache entry provides either the input (iff connected) or else zero.
position_measured_or_zero_ = &DeclareCacheEntry(
"position_measured_or_zero",
BasicVector<double>(num_joints + num_fingers),
&JacoCommandReceiver::CalcPositionMeasuredOrZero,
{position_measured_input_->ticket()});
// When a simulation begins, we will latch positions into a state variable,
// so that we will hold that pose until the first message is received.
// Prior to that event, we continue to use the unlatched value.
latched_position_measured_is_set_ = DeclareDiscreteState(VectorXd::Zero(1));
latched_position_measured_ = DeclareDiscreteState(
VectorXd::Zero(num_joints + num_fingers));
groomed_input_ = &DeclareCacheEntry(
"groomed_input", &JacoCommandReceiver::CalcInput,
{message_input_->ticket(),
discrete_state_ticket(latched_position_measured_is_set_),
discrete_state_ticket(latched_position_measured_),
position_measured_or_zero_->ticket()});
commanded_position_output_ = &DeclareVectorOutputPort(
"position", num_joints + num_fingers,
&JacoCommandReceiver::CalcPositionOutput,
{groomed_input_->ticket()});
commanded_velocity_output_ = &DeclareVectorOutputPort(
"velocity", num_joints + num_fingers,
&JacoCommandReceiver::CalcVelocityOutput,
{groomed_input_->ticket()});
time_output_ = &DeclareVectorOutputPort(
"time", 1, &JacoCommandReceiver::CalcTimeOutput,
{groomed_input_->ticket()});
}
void JacoCommandReceiver::CalcPositionMeasuredOrZero(
const Context<double>& context,
BasicVector<double>* result) const {
if (position_measured_input_->HasValue(context)) {
result->SetFromVector(position_measured_input_->Eval(context));
} else {
result->SetZero();
}
}
void JacoCommandReceiver::LatchInitialPosition(
const Context<double>& context,
DiscreteValues<double>* result) const {
const auto& bool_index = latched_position_measured_is_set_;
const auto& value_index = latched_position_measured_;
result->get_mutable_value(bool_index)[0] = 1.0;
result->get_mutable_vector(value_index).SetFrom(
position_measured_or_zero_->Eval<BasicVector<double>>(context));
}
void JacoCommandReceiver::LatchInitialPosition(
Context<double>* context) const {
DRAKE_THROW_UNLESS(context != nullptr);
LatchInitialPosition(*context, &context->get_mutable_discrete_state());
}
// TODO(jwnimmer-tri) This is quite a cumbersome syntax to use for declaring a
// "now" event. We should try to consolidate it with other similar uses within
// the source tree. Relates to #11403 somewhat.
void JacoCommandReceiver::DoCalcNextUpdateTime(
const Context<double>& context,
CompositeEventCollection<double>* events, double* time) const {
// We do not support events other than our own message timing events.
LeafSystem<double>::DoCalcNextUpdateTime(context, events, time);
DRAKE_THROW_UNLESS(events->HasEvents() == false);
DRAKE_THROW_UNLESS(std::isinf(*time));
// If we have a latched position already, then we do not have any updates.
if (context.get_discrete_state(0).get_value()[0] != 0.0) {
return;
}
// Schedule a discrete update event at now to latch the current position.
*time = context.get_time();
auto& discrete_events = events->get_mutable_discrete_update_events();
discrete_events.AddEvent(DiscreteUpdateEvent<double>(
[this](const System<double>&, const Context<double>& event_context,
const DiscreteUpdateEvent<double>&,
DiscreteValues<double>* next_values) {
LatchInitialPosition(event_context, next_values);
return systems::EventStatus::Succeeded();
}));
}
// Returns (in "result") the command message input, or if a message has not
// been received yet returns the initial command (as optionally set by the
// user). The result will always have num_joints_ positions and velocities.
void JacoCommandReceiver::CalcInput(
const Context<double>& context, lcmt_jaco_command* result) const {
if (!get_message_input_port().HasValue(context)) {
throw std::logic_error("JacoCommandReceiver has no input connected");
}
// Copy the input value into our tentative result.
*result = get_message_input_port().Eval<lcmt_jaco_command>(context);
// If we haven't received a non-default message yet, use the initial command.
// N.B. This works due to lcm::Serializer<>::CreateDefaultValue() using
// value-initialization.
if (lcm::AreLcmMessagesEqual(*result, lcmt_jaco_command{})) {
const BasicVector<double>& latch_is_set = context.get_discrete_state(
latched_position_measured_is_set_);
const BasicVector<double>& default_position =
latch_is_set[0]
? context.get_discrete_state(latched_position_measured_)
: position_measured_or_zero_->Eval<BasicVector<double>>(context);
result->num_joints = num_joints_;
const VectorXd& vec = default_position.value();
result->joint_position = {vec.data(), vec.data() + num_joints_};
result->joint_velocity.resize(num_joints_, 0);
result->num_fingers = num_fingers_;
if (num_fingers_) {
result->finger_position =
{vec.data() + num_joints_,
vec.data() + num_joints_ + num_fingers_};
result->finger_velocity.resize(num_fingers_, 0);
} else {
result->finger_position.clear();
result->finger_velocity.clear();
}
} else {
for (int i = 0; i < result->num_fingers; ++i) {
result->finger_position[i] *= kFingerSdkToUrdf;
result->finger_velocity[i] *= kFingerSdkToUrdf;
}
}
// Sanity check the joint sizes.
if (result->num_joints != num_joints_) {
throw std::runtime_error(fmt::format(
"JacoCommandReceiver expected num_joints = {}, but received {}",
num_joints_, result->num_joints));
}
if (result->num_fingers != num_fingers_) {
throw std::runtime_error(fmt::format(
"JacoCommandReceiver expected num_fingers = {}, but received {}",
num_fingers_, result->num_fingers));
}
}
void JacoCommandReceiver::CalcPositionOutput(
const Context<double>& context, BasicVector<double>* output) const {
const auto& message = groomed_input_->Eval<lcmt_jaco_command>(context);
if (message.num_joints != num_joints_) {
throw std::runtime_error(fmt::format(
"JacoCommandReceiver expected num_joints = {}, but received {}",
num_joints_, message.num_joints));
}
if (message.num_fingers != num_fingers_) {
throw std::runtime_error(fmt::format(
"JacoCommandReceiver expected num_fingers = {}, but received {}",
num_fingers_, message.num_fingers));
}
Eigen::VectorXd position(num_joints_ + num_fingers_);
position.head(num_joints_) = Eigen::Map<const VectorXd>(
message.joint_position.data(), message.joint_position.size());
if (num_fingers_) {
position.segment(num_joints_, num_fingers_) = Eigen::Map<const VectorXd>(
message.finger_position.data(), message.finger_position.size());
}
output->SetFromVector(position);
}
void JacoCommandReceiver::CalcVelocityOutput(
const Context<double>& context, BasicVector<double>* output) const {
const auto& message = groomed_input_->Eval<lcmt_jaco_command>(context);
if (message.num_joints != num_joints_) {
throw std::runtime_error(fmt::format(
"JacoCommandReceiver expected num_joints = {}, but received {}",
num_joints_, message.num_joints));
}
if (message.num_fingers != num_fingers_) {
throw std::runtime_error(fmt::format(
"JacoCommandReceiver expected num_fingers = {}, but received {}",
num_fingers_, message.num_fingers));
}
Eigen::VectorXd velocity(num_joints_ + num_fingers_);
velocity.head(num_joints_) = Eigen::Map<const VectorXd>(
message.joint_velocity.data(), message.joint_velocity.size());
if (num_fingers_) {
velocity.segment(num_joints_, num_fingers_) = Eigen::Map<const VectorXd>(
message.finger_velocity.data(), message.finger_velocity.size());
}
output->SetFromVector(velocity);
}
void JacoCommandReceiver::CalcTimeOutput(
const Context<double>& context, BasicVector<double>* output) const {
const auto& message = groomed_input_->Eval<lcmt_jaco_command>(context);
(*output)[0] = static_cast<double>(message.utime) / 1e6;
}
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_command_sender.h | #pragma once
#include "drake/common/drake_copyable.h"
#include "drake/lcmt_jaco_command.hpp"
#include "drake/manipulation/kinova_jaco/jaco_constants.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
/// Creates and outputs lcmt_jaco_command messages.
///
/// Note that this system does not actually send the message to an LCM
/// channel. To send the message, the output of this system should be
/// connected to a
/// systems::lcm::LcmPublisherSystem::Make<lcmt_jaco_command>().
///
/// This system has two mandatory vector-valued input ports containing the
/// desired position and velocity, and an optional vector-valued input port
/// for the command timestamp. If the time input port is not connected, the
/// context time will be used. Finger velocities will be translated to the
/// values used by the Kinova SDK from values appropriate for the finger
/// joints in the Jaco description (see jaco_constants.h).
///
/// This system has one abstract-valued output port of type lcmt_jaco_command.
///
/// @system
/// name: JacoCommandSender
/// input_ports:
/// - position
/// - velocity
/// - time (optional)
/// output_ports:
/// - lcmt_jaco_command
/// @endsystem
///
/// @see `lcmt_jaco_command.lcm` for additional documentation.
class JacoCommandSender : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(JacoCommandSender)
JacoCommandSender(int num_joints = kJacoDefaultArmNumJoints,
int num_fingers = kJacoDefaultArmNumFingers);
const systems::InputPort<double>& get_position_input_port() const {
return *position_input_;
}
const systems::InputPort<double>& get_velocity_input_port() const {
return *velocity_input_;
}
const systems::InputPort<double>& get_time_input_port() const {
return *time_input_;
}
private:
void CalcOutput(const systems::Context<double>&, lcmt_jaco_command*) const;
const int num_joints_;
const int num_fingers_;
const systems::InputPort<double>* position_input_{};
const systems::InputPort<double>* velocity_input_{};
const systems::InputPort<double>* time_input_{};
};
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/kinova_jaco/jaco_status_receiver.cc | #include "drake/manipulation/kinova_jaco/jaco_status_receiver.h"
#include "drake/common/drake_assert.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
using systems::BasicVector;
using systems::Context;
JacoStatusReceiver::JacoStatusReceiver(int num_joints, int num_fingers)
: num_joints_(num_joints),
num_fingers_(num_fingers) {
message_input_ = &DeclareAbstractInputPort(
"lcmt_jaco_status", Value<lcmt_jaco_status>{});
position_measured_output_ = &DeclareVectorOutputPort(
"position_measured", num_joints_ + num_fingers_,
&JacoStatusReceiver::CalcJointOutput<
&lcmt_jaco_status::joint_position,
&lcmt_jaco_status::finger_position, 1>);
velocity_measured_output_ = &DeclareVectorOutputPort(
"velocity_measured", num_joints_ + num_fingers_,
&JacoStatusReceiver::CalcJointOutput<
&lcmt_jaco_status::joint_velocity,
&lcmt_jaco_status::finger_velocity, 1>);
torque_measured_output_ = &DeclareVectorOutputPort(
"torque_measured", num_joints_ + num_fingers_,
&JacoStatusReceiver::CalcJointOutput<
&lcmt_jaco_status::joint_torque,
&lcmt_jaco_status::finger_torque, 0>);
torque_external_output_ = &DeclareVectorOutputPort(
"torque_external", num_joints_ + num_fingers_,
&JacoStatusReceiver::CalcJointOutput<
&lcmt_jaco_status::joint_torque_external,
&lcmt_jaco_status::finger_torque_external, 0>);
current_output_ = &DeclareVectorOutputPort(
"current", num_joints_ + num_fingers_,
&JacoStatusReceiver::CalcJointOutput<
&lcmt_jaco_status::joint_current,
&lcmt_jaco_status::finger_current, 0>);
// Declared after the previous points to preserve port numbers (even though
// this isn't a guaranteed stable part of the API).
time_measured_output_ = &DeclareVectorOutputPort(
"time_measured", 1,
&JacoStatusReceiver::CalcTimeOutput);
}
template <std::vector<double> drake::lcmt_jaco_status::* arm_ptr,
std::vector<double> drake::lcmt_jaco_status::* finger_ptr,
int finger_scale>
void JacoStatusReceiver::CalcJointOutput(
const Context<double>& context, BasicVector<double>* output) const {
const auto& status = get_input_port().Eval<lcmt_jaco_status>(context);
// If we're using a default constructed message (i.e., we haven't received
// any status message yet), output zero.
if (status.num_joints == 0) {
output->get_mutable_value().setZero();
return;
}
Eigen::VectorXd output_vec(num_joints_ + num_fingers_);
const auto& arm_field = status.*arm_ptr;
output_vec.head(num_joints_) = Eigen::Map<const Eigen::VectorXd>(
arm_field.data(), arm_field.size());
if (num_fingers_) {
constexpr double scale_factor = finger_scale ? kFingerSdkToUrdf : 1;
const auto& finger_field = status.*finger_ptr;
output_vec.tail(num_fingers_) = Eigen::Map<const Eigen::VectorXd>(
finger_field.data(), finger_field.size()) * scale_factor;
}
output->SetFromVector(output_vec);
}
void JacoStatusReceiver::CalcTimeOutput(const Context<double>& context,
BasicVector<double>* output) const {
const auto& status = get_input_port().Eval<lcmt_jaco_status>(context);
// If we're using a default constructed message (i.e., we haven't received
// any status message yet), output zero.
if (status.num_joints == 0) {
output->get_mutable_value().setZero();
} else {
(*output)[0] = static_cast<double>(status.utime) / 1e6;
}
}
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/kinova_jaco | /home/johnshepherd/drake/manipulation/kinova_jaco/test/jaco_command_sender_test.cc | #include "drake/manipulation/kinova_jaco/jaco_command_sender.h"
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
namespace {
using Eigen::VectorXd;
constexpr int N = kJacoDefaultArmNumJoints;
constexpr int N_F = kJacoDefaultArmNumFingers;
class JacoCommandSenderTestBase : public testing::Test {
public:
JacoCommandSenderTestBase(int num_joints, int num_fingers)
: dut_(num_joints, num_fingers),
context_ptr_(dut_.CreateDefaultContext()),
context_(*context_ptr_) {}
const lcmt_jaco_command& output() const {
return dut_.get_output_port().Eval<lcmt_jaco_command>(context_);
}
protected:
JacoCommandSender dut_;
std::unique_ptr<systems::Context<double>> context_ptr_;
systems::Context<double>& context_;
const Vector1d time_{Vector1d(1.2)};
};
class JacoCommandSenderTest : public JacoCommandSenderTestBase {
public:
JacoCommandSenderTest()
: JacoCommandSenderTestBase(
kJacoDefaultArmNumJoints, kJacoDefaultArmNumFingers) {}
};
class JacoCommandSenderNoFingersTest : public JacoCommandSenderTestBase {
public:
JacoCommandSenderNoFingersTest()
: JacoCommandSenderTestBase(
kJacoDefaultArmNumJoints, 0) {}
};
const std::vector<double> ToStdVec(const Eigen::VectorXd& in) {
return std::vector<double>{in.data(), in.data() + in.size()};
}
TEST_F(JacoCommandSenderTest, AcceptanceTestWithFingers) {
const VectorXd q0 = VectorXd::LinSpaced(N + N_F, 0.2, 0.3);
const VectorXd v0 = VectorXd::LinSpaced(N + N_F, 0.3, 0.4);
dut_.get_position_input_port().FixValue(&context_, q0);
dut_.get_velocity_input_port().FixValue(&context_, v0);
EXPECT_EQ(output().utime, 0);
EXPECT_EQ(output().num_joints, kJacoDefaultArmNumJoints);
EXPECT_EQ(output().joint_position, ToStdVec(q0.head(N)));
EXPECT_EQ(output().joint_velocity, ToStdVec(v0.head(N)));
EXPECT_EQ(output().num_fingers, kJacoDefaultArmNumFingers);
EXPECT_EQ(output().finger_position,
ToStdVec(q0.tail(N_F) * kFingerUrdfToSdk));
EXPECT_EQ(output().finger_velocity,
ToStdVec(v0.tail(N_F) * kFingerUrdfToSdk));
dut_.get_time_input_port().FixValue(&context_, time_);
EXPECT_EQ(output().utime, time_[0] * 1e6);
}
TEST_F(JacoCommandSenderNoFingersTest, AcceptanceNoFingers) {
const VectorXd q0 = VectorXd::LinSpaced(N, 0.2, 0.3);
const VectorXd v0 = VectorXd::LinSpaced(N, 0.3, 0.4);
dut_.get_position_input_port().FixValue(&context_, q0);
dut_.get_velocity_input_port().FixValue(&context_, v0);
EXPECT_EQ(output().num_joints, kJacoDefaultArmNumJoints);
EXPECT_EQ(output().joint_position, ToStdVec(q0));
EXPECT_EQ(output().joint_velocity, ToStdVec(v0));
}
} // namespace
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/kinova_jaco | /home/johnshepherd/drake/manipulation/kinova_jaco/test/jaco_status_sender_test.cc | #include "drake/manipulation/kinova_jaco/jaco_status_sender.h"
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
namespace {
using Eigen::VectorXd;
constexpr int N = kJacoDefaultArmNumJoints;
constexpr int N_F = kJacoDefaultArmNumFingers;
class JacoStatusSenderTestBase : public testing::Test {
public:
JacoStatusSenderTestBase(int num_joints, int num_fingers)
: dut_(num_joints, num_fingers),
context_ptr_(dut_.CreateDefaultContext()),
context_(*context_ptr_) {}
const lcmt_jaco_status& output() const {
return dut_.get_output_port().Eval<lcmt_jaco_status>(context_);
}
void Fix(const systems::InputPort<double>& port, const Eigen::VectorXd& v) {
port.FixValue(&context_, v);
}
protected:
JacoStatusSender dut_;
std::unique_ptr<systems::Context<double>> context_ptr_;
systems::Context<double>& context_;
};
class JacoStatusSenderTest : public JacoStatusSenderTestBase {
public:
JacoStatusSenderTest()
: JacoStatusSenderTestBase(
kJacoDefaultArmNumJoints, kJacoDefaultArmNumFingers) {}
};
class JacoStatusSenderNoFingersTest : public JacoStatusSenderTestBase {
public:
JacoStatusSenderNoFingersTest()
: JacoStatusSenderTestBase(
kJacoDefaultArmNumJoints, 0) {}
};
const std::vector<double> ToStdVec(const Eigen::VectorXd& in) {
return std::vector<double>{in.data(), in.data() + in.size()};
}
TEST_F(JacoStatusSenderTest, AcceptanceTestWithFingers) {
const VectorXd q0 = VectorXd::LinSpaced(N + N_F, 0.2, 0.3);
const VectorXd v0 = VectorXd::LinSpaced(N + N_F, 0.3, 0.4);
const VectorXd zero = VectorXd::Zero(N);
const VectorXd finger_zero = VectorXd::Zero(N_F);
dut_.get_position_input_port().FixValue(&context_, q0);
dut_.get_velocity_input_port().FixValue(&context_, v0);
EXPECT_EQ(output().utime, 0);
EXPECT_EQ(output().num_joints, kJacoDefaultArmNumJoints);
EXPECT_EQ(output().joint_position, ToStdVec(q0.head(N)));
EXPECT_EQ(output().joint_velocity, ToStdVec(v0.head(N) / 2));
EXPECT_EQ(output().num_fingers, kJacoDefaultArmNumFingers);
EXPECT_EQ(output().finger_position,
ToStdVec(q0.tail(N_F) * kFingerUrdfToSdk));
EXPECT_EQ(output().finger_velocity,
ToStdVec(v0.tail(N_F) * kFingerUrdfToSdk));
EXPECT_EQ(output().joint_torque, ToStdVec(zero));
EXPECT_EQ(output().joint_torque_external, ToStdVec(zero));
EXPECT_EQ(output().joint_current, ToStdVec(zero));
EXPECT_EQ(output().finger_torque, ToStdVec(finger_zero));
EXPECT_EQ(output().finger_torque_external, ToStdVec(finger_zero));
EXPECT_EQ(output().finger_current, ToStdVec(finger_zero));
const VectorXd time_measured = Vector1d(1.2);
const VectorXd t1 = VectorXd::LinSpaced(N + N_F, 0.4, 0.5);
const VectorXd t_ext1 = VectorXd::LinSpaced(N + N_F, 0.5, 0.6);
const VectorXd current1 = VectorXd::LinSpaced(N + N_F, 0.6, 0.7);
dut_.get_time_measured_input_port().FixValue(&context_, time_measured);
dut_.get_torque_input_port().FixValue(&context_, t1);
dut_.get_torque_external_input_port().FixValue(&context_, t_ext1);
dut_.get_current_input_port().FixValue(&context_, current1);
EXPECT_EQ(output().utime, time_measured[0] * 1e6);
EXPECT_EQ(output().joint_torque, ToStdVec(t1.head(N)));
EXPECT_EQ(output().joint_torque_external, ToStdVec(t_ext1.head(N)));
EXPECT_EQ(output().joint_current, ToStdVec(current1.head(N)));
EXPECT_EQ(output().finger_torque, ToStdVec(t1.tail(N_F)));
EXPECT_EQ(output().finger_torque_external, ToStdVec(t_ext1.tail(N_F)));
EXPECT_EQ(output().finger_current, ToStdVec(current1.tail(N_F)));
}
TEST_F(JacoStatusSenderNoFingersTest, AcceptanceNoFingers) {
const VectorXd q0 = VectorXd::LinSpaced(N, 0.2, 0.3);
const VectorXd v0 = VectorXd::LinSpaced(N, 0.3, 0.4);
dut_.get_position_input_port().FixValue(&context_, q0);
dut_.get_velocity_input_port().FixValue(&context_, v0);
EXPECT_EQ(output().num_joints, kJacoDefaultArmNumJoints);
EXPECT_EQ(output().joint_position, ToStdVec(q0));
EXPECT_EQ(output().joint_velocity, ToStdVec(v0 / 2));
EXPECT_EQ(output().num_fingers, 0);
}
} // namespace
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/kinova_jaco | /home/johnshepherd/drake/manipulation/kinova_jaco/test/jaco_status_receiver_test.cc | #include "drake/manipulation/kinova_jaco/jaco_status_receiver.h"
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
namespace {
using Eigen::VectorXd;
constexpr int N = kJacoDefaultArmNumJoints;
constexpr int N_F = kJacoDefaultArmNumFingers;
class JacoStatusReceiverTestBase : public testing::Test {
public:
JacoStatusReceiverTestBase(int num_joints, int num_fingers)
: dut_(num_joints, num_fingers),
context_ptr_(dut_.CreateDefaultContext()),
context_(*context_ptr_),
fixed_input_(
dut_.get_input_port().FixValue(&context_, lcmt_jaco_status{})) {}
// Test cases should call this to set the DUT's input value.
void SetInput() {
fixed_input_.GetMutableData()->
template get_mutable_value<lcmt_jaco_status>() = status_;
}
void Copy(const Eigen::VectorXd& from, std::vector<double>* to) {
*to = {from.data(), from.data() + from.size()};
}
protected:
JacoStatusReceiver dut_;
std::unique_ptr<systems::Context<double>> context_ptr_;
systems::Context<double>& context_;
systems::FixedInputPortValue& fixed_input_;
lcmt_jaco_status status_{};
};
class JacoStatusReceiverTest : public JacoStatusReceiverTestBase {
public:
JacoStatusReceiverTest()
: JacoStatusReceiverTestBase(
kJacoDefaultArmNumJoints, kJacoDefaultArmNumFingers) {}
};
class JacoStatusReceiverNoFingersTest : public JacoStatusReceiverTestBase {
public:
JacoStatusReceiverNoFingersTest()
: JacoStatusReceiverTestBase(
kJacoDefaultArmNumJoints, 0) {}
};
TEST_F(JacoStatusReceiverTest, ZeroOutputTest) {
// Confirm that output is zero for uninitialized lcm input.
const int num_output_ports = dut_.num_output_ports();
for (int i = 0; i < num_output_ports; ++i) {
const systems::LeafSystem<double>& leaf = dut_;
const auto& port = leaf.get_output_port(i);
EXPECT_TRUE(CompareMatrices(
port.Eval(context_), VectorXd::Zero(port.size())));
}
}
TEST_F(JacoStatusReceiverTest, AcceptanceTest) {
const int utime = 1661199485;
const VectorXd q0 = VectorXd::LinSpaced(N, 0.2, 0.3);
const VectorXd v0 = VectorXd::LinSpaced(N, 0.3, 0.4);
const VectorXd f_q0 = VectorXd::LinSpaced(N_F, 1.2, 1.3);
const VectorXd f_v0 = VectorXd::LinSpaced(N_F, 1.3, 1.4);
const VectorXd t0 = VectorXd::LinSpaced(N, 0.4, 0.5);
const VectorXd t_ext0 = VectorXd::LinSpaced(N, 0.5, 0.6);
const VectorXd current0 = VectorXd::LinSpaced(N, 0.6, 0.7);
const VectorXd f_t0 = VectorXd::LinSpaced(N_F, 1.4, 1.5);
const VectorXd f_t_ext0 = VectorXd::LinSpaced(N_F, 1.5, 1.6);
const VectorXd f_current0 = VectorXd::LinSpaced(N_F, 1.6, 1.7);
status_.utime = utime;
status_.num_joints = N;
status_.num_fingers = N_F;
Copy(q0, &status_.joint_position);
Copy(v0, &status_.joint_velocity);
Copy(f_q0, &status_.finger_position);
Copy(f_v0, &status_.finger_velocity);
Copy(t0, &status_.joint_torque);
Copy(t_ext0, &status_.joint_torque_external);
Copy(current0, &status_.joint_current);
Copy(f_t0, &status_.finger_torque);
Copy(f_t_ext0, &status_.finger_torque_external);
Copy(f_current0, &status_.finger_current);
SetInput();
VectorXd position_expected(N + N_F);
position_expected.head(N) = q0;
position_expected.tail(N_F) = f_q0 * kFingerSdkToUrdf;
VectorXd velocity_expected(N + N_F);
velocity_expected.head(N) = v0;
velocity_expected.tail(N_F) = f_v0 * kFingerSdkToUrdf;
EXPECT_TRUE(
CompareMatrices(dut_.get_time_measured_output_port().Eval(context_),
Vector1d(utime) / 1e6));
EXPECT_TRUE(CompareMatrices(
dut_.get_position_measured_output_port().Eval(context_),
position_expected));
EXPECT_TRUE(CompareMatrices(
dut_.get_velocity_measured_output_port().Eval(context_),
velocity_expected));
EXPECT_TRUE(CompareMatrices(
dut_.get_torque_measured_output_port().Eval(context_).head(N), t0));
EXPECT_TRUE(CompareMatrices(
dut_.get_torque_measured_output_port().Eval(context_).tail(N_F), f_t0));
EXPECT_TRUE(CompareMatrices(
dut_.get_torque_external_output_port().Eval(context_).head(N), t_ext0));
EXPECT_TRUE(CompareMatrices(
dut_.get_torque_external_output_port().Eval(context_).tail(N_F),
f_t_ext0));
EXPECT_TRUE(CompareMatrices(
dut_.get_current_output_port().Eval(context_).head(N), current0));
EXPECT_TRUE(CompareMatrices(
dut_.get_current_output_port().Eval(context_).tail(N_F), f_current0));
}
TEST_F(JacoStatusReceiverNoFingersTest, AcceptanceTestNoFingers) {
const VectorXd q0 = VectorXd::LinSpaced(N, 0.2, 0.3);
const VectorXd v0 = VectorXd::LinSpaced(N, 0.3, 0.4);
const VectorXd t0 = VectorXd::LinSpaced(N, 0.4, 0.5);
const VectorXd t_ext0 = VectorXd::LinSpaced(N, 0.5, 0.6);
const VectorXd current0 = VectorXd::LinSpaced(N, 0.6, 0.7);
status_.utime = 1;
status_.num_joints = N;
status_.num_fingers = 0;
Copy(q0, &status_.joint_position);
Copy(v0, &status_.joint_velocity);
Copy(t0, &status_.joint_torque);
Copy(t_ext0, &status_.joint_torque_external);
Copy(current0, &status_.joint_current);
SetInput();
EXPECT_TRUE(CompareMatrices(
dut_.get_position_measured_output_port().Eval(context_), q0));
EXPECT_TRUE(CompareMatrices(
dut_.get_velocity_measured_output_port().Eval(context_), v0));
EXPECT_TRUE(CompareMatrices(
dut_.get_torque_measured_output_port().Eval(context_), t0));
EXPECT_TRUE(CompareMatrices(
dut_.get_torque_external_output_port().Eval(context_), t_ext0));
EXPECT_TRUE(CompareMatrices(
dut_.get_current_output_port().Eval(context_), current0));
}
} // namespace
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation/kinova_jaco | /home/johnshepherd/drake/manipulation/kinova_jaco/test/jaco_command_receiver_test.cc | #include "drake/manipulation/kinova_jaco/jaco_command_receiver.h"
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace manipulation {
namespace kinova_jaco {
namespace {
using Eigen::VectorXd;
constexpr int N = kJacoDefaultArmNumJoints;
constexpr int N_F = kJacoDefaultArmNumFingers;
class JacoCommandReceiverTestBase : public testing::Test {
public:
JacoCommandReceiverTestBase(int num_joints, int num_fingers)
: dut_(num_joints, num_fingers),
context_ptr_(dut_.CreateDefaultContext()),
context_(*context_ptr_),
fixed_input_(FixInput()) {}
// For use only by our constructor.
systems::FixedInputPortValue& FixInput() {
return dut_.get_message_input_port().FixValue(
&context_, lcmt_jaco_command{});
}
// Test cases should call this to set the DUT's input value.
void SetInput(const lcmt_jaco_command& message) {
// TODO(jwnimmer-tri) This systems framework API is not very ergonomic.
fixed_input_.GetMutableData()->
template get_mutable_value<lcmt_jaco_command>() = message;
}
VectorXd position() const {
return dut_.get_commanded_position_output_port().Eval(context_);
}
VectorXd velocity() const {
return dut_.get_commanded_velocity_output_port().Eval(context_);
}
double time_output() const {
return dut_.get_time_output_port().Eval(context_)[0];
}
protected:
JacoCommandReceiver dut_;
std::unique_ptr<systems::Context<double>> context_ptr_;
systems::Context<double>& context_;
systems::FixedInputPortValue& fixed_input_;
};
constexpr double kCommandTime = 1.2;
class JacoCommandReceiverTest : public JacoCommandReceiverTestBase {
public:
JacoCommandReceiverTest()
: JacoCommandReceiverTestBase(
kJacoDefaultArmNumJoints, kJacoDefaultArmNumFingers) {}
};
class JacoCommandReceiverNoFingersTest : public JacoCommandReceiverTestBase {
public:
JacoCommandReceiverNoFingersTest()
: JacoCommandReceiverTestBase(
kJacoDefaultArmNumJoints, 0) {}
};
TEST_F(JacoCommandReceiverTest, AcceptanceTestWithoutMeasuredPositionInput) {
// When no message has been received and *no* position measurement is
// connected, the command is all zeros.
const VectorXd zero = VectorXd::Zero(N + N_F);
EXPECT_TRUE(CompareMatrices(position(), zero));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
EXPECT_EQ(time_output(), 0);
}
TEST_F(JacoCommandReceiverNoFingersTest,
AcceptanceTestWithoutMeasuredPositionInputNoFingers) {
// When no message has been received and *no* position measurement is
// connected, the command is all zeros.
const VectorXd zero = VectorXd::Zero(N);
EXPECT_TRUE(CompareMatrices(position(), zero));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
EXPECT_EQ(time_output(), 0);
}
TEST_F(JacoCommandReceiverNoFingersTest,
AcceptanceTestWithMeasuredPositionInputNoFingers) {
const VectorXd zero = VectorXd::Zero(N);
// When no message has been received and a measurement *is* connected, the
// command is to hold at the current position.
const VectorXd q0 = VectorXd::LinSpaced(N, 0.2, 0.3);
dut_.get_position_measured_input_port().FixValue(&context_, q0);
EXPECT_TRUE(CompareMatrices(position(), q0));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
EXPECT_EQ(time_output(), 0);
// Check that a real command trumps the initial position.
const VectorXd q1 = VectorXd::LinSpaced(N, 0.3, 0.4);
const VectorXd v1 = VectorXd::LinSpaced(N, 0.5, 0.6);
lcmt_jaco_command command{};
command.utime = kCommandTime * 1e6;
command.num_joints = N;
command.joint_position = {q1.data(), q1.data() + q1.size()};
command.joint_velocity = {v1.data(), v1.data() + v1.size()};
SetInput(command);
EXPECT_TRUE(CompareMatrices(position(), q1));
EXPECT_TRUE(CompareMatrices(velocity(), v1));
EXPECT_EQ(time_output(), kCommandTime);
}
TEST_F(JacoCommandReceiverNoFingersTest,
AcceptanceTestWithLatchingNoFingers) {
const VectorXd zero = VectorXd::Zero(N);
// When no message has been received and a measurement *is* connected, the
// command is to hold at the current position.
const VectorXd q0 = VectorXd::LinSpaced(N, 0.0, 0.1);
dut_.get_position_measured_input_port().FixValue(&context_, q0);
EXPECT_TRUE(CompareMatrices(position(), q0));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
EXPECT_EQ(time_output(), 0);
// Prior to any update events, changes to position_measured feed through.
const VectorXd q1 = VectorXd::LinSpaced(N, 0.1, 0.2);
dut_.get_position_measured_input_port().FixValue(&context_, q1);
EXPECT_TRUE(CompareMatrices(position(), q1));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
// Once an update event occurs, further changes to position_measured have no
// effect.
dut_.LatchInitialPosition(&context_);
const VectorXd q2 = VectorXd::LinSpaced(N, 0.3, 0.4);
dut_.get_position_measured_input_port().FixValue(&context_, q2);
EXPECT_TRUE(CompareMatrices(position(), q1));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
// Check that a real command trumps the initial position.
const VectorXd q3 = VectorXd::LinSpaced(N, 0.4, 0.5);
const VectorXd v3 = VectorXd::LinSpaced(N, 0.5, 0.6);
lcmt_jaco_command command{};
command.utime = kCommandTime * 1e6;
command.num_joints = N;
command.joint_position = {q3.data(), q3.data() + q3.size()};
command.joint_velocity = {v3.data(), v3.data() + v3.size()};
SetInput(command);
EXPECT_TRUE(CompareMatrices(position(), q3));
EXPECT_TRUE(CompareMatrices(velocity(), v3));
EXPECT_EQ(time_output(), kCommandTime);
}
TEST_F(JacoCommandReceiverTest,
AcceptanceTestWithMeasuredPositionInput) {
const VectorXd zero = VectorXd::Zero(N + N_F);
// When no message has been received and a measurement *is* connected, the
// command is to hold at the current position.
const VectorXd q0 = VectorXd::LinSpaced(N + N_F, 0.2, 0.3);
dut_.get_position_measured_input_port().FixValue(&context_, q0);
EXPECT_TRUE(CompareMatrices(position(), q0));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
EXPECT_EQ(time_output(), 0);
// Check that a real command trumps the initial position.
const VectorXd q1 = VectorXd::LinSpaced(N, 0.3, 0.4);
const VectorXd v1 = VectorXd::LinSpaced(N, 0.5, 0.6);
const VectorXd f_q1 = VectorXd::LinSpaced(N_F, 1.3, 1.4);
const VectorXd f_v1 = VectorXd::LinSpaced(N_F, 1.5, 1.6);
lcmt_jaco_command command{};
command.utime = kCommandTime * 1e6;
command.num_joints = N;
command.joint_position = {q1.data(), q1.data() + q1.size()};
command.joint_velocity = {v1.data(), v1.data() + v1.size()};
command.num_fingers = N_F;
command.finger_position = {f_q1.data(), f_q1.data() + f_q1.size()};
command.finger_velocity = {f_v1.data(), f_v1.data() + f_v1.size()};
SetInput(command);
VectorXd position_expected(N + N_F);
position_expected.head(N) = q1;
position_expected.tail(N_F) = f_q1 * kFingerSdkToUrdf;
VectorXd velocity_expected(N + N_F);
velocity_expected.head(N) = v1;
velocity_expected.tail(N_F) = f_v1 * kFingerSdkToUrdf;
EXPECT_TRUE(CompareMatrices(position(), position_expected));
EXPECT_TRUE(CompareMatrices(velocity(), velocity_expected));
EXPECT_EQ(time_output(), kCommandTime);
}
TEST_F(JacoCommandReceiverTest, AcceptanceTestWithLatching) {
const VectorXd zero = VectorXd::Zero(N + N_F);
// When no message has been received and a measurement *is* connected, the
// command is to hold at the current position.
const VectorXd q0 = VectorXd::LinSpaced(N + N_F, 0.0, 0.1);
dut_.get_position_measured_input_port().FixValue(&context_, q0);
EXPECT_TRUE(CompareMatrices(position(), q0));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
EXPECT_EQ(time_output(), 0);
// Prior to any update events, changes to position_measured feed through.
const VectorXd q1 = VectorXd::LinSpaced(N + N_F, 0.1, 0.2);
dut_.get_position_measured_input_port().FixValue(&context_, q1);
EXPECT_TRUE(CompareMatrices(position(), q1));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
// Once an update event occurs, further changes to position_measured have no
// effect.
dut_.LatchInitialPosition(&context_);
const VectorXd q2 = VectorXd::LinSpaced(N + N_F, 0.3, 0.4);
dut_.get_position_measured_input_port().FixValue(&context_, q2);
EXPECT_TRUE(CompareMatrices(position(), q1));
EXPECT_TRUE(CompareMatrices(velocity(), zero));
// Check that a real command trumps the initial position.
const VectorXd q3 = VectorXd::LinSpaced(N, 0.4, 0.5);
const VectorXd v3 = VectorXd::LinSpaced(N, 0.5, 0.6);
const VectorXd f_q3 = VectorXd::LinSpaced(N_F, 0.4, 0.5);
const VectorXd f_v3 = VectorXd::LinSpaced(N_F, 1.5, 1.6);
lcmt_jaco_command command{};
command.utime = kCommandTime * 1e6;
command.num_joints = N;
command.num_fingers = N_F;
command.joint_position = {q3.data(), q3.data() + q3.size()};
command.joint_velocity = {v3.data(), v3.data() + v3.size()};
command.finger_position = {f_q3.data(), f_q3.data() + f_q3.size()};
command.finger_velocity = {f_v3.data(), f_v3.data() + f_v3.size()};
SetInput(command);
VectorXd position_expected(N + N_F);
position_expected.head(N) = q3;
position_expected.tail(N_F) = f_q3 * kFingerSdkToUrdf;
VectorXd velocity_expected(N + N_F);
velocity_expected.head(N) = v3;
velocity_expected.tail(N_F) = f_v3 * kFingerSdkToUrdf;
EXPECT_TRUE(CompareMatrices(position(), position_expected));
EXPECT_TRUE(CompareMatrices(velocity(), velocity_expected));
EXPECT_EQ(time_output(), kCommandTime);
}
} // namespace
} // namespace kinova_jaco
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/util/robot_plan_interpolator.h | #pragma once
#include <memory>
#include <string>
#include <vector>
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace manipulation {
namespace util {
/// This enum specifies the type of interpolator to use in constructing
/// the piece-wise polynomial.
enum class InterpolatorType { ZeroOrderHold, FirstOrderHold, Pchip, Cubic };
/// This class implements a source of joint positions for a robot.
/// It has one input port for lcmt_robot_plan messages containing a
/// plan to follow.
///
/// The system has two output ports, one with the current desired
/// state (q,v) of the robot and another for the accelerations.
///
/// @system
/// name: RobotPlanInterpolator
/// input_ports:
/// - plan
/// output_ports:
/// - state
/// - acceleration
/// @endsystem
///
/// If a plan is received with no knot points, the system will create
/// a plan which commands the robot to hold at the measured position.
///
/// @ingroup manipulation_systems
class RobotPlanInterpolator : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RobotPlanInterpolator)
RobotPlanInterpolator(const std::string& model_path,
const InterpolatorType = InterpolatorType::Cubic,
double update_interval = kDefaultPlanUpdateInterval);
~RobotPlanInterpolator() override;
/// N.B. This input port is useless and may be left disconnected.
const systems::InputPort<double>& get_plan_input_port() const {
return this->get_input_port(plan_input_port_);
}
const systems::OutputPort<double>& get_state_output_port() const {
return this->get_output_port(state_output_port_);
}
const systems::OutputPort<double>& get_acceleration_output_port() const {
return this->get_output_port(acceleration_output_port_);
}
/**
* Makes a plan to hold at the measured joint configuration @p q0 starting at
* @p plan_start_time. This function needs to be explicitly called before any
* simulation. Otherwise this aborts in CalcOutput().
*/
void Initialize(double plan_start_time, const VectorX<double>& q0,
systems::State<double>* state) const;
/**
* Updates the plan if there is a new message on the input port.
* Normally this is done automatically by a Simulator; here we invoke
* the same periodic event handler that the Simulator would use.
*/
void UpdatePlan(systems::Context<double>* context) const {
UpdatePlanOnNewMessage(*context, &context->get_mutable_state());
}
const multibody::MultibodyPlant<double>& plant() { return plant_; }
private:
struct PlanData;
// Updates plan when a new message arrives.
systems::EventStatus UpdatePlanOnNewMessage(
const systems::Context<double>& context,
systems::State<double>* state) const;
// Calculator method for the state output port.
void OutputState(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
// Calculator method for the acceleration output port.
void OutputAccel(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
void MakeFixedPlan(double plan_start_time, const VectorX<double>& q0,
systems::State<double>* state) const;
static constexpr double kDefaultPlanUpdateInterval = 0.1;
const int plan_input_port_{};
int state_output_port_{-1};
int acceleration_output_port_{-1};
systems::AbstractStateIndex plan_index_;
systems::AbstractStateIndex init_flag_index_;
multibody::MultibodyPlant<double> plant_{0.0};
const InterpolatorType interp_type_;
};
} // namespace util
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/manipulation | /home/johnshepherd/drake/manipulation/util/zero_force_driver.h | #pragma once
#include "drake/common/drake_copyable.h"
#include "drake/common/name_value.h"
namespace drake {
namespace manipulation {
/** A driver that applies zero actuation to every joint of a model. Useful for
debugging and testing; useless in reality. No LCM channels are created. */
struct ZeroForceDriver {
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ZeroForceDriver)
ZeroForceDriver() = default;
// Currently there is no configuration here.
template <typename Archive>
void Serialize(Archive*) {}
};
} // namespace manipulation
} // namespace drake
| 0 |
Subsets and Splits