repo_id
stringclasses
205 values
file_path
stringlengths
33
141
content
stringlengths
1
307k
__index_level_0__
int64
0
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_tan_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Tan) { CHECK_UNARY_FUNCTION(tan, x, y, 0.1); CHECK_UNARY_FUNCTION(tan, x, y, -0.1); CHECK_UNARY_FUNCTION(tan, y, x, 0.1); CHECK_UNARY_FUNCTION(tan, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_addition_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Addition) { CHECK_BINARY_OP(+, x, y, 1.0); CHECK_BINARY_OP(+, x, y, -1.0); CHECK_BINARY_OP(+, y, x, 1.0); CHECK_BINARY_OP(+, y, x, -1.0); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/eigen_types_test.cc
#include "drake/common/eigen_types.h" #include <gtest/gtest.h> #include "drake/common/nice_type_name.h" #include "drake/common/test_utilities/expect_no_throw.h" using Eigen::MatrixXd; using Eigen::Matrix3d; using Eigen::VectorXd; using Eigen::Vector3d; using Eigen::ArrayXXd; using Eigen::Array33d; using Eigen::ArrayXd; using Eigen::Array3d; namespace drake { namespace { template <typename Derived> void CheckTraits(bool is_vector) { std::string info = "Type: " + NiceTypeName::Get<Derived>() + "\n"; EXPECT_TRUE(is_eigen_type<Derived>::value) << info; EXPECT_TRUE((is_eigen_scalar_same<Derived, double>::value)) << info; EXPECT_EQ(is_vector, (is_eigen_vector_of<Derived, double>::value)) << info; EXPECT_EQ(!is_vector, (is_eigen_nonvector_of<Derived, double>::value)) << info; } // Test traits within eigen_types.h GTEST_TEST(EigenTypesTest, TraitsPositive) { // MatrixBase<> CheckTraits<MatrixXd>(false); CheckTraits<Matrix3d>(false); CheckTraits<VectorXd>(true); CheckTraits<Vector3d>(true); // ArrayBase<> CheckTraits<ArrayXXd>(false); CheckTraits<Array33d>(false); CheckTraits<ArrayXd>(true); CheckTraits<Array3d>(true); } // SFINAE check. bool IsEigen(...) { return false; } template <typename T, typename Cond = typename std::enable_if_t< is_eigen_type<T>::value>> bool IsEigen(const T&) { return true; } // SFINAE check with edge case described below. bool IsEigenOfDouble(...) { return false; } template <typename T, typename Cond = typename std::enable_if_t< is_eigen_scalar_same<T, double>::value>> bool IsEigenOfDouble(const T&) { return true; } // Ensure that we do not capture non-eigen things. template <typename Derived> class NonEigenBase {}; class NonEigen : public NonEigenBase<NonEigen> { public: typedef double Scalar; }; GTEST_TEST(EigenTypesTest, TraitsSFINAE) { EXPECT_TRUE(IsEigen(MatrixXd())); EXPECT_TRUE(IsEigenOfDouble(MatrixXd())); EXPECT_TRUE(IsEigen(ArrayXXd())); EXPECT_TRUE(IsEigenOfDouble(ArrayXXd())); EXPECT_FALSE(IsEigen(NonEigen())); EXPECT_FALSE(IsEigenOfDouble(NonEigen())); EXPECT_FALSE(IsEigen(1)); // TODO(eric.cousineau): See if there is a way to short-circuit conditionals. // Presently, the following code will throw an error, even in SFINAE. // EXPECT_FALSE(IsEigenOfDouble(1)); // EXPECT_FALSE((is_eigen_vector_of<std::string, double>::value)); } GTEST_TEST(MapViewTest, CStyleArray) { double foo[3] = {}; EXPECT_EQ(EigenMapView(foo).rows(), 3); EXPECT_EQ(EigenMapView(foo).cols(), 1); EigenMapView(foo) = Vector3d::Constant(1.0); EXPECT_EQ(foo[1], 1.0); const double bar[3] = {1.0, 2.0, 3.0}; EXPECT_EQ(EigenMapView(bar).rows(), 3); EXPECT_EQ(EigenMapView(bar).cols(), 1); const Eigen::Vector3d quux = EigenMapView(bar); EXPECT_EQ(quux[1], 2.0); } GTEST_TEST(MapViewTest, StdArray) { std::array<double, 3> foo = {}; EigenMapView(foo) = Vector3d::Constant(1.0); EXPECT_EQ(foo[1], 1.0); const std::array<double, 3> bar = {1.0, 2.0, 3.0}; const Eigen::Vector3d quux = EigenMapView(bar); EXPECT_EQ(quux[1], 2.0); } GTEST_TEST(MapViewTest, StdVector) { std::vector<double> foo; EXPECT_EQ(EigenMapView(foo).size(), 0); foo.resize(3); EXPECT_EQ(EigenMapView(foo).rows(), 3); EXPECT_EQ(EigenMapView(foo).cols(), 1); EigenMapView(foo) = Vector3d::Constant(1.0); EXPECT_EQ(foo[1], 1.0); const std::vector<double> bar = {1.0, 2.0, 3.0}; EXPECT_EQ(EigenMapView(bar).rows(), 3); EXPECT_EQ(EigenMapView(bar).cols(), 1); const Eigen::Vector3d quux = EigenMapView(bar); EXPECT_EQ(quux[1], 2.0); } GTEST_TEST(EigenTypesTest, EigenPtr_Null) { EigenPtr<const Matrix3d> null_ptr = nullptr; EXPECT_FALSE(null_ptr); EXPECT_FALSE(null_ptr != nullptr); EXPECT_TRUE(!null_ptr); EXPECT_TRUE(null_ptr == nullptr); Matrix3d X; X.setConstant(0); EigenPtr<const Matrix3d> ptr = &X; EXPECT_TRUE(ptr); EXPECT_TRUE(ptr != nullptr); EXPECT_FALSE(!ptr); EXPECT_FALSE(ptr == nullptr); DRAKE_EXPECT_NO_THROW(*ptr); } bool ptr_optional_arg(EigenPtr<MatrixXd> arg = nullptr) { return arg; } GTEST_TEST(EigenTypesTest, EigenPtr_OptionalArg) { EXPECT_FALSE(ptr_optional_arg()); MatrixXd X(0, 0); EXPECT_TRUE(ptr_optional_arg(&X)); } // Sets M(i, j) = c. void set(EigenPtr<MatrixXd> M, const int i, const int j, const double c) { (*M)(i, j) = c; } // Returns M(i, j). double get(const EigenPtr<const MatrixXd> M, const int i, const int j) { return M->coeff(i, j); } GTEST_TEST(EigenTypesTest, EigenPtr) { Eigen::MatrixXd M1 = Eigen::MatrixXd::Zero(3, 3); const Eigen::MatrixXd M2 = Eigen::MatrixXd::Zero(3, 3); // Tests set. set(&M1, 0, 0, 1); // Sets M1(0,0) = 1 EXPECT_EQ(M1(0, 0), 1); // Checks M1(0, 0) = 1 // Tests get. EXPECT_EQ(get(&M1, 0, 0), 1); // Checks M1(0, 0) = 1 EXPECT_EQ(get(&M2, 0, 0), 0); // Checks M2(0, 0) = 1 // Shows how to use EigenPtr with .block(). Here we introduce `tmp` to avoid // taking the address of temporary object. auto tmp = M1.block(1, 1, 2, 2); set(&tmp, 0, 0, 1); // tmp(0, 0) = 1. That is, M1(1, 1) = 1. EXPECT_EQ(get(&M1, 1, 1), 1); } GTEST_TEST(EigenTypesTest, EigenPtr_EigenRef) { Eigen::MatrixXd M = Eigen::MatrixXd::Zero(3, 3); Eigen::Ref<Eigen::MatrixXd> M_ref(M); // Tests set. set(&M_ref, 0, 0, 1); // Sets M(0,0) = 1 EXPECT_EQ(M_ref(0, 0), 1); // Checks M(0, 0) = 1 // Tests get. EXPECT_EQ(get(&M_ref, 0, 0), 1); // Checks M(0, 0) = 1 } // EigenPtr_MixMatrixTypes1 and EigenPtr_MixMatrixTypes2 tests check if we can // mix static-size and dynamic-size matrices with EigenPtr. They only check if // the code compiles. There are no runtime assertions. GTEST_TEST(EigenTypesTest, EigenPtr_MixMatrixTypes1) { MatrixXd M(3, 3); Eigen::Ref<Matrix3d> M_ref(M); // MatrixXd -> Ref<Matrix3d> EigenPtr<Matrix3d> M_ptr(&M); // MatrixXd -> EigenPtr<Matrix3d> EigenPtr<MatrixXd> M_ptr_ref(&M_ref); // Ref<Matrix3d> -> EigenPtr<MatrixXd> EigenPtr<MatrixXd> M_ptr_ref2(M_ptr); // EigenPtr<MatrixXd> -> // EigenPtr<Matrix3d> } GTEST_TEST(EigenTypesTest, EigenPtr_MixMatrixTypes2) { Matrix3d M; Eigen::Ref<MatrixXd> M_ref(M); // Matrix3d -> Ref<MatrixXd> EigenPtr<MatrixXd> M_ptr(&M); // Matrix3d -> EigenPtr<MatrixXd> EigenPtr<Matrix3d> M_ptr_ref(&M_ref); // Ref<MatrixXd> -> EigenPtr<Matrix3d> EigenPtr<Matrix3d> M_ptr_ref2(M_ptr); // EigenPtr<Matrix3d> -> // EigenPtr<MatrixXd> } GTEST_TEST(EigenTypesTest, EigenPtr_Assignment) { const double a = 1; const double b = 2; Matrix3d A; A.setConstant(a); MatrixXd B(3, 3); B.setConstant(b); // Ensure that we can use const pointers. EigenPtr<const Matrix3d> const_ptr = &A; EXPECT_TRUE((const_ptr->array() == a).all()); const_ptr = &B; EXPECT_TRUE((const_ptr->array() == b).all()); // Test mutable pointers. EigenPtr<Matrix3d> mutable_ptr = &A; EXPECT_TRUE((mutable_ptr->array() == a).all()); mutable_ptr = &B; EXPECT_TRUE((mutable_ptr->array() == b).all()); // Ensure we have changed neither A nor B. EXPECT_TRUE((A.array() == a).all()); EXPECT_TRUE((B.array() == b).all()); // Ensure that we can assign nullptr. const_ptr = nullptr; EXPECT_FALSE(const_ptr); mutable_ptr = nullptr; EXPECT_FALSE(mutable_ptr); } GTEST_TEST(EigenTypesTest, FixedSizeVector) { Vector<double, 2> col; EXPECT_EQ(col.rows(), 2); EXPECT_EQ(col.cols(), 1); RowVector<double, 2> row; EXPECT_EQ(row.rows(), 1); EXPECT_EQ(row.cols(), 2); } GTEST_TEST(EigenTypesTest, LikewiseStorageOrder) { using LikewiseCol = MatrixLikewise<float, Vector3<double>>; using LikewiseRow = MatrixLikewise<float, RowVector3<double>>; EXPECT_EQ(static_cast<int>(LikewiseCol::Options) & Eigen::ColMajor, Eigen::ColMajor); EXPECT_EQ(static_cast<int>(LikewiseRow::Options) & Eigen::RowMajor, Eigen::RowMajor); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/find_cache_test.cc
#include "drake/common/find_cache.h" #include <cstdlib> #include <filesystem> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/temp_directory.h" namespace drake { namespace internal { namespace { namespace fs = std::filesystem; /* RAII to temporarily change an environment variable. */ class SetEnv { public: SetEnv(const std::string& var_name, std::optional<std::string> var_value) : var_name_(var_name) { const char* orig = std::getenv(var_name.c_str()); if (orig != nullptr) { orig_value_ = orig; } if (var_value.has_value()) { ::setenv(var_name.c_str(), var_value->c_str(), 1); } else { ::unsetenv(var_name.c_str()); } } ~SetEnv() { if (orig_value_.has_value()) { ::setenv(var_name_.c_str(), orig_value_->c_str(), 1); } else { ::unsetenv(var_name_.c_str()); } } private: std::string var_name_; std::optional<std::string> orig_value_; }; // Check the TEST_TMPDIR case. GTEST_TEST(FindCacheTest, TestTmpdir) { // Deny attempts to run this as `bazel-bin/...`; always use `bazel test`. DRAKE_DEMAND(std::getenv("TEST_TMPDIR") != nullptr); // Check the DUT. const PathOrError result = FindOrCreateCache("foo"); ASSERT_EQ(result.error, ""); EXPECT_TRUE(fs::exists(result.abspath)); const fs::path expected = fs::path(std::getenv("TEST_TMPDIR")) / ".cache" / "drake" / "foo"; EXPECT_EQ(result.abspath, expected); } // Check the XDG_CACHE_HOME case. GTEST_TEST(FindCacheTest, XdgCacheHome) { // Prepare the environment. const std::string xdg = temp_directory(); const SetEnv env1("TEST_TMPDIR", std::nullopt); const SetEnv env2("XDG_CACHE_HOME", xdg); // Check the DUT. const PathOrError result = FindOrCreateCache("bar"); ASSERT_EQ(result.error, ""); EXPECT_TRUE(fs::exists(result.abspath)); const fs::path expected = fs::path(xdg) / "drake" / "bar"; EXPECT_EQ(result.abspath, expected); } // Check the HOME case. GTEST_TEST(FindCacheTest, Home) { // Prepare the environment. const std::string home = temp_directory(); const SetEnv env1("TEST_TMPDIR", std::nullopt); const SetEnv env2("USER", std::nullopt); const SetEnv env3("HOME", home); // Check the DUT. const PathOrError result = FindOrCreateCache("baz"); ASSERT_EQ(result.error, ""); EXPECT_TRUE(fs::exists(result.abspath)); const fs::path expected = fs::path(home) / ".cache" / "drake" / "baz"; EXPECT_EQ(result.abspath, expected); } // When the cache directory is read-only, we get a reasonable error. GTEST_TEST(FindCacheTest, ReadOnlyCache) { // Prepare the environment. const std::string xdg = temp_directory(); const SetEnv env1("TEST_TMPDIR", std::nullopt); const SetEnv env2("XDG_CACHE_HOME", xdg); // Remove all permissions. fs::permissions(xdg, fs::perms{}); // Expect a failure. const PathOrError result = FindOrCreateCache("bar"); EXPECT_EQ(result.abspath.string(), ""); EXPECT_THAT(result.error, testing::MatchesRegex(".*not create.*drake.*")); } } // namespace } // namespace internal } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/eigen_autodiff_types_test.cc
#include <gtest/gtest.h> #include "drake/common/autodiff.h" namespace drake { namespace { GTEST_TEST(EigenAutodiffTypesTest, CheckingInheritance) { typedef double Scalar; typedef Eigen::Matrix<Scalar, 2, 2> Deriv; typedef Eigen::AutoDiffScalar<Deriv> AD; typedef std::numeric_limits<AD> ADLimits; typedef std::numeric_limits<Scalar> ScalarLimits; bool res = std::is_base_of_v<ScalarLimits, ADLimits>; EXPECT_TRUE(res); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/is_less_than_comparable_test.cc
#include "drake/common/is_less_than_comparable.h" #include <gtest/gtest.h> namespace drake { namespace { // Dummy operator< for checking is_less_than_comparable(). struct Z {}; bool operator<(const Z&, const Z&) { return true; } // Verifies that this class is comparable using the less than operator. GTEST_TEST(LessThanComparable, RunTime) { // Necessary to work around a Clang error. const Z z; operator<(z, z); struct X {}; struct Y { bool operator<(const Y&) const { return true; } }; EXPECT_TRUE(drake::is_less_than_comparable<int>::value); EXPECT_TRUE(drake::is_less_than_comparable<Y>::value); EXPECT_FALSE(drake::is_less_than_comparable<X>::value); EXPECT_TRUE(drake::is_less_than_comparable<Z>::value); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/is_approx_equal_abstol_test.cc
#include "drake/common/is_approx_equal_abstol.h" #include <Eigen/Dense> #include <gtest/gtest.h> using Eigen::MatrixXd; using Eigen::VectorXd; namespace drake { namespace { GTEST_TEST(IsApproxEqualMatrixTest, BasicTest) { const VectorXd ones1 = VectorXd::Ones(1); const VectorXd ones2 = VectorXd::Ones(2); const MatrixXd id22 = MatrixXd::Identity(2, 2); const MatrixXd id33 = MatrixXd::Identity(3, 3); const double lit_nudge = 1e-12; const double big_nudge = 1e-4; const VectorXd ones1_lit = ones1 + VectorXd::Constant(1, lit_nudge); const VectorXd ones1_big = ones1 + VectorXd::Constant(1, big_nudge); const VectorXd ones2_lit = ones2 + VectorXd::Constant(2, lit_nudge); const VectorXd ones2_big = ones2 + VectorXd::Constant(2, big_nudge); const MatrixXd id22_lit = id22 + MatrixXd::Constant(2, 2, lit_nudge); const MatrixXd id22_big = id22 + MatrixXd::Constant(2, 2, big_nudge); const MatrixXd id33_lit = id33 + MatrixXd::Constant(3, 3, lit_nudge); const MatrixXd id33_big = id33 + MatrixXd::Constant(3, 3, big_nudge); // Compare same-size matrices, within tolerances. const double tolerance = 1e-8; EXPECT_TRUE(is_approx_equal_abstol(ones1, ones1, tolerance)); EXPECT_TRUE(is_approx_equal_abstol(ones1, ones1_lit, tolerance)); EXPECT_FALSE(is_approx_equal_abstol(ones1, ones1_big, tolerance)); EXPECT_TRUE(is_approx_equal_abstol(ones2, ones2, tolerance)); EXPECT_TRUE(is_approx_equal_abstol(ones2, ones2_lit, tolerance)); EXPECT_FALSE(is_approx_equal_abstol(ones2, ones2_big, tolerance)); EXPECT_TRUE(is_approx_equal_abstol(id22, id22, tolerance)); EXPECT_TRUE(is_approx_equal_abstol(id22, id22_lit, tolerance)); EXPECT_FALSE(is_approx_equal_abstol(id22, id22_big, tolerance)); EXPECT_TRUE(is_approx_equal_abstol(id33, id33, tolerance)); EXPECT_TRUE(is_approx_equal_abstol(id33, id33_lit, tolerance)); EXPECT_FALSE(is_approx_equal_abstol(id33, id33_big, tolerance)); // Compare different-size matrices. EXPECT_FALSE(is_approx_equal_abstol(ones1, ones2, tolerance)); EXPECT_FALSE(is_approx_equal_abstol(id22, id33, tolerance)); // Special values do not compare equal. const double inf = std::numeric_limits<double>::infinity(); const VectorXd inf2 = VectorXd::Constant(2, inf); EXPECT_FALSE(is_approx_equal_abstol(inf2, inf2, tolerance)); EXPECT_FALSE(is_approx_equal_abstol(inf2, ones2, tolerance)); const double nan = std::numeric_limits<double>::quiet_NaN(); const VectorXd nan2 = VectorXd::Constant(2, nan); EXPECT_FALSE(is_approx_equal_abstol(nan2, nan2, tolerance)); EXPECT_FALSE(is_approx_equal_abstol(nan2, inf2, tolerance)); EXPECT_FALSE(is_approx_equal_abstol(nan2, ones2, tolerance)); } GTEST_TEST(IsApproxEqualAbstolPermutationTest, PermutationTest) { MatrixXd test(2, 3); // clang-format off test << 1, 2, 3, 4, 5, 6; // clang-format on const double tol = 1e-8; EXPECT_TRUE(IsApproxEqualAbsTolWithPermutedColumns(test, test, tol)); EXPECT_FALSE( IsApproxEqualAbsTolWithPermutedColumns(test, test.leftCols<2>(), tol)); EXPECT_FALSE( IsApproxEqualAbsTolWithPermutedColumns(test.leftCols<2>(), test, tol)); MatrixXd test2(2, 3); // Switch cols 2 and 3. // clang-format off test2 << 1, 3, 2, 4, 6, 5; // clang-format on EXPECT_TRUE(IsApproxEqualAbsTolWithPermutedColumns(test, test2, tol)); // All columns in test2 are in test1, but one is repeated. // clang-format off test2 << 1, 1, 2, 4, 4, 5; // clang-format on EXPECT_FALSE(IsApproxEqualAbsTolWithPermutedColumns(test, test2, tol)); EXPECT_FALSE(IsApproxEqualAbsTolWithPermutedColumns(test2, test, tol)); // Matching but with one duplicated columns. test2.resize(2, 4); // clang-format off test2 << 1, 1, 2, 3, 4, 4, 5, 6; // clang-format on EXPECT_FALSE(IsApproxEqualAbsTolWithPermutedColumns(test, test2, tol)); EXPECT_FALSE(IsApproxEqualAbsTolWithPermutedColumns(test2, test, tol)); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/reset_on_copy_test.cc
#include "drake/common/reset_on_copy.h" #include <utility> #include <gtest/gtest.h> #include "drake/common/drake_copyable.h" namespace drake { namespace { // A function that helps force an implicit conversion operator to int; without // it, EXPECT_EQ is underspecified whether we are unwrapping the first argument // or converting the second. int ForceInt(int value) { return value; } // The example from the documentation, fleshed out a little. class Foo { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Foo) Foo() : items_{1, 2, 3}, use_count_{25} {} const std::vector<int>& items() const { return items_; } int use_count() const { return use_count_; } private: std::vector<int> items_; reset_on_copy<int> use_count_; }; GTEST_TEST(ResetOnCopyTest, Constructor) { EXPECT_EQ(reset_on_copy<int>(), 0); EXPECT_EQ(reset_on_copy<int>(1), 1); } GTEST_TEST(ResetOnCopyTest, Nothrow) { // Default constructor. EXPECT_TRUE(noexcept(reset_on_copy<int>())); EXPECT_TRUE(noexcept(reset_on_copy<Foo*>())); // Initialize-from-lvalue constructor. int i{}; Foo foo{}; Foo* foo_ptr{}; EXPECT_TRUE(noexcept(reset_on_copy<int>{i})); EXPECT_TRUE(noexcept(reset_on_copy<Foo*>{foo_ptr})); // Initialize-from-rvalue constructor. EXPECT_TRUE(noexcept(reset_on_copy<int>{5})); EXPECT_TRUE(noexcept(reset_on_copy<Foo*>{&foo})); // Copy constructor & assignment (source must be lvalue). reset_on_copy<int> r_int, r_int2; reset_on_copy<Foo*> r_foo_ptr, r_foo_ptr2; EXPECT_TRUE(noexcept(reset_on_copy<int>{r_int})); EXPECT_TRUE(noexcept(reset_on_copy<Foo*>{r_foo_ptr})); EXPECT_TRUE(noexcept(r_int = r_int2)); EXPECT_TRUE(noexcept(r_foo_ptr = r_foo_ptr2)); // Move constructor & assignment. EXPECT_TRUE(noexcept(reset_on_copy<int>{std::move(r_int)})); EXPECT_TRUE(noexcept(reset_on_copy<Foo*>{std::move(r_foo_ptr)})); EXPECT_TRUE(noexcept(r_int = std::move(r_int2))); EXPECT_TRUE(noexcept(r_foo_ptr = std::move(r_foo_ptr2))); } GTEST_TEST(ResetOnCopyTest, Access) { // Assignment from a RHS of int (versus reset_on_copy<int>). reset_on_copy<int> x; x = 1; // Conversion operator, non-const value. EXPECT_EQ(x, 1); EXPECT_EQ(ForceInt(x), 1); // Conversion operator, const. const reset_on_copy<int>& x_cref = x; EXPECT_EQ(x_cref, 1); EXPECT_EQ(ForceInt(x_cref), 1); // Conversion operator, non-const reference. int& x_value_ref = x; EXPECT_EQ(x_value_ref, 1); EXPECT_EQ(ForceInt(x_value_ref), 1); // All values work okay. x = 2; EXPECT_EQ(x, 2); EXPECT_EQ(ForceInt(x), 2); EXPECT_EQ(x_cref, 2); EXPECT_EQ(ForceInt(x_cref), 2); EXPECT_EQ(x_value_ref, 2); EXPECT_EQ(ForceInt(x_value_ref), 2); } GTEST_TEST(ResetOnCopyTest, Pointers) { int i = 5; reset_on_copy<int*> i_ptr{&i}; reset_on_copy<const int*> i_cptr{&i}; EXPECT_EQ(*i_ptr, 5); EXPECT_EQ(*i_cptr, 5); *i_ptr = 6; EXPECT_EQ(*i_ptr, 6); EXPECT_EQ(*i_cptr, 6); reset_on_copy<int*> i_ptr2(i_ptr); reset_on_copy<const int*> i_cptr2(i_cptr); EXPECT_EQ(i_ptr2, nullptr); EXPECT_EQ(i_cptr2, nullptr); Foo my_foo; reset_on_copy<Foo*> my_foo_ptr{&my_foo}; EXPECT_EQ(my_foo_ptr, &my_foo); // Make sure there's no cloning happening. EXPECT_EQ(&*my_foo_ptr, &my_foo); EXPECT_EQ(my_foo_ptr->use_count(), 25); EXPECT_EQ((*my_foo_ptr).use_count(), 25); // Moving should preserve the pointer and nuke the old one. reset_on_copy<Foo*> moved{std::move(my_foo_ptr)}; EXPECT_EQ(moved, &my_foo); EXPECT_EQ(my_foo_ptr, nullptr); } // Copy construction and assignment should ignore the source and // value-initialize the destinatation, except for self-assign which should // do nothing. GTEST_TEST(ResetOnCopyTest, Copy) { reset_on_copy<int> x{1}; EXPECT_EQ(x, 1); // Copy-construction (from non-const reference) and lack of aliasing. reset_on_copy<int> y{x}; EXPECT_EQ(x, 1); EXPECT_EQ(y, 0); // Copy-construction (from const reference) and lack of aliasing. const reset_on_copy<int>& x_cref = x; reset_on_copy<int> z{x_cref}; x = 3; EXPECT_EQ(x, 3); EXPECT_EQ(z, 0); // Copy-assignment and lack of aliasing. reset_on_copy<int> w{22}; EXPECT_EQ(w, 22); w = x; EXPECT_EQ(x, 3); EXPECT_EQ(w, 0); // reset, not reinitialized to 22! w = 4; EXPECT_EQ(x, 3); EXPECT_EQ(w, 4); // Self copy assignment preserves value. auto const& other = w; w = other; EXPECT_EQ(w, 4); // Make sure the example works. Foo source; Foo copy(source); EXPECT_EQ(source.items().size(), 3); EXPECT_EQ(copy.items().size(), 3); for (size_t i=0; i < 3; ++i) { EXPECT_EQ(source.items()[i], i + 1); EXPECT_EQ(copy.items()[i], i + 1); } EXPECT_EQ(source.use_count(), 25); EXPECT_EQ(copy.use_count(), 0); } // We need to indirect self-move-assign through this function; doing it // directly in the test code generates a compiler warning. void MoveAssign(reset_on_copy<int>* target, reset_on_copy<int>* donor) { *target = std::move(*donor); } // Move construction and assignment should preserve the current value in the // destination, and reset the source to be value-initialized. However, // self-move assign should do nothing. GTEST_TEST(ResetOnCopyTest, Move) { reset_on_copy<int> x{1}; EXPECT_EQ(x, 1); // Move-construction and lack of aliasing. reset_on_copy<int> y{std::move(x)}; EXPECT_EQ(x, 0); EXPECT_EQ(y, 1); x = 2; EXPECT_EQ(x, 2); EXPECT_EQ(y, 1); // Second move-construction and lack of aliasing. reset_on_copy<int> z{std::move(x)}; EXPECT_EQ(x, 0); EXPECT_EQ(y, 1); EXPECT_EQ(z, 2); // Move-assignment and lack of aliasing. reset_on_copy<int> w{22}; EXPECT_EQ(w, 22); x = 3; w = std::move(x); EXPECT_EQ(x, 0); EXPECT_EQ(y, 1); EXPECT_EQ(z, 2); EXPECT_EQ(w, 3); x = 4; EXPECT_EQ(x, 4); EXPECT_EQ(y, 1); EXPECT_EQ(z, 2); EXPECT_EQ(w, 3); // Self-assignment during move. MoveAssign(&w, &w); EXPECT_EQ(w, 3); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_sin_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Sin) { CHECK_UNARY_FUNCTION(sin, x, y, 0.1); CHECK_UNARY_FUNCTION(sin, x, y, -0.1); CHECK_UNARY_FUNCTION(sin, y, x, 0.1); CHECK_UNARY_FUNCTION(sin, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/scalar_casting_test.cc
/* Shows implicit / explicit casting behaviors for scalar types. */ #include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/extract_double.h" #include "drake/common/symbolic/expression.h" namespace drake { namespace { using symbolic::Expression; GTEST_TEST(ScalarCastingTest, Casting) { // From double. const AutoDiffXd ad = 1.0; EXPECT_EQ(ad, 1.0); const Expression sym = 1.0; EXPECT_EQ(sym, 1.0); // To double. // const double ad_to_double = ad; // Compile error. const double ad_to_double = ExtractDoubleOrThrow(ad); EXPECT_EQ(ad_to_double, 1.0); // const double sym_to_double = sym; // Compile error. const double sym_to_double = ExtractDoubleOrThrow(sym); EXPECT_EQ(sym_to_double, 1.0); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/openmp_test.cc
#include <numeric> #include <unordered_set> #include <gmock/gmock.h> #include <gtest/gtest.h> #if defined(_OPENMP) #include <omp.h> #endif #include "drake/common/text_logging.h" namespace drake { namespace { #if defined(_OPENMP) constexpr bool kHasOpenmp = true; #else constexpr bool kHasOpenmp = false; // TODO(jwnimmer-tri) This should be a Drake helper function wrapper that // abstracts away this difference. The openmp_helpers.hpp wrapper from // common_robotics_utilities is a likely candidate to delegate to, or at // least take as inspiration. int omp_get_thread_num() { return 0; } #endif // Mostly, this just checks for compilation failures. GTEST_TEST(OpenmpTest, ParallelFor) { drake::log()->info("Using kHasOpenmp = {}", kHasOpenmp); // Allocate storage for one integer result per loop. constexpr int num_outputs = 100; std::vector<int> outputs(static_cast<size_t>(num_outputs), 0); // Populate the storage, in parallel. #if defined(_OPENMP) #pragma omp parallel for #endif for (int i = 0; i < num_outputs; ++i) { outputs[i] = omp_get_thread_num(); } // Our BUILD rule will run this program with a maximum of two threads. // Confirm how many threads were used and that their thread numbers were the // expected set of either {0, 1} (with OpenMP) or {0} (without OpenMP). std::unordered_set<int> thread_nums(outputs.begin(), outputs.end()); if (kHasOpenmp) { EXPECT_THAT(thread_nums, testing::UnorderedElementsAre(0, 1)); } else { EXPECT_THAT(thread_nums, testing::UnorderedElementsAre(0)); } } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/text_logging_ostream_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/text_logging.h" /* clang-format on */ #include <ostream> #include <sstream> #include <gmock/gmock.h> #include <gtest/gtest.h> // The BUILD.bazel rules must supply this flag. This test code is compiled and // run twice -- once with spdlog, and once without. #ifndef TEXT_LOGGING_TEST_SPDLOG #error Missing a required definition to compile this test case. #endif // Check for the expected HAVE_SPDLOG value. #if TEXT_LOGGING_TEST_SPDLOG #ifndef HAVE_SPDLOG #error Missing HAVE_SPDLOG. #endif #else #ifdef HAVE_SPDLOG #error Unwanted HAVE_SPDLOG. #endif #endif #ifdef HAVE_SPDLOG #include <spdlog/sinks/dist_sink.h> #include <spdlog/sinks/ostream_sink.h> #endif // HAVE_SPDLOG #include "drake/common/fmt_ostream.h" namespace { class Streamable { [[maybe_unused]] // If we don't have spdlog, this function is dead code. friend std::ostream& operator<<(std::ostream& os, const Streamable& c) { return os << "OK"; } }; using drake::fmt_streamed; // Call each API function and macro to ensure that all of them compile. // These should all compile and run both with and without spdlog. GTEST_TEST(TextLoggingTest, SmokeTestStreamable) { Streamable obj; drake::log()->trace("drake::log()->trace test: {} {}", "OK", fmt_streamed(obj)); drake::log()->debug("drake::log()->debug test: {} {}", "OK", fmt_streamed(obj)); drake::log()->info("drake::log()->info test: {} {}", "OK", fmt_streamed(obj)); drake::log()->warn("drake::log()->warn test: {} {}", "OK", fmt_streamed(obj)); drake::log()->error("drake::log()->error test: {} {}", "OK", fmt_streamed(obj)); drake::log()->critical("drake::log()->critical test: {} {}", "OK", fmt_streamed(obj)); DRAKE_LOGGER_TRACE("DRAKE_LOGGER_TRACE macro test: {}, {}", "OK", fmt_streamed(obj)); DRAKE_LOGGER_DEBUG("DRAKE_LOGGER_DEBUG macro test: {}, {}", "OK", fmt_streamed(obj)); } // We must run this test last because it changes the default configuration. GTEST_TEST(TextLoggingTest, ZZZ_ChangeDefaultSink) { // The getter should never return nullptr, even with spdlog disabled. drake::logging::sink* const sink_base = drake::logging::get_dist_sink(); ASSERT_NE(sink_base, nullptr); // The remainder of the test case only makes sense when spdlog is enabled. #if TEXT_LOGGING_TEST_SPDLOG // Our API promises that the result always has this subtype. auto* const sink = dynamic_cast<spdlog::sinks::dist_sink_mt*>(sink_base); ASSERT_NE(sink, nullptr); // Redirect all logs to a memory stream. std::ostringstream messages; auto custom_sink = std::make_shared<spdlog::sinks::ostream_sink_st>( messages, true /* flush */); sink->set_sinks({custom_sink}); drake::log()->info("This is some good info!"); EXPECT_THAT(messages.str(), testing::EndsWith( "[console] [info] This is some good info!\n")); #endif } } // namespace // To enable compiling without depending on @spdlog, we need to provide our own // main routine. The default drake_cc_googletest_main depends on @spdlog. int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/drake_copyable_test.cc
#include "drake/common/drake_copyable.h" #include <utility> #include <gtest/gtest.h> #include "drake/common/unused.h" namespace drake { namespace { // When a class has a user-defined destructor, the implicit generation of the // copy constructor and copy-assignment operator is deprecated as of C++11. // // Under Drake's Clang configuration, relying on the deprecated operator // produces an error under -Werror=deprecated. // // Therefore, if DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN failed to default those // operations, then this unit test would no longer compile (under Clang). class ExampleDefault { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ExampleDefault); ExampleDefault() = default; ~ExampleDefault() = default; }; GTEST_TEST(DrakeCopyableTest, DefaultCopyConstruct) { ExampleDefault foo; ExampleDefault bar(foo); unused(bar); } GTEST_TEST(DrakeCopyableTest, DefaultCopyAssign) { ExampleDefault foo, bar; bar = foo; unused(bar); } GTEST_TEST(DrakeCopyableTest, DefaultMoveConstruct) { ExampleDefault foo; ExampleDefault bar(std::move(foo)); unused(bar); } GTEST_TEST(DrakeCopyableTest, DefaultMoveAssign) { ExampleDefault foo, bar; bar = std::move(foo); unused(bar); } // Confirm that private (and by association, protected) access for this macro // is permitted. If not, this class would fail to compile. class ExampleDefaultPrivate { private: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ExampleDefaultPrivate); }; // When we can't use the default implementations, but are still able to provide // the same functionality with custom implementations, // DRAKE_DECLARE_COPY_AND_MOVE_AND_ASSIGN is used instead to provide uniform // declarations and documentation. We're just checking here that it provides // the right declarations. class ExampleDeclare { public: DRAKE_DECLARE_COPY_AND_MOVE_AND_ASSIGN(ExampleDeclare); ExampleDeclare() = default; ~ExampleDeclare() = default; }; ExampleDeclare::ExampleDeclare(const ExampleDeclare&) {} ExampleDeclare& ExampleDeclare::operator=(const ExampleDeclare&) { return *this; } ExampleDeclare::ExampleDeclare(ExampleDeclare&&) {} ExampleDeclare& ExampleDeclare::operator=(ExampleDeclare&&) { return *this; } GTEST_TEST(DrakeCopyableTest, DeclareCopyConstruct) { ExampleDeclare foo; ExampleDeclare bar(foo); unused(bar); } GTEST_TEST(DrakeCopyableTest, DeclareCopyAssign) { ExampleDeclare foo, bar; bar = foo; unused(bar); } GTEST_TEST(DrakeCopyableTest, DeclareMoveConstruct) { ExampleDeclare foo; ExampleDeclare bar(std::move(foo)); unused(bar); } GTEST_TEST(DrakeCopyableTest, DeclareMoveAssign) { ExampleDeclare foo, bar; bar = std::move(foo); unused(bar); } // Confirm that private (and by association, protected) access for this macro // is permitted. If not, this class would fail to compile. class ExampleDeclarePrivate { private: DRAKE_DECLARE_COPY_AND_MOVE_AND_ASSIGN(ExampleDeclarePrivate); }; } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/diagnostic_policy_test.cc
#include "drake/common/diagnostic_policy.h" #include <vector> #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" namespace drake { namespace internal { namespace { GTEST_TEST(DiagnosticPolicyTest, DetailTest) { DiagnosticDetail detail; detail.message = "hey"; EXPECT_EQ(detail.Format("meh"), "meh: hey"); EXPECT_EQ(detail.FormatWarning(), "warning: hey"); EXPECT_EQ(detail.FormatError(), "error: hey"); detail.filename = "something.txt"; EXPECT_EQ(detail.Format("meh"), "something.txt: meh: hey"); EXPECT_EQ(detail.FormatWarning(), "something.txt: warning: hey"); EXPECT_EQ(detail.FormatError(), "something.txt: error: hey"); detail.line = 22; EXPECT_EQ(detail.Format("meh"), "something.txt:22: meh: hey"); EXPECT_EQ(detail.FormatWarning(), "something.txt:22: warning: hey"); EXPECT_EQ(detail.FormatError(), "something.txt:22: error: hey"); } GTEST_TEST(DiagnosticPolicyTest, WarningDefaultAction) { DiagnosticPolicy dut; DiagnosticDetail detail{"a.txt", 22, "well"}; // Warnings, by default, do not throw. // An untested side-effect is that a message is logged; verify manually. EXPECT_NO_THROW(dut.WarningDefaultAction(detail)); } GTEST_TEST(DiagnosticPolicyTest, ErrorDefaultAction) { DiagnosticPolicy dut; DiagnosticDetail detail{"a.txt", 22, "well"}; // Errors, by default, throw. DRAKE_EXPECT_THROWS_MESSAGE(dut.ErrorDefaultAction(detail), "a.txt:22: error: well"); } GTEST_TEST(DiagnosticPolicyTest, SetActionForWarnings) { DiagnosticPolicy dut; DiagnosticDetail detail{"a.txt", 22, "well"}; std::vector<DiagnosticDetail> details; auto warning_action = [&details](const DiagnosticDetail& d) { details.push_back(d); }; dut.SetActionForWarnings(warning_action); // Errors are unchanged; they still throw. EXPECT_THROW(dut.Error("ouch"), std::exception); EXPECT_THROW(dut.Error(detail), std::exception); // Warnings just increment the count. EXPECT_EQ(details.size(), 0); dut.Warning("ahem"); EXPECT_EQ(details.size(), 1); EXPECT_FALSE(details.back().filename.has_value()); EXPECT_FALSE(details.back().line.has_value()); EXPECT_EQ(details.back().message, "ahem"); dut.Warning(detail); EXPECT_EQ(details.size(), 2); EXPECT_EQ(*details.back().filename, "a.txt"); EXPECT_EQ(*details.back().line, 22); EXPECT_EQ(details.back().message, "well"); // Setting nullptr action restores default behavior. dut.SetActionForWarnings(nullptr); EXPECT_NO_THROW(dut.Warning("ahem")); EXPECT_EQ(details.size(), 2); EXPECT_NO_THROW(dut.Warning(detail)); EXPECT_EQ(details.size(), 2); } GTEST_TEST(DiagnosticPolicyTest, SetActionForErrors) { DiagnosticPolicy dut; DiagnosticDetail detail{"a.txt", 22, "well"}; std::vector<DiagnosticDetail> details; auto error_action = [&details](const DiagnosticDetail& d) { details.push_back(d); }; dut.SetActionForErrors(error_action); // Warnings are unchanged; they do not throw, and log a message. // Verify the messages manually. EXPECT_NO_THROW(dut.Warning("ouch")); EXPECT_NO_THROW(dut.Warning(detail)); // Errors just increment the count. EXPECT_EQ(details.size(), 0); dut.Error("ahem"); EXPECT_EQ(details.size(), 1); EXPECT_FALSE(details.back().filename.has_value()); EXPECT_FALSE(details.back().line.has_value()); EXPECT_EQ(details.back().message, "ahem"); dut.Error(detail); EXPECT_EQ(details.size(), 2); EXPECT_EQ(*details.back().filename, "a.txt"); EXPECT_EQ(*details.back().line, 22); EXPECT_EQ(details.back().message, "well"); // Setting nullptr action restores default behavior. dut.SetActionForErrors(nullptr); EXPECT_THROW(dut.Error("ahem"), std::exception); EXPECT_EQ(details.size(), 2); EXPECT_THROW(dut.Error(detail), std::exception); EXPECT_EQ(details.size(), 2); } } // namespace } // namespace internal } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_division_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Division) { CHECK_BINARY_OP(/, x, y, 1.0); CHECK_BINARY_OP(/, x, y, -1.0); CHECK_BINARY_OP(/, y, x, 1.0); CHECK_BINARY_OP(/, y, x, -1.0); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/polynomial_test.cc
#include "drake/common/polynomial.h" #include <cmath> #include <cstddef> #include <map> #include <sstream> #include <stdexcept> #include <vector> #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/symbolic/expression.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/random_polynomial_matrix.h" using Eigen::VectorXd; using std::default_random_engine; using std::map; using std::runtime_error; using std::uniform_int_distribution; using std::uniform_real_distribution; using std::vector; namespace drake { namespace { using std::pow; template <typename T> void testIntegralAndDerivative() { VectorXd coefficients = VectorXd::Random(5); Polynomial<T> poly(coefficients); EXPECT_TRUE(CompareMatrices(poly.GetCoefficients(), poly.Derivative(0).GetCoefficients(), 1e-14, MatrixCompareType::absolute)); const T x{1.32}; Polynomial<T> first_derivative = poly.Derivative(1); EXPECT_NEAR(poly.EvaluateUnivariate(x, 1), first_derivative.EvaluateUnivariate(x), 1e-14); Polynomial<T> third_derivative = poly.Derivative(3); EXPECT_NEAR(poly.EvaluateUnivariate(x, 3), third_derivative.EvaluateUnivariate(x), 1e-14); Polynomial<T> third_derivative_check = poly.Derivative().Derivative().Derivative(); EXPECT_TRUE(CompareMatrices(third_derivative.GetCoefficients(), third_derivative_check.GetCoefficients(), 1e-14, MatrixCompareType::absolute)); Polynomial<T> tenth_derivative = poly.Derivative(10); EXPECT_TRUE(CompareMatrices(tenth_derivative.GetCoefficients(), VectorXd::Zero(1), 1e-14, MatrixCompareType::absolute)); Polynomial<T> integral = poly.Integral(0.0); Polynomial<T> poly_back = integral.Derivative(); EXPECT_TRUE(CompareMatrices(poly_back.GetCoefficients(), poly.GetCoefficients(), 1e-14, MatrixCompareType::absolute)); } template <typename T> void testOperators() { int max_num_coefficients = 6; int num_tests = 10; default_random_engine generator; std::uniform_int_distribution<> int_distribution(1, max_num_coefficients); uniform_real_distribution<double> uniform; for (int i = 0; i < num_tests; ++i) { VectorXd coeff1 = VectorXd::Random(int_distribution(generator)); Polynomial<T> poly1(coeff1); VectorXd coeff2 = VectorXd::Random(int_distribution(generator)); Polynomial<T> poly2(coeff2); double scalar = uniform(generator); Polynomial<T> sum = poly1 + poly2; Polynomial<T> difference = poly2 - poly1; Polynomial<T> product = poly1 * poly2; Polynomial<T> poly1_plus_scalar = poly1 + scalar; Polynomial<T> poly1_minus_scalar = poly1 - scalar; Polynomial<T> poly1_scaled = poly1 * scalar; Polynomial<T> poly1_div = poly1 / scalar; Polynomial<T> poly1_times_poly1 = poly1; const Polynomial<T> pow_poly1_3{pow(poly1, 3)}; const Polynomial<T> pow_poly1_4{pow(poly1, 4)}; const Polynomial<T> pow_poly1_10{pow(poly1, 10)}; poly1_times_poly1 *= poly1_times_poly1; double t = uniform(generator); EXPECT_NEAR(sum.EvaluateUnivariate(t), poly1.EvaluateUnivariate(t) + poly2.EvaluateUnivariate(t), 1e-8); EXPECT_NEAR(difference.EvaluateUnivariate(t), poly2.EvaluateUnivariate(t) - poly1.EvaluateUnivariate(t), 1e-8); EXPECT_NEAR(product.EvaluateUnivariate(t), poly1.EvaluateUnivariate(t) * poly2.EvaluateUnivariate(t), 1e-8); EXPECT_NEAR(poly1_plus_scalar.EvaluateUnivariate(t), poly1.EvaluateUnivariate(t) + scalar, 1e-8); EXPECT_NEAR(poly1_minus_scalar.EvaluateUnivariate(t), poly1.EvaluateUnivariate(t) - scalar, 1e-8); EXPECT_NEAR(poly1_scaled.EvaluateUnivariate(t), poly1.EvaluateUnivariate(t) * scalar, 1e-8); EXPECT_NEAR(poly1_div.EvaluateUnivariate(t), poly1.EvaluateUnivariate(t) / scalar, 1e-8); EXPECT_NEAR(poly1_times_poly1.EvaluateUnivariate(t), poly1.EvaluateUnivariate(t) * poly1.EvaluateUnivariate(t), 1e-8); EXPECT_NEAR(pow_poly1_3.EvaluateUnivariate(t), pow(poly1.EvaluateUnivariate(t), 3), 1e-8); EXPECT_NEAR(pow_poly1_4.EvaluateUnivariate(t), pow(poly1.EvaluateUnivariate(t), 4), 1e-8); EXPECT_NEAR(pow_poly1_10.EvaluateUnivariate(t), pow(poly1.EvaluateUnivariate(t), 10), 1e-8); EXPECT_NEAR(pow_poly1_3.EvaluateUnivariate(t) * pow_poly1_4.EvaluateUnivariate(t) * pow_poly1_3.EvaluateUnivariate(t), pow_poly1_10.EvaluateUnivariate(t), 1e-8); // Check the '==' operator. EXPECT_TRUE(poly1 + poly2 == sum); EXPECT_FALSE(poly1 == sum); } } template <typename T> void testRoots() { int max_num_coefficients = 6; default_random_engine generator; std::uniform_int_distribution<> int_distribution(1, max_num_coefficients); int num_tests = 50; for (int i = 0; i < num_tests; ++i) { VectorXd coeffs = VectorXd::Random(int_distribution(generator)); Polynomial<T> poly(coeffs); auto roots = poly.Roots(); EXPECT_EQ(roots.rows(), poly.GetDegree()); for (int k = 0; k < roots.size(); k++) { auto value = poly.EvaluateUnivariate(roots[k]); EXPECT_NEAR(std::abs(value), 0.0, 1e-8); } } } void testEvalType() { int max_num_coefficients = 6; default_random_engine generator; std::uniform_int_distribution<> int_distribution(1, max_num_coefficients); VectorXd coeffs = VectorXd::Random(int_distribution(generator)); Polynomial<double> poly(coeffs); auto valueIntInput = poly.EvaluateUnivariate(1); EXPECT_EQ(typeid(decltype(valueIntInput)), typeid(double)); auto valueComplexInput = poly.EvaluateUnivariate(std::complex<double>(1.0, 2.0)); EXPECT_EQ(typeid(decltype(valueComplexInput)), typeid(std::complex<double>)); } template <typename T> void testPolynomialMatrix() { int max_matrix_rows_cols = 7; int num_coefficients = 6; default_random_engine generator; uniform_int_distribution<> matrix_size_distribution(1, max_matrix_rows_cols); int rows_A = matrix_size_distribution(generator); int cols_A = matrix_size_distribution(generator); int rows_B = cols_A; int cols_B = matrix_size_distribution(generator); auto A = test::RandomPolynomialMatrix<T>(num_coefficients, rows_A, cols_A); auto B = test::RandomPolynomialMatrix<T>(num_coefficients, rows_B, cols_B); auto C = test::RandomPolynomialMatrix<T>(num_coefficients, rows_A, cols_A); auto product = A * B; auto sum = A + C; uniform_real_distribution<double> uniform; for (int row = 0; row < A.rows(); ++row) { for (int col = 0; col < A.cols(); ++col) { double t = uniform(generator); EXPECT_NEAR(sum(row, col).evaluateUnivariate(t), A(row, col).evaluateUnivariate(t) + C(row, col).evaluateUnivariate(t), 1e-8); double expected_product = 0.0; for (int i = 0; i < A.cols(); ++i) { expected_product += A(row, i).evaluateUnivariate(t) * B(i, col).evaluateUnivariate(t); } EXPECT_NEAR(product(row, col).evaluateUnivariate(t), expected_product, 1e-8); } } C.setZero(); // this was a problem before } GTEST_TEST(PolynomialTest, CoefficientsConstructor) { const VectorXd coefficients = Eigen::Vector3d(0.25, 0.0, 2.0); Polynomial<double> dut(coefficients); EXPECT_TRUE(CompareMatrices(dut.GetCoefficients(), coefficients)); } GTEST_TEST(PolynomialTest, CoefficientsConstructorEmpty) { // An empty coefficients vector is promoted to a single zero. const VectorXd coefficients; Polynomial<double> dut(coefficients); const VectorXd expected = VectorXd::Constant(1, 0.0); EXPECT_TRUE(CompareMatrices(dut.GetCoefficients(), expected)); } GTEST_TEST(PolynomialTest, CoefficientsConstructorNoMatrix) { // Non-vector matrices are rejected. const Eigen::MatrixXd coefficients = Eigen::MatrixXd::Zero(3, 5); EXPECT_THROW(Polynomial<double>{coefficients}, std::exception); } GTEST_TEST(PolynomialTest, IntegralAndDerivative) { testIntegralAndDerivative<double>(); } GTEST_TEST(PolynomialTest, TestMakeMonomialsUnique) { Eigen::Vector2d coefficients(1, 2); Polynomial<double> poly(coefficients); const auto poly_squared = poly * poly; EXPECT_EQ(poly_squared.GetNumberOfCoefficients(), 3); } GTEST_TEST(PolynomialTest, Operators) { testOperators<double>(); } GTEST_TEST(PolynomialTest, Roots) { testRoots<double>(); } GTEST_TEST(PolynomialTest, EvalType) { testEvalType(); } GTEST_TEST(PolynomialTest, IsAffine) { Polynomiald x("x"); Polynomiald y("y"); EXPECT_TRUE(x.IsAffine()); EXPECT_TRUE(y.IsAffine()); EXPECT_TRUE((2 + x).IsAffine()); EXPECT_TRUE((2 * x).IsAffine()); EXPECT_FALSE((x * x).IsAffine()); EXPECT_FALSE((x * y).IsAffine()); EXPECT_TRUE((x + y).IsAffine()); EXPECT_TRUE((2 + x + y).IsAffine()); EXPECT_TRUE((2 + (2 * x) + y).IsAffine()); EXPECT_FALSE((2 + (y * x) + y).IsAffine()); } GTEST_TEST(PolynomialTest, VariableIdGeneration) { // Probe the outer edge cases of variable ID generation. // There is no documented maximum ID, but empirically it is 2325. What we // really care about here is just that there is some value below which it // succeeds and above which it fails. static const int kMaxId = 2325; DRAKE_EXPECT_NO_THROW(Polynomial<double>("x", kMaxId)); DRAKE_EXPECT_NO_THROW(Polynomial<double>("zzzz", 1)); DRAKE_EXPECT_NO_THROW(Polynomial<double>("zzzz", kMaxId)); EXPECT_THROW(Polynomial<double>("!"), std::runtime_error); // Illegal character. EXPECT_THROW(Polynomial<double>("zzzz@"), std::runtime_error); // Illegal length. EXPECT_THROW(Polynomial<double>("z", 0), std::runtime_error); // Illegal ID. EXPECT_THROW(Polynomial<double>("z", kMaxId + 1), std::runtime_error); // Illegal ID. // Test that ID generation round-trips correctly. std::stringstream test_stream; test_stream << Polynomial<double>("x", 1); std::string result; test_stream >> result; EXPECT_EQ(result, "x1"); } GTEST_TEST(PolynomialTest, GetVariables) { Polynomiald x = Polynomiald("x"); Polynomiald::VarType x_var = x.GetSimpleVariable(); Polynomiald y = Polynomiald("y"); Polynomiald::VarType y_var = y.GetSimpleVariable(); Polynomiald z = Polynomiald("z"); Polynomiald::VarType z_var = z.GetSimpleVariable(); EXPECT_TRUE(x.GetVariables().contains(x_var)); EXPECT_FALSE(x.GetVariables().contains(y_var)); EXPECT_FALSE(Polynomiald().GetVariables().contains(x_var)); EXPECT_TRUE((x + x).GetVariables().contains(x_var)); EXPECT_TRUE((x + y).GetVariables().contains(x_var)); EXPECT_TRUE((x + y).GetVariables().contains(y_var)); EXPECT_TRUE((x * y * y + z).GetVariables().contains(x_var)); EXPECT_TRUE((x * y * y + z).GetVariables().contains(y_var)); EXPECT_TRUE((x * y * y + z).GetVariables().contains(z_var)); EXPECT_FALSE(x.Derivative().GetVariables().contains(x_var)); } GTEST_TEST(PolynomialTest, Simplification) { Polynomiald x = Polynomiald("x"); Polynomiald y = Polynomiald("y"); { // Test duplicate monomials. std::stringstream test_stream; test_stream << ((x * y) + (x * y)); std::string result; test_stream >> result; EXPECT_EQ(result, "(2)*x1*y1"); } { // Test monomials that are duplicates under commutativity. std::stringstream test_stream; test_stream << ((x * y) + (y * x)); std::string result; test_stream >> result; EXPECT_EQ(result, "(2)*x1*y1"); } } GTEST_TEST(PolynomialTest, MonomialFactor) { Polynomiald x = Polynomiald("x"); Polynomiald y = Polynomiald("y"); // "m_" prefix denotes monomial. Polynomiald::Monomial m_one = Polynomiald(1).GetMonomials()[0]; Polynomiald::Monomial m_two = Polynomiald(2).GetMonomials()[0]; Polynomiald::Monomial m_x = x.GetMonomials()[0]; Polynomiald::Monomial m_y = y.GetMonomials()[0]; Polynomiald::Monomial m_2x = (x * 2).GetMonomials()[0]; Polynomiald::Monomial m_x2 = (x * x).GetMonomials()[0]; Polynomiald::Monomial m_x2y = (x * x * y).GetMonomials()[0]; // Expect failures EXPECT_EQ(m_x.Factor(m_y).coefficient, 0); EXPECT_EQ(m_x.Factor(m_x2).coefficient, 0); // Expect successes EXPECT_EQ(m_x.Factor(m_x), m_one); EXPECT_EQ(m_2x.Factor(m_x), m_two); EXPECT_EQ(m_x2.Factor(m_x), m_x); EXPECT_EQ(m_x2y.Factor(m_x2), m_y); EXPECT_EQ(m_x2y.Factor(m_y), m_x2); } GTEST_TEST(PolynomialTest, MultivariateValue) { Polynomiald x = Polynomiald("x"); Polynomiald y = Polynomiald("y"); const Polynomiald p{x * x + 2 * x * y + y * y + 2}; const Polynomiald pow_p_2{pow(p, 2)}; const Polynomiald pow_p_3{pow(p, 3)}; const Polynomiald pow_p_7{pow(p, 7)}; const std::map<Polynomiald::VarType, double> eval_point = { {x.GetSimpleVariable(), 1}, {y.GetSimpleVariable(), 2}}; EXPECT_EQ((x * x + y).EvaluateMultivariate(eval_point), 3); EXPECT_EQ((2 * x * x + y).EvaluateMultivariate(eval_point), 4); EXPECT_EQ((x * x + 2 * y).EvaluateMultivariate(eval_point), 5); EXPECT_EQ((x * x + x * y).EvaluateMultivariate(eval_point), 3); EXPECT_NEAR(pow_p_2.EvaluateMultivariate(eval_point), pow(p.EvaluateMultivariate(eval_point), 2), 1e-8); EXPECT_NEAR(pow_p_3.EvaluateMultivariate(eval_point), pow(p.EvaluateMultivariate(eval_point), 3), 1e-8); EXPECT_NEAR(pow_p_7.EvaluateMultivariate(eval_point), pow(p.EvaluateMultivariate(eval_point), 7), 1e-8); EXPECT_NEAR((pow_p_2 * pow_p_3 * pow_p_2).EvaluateMultivariate(eval_point), pow_p_7.EvaluateMultivariate(eval_point), 1e-8); } GTEST_TEST(PolynomialTest, Conversion) { // Confirm that these conversions compile okay. Polynomial<double> x(1.0); Polynomial<double> y = 2.0; Polynomial<double> z = 3; } GTEST_TEST(PolynomialTest, EvaluatePartial) { Polynomiald x = Polynomiald("x"); Polynomiald y = Polynomiald("y"); Polynomiald dut = (5 * x * x * x) + (3 * x * y) + (2 * y) + 1; const std::map<Polynomiald::VarType, double> eval_point_null; const std::map<Polynomiald::VarType, double> eval_point_x = { {x.GetSimpleVariable(), 7}}; const std::map<Polynomiald::VarType, double> eval_point_y = { {y.GetSimpleVariable(), 11}}; const std::map<Polynomiald::VarType, double> eval_point_xy = { {x.GetSimpleVariable(), 7}, {y.GetSimpleVariable(), 11}}; // Test a couple of straightforward explicit cases. EXPECT_EQ(dut.EvaluatePartial(eval_point_null).GetMonomials(), dut.GetMonomials()); // TODO(#2216) These fail due to a known drake bug: #if 0 EXPECT_EQ(dut.evaluatePartial(eval_point_x).getMonomials(), ((23 * y) + 1716).getMonomials()); EXPECT_EQ(dut.evaluatePartial(eval_point_y).getMonomials(), ((5 * x * x * x) + (33 * x) + 23).getMonomials()); #endif // Test that every order of partial and then complete evaluation gives the // same answer. const double expected_result = dut.EvaluateMultivariate(eval_point_xy); EXPECT_EQ( dut.EvaluatePartial(eval_point_null).EvaluateMultivariate(eval_point_xy), expected_result); EXPECT_EQ( dut.EvaluatePartial(eval_point_xy).EvaluateMultivariate(eval_point_null), expected_result); EXPECT_EQ( dut.EvaluatePartial(eval_point_x).EvaluateMultivariate(eval_point_y), expected_result); EXPECT_EQ( dut.EvaluatePartial(eval_point_y).EvaluateMultivariate(eval_point_x), expected_result); // Test that zeroing out one term gives a sensible result. EXPECT_EQ(dut.EvaluatePartial( std::map<Polynomiald::VarType, double>{{x.GetSimpleVariable(), 0}}), (2 * y) + 1); EXPECT_EQ(dut.EvaluatePartial( std::map<Polynomiald::VarType, double>{{y.GetSimpleVariable(), 0}}), (5 * x * x * x) + 1); } GTEST_TEST(PolynomialTest, FromExpression) { using symbolic::Environment; using symbolic::Expression; using symbolic::Variable; const Variable x{"x"}; const Variable y{"y"}; const Variable z{"z"}; Environment env{{x, 1.0}, {y, 2.0}, {z, 3.0}}; const map<Polynomiald::VarType, double> eval_point{ {x.get_id(), env[x]}, {y.get_id(), env[y]}, {z.get_id(), env[z]}}; const Expression e0{42.0}; const Expression e1{pow(x, 2)}; const Expression e2{3 + x + y + z}; const Expression e3{1 + pow(x, 2) + pow(y, 2)}; const Expression e4{pow(x, 2) * pow(y, 2)}; const Expression e5{pow(x + y + z, 3)}; const Expression e6{pow(x + y + z, 3) / 10}; const Expression e7{-pow(y, 3)}; const Expression e8{pow(pow(x, 3), 1.0 / 3)}; EXPECT_NEAR( e0.Evaluate(env), Polynomial<double>::FromExpression(e0).EvaluateMultivariate(eval_point), 1e-8); EXPECT_NEAR( e1.Evaluate(env), Polynomial<double>::FromExpression(e1).EvaluateMultivariate(eval_point), 1e-8); EXPECT_NEAR( e2.Evaluate(env), Polynomial<double>::FromExpression(e2).EvaluateMultivariate(eval_point), 1e-8); EXPECT_NEAR( e3.Evaluate(env), Polynomial<double>::FromExpression(e3).EvaluateMultivariate(eval_point), 1e-8); EXPECT_NEAR( e4.Evaluate(env), Polynomial<double>::FromExpression(e4).EvaluateMultivariate(eval_point), 1e-8); EXPECT_NEAR( e5.Evaluate(env), Polynomial<double>::FromExpression(e5).EvaluateMultivariate(eval_point), 1e-8); EXPECT_NEAR( e6.Evaluate(env), Polynomial<double>::FromExpression(e6).EvaluateMultivariate(eval_point), 1e-8); EXPECT_NEAR( e7.Evaluate(env), Polynomial<double>::FromExpression(e7).EvaluateMultivariate(eval_point), 1e-8); EXPECT_NEAR( e8.Evaluate(env), Polynomial<double>::FromExpression(e8).EvaluateMultivariate(eval_point), 1e-8); const vector<Expression> test_vec{ log(x), abs(x), exp(x), sqrt(x), sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), atan2(x, y), sinh(x), cosh(x), tanh(x), min(x, y), max(x, y), ceil(x), floor(x), if_then_else(x > y, x, y), Expression::NaN(), symbolic::uninterpreted_function("uf", {x, y})}; for (const Expression& e : test_vec) { EXPECT_FALSE(e.is_polynomial()); EXPECT_THROW(Polynomial<double>::FromExpression(e), runtime_error); } } template <typename T> void TestScalarType() { Eigen::Vector3d coeffs(1., 2., 3.); const Polynomial<T> p(coeffs); EXPECT_NEAR(ExtractDoubleOrThrow(p.EvaluateUnivariate(0.0)), coeffs(0), 1e-14); EXPECT_THROW(p.Roots(), std::runtime_error); EXPECT_TRUE(static_cast<bool>(p.CoefficientsAlmostEqual(p, 1e-14))); Polynomial<T> x("x", 1); Polynomial<T> y("y", 1); const std::map<Polynomiald::VarType, double> eval_point = { {x.GetSimpleVariable(), 1}, {y.GetSimpleVariable(), 2}}; EXPECT_NEAR( ExtractDoubleOrThrow((x * x + y).EvaluateMultivariate(eval_point)), 3, 1e-14); } GTEST_TEST(PolynomialTest, ScalarTypes) { TestScalarType<AutoDiffXd>(); TestScalarType<symbolic::Expression>(); // Checks that we can create an instance, Polynomial<T>(0). `Scalar(0)` (where // Scalar = Polynomial<T>) is a common pattern in Eigen internals and we want // to make sure that we can build these instances. const Polynomial<double> p_double(0); const Polynomial<AutoDiffXd> p_autodiffxd(0); const Polynomial<symbolic::Expression> p_symbolic(0); } GTEST_TEST(PolynomialTest, CoefficientsAlmostEqualTest) { Polynomiald x = Polynomiald("x"); Polynomiald y = Polynomiald("y"); EXPECT_FALSE(x.CoefficientsAlmostEqual(y)); EXPECT_TRUE((x + y).CoefficientsAlmostEqual(y + x)); EXPECT_TRUE((x + x * x + 3 * pow(x, 3)) .CoefficientsAlmostEqual(3 * pow(x, 3) + x + x * x)); // Test relative and absolute tolerance. EXPECT_TRUE( (100 * x).CoefficientsAlmostEqual(99 * x, 0.1, ToleranceType::kRelative)); EXPECT_FALSE( (100 * x).CoefficientsAlmostEqual(99 * x, 0.1, ToleranceType::kAbsolute)); EXPECT_FALSE((0.01 * x).CoefficientsAlmostEqual(0.02 * x, 0.1, ToleranceType::kRelative)); EXPECT_TRUE((0.01 * x).CoefficientsAlmostEqual(0.02 * x, 0.1, ToleranceType::kAbsolute)); // Test missing monomials. EXPECT_FALSE((x + y + 0.01 * x * x).CoefficientsAlmostEqual(x + y)); EXPECT_FALSE((x + y).CoefficientsAlmostEqual(x + y + 0.01 * x * x)); // Missing monomials is ok only for absolute tolerance. EXPECT_TRUE( (x + y + 0.01 * x * x) .CoefficientsAlmostEqual(x + y, 0.02, ToleranceType::kAbsolute)); EXPECT_TRUE((x + y).CoefficientsAlmostEqual(x + y + 0.01 * x * x, 0.02, ToleranceType::kAbsolute)); EXPECT_FALSE( (x + y + 0.01 * x * x) .CoefficientsAlmostEqual(x + y, 0.02, ToleranceType::kRelative)); EXPECT_FALSE((x + y).CoefficientsAlmostEqual(x + y + 0.01 * x * x, 0.02, ToleranceType::kRelative)); } GTEST_TEST(PolynomialTest, SubsitutionTest) { Polynomiald x = Polynomiald("x"); Polynomiald y = Polynomiald("y"); Polynomiald::VarType xvar = x.GetSimpleVariable(); Polynomiald::VarType yvar = y.GetSimpleVariable(); EXPECT_TRUE(x.Substitute(xvar, y).CoefficientsAlmostEqual(y)); Polynomiald p1 = x + 3 * x * x + 3 * y; EXPECT_TRUE( p1.Substitute(xvar, 1 + x) .CoefficientsAlmostEqual(1 + x + 3 * (1 + x) * (1 + x) + 3 * y)); EXPECT_TRUE(p1.Substitute(yvar, 1 + x) .CoefficientsAlmostEqual(3 + 4 * x + 3 * x * x)); EXPECT_TRUE(p1.Substitute(xvar, x * x) .CoefficientsAlmostEqual(x * x + 3 * pow(x, 4) + 3 * y)); } GTEST_TEST(PolynomialTest, IsUnivariateTrue) { const VectorXd coefficients = Eigen::Vector3d(0.25, 0.0, 2.0); Polynomial<double> dut(coefficients); EXPECT_TRUE(dut.is_univariate()); } GTEST_TEST(PolynomialTest, IsUnivariateFalse) { Polynomiald x("x"); Polynomiald y("y"); EXPECT_FALSE((x+y).is_univariate()); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_log_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Log) { CHECK_UNARY_FUNCTION(log, x, y, 0.1); CHECK_UNARY_FUNCTION(log, x, y, -0.1); CHECK_UNARY_FUNCTION(log, y, x, 0.1); CHECK_UNARY_FUNCTION(log, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/network_policy_test.cc
#include "drake/common/network_policy.h" #include <stdlib.h> #include <gtest/gtest.h> namespace drake { namespace internal { namespace { constexpr const char kAllow[] = "DRAKE_ALLOW_NETWORK"; GTEST_TEST(NetworkPolicyTest, Missing) { ASSERT_EQ(::unsetenv(kAllow), 0); EXPECT_TRUE(IsNetworkingAllowed("foo")); } GTEST_TEST(NetworkPolicyTest, Empty) { ASSERT_EQ(::setenv(kAllow, "", 1), 0); EXPECT_TRUE(IsNetworkingAllowed("foo")); } GTEST_TEST(NetworkPolicyTest, None) { ASSERT_EQ(::setenv(kAllow, "none", 1), 0); EXPECT_FALSE(IsNetworkingAllowed("foo")); } GTEST_TEST(NetworkPolicyTest, MixedNone) { // N.B. This prints a spdlog warning. ASSERT_EQ(::setenv(kAllow, "none:foo", 1), 0); EXPECT_FALSE(IsNetworkingAllowed("foo")); } GTEST_TEST(NetworkPolicyTest, YesMatch) { ASSERT_EQ(::setenv(kAllow, "foo", 1), 0); EXPECT_TRUE(IsNetworkingAllowed("foo")); ASSERT_EQ(::setenv(kAllow, "foo:bar", 1), 0); EXPECT_TRUE(IsNetworkingAllowed("foo")); ASSERT_EQ(::setenv(kAllow, "bar:foo:baz", 1), 0); EXPECT_TRUE(IsNetworkingAllowed("foo")); } GTEST_TEST(NetworkPolicyTest, NoMatch) { ASSERT_EQ(::setenv(kAllow, "bar", 1), 0); EXPECT_FALSE(IsNetworkingAllowed("foo")); ASSERT_EQ(::setenv(kAllow, "bar:baz", 1), 0); EXPECT_FALSE(IsNetworkingAllowed("foo")); ASSERT_EQ(::setenv(kAllow, ":bar:baz:", 1), 0); EXPECT_FALSE(IsNetworkingAllowed("foo")); } GTEST_TEST(NetworkPolicyTest, BadName) { EXPECT_THROW(IsNetworkingAllowed(""), std::exception); EXPECT_THROW(IsNetworkingAllowed("none"), std::exception); EXPECT_THROW(IsNetworkingAllowed("LCM"), std::exception); } } // namespace } // namespace internal } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/find_resource_test.cc
#include "drake/common/find_resource.h" #include <cstdlib> #include <filesystem> #include <functional> #include <memory> #include <stdexcept> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/drake_path.h" #include "drake/common/drake_throw.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/expect_throws_message.h" using std::string; namespace drake { namespace { using Result = FindResourceResult; GTEST_TEST(FindResourceTest, EmptyResult) { const auto& result = Result::make_empty(); EXPECT_EQ(result.get_resource_path(), ""); EXPECT_FALSE(result.get_absolute_path()); EXPECT_THROW(result.get_absolute_path_or_throw(), std::runtime_error); ASSERT_TRUE(result.get_error_message()); } GTEST_TEST(FindResourceTest, NonRelativeRequest) { const string abspath = "/dev/null"; const auto& result = FindResource(abspath); EXPECT_EQ(result.get_resource_path(), abspath); // We don't get a path back. EXPECT_FALSE(result.get_absolute_path()); EXPECT_THROW(result.get_absolute_path_or_throw(), std::runtime_error); // We get an error back. const std::optional<string> error_message = result.get_error_message(); ASSERT_TRUE(error_message); EXPECT_EQ(*error_message, "Drake resource_path '/dev/null' is not a relative path."); } GTEST_TEST(FindResourceTest, NotFound) { const string relpath = "drake/this_file_does_not_exist"; const auto& result = FindResource(relpath); EXPECT_EQ(result.get_resource_path(), relpath); // We don't get a path back. EXPECT_FALSE(result.get_absolute_path()); EXPECT_THROW(result.get_absolute_path_or_throw(), std::runtime_error); // We get an error back. const std::optional<string> error_message = result.get_error_message(); ASSERT_TRUE(error_message); EXPECT_THAT(*error_message, testing::ContainsRegex( "Sought '" + relpath + "' in runfiles.*not exist.*on the manifest")); // Sugar works the same way. EXPECT_THROW(FindResourceOrThrow(relpath), std::runtime_error); } GTEST_TEST(FindResourceTest, FoundDeclaredData) { const string relpath = "drake/common/test/find_resource_test_data.txt"; const auto& result = FindResource(relpath); EXPECT_EQ(result.get_resource_path(), relpath); // We don't get an error back. EXPECT_FALSE(result.get_error_message()); // We get a path back. string absolute_path; DRAKE_EXPECT_NO_THROW(absolute_path = result.get_absolute_path_or_throw()); ASSERT_TRUE(result.get_absolute_path()); EXPECT_EQ(*result.get_absolute_path(), absolute_path); // The path is the correct answer. ASSERT_FALSE(absolute_path.empty()); EXPECT_EQ(absolute_path[0], '/'); EXPECT_EQ(ReadFileOrThrow(absolute_path), "Test data for drake/common/test/find_resource_test.cc.\n"); // Sugar works the same way. EXPECT_EQ(FindResourceOrThrow(relpath), absolute_path); } GTEST_TEST(FindResourceTest, FoundDirectory) { // Looking up a directory (not file) should fail. const string relpath = "drake/common"; const auto& result = FindResource(relpath); ASSERT_TRUE(result.get_error_message()); } GTEST_TEST(GetDrakePathTest, BasicTest) { // Just test that we find a path, without any exceptions. const auto& result = MaybeGetDrakePath(); ASSERT_TRUE(result); EXPECT_GT(result->length(), 5); } GTEST_TEST(GetDrakePathTest, PathIncludesDrake) { // Tests that the path returned includes the root of drake. const auto& result = MaybeGetDrakePath(); ASSERT_TRUE(result); const std::filesystem::path expected = std::filesystem::path(*result) / std::filesystem::path("common/test/find_resource_test_data.txt"); EXPECT_TRUE(std::filesystem::exists(expected)); } GTEST_TEST(ReadFileTest, NoSuchPath) { EXPECT_FALSE(ReadFile("/foo/bar/missing")); DRAKE_EXPECT_THROWS_MESSAGE(ReadFileOrThrow("/foo/bar/missing"), "Error reading.*/foo/bar/missing.*"); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/sha256_test.cc
#include "drake/common/sha256.h" #include <fstream> #include <gtest/gtest.h> #include "drake/common/drake_throw.h" #include "drake/common/temp_directory.h" namespace drake { namespace { // Our default constructor produces a dummy hash. GTEST_TEST(Sha256Test, Default) { EXPECT_EQ(Sha256{}.to_string(), std::string(64, '0')); } // Since we're just a tiny wrapper around picosha, we don't need much testing of // the actual checksum math. We'll just spot-test a well-known value: one of the // standard test vectors for the SHA-2 family. GTEST_TEST(Sha256Test, WellKnownValue) { const std::string data = "abc"; const std::string expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; EXPECT_EQ(Sha256::Checksum(data).to_string(), expected); EXPECT_EQ(Sha256::Parse(expected), Sha256::Checksum(data)); } // Hex strings can be uppercase and/or lowercase. GTEST_TEST(Sha256Test, ParseIgnoresCase) { EXPECT_EQ(Sha256::Parse(std::string(64, 'c')), Sha256::Parse(std::string(64, 'C'))); } // A valid parse requires a 64-character hex string. GTEST_TEST(Sha256Test, ParseErrors) { // Wrong number of characters. EXPECT_FALSE(Sha256::Parse(std::string(60, '0'))); EXPECT_FALSE(Sha256::Parse(std::string(70, '0'))); // Non-hex letter. EXPECT_FALSE(Sha256::Parse(std::string(64, 'z'))); } // Here, we're cross-checking the exact implementation of our hash function // ("glass-box testing"). If we ever change to a different implementation, // we'll need to adjust this test to allow for it. GTEST_TEST(Sha256Test, Hash) { const std::hash<Sha256> hasher; EXPECT_EQ(hasher(Sha256{}), 0); EXPECT_EQ(hasher(Sha256::Checksum("abc")), // In our hash, the four words are directly XOR'd together. The // to_string() prints the low-order byte first, but literals in C // code give the high-order byte first, therefore the constants here // are "reversed" versions of the words from the to_string(). 0xeacf018fbf1678baULL ^ // ba7816bf8f01cfea, byte-reversed 0x2322ae5dde404141ULL ^ // 414140de5dae2223, byte-reversed 0x9c7a1796a36103b0ULL ^ // b00361a396177a9c, byte-reversed 0xad1500f261ff10b4ULL ^ // b410ff61f20015ad, byte-reversed 0); } GTEST_TEST(Sha256Test, Comparisons) { auto zero = Sha256(); auto abc = Sha256::Checksum("abc"); EXPECT_TRUE(zero == zero); EXPECT_TRUE(abc == abc); EXPECT_FALSE(zero == abc); EXPECT_FALSE(abc == zero); EXPECT_FALSE(zero != zero); EXPECT_FALSE(abc != abc); EXPECT_TRUE(zero != abc); EXPECT_TRUE(abc != zero); EXPECT_FALSE(zero < zero); EXPECT_FALSE(abc < abc); EXPECT_TRUE(zero < abc); EXPECT_FALSE(abc < zero); } // Reading from an empty file. GTEST_TEST(Sha256Test, EmptyFileTest) { std::ifstream devnull("/dev/null"); EXPECT_EQ(Sha256::Checksum(&devnull), Sha256::Checksum("")); } // Reading from a non-empty file. GTEST_TEST(Sha256Test, RealFileTest) { const std::string data = "abc"; const std::string temp_filename = temp_directory() + "/abc.txt"; { std::ofstream temp_write(temp_filename); temp_write << data; DRAKE_THROW_UNLESS(temp_write.good()); } std::ifstream temp_read(temp_filename); EXPECT_EQ(Sha256::Checksum(&temp_read), Sha256::Checksum(data)); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_min_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Min) { CHECK_BINARY_FUNCTION_ADS_ADS(min, x, y, 0.3); CHECK_BINARY_FUNCTION_ADS_ADS(min, x, y, -0.3); CHECK_BINARY_FUNCTION_ADS_ADS(min, y, x, 0.4); CHECK_BINARY_FUNCTION_ADS_ADS(min, y, x, -0.4); } TEST_F(AutoDiffXdTest, TieBreakingCheckMinBothNonEmpty) { // Given `min(v1, v2)`, our overload returns the first argument `v1` when // `v1 == v2` holds if both `v1` and `v2` have non-empty derivatives. In // Drake, we rely on this implementation-detail. This test checks if the // property holds so that we can detect a possible change in future. const AutoDiffXd v1{1.0, Vector1<double>(3.)}; const AutoDiffXd v2{1.0, Vector1<double>(2.)}; EXPECT_EQ(min(v1, v2).derivatives()[0], 3.0); // Returns v1, not v2. } TEST_F(AutoDiffXdTest, TieBreakingCheckMinOneNonEmpty) { // Given `min(v1, v2)`, our overload returns whichever argument has non-empty // derivatives in the case where only one has non-empty derivatives. In // Drake, we rely on this implementation-detail. This test checks if the // property holds so that we can detect a possible change in future. const AutoDiffXd v1{1.0}; const AutoDiffXd v2{1.0, Vector1<double>(2.)}; EXPECT_TRUE(CompareMatrices(min(v1, v2).derivatives(), Vector1<double>(2.))); // Returns v2, not v1. EXPECT_TRUE(CompareMatrices(min(v2, v1).derivatives(), Vector1<double>(2.))); // Returns v2, not v1. } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_exp_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Exp) { CHECK_UNARY_FUNCTION(exp, x, y, 0.1); CHECK_UNARY_FUNCTION(exp, x, y, -0.1); CHECK_UNARY_FUNCTION(exp, y, x, 0.1); CHECK_UNARY_FUNCTION(exp, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/ssize_test.cc
#include "drake/common/ssize.h" #include <array> #include <string> #include <vector> #include <gtest/gtest.h> namespace drake { namespace { // We have to polyfill for std::ssize() for C++ < C++20. GTEST_TEST(Ssize, BasicTest) { int c[] = {-5, 10, 15}; EXPECT_EQ(ssize(c), 3); std::array<double, 4> a = {1.0, 2.0, 3.0, 4.0}; EXPECT_EQ(ssize(a), 4); std::string s = "abcdefg"; EXPECT_EQ(ssize(s), 7); std::vector<int> v = {3, 1, 4, 1, 5, 9}; EXPECT_EQ(ssize(v), 6); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_multiplication_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Multiplication) { CHECK_BINARY_OP(*, x, y, 1.0); CHECK_BINARY_OP(*, x, y, -1.0); CHECK_BINARY_OP(*, y, x, 1.0); CHECK_BINARY_OP(*, y, x, -1.0); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/overloaded_test.cc
#include "drake/common/overloaded.h" #include <variant> #include <gtest/gtest.h> namespace drake { namespace { GTEST_TEST(OverloadedTest, CommentExampleTest) { // Test the exact text of the example in the file comment. using MyVariant = std::variant<int, std::string>; MyVariant v = 5; std::string result = std::visit<const char*>(overloaded{ [](const int arg) { return "found an int"; }, [](const std::string& arg) { return "found a string"; } }, v); EXPECT_EQ(result, "found an int"); } GTEST_TEST(OverloadedTest, AutoTest) { using MyVariant = std::variant<int, std::string>; MyVariant v = 5; // An 'auto' arm doesn't match if there's any explicit match, // no matter if it's earlier or later in the list. std::string result = std::visit<const char*>(overloaded{ [](const auto arg) { return "found an auto"; }, [](const int arg) { return "found an int"; }, [](const std::string& arg) { return "found a string"; }, [](const auto arg) { return "found an auto"; }, }, v); EXPECT_EQ(result, "found an int"); // An 'auto' arm matches if there's no explicit match. result = std::visit<const char*>(overloaded{ [](const auto arg) { return "found an auto"; }, [](const std::string& arg) { return "found a string"; }, }, v); EXPECT_EQ(result, "found an auto"); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_tanh_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Tanh) { CHECK_UNARY_FUNCTION(tanh, x, y, 0.1); CHECK_UNARY_FUNCTION(tanh, x, y, -0.1); CHECK_UNARY_FUNCTION(tanh, y, x, 0.1); CHECK_UNARY_FUNCTION(tanh, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/fmt_eigen_test.cc
#include "drake/common/fmt_eigen.h" #include <Eigen/Core> #include <gtest/gtest.h> namespace drake { namespace { // TODO(jwnimer-tri) The expected values below are what Eigen prints for us by // default. In the future, we might decide to use some different formatting. // In that case, it's fine to update the test goals here to reflect those // updated defaults. GTEST_TEST(FmtEigenTest, RowVector3d) { const Eigen::RowVector3d value{1.1, 2.2, 3.3}; EXPECT_EQ(fmt::format("{}", fmt_eigen(value)), "1.1 2.2 3.3"); } GTEST_TEST(FmtEigenTest, Vector3d) { const Eigen::Vector3d value{1.1, 2.2, 3.3}; EXPECT_EQ(fmt::format("{}", fmt_eigen(value)), "1.1\n2.2\n3.3"); } GTEST_TEST(FmtEigenTest, EmptyMatrix) { const Eigen::MatrixXd value; EXPECT_EQ(fmt::format("{}", fmt_eigen(value)), ""); } GTEST_TEST(FmtEigenTest, Matrix3d) { Eigen::Matrix3d value; value << 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 3.1, 3.2, 3.3; EXPECT_EQ(fmt::format("{}", fmt_eigen(value)), "1.1 1.2 1.3\n" "2.1 2.2 2.3\n" "3.1 3.2 3.3"); } GTEST_TEST(FmtEigenTest, Matrix3dNeedsPadding) { Eigen::Matrix3d value; value << 10.1, 1.2, 1.3, 2.1, 2.2, 2.3, 3.1, 3.2, 3.3; EXPECT_EQ(fmt::format("{}", fmt_eigen(value)), "10.1 1.2 1.3\n" " 2.1 2.2 2.3\n" " 3.1 3.2 3.3"); } GTEST_TEST(FmtEigenTest, Matrix3i) { Eigen::Matrix3i value; value << 11, 12, 13, 21, 22, 23, 31, 32, 33; EXPECT_EQ(fmt::format("{}", fmt_eigen(value)), "11 12 13\n" "21 22 23\n" "31 32 33"); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_max_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Max) { CHECK_BINARY_FUNCTION_ADS_ADS(max, x, y, 0.5); CHECK_BINARY_FUNCTION_ADS_ADS(max, x, y, -0.3); CHECK_BINARY_FUNCTION_ADS_ADS(max, y, x, 0.4); CHECK_BINARY_FUNCTION_ADS_ADS(max, y, x, -0.4); } TEST_F(AutoDiffXdTest, TieBreakingCheckMaxBothNonEmpty) { // Given `max(v1, v2)`, our overload returns the first argument `v1` when // `v1 == v2` holds if both `v1` and `v2` have non-empty derivatives. In // Drake, we rely on this implementation-detail. This test checks if the // property holds so that we can detect a possible change in future. const AutoDiffXd v1{1.0, Vector1<double>(3.)}; const AutoDiffXd v2{1.0, Vector1<double>(2.)}; EXPECT_EQ(max(v1, v2).derivatives()[0], 3.0); // Returns v1, not v2. } TEST_F(AutoDiffXdTest, TieBreakingCheckMaxOneNonEmpty) { // Given `max(v1, v2)`, our overload returns whichever argument has non-empty // derivatives in the case where only one has non-empty derivatives. In // Drake, we rely on this implementation-detail. This test checks if the // property holds so that we can detect a possible change in future. const AutoDiffXd v1{1.0}; const AutoDiffXd v2{1.0, Vector1<double>(2.)}; EXPECT_TRUE(CompareMatrices(min(v1, v2).derivatives(), Vector1<double>(2.))); // Returns v2, not v1. EXPECT_TRUE(CompareMatrices(min(v2, v1).derivatives(), Vector1<double>(2.))); // Returns v2, not v1. } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/cond_test.cc
#include "drake/common/cond.h" #include <gtest/gtest.h> #include "drake/common/double_overloads.h" namespace drake { namespace { // Mostly, this just checks for compilation failures. GTEST_TEST(CondTest, BasicTest) { const double x = cond(true, 1, 2); const double y = cond(false, 3, 4); EXPECT_EQ(x, 1); EXPECT_EQ(y, 4); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/scoped_singleton_test.cc
#include "drake/common/scoped_singleton.h" #include <chrono> #include <memory> #include <string> #include <thread> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/never_destroyed.h" namespace drake { namespace { using std::make_shared; using std::shared_ptr; using std::weak_ptr; /* * A trivial singleton class that tracks the total number of instances alive. */ class InstanceCountedDummy { public: InstanceCountedDummy() { const int momentary_total = ++mutable_instance_count(); DRAKE_DEMAND(momentary_total <= max_instance_count()); } ~InstanceCountedDummy() { const int momentary_total = --mutable_instance_count(); DRAKE_DEMAND(momentary_total >= 0); } static int instance_count() { return mutable_instance_count(); } static int max_instance_count() { return mutable_max_instance_count(); } static std::atomic<int>& mutable_instance_count() { static never_destroyed<std::atomic<int>> global_counter(0); return global_counter.access(); } static std::atomic<int>& mutable_max_instance_count() { static never_destroyed<std::atomic<int>> global_counter(1); return global_counter.access(); } }; // Trivial type for specializing. struct Specialized {}; /* * Test neatly nested locks. */ GTEST_TEST(ScopedSingletonTest, NestedAndSpecializedTest) { InstanceCountedDummy::mutable_max_instance_count() = 2; weak_ptr<InstanceCountedDummy> wref; EXPECT_EQ(0, wref.use_count()); EXPECT_EQ(0, InstanceCountedDummy::instance_count()); { auto ref_1 = GetScopedSingleton<InstanceCountedDummy>(); wref = ref_1; EXPECT_EQ(1, wref.use_count()); EXPECT_EQ(1, InstanceCountedDummy::instance_count()); { auto ref_2 = GetScopedSingleton<InstanceCountedDummy>(); EXPECT_EQ(2, wref.use_count()); EXPECT_EQ(1, InstanceCountedDummy::instance_count()); // Use specialized version. auto ref_a = GetScopedSingleton<InstanceCountedDummy, Specialized>(); EXPECT_EQ(1, ref_a.use_count()); // Original singleton's reference count should not change. EXPECT_EQ(2, wref.use_count()); // We should have two unique InstanceCountedDummy instances. EXPECT_EQ(2, InstanceCountedDummy::instance_count()); } EXPECT_EQ(1, wref.use_count()); EXPECT_EQ(1, InstanceCountedDummy::instance_count()); } EXPECT_EQ(0, wref.use_count()); EXPECT_EQ(0, InstanceCountedDummy::instance_count()); } GTEST_TEST(ScopedSingletonTest, ThreadedTest) { // Abort if a violation of the singleton requirement is detected. InstanceCountedDummy::mutable_max_instance_count() = 1; EXPECT_EQ(InstanceCountedDummy::instance_count(), 0); // In each thread, ask for a singleton reference and then sleep. auto thread_action = []() { auto handle = GetScopedSingleton<InstanceCountedDummy>(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); }; // Launch many threads as quickly as possible, each doing thread_action. std::vector<std::thread> threads; for (int i = 0; i < 20; ++i) { threads.emplace_back(thread_action); } // Wait for them all to finish. for (auto& item : threads) { item.join(); } EXPECT_EQ(InstanceCountedDummy::instance_count(), 0); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiff_overloads_test.cc
#include <type_traits> #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/cond.h" #include "drake/common/eigen_types.h" #include "drake/common/extract_double.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" using Eigen::MatrixXd; using Eigen::VectorXd; namespace drake { namespace common { namespace { // Test nominal behavior of `AutoDiff`, checking implicit and explicit casting. GTEST_TEST(AutodiffOverloadsTest, Casting) { VectorXd dx(3); dx << 0, 1, 2; VectorXd dx0(3); dx0.setZero(); // No derivatives supplied. AutoDiffXd x(1); EXPECT_EQ(x.value(), 1); EXPECT_EQ(x.derivatives().size(), 0); // Persists. x = 2; EXPECT_EQ(x.value(), 2); EXPECT_EQ(x.derivatives().size(), 0); // Update derivative. x.derivatives() = dx; EXPECT_EQ(x.value(), 2); EXPECT_EQ(x.derivatives(), dx); // Implicitly castable, resets derivatives to zero. x = 10; EXPECT_EQ(x.value(), 10); EXPECT_EQ(x.derivatives(), dx0); // Resets derivative size. x = AutoDiffXd(10); EXPECT_EQ(x.value(), 10); EXPECT_EQ(x.derivatives().size(), 0); // Only explicitly castable to double. double xs = x.value(); EXPECT_EQ(xs, 10); // Can mix zero-size derivatives: interpreted as constants. x = AutoDiffXd(2, dx); AutoDiffXd y(3); AutoDiffXd z = x * y; EXPECT_EQ(z.value(), 6); EXPECT_EQ(z.derivatives().size(), 3); // The following causes failure, because of mixed derivative size. // y.derivatives() = VectorXd::Zero(2); // EXPECT_EQ((x * y).value(), 10); } // Tests ExtractDoubleOrThrow on autodiff. GTEST_TEST(AutodiffOverloadsTest, ExtractDouble) { // On autodiff. Eigen::AutoDiffScalar<Eigen::Vector2d> x; x.value() = 1.0; EXPECT_EQ(ExtractDoubleOrThrow(x), 1.0); // A double still works, too. double y = 1.0; EXPECT_EQ(ExtractDoubleOrThrow(y), 1.0); // Eigen variant. Vector2<Eigen::AutoDiffScalar<Eigen::Vector2d>> v{9.0, 7.0}; EXPECT_TRUE( CompareMatrices(ExtractDoubleOrThrow(v), Eigen::Vector2d{9.0, 7.0})); } // Tests correctness of nexttoward. GTEST_TEST(AutodiffOverloadsTest, NextToward) { const long double inf = std::numeric_limits<long double>::infinity(); const double eps = std::numeric_limits<double>::epsilon(); Eigen::AutoDiffScalar<Eigen::Vector2d> x; x.value() = 1.0; EXPECT_EQ(nexttoward(x, inf) - 1, eps); } // Tests correctness of isfinite. GTEST_TEST(AutodiffOverloadsTest, IsFinite) { Eigen::AutoDiffScalar<Eigen::Vector2d> x; x.value() = 1.0 / 0.0; EXPECT_EQ(isfinite(x), false); x.value() = 0.0; EXPECT_EQ(isfinite(x), true); x.derivatives()[0] = 1.0 / 0.0; // The derivatives() are ignored. EXPECT_EQ(isfinite(x), true); } // Tests correctness of isinf. GTEST_TEST(AutodiffOverloadsTest, IsInf) { Eigen::AutoDiffScalar<Eigen::Vector2d> x; x.value() = 1.0 / 0.0; EXPECT_EQ(isinf(x), true); x.value() = 0.0; EXPECT_EQ(isinf(x), false); x.derivatives()[0] = 1.0 / 0.0; // The derivatives() are ignored. EXPECT_EQ(isinf(x), false); } // Tests correctness of isnan. GTEST_TEST(AutodiffOverloadsTest, IsNaN) { Eigen::AutoDiffScalar<Eigen::Vector2d> x; x.value() = 0.0 / 0.0; EXPECT_EQ(isnan(x), true); x.value() = 0.0; EXPECT_EQ(isnan(x), false); } GTEST_TEST(AutodiffOverloadsTests, CopySign) { Eigen::AutoDiffScalar<Eigen::Vector2d> x, y, z; x.derivatives() = Eigen::VectorXd::Unit(2, 0); y.derivatives() = Eigen::VectorXd::Unit(2, 1); // Positive, positive. x.value() = 1.1; y.value() = 2.5; z = copysign(x, y); EXPECT_DOUBLE_EQ(z.value(), x.value()); EXPECT_TRUE(CompareMatrices(z.derivatives(), x.derivatives())); // Positive, negative. x.value() = 1.1; y.value() = -2.5; z = copysign(x, y); EXPECT_DOUBLE_EQ(z.value(), -x.value()); EXPECT_TRUE(CompareMatrices(z.derivatives(), -x.derivatives())); // Negative, positive. x.value() = -1.1; y.value() = 2.5; z = copysign(x, y); EXPECT_DOUBLE_EQ(z.value(), -x.value()); EXPECT_TRUE(CompareMatrices(z.derivatives(), -x.derivatives())); // Negative, negative. x.value() = -1.1; y.value() = -2.5; z = copysign(x, y); EXPECT_DOUBLE_EQ(z.value(), x.value()); EXPECT_TRUE(CompareMatrices(z.derivatives(), x.derivatives())); // Test w/ double y (Negative, positive). z = copysign(x, 2.5); EXPECT_DOUBLE_EQ(z.value(), -x.value()); EXPECT_TRUE(CompareMatrices(z.derivatives(), -x.derivatives())); } // Tests that pow(AutoDiffScalar, AutoDiffScalar) applies the chain rule. GTEST_TEST(AutodiffOverloadsTest, Pow) { Eigen::AutoDiffScalar<Eigen::Vector2d> x; x.value() = 1.1; x.derivatives() = Eigen::VectorXd::Unit(2, 0); Eigen::AutoDiffScalar<Eigen::Vector2d> y; y.value() = 2.5; y.derivatives() = Eigen::VectorXd::Unit(2, 1); x = x * (y + 2); EXPECT_DOUBLE_EQ(4.95, x.value()); // The derivative of x with respect to its original value is y + 2 = 4.5. EXPECT_DOUBLE_EQ(4.5, x.derivatives()[0]); // The derivative of x with respect to y is x = 1.1. EXPECT_DOUBLE_EQ(1.1, x.derivatives()[1]); // The following should be the same as `pow(x, y)`, but we want to test this // one to check Drake's pow(ADS<DerType&>, ADS<DerType&>) works. auto z = pow(x + 0.0, y + 0.0); // z is x^y = 4.95^2.5 ~= 54.51. EXPECT_DOUBLE_EQ(std::pow(4.95, 2.5), z.value()); // ∂z/∂x is y*x^(y-1) = 2.5 * 4.95^1.5 ~= 27.53. const double dzdx = 2.5 * std::pow(4.95, 1.5); // ∂z/∂y is (x^y)*ln(x) = (4.95^2.5)*ln(4.95) ~= 87.19. const double dzdy = std::pow(4.95, 2.5) * std::log(4.95); // By the chain rule, dz/dv is 27.53 * xgrad + 87.19 * ygrad EXPECT_DOUBLE_EQ(dzdx * 4.5 + dzdy * 0.0, z.derivatives()[0]); EXPECT_DOUBLE_EQ(dzdx * 1.1 + dzdy * 1.0, z.derivatives()[1]); } // Tests that pow(AutoDiffScalar, AutoDiffScalar) computes sane derivatives for // base^exponent at the corner case base = 0, exponent.derivatives() = {0}. GTEST_TEST(AutodiffOverloadsTest, PowEmptyExponentDerivative) { Eigen::AutoDiffScalar<Vector1d> x; x.value() = 0.; x.derivatives() = Eigen::VectorXd::Unit(1, 0); Eigen::AutoDiffScalar<Vector1d> y; y.value() = 2.5; y.derivatives() = Eigen::VectorXd::Zero(1); const auto z = pow(x, y); EXPECT_DOUBLE_EQ(0., z.value()); // ∂z/∂v = ∂z/∂x, which is y*x^(y-1) = 0 (as opposed to NAN, had the chain // rule been applied). EXPECT_TRUE(CompareMatrices(Vector1d{0.}, z.derivatives())); } GTEST_TEST(AutodiffOverloadsTest, IfThenElse1) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{if_then_else(x >= 0, x * x, x * x * x)}; EXPECT_DOUBLE_EQ(y.value(), x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * 2 * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[1], 2 * x.value()); } GTEST_TEST(AutodiffOverloadsTest, IfThenElse2) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{-10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{if_then_else(x >= 0, x * x, x * x * x)}; EXPECT_DOUBLE_EQ(y.value(), x.value() * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * 3 * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[1], 3 * x.value() * x.value()); } GTEST_TEST(AutodiffOverloadsTest, IfThenElse3) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{if_then_else(x >= 0, x + 1, x)}; EXPECT_DOUBLE_EQ(y.value(), x.value() + 1); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * 1); EXPECT_DOUBLE_EQ(y.derivatives()[1], 1); } GTEST_TEST(AutodiffOverloadsTest, IfThenElse4) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{-10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{if_then_else(x >= 0, x, x)}; EXPECT_DOUBLE_EQ(y.value(), x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2); EXPECT_DOUBLE_EQ(y.derivatives()[1], 1); } GTEST_TEST(AutodiffOverloadsTest, IfThenElse5) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{-10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{if_then_else(x >= 0, -x, -x * x * x)}; EXPECT_DOUBLE_EQ(y.value(), -x.value() * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * -3 * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[1], -3 * x.value() * x.value()); } GTEST_TEST(AutodiffOverloadsTest, IfThenElse6) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{if_then_else(x >= 0, -x, x * x * x)}; EXPECT_DOUBLE_EQ(y.value(), -x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * -1); EXPECT_DOUBLE_EQ(y.derivatives()[1], -1); } GTEST_TEST(AutodiffOverloadsTest, IfThenElse7) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{5.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> z{if_then_else(true, x * x, y * y * y)}; EXPECT_DOUBLE_EQ(z.value(), x.value() * x.value()); EXPECT_DOUBLE_EQ(z.derivatives()[0], 2 * 2 * x.value()); EXPECT_DOUBLE_EQ(z.derivatives()[1], 2 * x.value()); } GTEST_TEST(AutodiffOverloadsTest, IfThenElse8) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{5.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> z{if_then_else(false, x * x, y * y * y)}; EXPECT_DOUBLE_EQ(z.value(), y.value() * y.value() * y.value()); EXPECT_DOUBLE_EQ(z.derivatives()[0], 2 * 3 * y.value() * y.value()); EXPECT_DOUBLE_EQ(z.derivatives()[1], 3 * y.value() * y.value()); } GTEST_TEST(AutodiffOverloadsTest, Cond1) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{-10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{cond(x >= 0, x * x, x * x * x)}; EXPECT_DOUBLE_EQ(y.value(), x.value() * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * 3 * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[1], 3 * x.value() * x.value()); } GTEST_TEST(AutodiffOverloadsTest, Cond2) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{cond(x >= 0, x * x, x * x * x)}; EXPECT_DOUBLE_EQ(y.value(), x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * 2 * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[1], 2 * x.value()); } GTEST_TEST(AutodiffOverloadsTest, Cond3) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{10.0, DerType{2, 1}}; // clang-format off Eigen::AutoDiffScalar<DerType> y{cond(x >= 10, 10 * x * x, x >= 5, 5 * x * x * x, x >= 3, -3 * x, x * x)}; // clang-format on EXPECT_DOUBLE_EQ(y.value(), 10 * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * 10 * 2 * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[1], 10 * 2 * x.value()); } GTEST_TEST(AutodiffOverloadsTest, Cond4) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{8.0, DerType{2, 1}}; // clang-format off Eigen::AutoDiffScalar<DerType> y{cond(x >= 10, 10 * x * x, x >= 5, 5 * x * x * x, x >= 3, -3 * x, x * x)}; // clang-format on EXPECT_DOUBLE_EQ(y.value(), 5 * x.value() * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * 5 * 3 * x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[1], 5 * 3 * x.value() * x.value()); } GTEST_TEST(AutodiffOverloadsTest, Cond5) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{4.0, DerType{2, 1}}; // clang-format off Eigen::AutoDiffScalar<DerType> y{cond(x >= 10, 10 * x * x, x >= 5, 5 * x * x * x, x >= 3, -3 * x, x * x)}; // clang-format on EXPECT_DOUBLE_EQ(y.value(), -3 * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * -3); EXPECT_DOUBLE_EQ(y.derivatives()[1], -3); } GTEST_TEST(AutodiffOverloadsTest, Cond6) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{2.0, DerType{2, 1}}; // clang-format off Eigen::AutoDiffScalar<DerType> y{cond(x >= 10, 10 * x * x, x >= 5, 5 * x * x * x, x >= 3, -3 * x, x * x)}; // clang-format on EXPECT_DOUBLE_EQ(y.value(), x.value() * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[0], 2 * 2 * x.value()); EXPECT_DOUBLE_EQ(y.derivatives()[1], 2 * x.value()); } GTEST_TEST(AutodiffOverloadsTest, Cond7) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{10.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{2.0, DerType{4, 2}}; // clang-format off Eigen::AutoDiffScalar<DerType> z{cond(x >= 10, 10 * x * x, x >= 5, 5 * y * y * y, x * x)}; // clang-format on EXPECT_DOUBLE_EQ(z.value(), 10 * x.value() * x.value()); EXPECT_DOUBLE_EQ(z.derivatives()[0], 2 * 10 * 2 * x.value()); EXPECT_DOUBLE_EQ(z.derivatives()[1], 10 * 2 * x.value()); } GTEST_TEST(AutodiffOverloadsTest, Cond8) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{7.0, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{2.0, DerType{4, 2}}; // clang-format off Eigen::AutoDiffScalar<DerType> z{cond(x >= 10, 10 * x * x, x >= 5, 5 * y * y * y, x * x)}; // clang-format on EXPECT_DOUBLE_EQ(z.value(), 5 * y.value() * y.value() * y.value()); EXPECT_DOUBLE_EQ(z.derivatives()[0], 4 * 5 * 3 * y.value() * y.value()); EXPECT_DOUBLE_EQ(z.derivatives()[1], 2 * 5 * 3 * y.value() * y.value()); } GTEST_TEST(AutodiffOverloadsTest, Cond9) { using DerType = Eigen::Vector2d; Eigen::AutoDiffScalar<DerType> x{3, DerType{2, 1}}; Eigen::AutoDiffScalar<DerType> y{2.0, DerType{4, 2}}; // clang-format off Eigen::AutoDiffScalar<DerType> z{cond(x >= 10, 10 * x * x, x >= 5, 5 * y * y * y, x * x)}; // clang-format on EXPECT_DOUBLE_EQ(z.value(), x.value() * x.value()); EXPECT_DOUBLE_EQ(z.derivatives()[0], 2 * 2 * x.value()); EXPECT_DOUBLE_EQ(z.derivatives()[1], 2 * x.value()); } // This is just a sanity check to make sure that Eigen::NumTraits::Literal // is the right way to dig through an AutoDiffScalar to find the underlying // floating point type. If this compiles it succeeds. GTEST_TEST(AutodiffOverloadsTest, CheckEigenLiteral) { using DerTyped = Eigen::Vector2d; using DerTypef = Eigen::Vector2f; using Td = Eigen::AutoDiffScalar<DerTyped>; using Tf = Eigen::AutoDiffScalar<DerTypef>; using Literald = typename Eigen::NumTraits<Td>::Literal; using Literalf = typename Eigen::NumTraits<Tf>::Literal; static_assert(std::is_same_v<Literald, double> && std::is_same_v<Literalf, float>, "Eigen::NumTraits<T>::Literal didn't behave as expected."); } GTEST_TEST(AutodiffOverloadsTest, DummyValueX) { using T = Eigen::AutoDiffScalar<Eigen::VectorXd>; const T dummy_xd = dummy_value<T>::get(); const double value = dummy_xd.value(); EXPECT_TRUE(std::isnan(value)); const Eigen::VectorXd derivatives = dummy_xd.derivatives(); EXPECT_EQ(derivatives.rows(), 0); } GTEST_TEST(AutodiffOverloadsTest, DummyValue2) { using T = Eigen::AutoDiffScalar<Eigen::Vector2d>; const T dummy_2d = dummy_value<T>::get(); const double value = dummy_2d.value(); EXPECT_TRUE(std::isnan(value)); const Eigen::Vector2d derivatives = dummy_2d.derivatives(); EXPECT_EQ(derivatives.rows(), 2); EXPECT_TRUE(std::isnan(derivatives(0))); EXPECT_TRUE(std::isnan(derivatives(1))); } } // namespace } // namespace common } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_heap_test.cc
#include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/limit_malloc.h" using Eigen::VectorXd; namespace drake { namespace test { namespace { // Provide some autodiff variables that don't expire at scope end for test // cases. class AutoDiffXdHeapTest : public ::testing::Test { protected: AutoDiffXd x_{0.4, Eigen::VectorXd::Ones(3)}; AutoDiffXd y_{0.3, Eigen::VectorXd::Ones(3)}; }; // @note The test cases use a sum in function arguments to induce a temporary // that can potentially be consumed by pass-by-value optimizations. As of this // writing, none of the tested functions uses the optimization, so current heap // counts are a baseline for the existing implementations. // @note The tests cases use `volatile` variables to prevent optimizers from // removing the tested function calls entirely. As of this writing, there is no // evidence that the technique is strictly necessary. However, future // implementations may be vulnerable to dead-code elimination. TEST_F(AutoDiffXdHeapTest, Abs) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = abs(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Abs2) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = abs2(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Acos) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = acos(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Asin) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = asin(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Atan) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = atan(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Atan2) { { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = atan2(x_ + y_, y_); } { LimitMalloc guard({.max_num_allocations = 2, .min_num_allocations = 2}); // Right-hand parameter moves are blocked by code in Eigen; see #14039. volatile auto v = atan2(y_, x_ + y_); } } TEST_F(AutoDiffXdHeapTest, Cos) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = cos(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Cosh) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = cosh(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Exp) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = exp(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Log) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = log(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Min) { LimitMalloc guard({.max_num_allocations = 4, .min_num_allocations = 4}); volatile auto v = min(x_ + y_, y_); volatile auto w = min(x_, x_ + y_); } TEST_F(AutoDiffXdHeapTest, Max) { LimitMalloc guard({.max_num_allocations = 4, .min_num_allocations = 4}); volatile auto v = max(x_ + y_, y_); volatile auto w = max(x_, x_ + y_); } TEST_F(AutoDiffXdHeapTest, Pow) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = pow(x_ + y_, 2.0); } TEST_F(AutoDiffXdHeapTest, Sin) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = sin(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Sinh) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = sinh(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Sqrt) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = sqrt(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Tan) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = tan(x_ + y_); } TEST_F(AutoDiffXdHeapTest, Tanh) { LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1}); volatile auto v = tanh(x_ + y_); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/timer_test.cc
#include "drake/common/timer.h" #include <thread> #include "gtest/gtest.h" namespace drake { GTEST_TEST(TimeTest, Everything) { SteadyTimer timer; // Clock starts upon construction. Allow some time to pass and confirm // positive measurement. using std::chrono::duration; const duration<double> kTestInterval = std::chrono::milliseconds(100); std::this_thread::sleep_for(kTestInterval); // sleep for at least 100ms const double T1 = timer.Tick(); EXPECT_GT(T1, 0.0); EXPECT_GE(T1, kTestInterval.count()); // Start restarts the timer, the new measurement should be less than T1. timer.Start(); const double T2 = timer.Tick(); EXPECT_GE(T2, 0.0); EXPECT_LT(T2, T1); // ensure we measured less time after call to Start() // As time progresses, the tick value monotonically increases. EXPECT_GT(timer.Tick(), T2); } } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/extract_double_test.cc
#include "drake/common/extract_double.h" #include <stdexcept> #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace { GTEST_TEST(ExtractDoubleTest, BasicTest) { // A double works. double x = 1.0; EXPECT_EQ(ExtractDoubleOrThrow(x), 1.0); // A const double works. const double y = 2.0; EXPECT_EQ(ExtractDoubleOrThrow(y), 2.0); } GTEST_TEST(ExtractDoubleTest, MatrixTest) { // Fixed size matrices work. Eigen::Matrix2d x; x << 1.0, 2.0, 3.0, 4.0; EXPECT_TRUE(CompareMatrices(ExtractDoubleOrThrow(x), x)); // Dynamically-sized matrices work. Eigen::MatrixXd y(1, 5); y << 1, 2, 3, 4, 5; EXPECT_TRUE(CompareMatrices(ExtractDoubleOrThrow(y), y)); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_cos_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Cos) { CHECK_UNARY_FUNCTION(cos, x, y, 0.1); CHECK_UNARY_FUNCTION(cos, x, y, -0.1); CHECK_UNARY_FUNCTION(cos, y, x, 0.1); CHECK_UNARY_FUNCTION(cos, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/find_runfiles_test.cc
#include "drake/common/find_runfiles.h" #include <filesystem> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/temp_directory.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/text_logging.h" namespace drake { namespace { GTEST_TEST(FindRunfilesTest, AcceptanceTest) { EXPECT_TRUE(HasRunfiles()); const auto result = FindRunfile( "drake/common/test/find_resource_test_data.txt"); drake::log()->debug("result.abspath: {}", result.abspath); EXPECT_GT(result.abspath.size(), 0); EXPECT_TRUE(std::filesystem::is_regular_file({result.abspath})); EXPECT_EQ(result.error, ""); } GTEST_TEST(FindRunfilesTest, NotDeclaredTest) { const auto result = FindRunfile("foo"); EXPECT_THAT(result.error, testing::MatchesRegex( "Sought 'foo' in runfiles directory '.*' but " "the file does not exist at that location nor is it on the " "manifest; perhaps a 'data = ..' dependency is missing.")); }; GTEST_TEST(FindRunfilesTest, AbsolutePathTest) { const auto result = FindRunfile("/dev/null"); EXPECT_THAT(result.error, testing::MatchesRegex( ".*must not be an absolute path.*")); }; GTEST_TEST(FindRunfilesTest, EmptyPathTest) { const auto result = FindRunfile(""); EXPECT_THAT(result.error, testing::MatchesRegex( ".*must not be empty.*")); }; } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/lib_is_real.cc
// This is a dummy source file and function to create `lib_is_real.so` for // `find_loaded_library_test`. void lib_is_real_dummy_function() {}
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/drake_assert_test.cc
#include "drake/common/drake_assert.h" #include <string> #include <vector> #include <gtest/gtest.h> namespace { GTEST_TEST(DrakeAssertTest, MatchingConfigTest) { #ifdef DRAKE_ASSERT_IS_ARMED EXPECT_TRUE(::drake::kDrakeAssertIsArmed); EXPECT_FALSE(::drake::kDrakeAssertIsDisarmed); #else EXPECT_FALSE(::drake::kDrakeAssertIsArmed); EXPECT_TRUE(::drake::kDrakeAssertIsDisarmed); #endif #ifdef DRAKE_ASSERT_IS_DISARMED EXPECT_FALSE(::drake::kDrakeAssertIsArmed); EXPECT_TRUE(::drake::kDrakeAssertIsDisarmed); #else EXPECT_TRUE(::drake::kDrakeAssertIsArmed); EXPECT_FALSE(::drake::kDrakeAssertIsDisarmed); #endif } namespace { [[maybe_unused]] void VoidFunction() {} } GTEST_TEST(DrakeAssertTest, AssertVoidCompilesOkay) { DRAKE_ASSERT_VOID(VoidFunction()); } // Note that Drake's styleguide forbids death tests, but our only choice here // is to use death tests because our implementation is documented to abort(). GTEST_TEST(DrakeAssertDeathTest, DemandTest) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ASSERT_DEATH( { DRAKE_DEMAND(false); }, "abort: Failure at .*drake_assert_test.cc:.. in TestBody..: " "condition 'false' failed"); } struct BoolConvertible { operator bool() const { return true; } }; GTEST_TEST(DrakeAssertDeathTest, AssertSyntaxTest) { // These should compile. DRAKE_ASSERT((2 + 2) == 4); DRAKE_ASSERT(BoolConvertible()); } GTEST_TEST(DrakeAssertDeathTest, AssertFalseTest) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; if (::drake::kDrakeAssertIsArmed) { ASSERT_DEATH( { DRAKE_ASSERT(2 + 2 == 5); }, "abort: Failure at .*drake_assert_test.cc:.. in TestBody..: " "condition '2 \\+ 2 == 5' failed"); } else { DRAKE_ASSERT(2 + 2 == 5); } } GTEST_TEST(DrakeAssertDeathTest, AssertVoidTestArmed) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; if (::drake::kDrakeAssertIsArmed) { ASSERT_DEATH( { DRAKE_ASSERT_VOID(::abort()); }, ""); } else { DRAKE_ASSERT_VOID(::abort()); } } } // namespace
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/drake_cc_googletest_main_test.py
"""This program unit tests the command-line processing capabilities of the drake_cc_googletest bazel macro, by running `bazel-bin/drake/common/drake_cc_googletest_main_test` with a variety of command-line flags. """ import re import subprocess import os import sys import unittest class TestGtestMain(unittest.TestCase): def setUp(self): self._main_exe, = sys.argv[1:] self.assertTrue( os.path.exists(self._main_exe), "Could not find " + self._main_exe) def _check_call(self, args, expected_returncode=0): """Run _main_exe with the given args; return output. """ try: output = subprocess.check_output( [self._main_exe] + args, stderr=subprocess.STDOUT) returncode = 0 except subprocess.CalledProcessError as e: output = e.output returncode = e.returncode self.assertEqual( returncode, expected_returncode, "Expected returncode %r from %r but got %r with output %r" % ( expected_returncode, args, returncode, output)) return output.decode('utf8') def test_pass(self): # The device under test should pass when -magic_number=1.0 is present. self._check_call(["-magic_number=1.0"], expected_returncode=0) def test_no_arguments(self): # The device under test should fail when -magic_number=1.0 is missing. output = self._check_call([], expected_returncode=1) self.assertTrue("Expected equality of these values:\n" " FLAGS_magic_number" in output) def test_help(self): # The help string should mention all options. Just spot-check for one # option from each expected contributor. output = self._check_call([ "--help", ], expected_returncode=1) self.assertGreater(len(output), 1000) self.assertTrue("Using drake_cc_googletest_main" in output) self.assertTrue("-gtest_list_tests" in output) self.assertTrue("-spdlog_level" in output) self.assertTrue("-magic_number" in output) def test_logging(self): # The spdlog flags should be able to enable debug logging. # By default, there is no debug log. log_message = "[debug] Cross your fingers for the magic_number 1" args = ["-magic_number=1.0"] output = self._check_call(args, expected_returncode=0) self.assertFalse(log_message in output, output) # Once enabled, we see a debug log. args.append("-spdlog_level=debug") output = self._check_call(args, expected_returncode=0) self.assertTrue(log_message in output, output)
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/double_overloads_test.cc
#include "drake/common/double_overloads.h" #include <gtest/gtest.h> #include "drake/common/cond.h" namespace drake { namespace common { namespace { GTEST_TEST(Cond, DoubleIfThenElse) { const double x = 10.0; const double y = 5.0; EXPECT_DOUBLE_EQ(if_then_else(x > y, x, y), x); EXPECT_DOUBLE_EQ(if_then_else(x < y, x, y), y); } GTEST_TEST(Cond, Cond0) { const double x = 10.0; // clang-format off const double cond_result{cond(true, x + 20.0, false, x + 5.0, true, x + 3.0, 0.0)}; // clang-format on EXPECT_DOUBLE_EQ(cond_result, x + 20.0); } GTEST_TEST(Cond, Cond1) { const double x = 10.0; // clang-format off const double cond_result{cond(x >= 10.0, x + 20.0, x >= 5.0, x + 5.0, x >= 3.0, x + 3.0, 0.0)}; // clang-format on EXPECT_DOUBLE_EQ(cond_result, x + 20.0); } GTEST_TEST(Cond, Cond2) { const double x = 8.0; // clang-format off const double cond_result{cond(x >= 10.0, x + 20.0, x >= 5.0, x + 5.0, x >= 3.0, x + 3.0, 0.0)}; // clang-format on EXPECT_DOUBLE_EQ(cond_result, x + 5.0); } GTEST_TEST(Cond, Cond3) { const double x = 3.0; // clang-format off const double cond_result{cond(x >= 10.0, x + 20.0, x >= 5.0, x + 5.0, x >= 3.0, x + 3.0, 0.0)}; // clang-format on EXPECT_DOUBLE_EQ(cond_result, x + 3.0); } GTEST_TEST(Cond, Cond4) { const double x = -10.0; // clang-format off const double cond_result{cond(x >= 10.0, x + 20.0, x >= 5.0, x + 5.0, x >= 3.0, x + 3.0, 0.0)}; // clang-format on EXPECT_DOUBLE_EQ(cond_result, 0.0); } } // namespace } // namespace common } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/type_safe_index_test.cc
#include "drake/common/type_safe_index.h" #include <limits> #include <regex> #include <sstream> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include <gtest/gtest.h> #include "drake/common/sorted_pair.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/expect_throws_message.h" namespace drake { namespace common { namespace { using std::regex; using std::regex_match; // Create dummy index types to exercise the functionality using AIndex = TypeSafeIndex<class A>; using BIndex = TypeSafeIndex<class B>; using std::string; // Verifies the constructor behavior -- in debug and release modes. GTEST_TEST(TypeSafeIndex, Constructor) { AIndex index(1); EXPECT_EQ(index, 1); // This also tests operator==(int). AIndex index2(index); // Copy constructor. EXPECT_EQ(index2, 1); AIndex index3(std::move(index2)); // Move constructor. EXPECT_EQ(index3, 1); EXPECT_FALSE(index2.is_valid()); // Construction with invalid index. AIndex invalid; // Default constructor. EXPECT_FALSE(invalid.is_valid()); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( AIndex(-1), "Explicitly constructing an invalid index.+"); DRAKE_EXPECT_NO_THROW(AIndex{invalid}); // Copy construct invalid index. } // Verifies the constructor behavior -- in debug and release modes. GTEST_TEST(TypeSafeIndex, IndexAssignment) { // Set up test initial conditions. AIndex index1(1); AIndex index2(2); EXPECT_NE(index2, index1); // Copy assignment[ index2 = index1; EXPECT_EQ(index2, index1); // Move assignment. AIndex index3(2); EXPECT_NE(index3, index2); index3 = std::move(index1); EXPECT_EQ(index3, index2); EXPECT_FALSE(index1.is_valid()); // Assignment involving invalid indices. // Copy assign *to* invalid. { AIndex source(3); AIndex starts_invalid; DRAKE_EXPECT_NO_THROW(starts_invalid = source); EXPECT_EQ(source, 3); EXPECT_EQ(starts_invalid, source); } // Copy assign *from* invalid. { AIndex invalid; AIndex target(3); DRAKE_EXPECT_NO_THROW(target = invalid); EXPECT_FALSE(target.is_valid()); } // Move assign *to* invalid. { AIndex invalid; AIndex target(2); EXPECT_TRUE(target.is_valid()); DRAKE_EXPECT_NO_THROW(invalid = std::move(target)); EXPECT_FALSE(target.is_valid()); EXPECT_EQ(invalid, 2); } // Move assign *from* invalid. { AIndex invalid; AIndex target(3); DRAKE_EXPECT_NO_THROW(target = std::move(invalid)); EXPECT_FALSE(target.is_valid()); EXPECT_FALSE(invalid.is_valid()); } } // Verifies implicit conversion from index to int. GTEST_TEST(TypeSafeIndex, ConversionToInt) { AIndex index(4); int four = index; EXPECT_EQ(four, index); AIndex invalid; DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(static_cast<int>(invalid), "Converting to an int.+"); } // Tests valid comparisons of like-typed index instances. GTEST_TEST(TypeSafeIndex, IndexComparisonOperators) { AIndex index1(5); AIndex index2(5); AIndex index3(7); // true-returning coverage. EXPECT_TRUE(index1 == index2); // operator== EXPECT_TRUE(index1 != index3); // operator!= EXPECT_TRUE(index1 < index3); // operator< EXPECT_TRUE(index1 <= index2); // operator<= EXPECT_TRUE(index3 > index1); // operator> EXPECT_TRUE(index2 >= index1); // operator>= // false-returning coverage. EXPECT_FALSE(index1 == index3); // operator== EXPECT_FALSE(index1 != index2); // operator!= EXPECT_FALSE(index3 < index1); // operator< EXPECT_FALSE(index3 <= index1); // operator<= EXPECT_FALSE(index1 > index3); // operator> EXPECT_FALSE(index1 >= index3); // operator>= } // Performs comparison operations on an invalid index. in Debug mode. these // operations throw. GTEST_TEST(TypeSafeIndex, InvalidIndexComparisonOperators) { AIndex valid(1); AIndex invalid; // Comparison operators. DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(invalid == valid, "Testing == with invalid LHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(valid == invalid, "Testing == with invalid RHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(invalid != valid, "Testing != with invalid LHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(valid != invalid, "Testing != with invalid RHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(invalid < valid, "Testing < with invalid LHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(valid < invalid, "Testing < with invalid RHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(invalid <= valid, "Testing <= with invalid LHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(valid <= invalid, "Testing <= with invalid RHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(invalid > valid, "Testing > with invalid LHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(valid > invalid, "Testing > with invalid RHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(invalid >= valid, "Testing >= with invalid LHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(valid >= invalid, "Testing >= with invalid RHS.+"); } // Tests the prefix increment behavior. GTEST_TEST(TypeSafeIndex, PrefixIncrement) { AIndex index(8); EXPECT_EQ(index, AIndex(8)); AIndex index_plus = ++index; EXPECT_EQ(index, AIndex(9)); EXPECT_EQ(index_plus, AIndex(9)); // In Debug builds, some increment operations will throw. // Overflow produces an invalid index. AIndex max_index(std::numeric_limits<int>::max()); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( ++max_index, "Pre-incrementing produced an invalid index.+"); // Increment invalid index. AIndex invalid; DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(++invalid, "Pre-incrementing an invalid index.+"); } // Tests the postfix increment behavior. GTEST_TEST(TypeSafeIndex, PostfixIncrement) { AIndex index(8); EXPECT_EQ(index, AIndex(8)); AIndex index_plus = index++; EXPECT_EQ(index, AIndex(9)); EXPECT_EQ(index_plus, AIndex(8)); // In Debug builds, some increment operations will throw. // Overflow produces an invalid index. AIndex max_index(std::numeric_limits<int>::max()); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( max_index++, "Post-incrementing produced an invalid index.+"); // Increment invalid index. AIndex invalid; DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(invalid++, "Post-incrementing an invalid index.+"); } // Tests the prefix decrement behavior. GTEST_TEST(TypeSafeIndex, PrefixDecrement) { AIndex index(8); EXPECT_EQ(index, AIndex(8)); AIndex index_minus = --index; EXPECT_EQ(index, AIndex(7)); EXPECT_EQ(index_minus, AIndex(7)); // In Debug builds decrements leading to a negative result will throw. AIndex about_to_be_negative_index(0); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( --about_to_be_negative_index, "Pre-decrementing produced an invalid index.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(--AIndex(), "Pre-decrementing an invalid index.+"); } // Tests the postfix decrement behavior. GTEST_TEST(TypeSafeIndex, PostfixDecrement) { AIndex index(8); EXPECT_EQ(index, AIndex(8)); AIndex index_minus = index--; EXPECT_EQ(index, AIndex(7)); EXPECT_EQ(index_minus, AIndex(8)); // In Debug builds decrements leading to a negative result will throw. AIndex about_to_be_negative_index(0); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( about_to_be_negative_index--, "Post-decrementing produced an invalid index.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(AIndex()--, "Post-decrementing an invalid index.+"); } // Tests integer addition and subtraction. GTEST_TEST(TypeSafeIndex, AdditionAndSubtraction) { // NOTE: The result of binary operations will *always* be an int. To // perform these operations, the index is implicitly converted to an int in // all cases. AIndex index1(8); AIndex index2(5); EXPECT_EQ(index1 + index2, AIndex(13)); EXPECT_EQ(index1 - index2, AIndex(3)); // A negative result would be an invalid index, but it *is* a valid int. EXPECT_EQ(index2 - index1, -3); } // Tests in-place addition. GTEST_TEST(TypeSafeIndex, InPlaceAddition) { AIndex index(8); AIndex index_plus_seven = index += 7; EXPECT_EQ(index, AIndex(15)); EXPECT_EQ(index_plus_seven, AIndex(15)); EXPECT_EQ(index, index_plus_seven); // In Debug builds additions leading to a negative result will throw. // In-place with an int. AIndex about_to_be_negative_index(7); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( about_to_be_negative_index += (-9), "In-place addition with an int produced an invalid index.+"); AIndex invalid; DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( invalid += 1, "In-place addition with an int on an invalid index.+"); // In-place with an index. AIndex max_index(std::numeric_limits<int>::max()); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( max_index += AIndex(1), "In-place addition with another index produced an invalid index.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( invalid += AIndex(1), "In-place addition with another index invalid LHS.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( index += invalid, "In-place addition with another index invalid RHS.+"); } // Tests in-place subtraction. GTEST_TEST(TypeSafeIndex, InPlaceSubtract) { AIndex index(8); AIndex index_minus_seven = index -= 7; EXPECT_EQ(index, AIndex(1)); EXPECT_EQ(index_minus_seven, AIndex(1)); EXPECT_EQ(index, index_minus_seven); // In Debug builds decrements leading to a negative result will throw. // In-place with an int. AIndex about_to_be_negative_index(0); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( about_to_be_negative_index -= 7, "In-place subtraction with an int produced an invalid index.+"); AIndex invalid; DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( invalid -= -3, "In-place subtraction with an int on an invalid index.+"); // In-place with an index. about_to_be_negative_index = AIndex(0); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( about_to_be_negative_index -= AIndex(1), "In-place subtraction with another index produced an invalid index.+"); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( invalid -= AIndex(1), "In-place subtraction with another index invalid LHS.+"); about_to_be_negative_index = AIndex(0); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( about_to_be_negative_index -= invalid, "In-place subtraction with another index invalid RHS.+"); } // Tests stream insertion. GTEST_TEST(TypeSafeIndex, StreamInsertion) { AIndex index(8); std::stringstream stream; stream << index; EXPECT_EQ(stream.str(), "8"); AIndex invalid; DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(stream << invalid, "Converting to an int.+"); } // Tests conversion to string via std::to_string function. GTEST_TEST(TypeSafeIndex, ToString) { const int value = 17; AIndex index(value); EXPECT_EQ(std::to_string(index), std::to_string(value)); AIndex invalid; DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( std::to_string(invalid), "Converting to an int.+"); } // Verifies that it is not possible to convert between two different // index types. GTEST_TEST(TypeSafeIndex, ConversionNotAllowedBetweenDifferentTypes) { // Conversion is not allowed between two different index types. // Note: the extra set of parentheses are needed to avoid the test macro // getting confused with the comma inside the template brackets. EXPECT_FALSE((std::is_convertible_v<AIndex, BIndex>)); // The trivial case of course is true. EXPECT_TRUE((std::is_convertible_v<AIndex, AIndex>)); EXPECT_TRUE((std::is_convertible_v<BIndex, BIndex>)); } // Exercises the index in an STL context. This isn't intended to be exhaustive, // merely the canary in the coal mine. GTEST_TEST(TypeSafeIndex, UseInStl) { std::vector<AIndex> indices; DRAKE_EXPECT_NO_THROW(indices.resize(3)); EXPECT_FALSE(indices[0].is_valid()); DRAKE_EXPECT_NO_THROW(indices[1] = AIndex(1)); DRAKE_EXPECT_NO_THROW(indices[2] = AIndex()); // Valid for *move* assignment. AIndex invalid; DRAKE_EXPECT_NO_THROW(indices[2] = invalid); DRAKE_EXPECT_NO_THROW(indices.emplace_back(3)); DRAKE_EXPECT_NO_THROW(indices.emplace_back(AIndex(4))); DRAKE_EXPECT_NO_THROW(indices.emplace_back()); DRAKE_EXPECT_NO_THROW(indices.emplace_back(AIndex())); } //------------------------------------------------------------------- // Helper functions for testing TypeSafeIndex interoperability with certain // integer types. template <typename Scalar> void TestScalarComparisons() { Scalar small_value{10}; Scalar equal_value{15}; Scalar big_value{20}; AIndex index{static_cast<int>(equal_value)}; EXPECT_TRUE(small_value != index); EXPECT_TRUE(index != small_value); EXPECT_TRUE(equal_value == index); EXPECT_TRUE(index == equal_value); EXPECT_TRUE(small_value < index); EXPECT_TRUE(index < big_value); EXPECT_TRUE(small_value <= index); EXPECT_TRUE(index <= big_value); EXPECT_TRUE(index <= equal_value); EXPECT_TRUE(big_value > index); EXPECT_TRUE(index > small_value); EXPECT_TRUE(big_value >= index); EXPECT_TRUE(index >= small_value); EXPECT_TRUE(index >= equal_value); } template <typename Scalar> void TestScalarIncrement() { const int initial_value = 5; AIndex index{initial_value}; Scalar offset{1}; index += offset; ASSERT_EQ(index, initial_value + offset); index -= offset; ASSERT_EQ(index, initial_value); } // Explicit tests to confirm operations between integral types and indices work // as expected. GTEST_TEST(IntegralComparisons, CompareInt) { TestScalarComparisons<int>(); TestScalarIncrement<int>(); const int value = 3; AIndex constructed(value); ASSERT_TRUE(constructed.is_valid()); } GTEST_TEST(IntegralComparisons, CompareInt64) { TestScalarComparisons<int64_t>(); TestScalarIncrement<int64_t>(); // Implicit narrowing for a valid value. const int64_t valid_value = 3; AIndex valid(valid_value); ASSERT_TRUE(valid.is_valid()); // Implicit narrowing of value that is too large. In contrast to size_t // (see below), the compiler warns about compile-time issues with this // assignment. The lambda function provides sufficient indirection that // compiler won't warn about the implicit conversion of the too-large int64_t // value. auto indirect_call = [](const int64_t local_value) { AIndex a; DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( a = AIndex(local_value), "Explicitly constructing an invalid index. Type .* has an invalid " "value; it must lie in the range .*"); }; // The too-large number, when truncated, would produce a negative index which // is inherently invalid. const int64_t small_overflow_value = 2300000000; EXPECT_LT(static_cast<int>(small_overflow_value), 0); indirect_call(small_overflow_value); // The too-large number, when truncated, would produce a positive index which // is inherently valid; but the pre-truncation value is validated. const int64_t big_overflow_value = (1L << 48) | 0x1; EXPECT_GT(static_cast<int>(big_overflow_value), 0); indirect_call(big_overflow_value); } GTEST_TEST(IntegralComparisons, CompareSizeT) { TestScalarComparisons<size_t>(); TestScalarIncrement<size_t>(); // Implicit narrowing for a valid value. const size_t valid_value = 3; AIndex valid(valid_value); ASSERT_TRUE(valid.is_valid()); // Implicit narrowing of value that is too large. // The too-large number, when truncated, would produce a negative index which // is inherently invalid. const size_t small_overflow_value = 2300000000; EXPECT_LT(static_cast<int>(small_overflow_value), 0); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( AIndex(small_overflow_value), "Explicitly constructing an invalid index. Type .* has an invalid " "value; it must lie in the range .*"); // The too-large number, when truncated, would produce a positive index which // is inherently valid; but the pre-truncation value is validated. const size_t big_overflow_value = (1L << 48) | 0x1; EXPECT_GT(static_cast<int>(big_overflow_value), 0); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( AIndex(big_overflow_value), "Explicitly constructing an invalid index. Type .* has an invalid " "value; it must lie in the range .*"); // Now we test right out at the limit of the *smaller* type -- the int. const AIndex biggest_index{std::numeric_limits<int>::max()}; const size_t equal(static_cast<int>(biggest_index)); const size_t bigger = equal + 1; const size_t smaller = equal - 1; EXPECT_FALSE(biggest_index == smaller); EXPECT_TRUE(biggest_index != smaller); EXPECT_FALSE(biggest_index < smaller); EXPECT_FALSE(biggest_index <= smaller); EXPECT_TRUE(biggest_index > smaller); EXPECT_TRUE(biggest_index >= smaller); EXPECT_TRUE(biggest_index == equal); EXPECT_FALSE(biggest_index != equal); EXPECT_FALSE(biggest_index < equal); EXPECT_TRUE(biggest_index <= equal); EXPECT_FALSE(biggest_index > equal); EXPECT_TRUE(biggest_index >= equal); EXPECT_FALSE(biggest_index == bigger); EXPECT_TRUE(biggest_index != bigger); EXPECT_TRUE(biggest_index < bigger); EXPECT_TRUE(biggest_index <= bigger); EXPECT_FALSE(biggest_index > bigger); EXPECT_FALSE(biggest_index >= bigger); } // Confirms that comparisons with unsigned types that have fewer bits than // TypeSafeIndex's underlying int report property. GTEST_TEST(TypeSafeIndex, CompareUnsignedShort) { TestScalarComparisons<uint16_t>(); TestScalarIncrement<uint16_t>(); // Test right out at the limit of the *smaller* type -- the uint16_t. const uint16_t big_unsigned = std::numeric_limits<uint16_t>::max(); const AIndex bigger_index{static_cast<int>(big_unsigned) + 1}; const AIndex smaller_index{static_cast<int>(big_unsigned) - 1}; const AIndex equal_index(static_cast<int>(big_unsigned)); EXPECT_FALSE(bigger_index == big_unsigned); EXPECT_TRUE(bigger_index != big_unsigned); EXPECT_FALSE(bigger_index < big_unsigned); EXPECT_FALSE(bigger_index <= big_unsigned); EXPECT_TRUE(bigger_index > big_unsigned); EXPECT_TRUE(bigger_index >= big_unsigned); EXPECT_TRUE(equal_index == big_unsigned); EXPECT_FALSE(equal_index != big_unsigned); EXPECT_FALSE(equal_index < big_unsigned); EXPECT_TRUE(equal_index <= big_unsigned); EXPECT_FALSE(equal_index > big_unsigned); EXPECT_TRUE(equal_index >= big_unsigned); EXPECT_FALSE(smaller_index == big_unsigned); EXPECT_TRUE(smaller_index != big_unsigned); EXPECT_TRUE(smaller_index < big_unsigned); EXPECT_TRUE(smaller_index <= big_unsigned); EXPECT_FALSE(smaller_index > big_unsigned); EXPECT_FALSE(smaller_index >= big_unsigned); } // This tests that one index cannot be *constructed* from another index type, // but can be constructed from int types. template <typename T, typename U, typename = decltype(T(U()))> bool has_construct_helper(int) { return true; } template <typename T, typename U> bool has_construct_helper(...) { return false; } template <typename T, typename U> bool has_constructor() { return has_construct_helper<T, U>(1); } GTEST_TEST(TypeSafeIndex, ConstructorAvailability) { EXPECT_FALSE((has_constructor<AIndex, BIndex>())); EXPECT_TRUE((has_constructor<AIndex, int>())); EXPECT_TRUE((has_constructor<AIndex, size_t>())); EXPECT_TRUE((has_constructor<AIndex, int64_t>())); } // Confirms that type safe indexes are configured to serve as key and/or values // within std::unordered_map GTEST_TEST(TypeSafeIndex, CompatibleWithUnorderedMap) { std::unordered_map<AIndex, std::string> indexes; AIndex a1(1), a2(2), a3(3); std::string s1("hello"), s2("unordered"), s3("map"); indexes.emplace(a1, s1); indexes.emplace(a2, s2); EXPECT_EQ(indexes.find(a3), indexes.end()); EXPECT_NE(indexes.find(a2), indexes.end()); EXPECT_NE(indexes.find(a1), indexes.end()); indexes[a3] = s3; EXPECT_NE(indexes.find(a3), indexes.end()); } // Confirms that type safe indexes are configured to serve as values // within std::unordered_set GTEST_TEST(TypeSafeIndex, CompatibleWithUnorderedSet) { std::unordered_set<AIndex> indexes; AIndex a1(1), a2(2), a3(3); indexes.emplace(a1); indexes.insert(a2); EXPECT_EQ(indexes.size(), 2); EXPECT_EQ(indexes.find(a3), indexes.end()); EXPECT_NE(indexes.find(a1), indexes.end()); EXPECT_NE(indexes.find(a2), indexes.end()); } // Confirms that a SortedPair<IndexType> can be used as a key in a hashing // container. This is representative of TypeSafeIndex's compatibility with the // DrakeHash notion. GTEST_TEST(TypeSafeIndex, SortedPairIndexHashable) { AIndex a1(1); AIndex a2(2); std::unordered_set<SortedPair<AIndex>> pairs; pairs.insert({a2, a1}); EXPECT_TRUE(pairs.contains(SortedPair<AIndex>(a1, a2))); } } // namespace } // namespace common } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/find_resource_test_data.txt
Test data for drake/common/test/find_resource_test.cc.
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/text_logging_test.cc
#include "drake/common/text_logging.h" #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> // The BUILD.bazel rules must supply this flag. This test code is compiled and // run twice -- once with spdlog, and once without. #ifndef TEXT_LOGGING_TEST_SPDLOG #error Missing a required definition to compile this test case. #endif // Check for the expected HAVE_SPDLOG value. #if TEXT_LOGGING_TEST_SPDLOG #ifndef HAVE_SPDLOG #error Missing HAVE_SPDLOG. #endif #else #ifdef HAVE_SPDLOG #error Unwanted HAVE_SPDLOG. #endif #endif namespace { class Formattable { public: std::string to_string() const { return "OK"; } }; } // namespace DRAKE_FORMATTER_AS(, , Formattable, x, x.to_string()) namespace { using drake::logging::kHaveSpdlog; // Call each API function and macro to ensure that all of them compile. // These should all compile and run both with and without spdlog. GTEST_TEST(TextLoggingTest, SmokeTestFormattable) { Formattable obj; drake::log()->trace("drake::log()->trace test: {} {}", "OK", obj); drake::log()->debug("drake::log()->debug test: {} {}", "OK", obj); drake::log()->info("drake::log()->info test: {} {}", "OK", obj); drake::log()->warn("drake::log()->warn test: {} {}", "OK", obj); drake::log()->error("drake::log()->error test: {} {}", "OK", obj); drake::log()->critical("drake::log()->critical test: {} {}", "OK", obj); DRAKE_LOGGER_TRACE("DRAKE_LOGGER_TRACE macro test: {}, {}", "OK", obj); DRAKE_LOGGER_DEBUG("DRAKE_LOGGER_DEBUG macro test: {}, {}", "OK", obj); } // Check that floating point values format sensibly. We'll just test fmt // directly, since we know that spdlog uses it internally. GTEST_TEST(TextLoggingTest, FloatingPoint) { EXPECT_EQ(fmt::format("{}", 1.1), "1.1"); // This number is particularly challenging. EXPECT_EQ(fmt::format("{}", 0.009), "0.009"); } // Check that the constexpr bool is set correctly. GTEST_TEST(TextLoggingTest, ConstantTest) { #if TEXT_LOGGING_TEST_SPDLOG EXPECT_TRUE(kHaveSpdlog); #else EXPECT_FALSE(kHaveSpdlog); #endif } // Check that the "warn once" idiom compiles and doesn't crash at runtime. GTEST_TEST(TextLoggingTest, WarnOnceTest) { static const drake::logging::Warn log_once( "The log_once happened as expected."); } // Abuse gtest internals to verify that logging actually prints when enabled, // and that the default level is INFO. GTEST_TEST(TextLoggingTest, CaptureOutputTest) { testing::internal::CaptureStderr(); drake::log()->trace("bad sentinel"); drake::log()->debug("bad sentinel"); drake::log()->info("good sentinel"); std::string output = testing::internal::GetCapturedStderr(); #if TEXT_LOGGING_TEST_SPDLOG EXPECT_TRUE(output.find("good sentinel") != std::string::npos); EXPECT_TRUE(output.find("bad sentinel") == std::string::npos); #else EXPECT_EQ(output, ""); #endif } // Verify that DRAKE_LOGGER macros succeed in avoiding evaluation of their // arguments. GTEST_TEST(TextLoggingTest, DrakeMacrosDontEvaluateArguments) { int tracearg = 0, debugarg = 0; // Shouldn't increment argument whether the macro expanded or not, since // logging is off. #if TEXT_LOGGING_TEST_SPDLOG drake::log()->set_level(spdlog::level::off); #endif DRAKE_LOGGER_TRACE("tracearg={}", ++tracearg); DRAKE_LOGGER_DEBUG("debugarg={}", ++debugarg); EXPECT_EQ(tracearg, 0); EXPECT_EQ(debugarg, 0); tracearg = 0; debugarg = 0; // Should increment arg only if the macro expanded. #if TEXT_LOGGING_TEST_SPDLOG drake::log()->set_level(spdlog::level::trace); #endif DRAKE_LOGGER_TRACE("tracearg={}", ++tracearg); DRAKE_LOGGER_DEBUG("debugarg={}", ++debugarg); #ifndef NDEBUG EXPECT_EQ(tracearg, kHaveSpdlog ? 1 : 0); EXPECT_EQ(debugarg, kHaveSpdlog ? 1 : 0); #else EXPECT_EQ(tracearg, 0); EXPECT_EQ(debugarg, 0); #endif tracearg = 0; debugarg = 0; // Only DEBUG should increment arg since trace is not enabled. #if TEXT_LOGGING_TEST_SPDLOG drake::log()->set_level(spdlog::level::debug); #endif DRAKE_LOGGER_TRACE("tracearg={}", ++tracearg); DRAKE_LOGGER_DEBUG("debugarg={}", ++debugarg); #ifndef NDEBUG EXPECT_EQ(tracearg, 0); EXPECT_EQ(debugarg, kHaveSpdlog ? 1 : 0); #else EXPECT_EQ(tracearg, 0); EXPECT_EQ(debugarg, 0); #endif tracearg = 0; debugarg = 0; } GTEST_TEST(TextLoggingTest, SetLogLevel) { using drake::logging::set_log_level; #if TEXT_LOGGING_TEST_SPDLOG EXPECT_THROW(set_log_level("bad"), std::runtime_error); const std::vector<std::string> levels = { "trace", "debug", "info", "warn", "err", "critical", "off"}; const std::string first_level = set_log_level("unchanged"); std::string prev_level = "off"; set_log_level(prev_level); for (const std::string& level : levels) { EXPECT_EQ(set_log_level(level), prev_level); prev_level = level; } set_log_level(first_level); #else ASSERT_EQ(drake::logging::set_log_level("anything really"), ""); #endif } GTEST_TEST(TextLoggingTest, SetLogPattern) { using drake::logging::set_log_pattern; #if TEXT_LOGGING_TEST_SPDLOG set_log_pattern("%v"); set_log_pattern("%+"); #else set_log_pattern("anything really"); #endif } } // namespace // To enable compiling without depending on @spdlog, we need to provide our own // main routine. The default drake_cc_googletest_main depends on @spdlog. int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_cosh_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Cosh) { CHECK_UNARY_FUNCTION(cosh, x, y, 0.1); CHECK_UNARY_FUNCTION(cosh, x, y, -0.1); CHECK_UNARY_FUNCTION(cosh, y, x, 0.1); CHECK_UNARY_FUNCTION(cosh, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/drake_throw_test.cc
#include "drake/common/drake_throw.h" #include <stdexcept> #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_no_throw.h" namespace { GTEST_TEST(DrakeThrowTest, BasicTest) { DRAKE_EXPECT_NO_THROW(DRAKE_THROW_UNLESS(true)); EXPECT_THROW(DRAKE_THROW_UNLESS(false), std::runtime_error); } } // namespace
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_pow_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Pow1) { CHECK_BINARY_FUNCTION_ADS_ADS(pow, x, y, 0.3); CHECK_BINARY_FUNCTION_ADS_ADS(pow, x, y, -0.3); CHECK_BINARY_FUNCTION_ADS_ADS(pow, y, x, 0.4); CHECK_BINARY_FUNCTION_ADS_ADS(pow, y, x, -0.4); } TEST_F(AutoDiffXdTest, Pow2) { CHECK_BINARY_FUNCTION_ADS_SCALAR(pow, x, y, 0.3); CHECK_BINARY_FUNCTION_ADS_SCALAR(pow, x, y, -0.3); CHECK_BINARY_FUNCTION_ADS_SCALAR(pow, y, x, 0.4); CHECK_BINARY_FUNCTION_ADS_SCALAR(pow, y, x, -0.4); // Note that Eigen's AutoDiffScalar does not provide an implementation for // pow(double, ADS). Therefore, we do not provide tests for that here. } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/find_runfiles_fail_test.cc
#include <stdlib.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/find_runfiles.h" #include "drake/common/text_logging.h" namespace drake { namespace { // Test error message codepaths. We purposefully lobotomize the environment // variables before latch-initializing the runfiles singleton. Because we // can't reinitialize it, we can only write a single unit test in this file and // we need to keep this case separate from the find_runfiles_test.cc cases. GTEST_TEST(FindRunfilesFailTest, ErrorMessageTest) { drake::logging::set_log_level("trace"); ASSERT_EQ(::setenv("TEST_SRCDIR", "/no_such_srcdir", 1), 0); ASSERT_EQ(::unsetenv("RUNFILES_DIR"), 0); ASSERT_EQ(::unsetenv("RUNFILES_MANIFEST_FILE"), 0); EXPECT_FALSE(HasRunfiles()); const auto result = FindRunfile("drake/nothing"); EXPECT_EQ(result.abspath, ""); EXPECT_THAT(result.error, testing::MatchesRegex( "ERROR: .* cannot find runfiles .*" "created using TEST_SRCDIR with TEST_SRCDIR=/no_such_srcdir " "and RUNFILES_MANIFEST_FILE=nullptr and RUNFILES_DIR=nullptr.")); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/temp_directory_test.cc
#include "drake/common/temp_directory.h" #include <cstdlib> #include <filesystem> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" namespace drake { namespace { namespace fs = std::filesystem; GTEST_TEST(TempDirectoryTest, TestTmpdirSet) { const char* test_tmpdir = std::getenv("TEST_TMPDIR"); ASSERT_STRNE(nullptr, test_tmpdir); const std::string temp_directory_with_test_tmpdir_set = temp_directory(); EXPECT_NE('/', temp_directory_with_test_tmpdir_set.back()); fs::path temp_path(temp_directory_with_test_tmpdir_set); EXPECT_EQ(std::string(test_tmpdir), temp_path.parent_path().string()); EXPECT_THAT(temp_path.filename().string(), testing::MatchesRegex("robotlocomotion_drake_[^/]{6}$")); } GTEST_TEST(TempDirectoryTest, TestTmpdirUnset) { // Temporarily set TMP to TEST_TMPDIR and unset TEST_TMPDIR, and then see // what temp_directory() returns. const char* tmpdir = std::getenv("TMPDIR"); const char* test_tmpdir = std::getenv("TEST_TMPDIR"); ASSERT_STRNE(nullptr, test_tmpdir); DRAKE_DEMAND(::setenv("TMPDIR", test_tmpdir, 1) == 0); DRAKE_DEMAND(::unsetenv("TEST_TMPDIR") == 0); const std::string temp_directory_result = temp_directory(); // Revert the environment changes. DRAKE_DEMAND(::setenv("TEST_TMPDIR", test_tmpdir, 1) == 0); if (tmpdir == nullptr) { DRAKE_DEMAND(::unsetenv("TMPDIR") == 0); } else { DRAKE_DEMAND(::setenv("TMPDIR", tmpdir, 1) == 0); } // Check the expected result. fs::path expected_prefix(test_tmpdir); expected_prefix.append("robotlocomotion_drake_"); EXPECT_THAT(temp_directory_result, ::testing::StartsWith(expected_prefix.string())); } GTEST_TEST(TempDirectoryTest, TestTmpdirTrailingSlash) { // Temporarily append a '/' to test_tmpdir, and then see what // temp_directory() returns. const char* test_tmpdir = std::getenv("TEST_TMPDIR"); ASSERT_STRNE(nullptr, test_tmpdir); std::string new_value(test_tmpdir); new_value.push_back('/'); DRAKE_DEMAND(::setenv("TEST_TMPDIR", new_value.c_str(), 1) == 0); const std::string temp_directory_result = temp_directory(); // Revert the environment change. DRAKE_DEMAND(::setenv("TEST_TMPDIR", test_tmpdir, 1) == 0); // Check the expected result. fs::path expected_prefix(test_tmpdir); expected_prefix.append("robotlocomotion_drake_"); EXPECT_THAT(temp_directory_result, testing::Not(testing::EndsWith("/"))); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_sqrt_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Sqrt) { CHECK_UNARY_FUNCTION(sqrt, x, y, 0.1); CHECK_UNARY_FUNCTION(sqrt, x, y, -0.1); CHECK_UNARY_FUNCTION(sqrt, y, x, 0.1); CHECK_UNARY_FUNCTION(sqrt, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/random_test.cc
#include "drake/common/random.h" #include <limits> #include <type_traits> #include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/test_utilities/limit_malloc.h" namespace drake { namespace { constexpr double kEps = std::numeric_limits<double>::epsilon(); // The mt19937 inside our RandomGenerator implementation has a large block of // pre-computed internal state that is only updated (in bulk) after a certain // number of random outputs. Extracting this many outputs is sufficient to // ensure that we trigger the internal update, in case it might be relevant // to our memory-safety tests in the below. // // For details, refer to state_size (which is n == 624 in our case) here: // https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine constexpr int kNumSteps = 700; GTEST_TEST(RandomGeneratorTest, Traits) { EXPECT_TRUE(std::is_default_constructible_v<RandomGenerator>); EXPECT_TRUE(std::is_copy_constructible_v<RandomGenerator>); EXPECT_TRUE(std::is_copy_assignable_v<RandomGenerator>); EXPECT_TRUE(std::is_move_constructible_v<RandomGenerator>); EXPECT_TRUE(std::is_move_assignable_v<RandomGenerator>); } GTEST_TEST(RandomGeneratorTest, Efficiency) { // Check an insanity upper bound, to demonstrate that we don't store large // random state on the stack. EXPECT_LE(sizeof(RandomGenerator), 64); { // Default construction is heap-free. drake::test::LimitMalloc guard; RandomGenerator dut; } } // Copying a defaulted generator produces identical outputs. GTEST_TEST(RandomGeneratorTest, Copy0) { RandomGenerator foo; RandomGenerator bar(foo); for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } // Copying a seeded generator produces identical outputs. GTEST_TEST(RandomGeneratorTest, Copy1) { RandomGenerator foo(123); RandomGenerator bar(foo); for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } // Copy-assigning a defaulted generator produces identical outputs. GTEST_TEST(RandomGeneratorTest, CopyAssign0) { RandomGenerator foo; RandomGenerator bar; bar = foo; for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } // Copy-assigning a seeded generator produces identical outputs. GTEST_TEST(RandomGeneratorTest, CopyAssign1) { RandomGenerator foo(123); RandomGenerator bar; bar = foo; for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } // Moving from a defaulted generator produces identical outputs. GTEST_TEST(RandomGeneratorTest, Move0) { RandomGenerator foo; RandomGenerator temp; RandomGenerator bar(std::move(temp)); for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } // Moving from a seeded generator produces identical outputs. GTEST_TEST(RandomGeneratorTest, Move1) { RandomGenerator foo(123); RandomGenerator temp(123); RandomGenerator bar(std::move(temp)); for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } // Move-assigning from a defaulted generator produces identical outputs. GTEST_TEST(RandomGeneratorTest, MoveAssign0) { RandomGenerator foo; RandomGenerator bar; bar = RandomGenerator(); for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } // Move-assigning from a seeded generator produces identical outputs. GTEST_TEST(RandomGeneratorTest, MoveAssign1) { RandomGenerator foo(123); RandomGenerator bar; bar = RandomGenerator(123); for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } // Using a moved-from defaulted generator does not segfault. GTEST_TEST(RandomGeneratorTest, MovedFrom0) { RandomGenerator foo; RandomGenerator bar = std::move(foo); for (int i = 0; i < kNumSteps; ++i) { EXPECT_NO_THROW(foo()); EXPECT_NO_THROW(bar()); } } // Using a moved-from seeded generator does not segfault. GTEST_TEST(RandomGeneratorTest, MovedFrom1) { RandomGenerator foo(123); RandomGenerator bar = std::move(foo); for (int i = 0; i < kNumSteps; ++i) { EXPECT_NO_THROW(foo()); EXPECT_NO_THROW(bar()); } } GTEST_TEST(RandomGeneratorTest, CompareWith19337) { std::mt19937 oracle; RandomGenerator dut; EXPECT_EQ(dut.min(), oracle.min()); EXPECT_EQ(dut.max(), oracle.max()); for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(dut(), oracle()) << "with i = " << i; } } // The sequence from a default-constructed generator is the same as explicitly // passing in the default seed. GTEST_TEST(RandomGeneratorTest, DefaultMatchesSeedConstant) { RandomGenerator foo; RandomGenerator bar(RandomGenerator::default_seed); for (int i = 0; i < kNumSteps; ++i) { ASSERT_EQ(foo(), bar()) << "with i = " << i; } } template <typename T> void CheckCalcProbabilityDensityUniform() { // Sample with non-zero probability. for (const auto& x : {Vector2<T>(0.1, 0.5), Vector2<T>(0., 0.5), Vector2<T>(0.1, 1.)}) { T density = CalcProbabilityDensity<T>(RandomDistribution::kUniform, x); EXPECT_EQ(ExtractDoubleOrThrow(density), 1.); } // Sample with zero probability. for (const auto& x_zero_prob : {Vector2<T>(-0.1, 0.5), Vector2<T>(0.2, 1.5), Vector2<T>(-0.1, 1.2)}) { T density = CalcProbabilityDensity<T>(RandomDistribution::kUniform, x_zero_prob); EXPECT_EQ(ExtractDoubleOrThrow(density), 0.); } } GTEST_TEST(RandomTest, CalcProbabilityDensityUniform) { CheckCalcProbabilityDensityUniform<double>(); CheckCalcProbabilityDensityUniform<AutoDiffXd>(); } template <typename T> void CheckCalcProbabilityDensityGaussian() { for (const auto& x : {Vector3<T>(0.5, 1.2, 3.5), Vector3<T>(-0.2, -1., 2.1)}) { // Compute the pdf of each variable separately, and then multiply their // pdf together since the variables are independent. T density_expected = T(1); for (int i = 0; i < 3; ++i) { using std::exp; using std::sqrt; density_expected *= exp(-0.5 * x(i) * x(i)) / sqrt(2 * M_PI); } const T density = CalcProbabilityDensity<T>(RandomDistribution::kGaussian, x); EXPECT_NEAR(ExtractDoubleOrThrow(density), ExtractDoubleOrThrow(density_expected), 10 * kEps); } } GTEST_TEST(RandomTest, CalcProbabilityDensityGaussian) { CheckCalcProbabilityDensityGaussian<double>(); CheckCalcProbabilityDensityGaussian<AutoDiffXd>(); } template <typename T> void CheckCalcProbabilityDensityExponential() { // Check samples with non-zero probability. for (const auto& x : {Vector3<T>(0.1, 0.5, 0.), Vector3<T>(0.1, 0.9, 1.5)}) { // Compute the pdf of each variable separately, and then multiply them // together. T density_expected(1.); for (int i = 0; i < 3; ++i) { using std::exp; density_expected *= exp(-x(i)); } EXPECT_NEAR(ExtractDoubleOrThrow(CalcProbabilityDensity<T>( RandomDistribution::kExponential, x)), ExtractDoubleOrThrow(density_expected), 10 * kEps); } // Check samples with zero probability. for (const Vector3<T>& x_zero_prob : {Vector3<T>(-0.5, 1., 2.), Vector3<T>(-0.01, 0.01, 1)}) { EXPECT_EQ(ExtractDoubleOrThrow(CalcProbabilityDensity<T>( RandomDistribution::kExponential, x_zero_prob)), 0.); } } GTEST_TEST(RandomTest, CalcProbabilityDensityExponential) { CheckCalcProbabilityDensityExponential<double>(); CheckCalcProbabilityDensityExponential<AutoDiffXd>(); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_acos_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Acos) { CHECK_UNARY_FUNCTION(acos, x, y, 0.1); CHECK_UNARY_FUNCTION(acos, x, y, -0.1); CHECK_UNARY_FUNCTION(acos, y, x, 0.1); CHECK_UNARY_FUNCTION(acos, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/string_container_test.cc
#include <gtest/gtest.h> #include "drake/common/string_map.h" #include "drake/common/string_set.h" #include "drake/common/string_unordered_map.h" #include "drake/common/string_unordered_set.h" #include "drake/common/test_utilities/limit_malloc.h" namespace drake { namespace { GTEST_TEST(StringContainerTest, string_set) { string_set dut; dut.insert("hello"); dut.insert("hello"); const int count = 1; EXPECT_EQ(dut.count("hello"), count); EXPECT_EQ(dut.count(std::string{"hello"}), count); EXPECT_EQ(dut.count(std::string_view{"hello"}), count); } GTEST_TEST(StringContainerTest, string_multiset) { string_multiset dut; dut.insert("hello"); dut.insert("hello"); const int count = 2; EXPECT_EQ(dut.count("hello"), count); EXPECT_EQ(dut.count(std::string{"hello"}), count); EXPECT_EQ(dut.count(std::string_view{"hello"}), count); } GTEST_TEST(StringContainerTest, string_unordered_set) { string_unordered_set dut; dut.insert("hello"); dut.insert("hello"); const int count = 1; EXPECT_EQ(dut.count("hello"), count); EXPECT_EQ(dut.count(std::string{"hello"}), count); EXPECT_EQ(dut.count(std::string_view{"hello"}), count); // Demonstrate that the container is unordered. EXPECT_GT(dut.bucket_count(), 0); } GTEST_TEST(StringContainerTest, string_unordered_multiset) { string_unordered_multiset dut; dut.insert("hello"); dut.insert("hello"); const int count = 2; EXPECT_EQ(dut.count("hello"), count); EXPECT_EQ(dut.count(std::string{"hello"}), count); EXPECT_EQ(dut.count(std::string_view{"hello"}), count); // Demonstrate that the container is unordered. EXPECT_GT(dut.bucket_count(), 0); } GTEST_TEST(StringContainerTest, string_map) { string_map<int> dut; dut.emplace("hello", 1); dut.emplace("hello", 2); const int count = 1; EXPECT_EQ(dut.count("hello"), count); EXPECT_EQ(dut.count(std::string{"hello"}), count); EXPECT_EQ(dut.count(std::string_view{"hello"}), count); } GTEST_TEST(StringContainerTest, string_multimap) { string_multimap<int> dut; dut.emplace("hello", 1); dut.emplace("hello", 2); const int count = 2; EXPECT_EQ(dut.count("hello"), count); EXPECT_EQ(dut.count(std::string{"hello"}), count); EXPECT_EQ(dut.count(std::string_view{"hello"}), count); } GTEST_TEST(StringContainerTest, string_unordered_map) { string_unordered_map<int> dut; dut.emplace("hello", 1); dut.emplace("hello", 2); const int count = 1; EXPECT_EQ(dut.count("hello"), count); EXPECT_EQ(dut.count(std::string{"hello"}), count); EXPECT_EQ(dut.count(std::string_view{"hello"}), count); // Demonstrate that the container is unordered. EXPECT_GT(dut.bucket_count(), 0); } GTEST_TEST(StringContainerTest, string_unordered_multimap) { string_unordered_multimap<int> dut; dut.emplace("hello", 1); dut.emplace("hello", 2); const int count = 2; EXPECT_EQ(dut.count("hello"), count); EXPECT_EQ(dut.count(std::string{"hello"}), count); EXPECT_EQ(dut.count(std::string_view{"hello"}), count); // Demonstrate that the container is unordered. EXPECT_GT(dut.bucket_count(), 0); } GTEST_TEST(StringContainerTest, NoMalloc) { string_set alpha; string_multiset bravo; string_unordered_set charlie; string_unordered_multiset delta; string_map<int> echo; string_multimap<int> foxtrot; string_unordered_map<int> gulf; string_unordered_multimap<int> hotel; alpha.insert("hello"); bravo.insert("hello"); charlie.insert("hello"); delta.insert("hello"); echo.emplace("hello", 1); foxtrot.emplace("hello", 1); gulf.emplace("hello", 1); hotel.emplace("hello", 1); { drake::test::LimitMalloc guard; alpha.contains("hello"); bravo.contains("hello"); charlie.contains("hello"); delta.contains("hello"); echo.contains("hello"); foxtrot.contains("hello"); gulf.contains("hello"); hotel.contains("hello"); alpha.contains(std::string_view{"world"}); bravo.contains(std::string_view{"world"}); charlie.contains(std::string_view{"world"}); delta.contains(std::string_view{"world"}); echo.contains(std::string_view{"world"}); foxtrot.contains(std::string_view{"world"}); gulf.contains(std::string_view{"world"}); hotel.contains(std::string_view{"world"}); } } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_sinh_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Sinh) { CHECK_UNARY_FUNCTION(sinh, x, y, 0.1); CHECK_UNARY_FUNCTION(sinh, x, y, -0.1); CHECK_UNARY_FUNCTION(sinh, y, x, 0.1); CHECK_UNARY_FUNCTION(sinh, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_abs_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Abs) { CHECK_UNARY_FUNCTION(abs, x, y, 0.1); CHECK_UNARY_FUNCTION(abs, x, y, -0.1); CHECK_UNARY_FUNCTION(abs, y, x, 0.1); CHECK_UNARY_FUNCTION(abs, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/dummy_value_test.cc
#include "drake/common/dummy_value.h" #include <cmath> #include <gtest/gtest.h> namespace drake { namespace { GTEST_TEST(DummyValueTest, Double) { EXPECT_TRUE(std::isnan(dummy_value<double>::get())); } GTEST_TEST(DummyValueTest, Int) { EXPECT_NE(dummy_value<int>::get(), 0); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_abs2_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Abs2) { CHECK_UNARY_FUNCTION(abs2, x, y, 0.1); CHECK_UNARY_FUNCTION(abs2, x, y, -0.1); CHECK_UNARY_FUNCTION(abs2, y, x, 0.1); CHECK_UNARY_FUNCTION(abs2, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/drake_bool_test.cc
#include "drake/common/drake_bool.h" #include <utility> #include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/symbolic/expression.h" #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { using symbolic::Expression; using symbolic::Formula; using symbolic::Variable; using symbolic::test::ExprEqual; using symbolic::test::FormulaEqual; // --------------- // Case T = double // --------------- class BoolTestDouble : public ::testing::Test { protected: void SetUp() override { // clang-format off m_ << 1, 2, 3, 4; // clang-format on } MatrixX<double> m_{2, 2}; MatrixX<double> zero_m_{0, 0}; }; TEST_F(BoolTestDouble, TypeCheck) { static_assert(std::is_same_v<boolean<double>, bool>, "boolean<double> should be bool"); static_assert(std::is_same_v<scalar_predicate<double>::type, bool>, "scalar_predicate<double>::type should be bool"); static_assert(scalar_predicate<double>::is_bool, "scalar_predicate<double>::is_bool should be true"); } TEST_F(BoolTestDouble, All) { auto bools = Eigen::Matrix<bool, 3, 3>::Constant(true).eval(); EXPECT_TRUE(drake::all(bools)); bools(0, 0) = false; EXPECT_FALSE(drake::all(bools)); // Vacuously true. EXPECT_TRUE(drake::all(Eigen::Matrix<bool, 0, 0>::Constant(false))); } TEST_F(BoolTestDouble, AllOf) { EXPECT_TRUE(all_of(m_, [](const double v) { return v >= 0.0; })); EXPECT_FALSE(all_of(m_, [](const double v) { return v >= 2.0; })); // Vacuously true. EXPECT_TRUE(all_of(zero_m_, [](const double v) { return v >= 0.0; })); } TEST_F(BoolTestDouble, Any) { auto bools = Eigen::Matrix<bool, 3, 3>::Constant(false).eval(); EXPECT_FALSE(any(bools)); bools(0, 0) = true; EXPECT_TRUE(any(bools)); // Vacuously false. EXPECT_FALSE(any(Eigen::Matrix<bool, 0, 0>::Constant(true))); } TEST_F(BoolTestDouble, AnyOf) { EXPECT_TRUE(any_of(m_, [](const double v) { return v >= 4.0; })); EXPECT_FALSE(any_of(m_, [](const double v) { return v >= 5.0; })); // Vacuously false. EXPECT_FALSE( any_of(zero_m_, [](const double v) { return v >= 0.0; })); } TEST_F(BoolTestDouble, None) { auto bools = Eigen::Matrix<bool, 3, 3>::Constant(false).eval(); EXPECT_TRUE(none(bools)); bools(0, 0) = true; EXPECT_FALSE(none(bools)); // Vacuously true. EXPECT_TRUE(none(Eigen::Matrix<bool, 0, 0>::Constant(true))); } TEST_F(BoolTestDouble, NoneOf) { EXPECT_TRUE(none_of(m_, [](const double v) { return v >= 5.0; })); EXPECT_FALSE(none_of(m_, [](const double v) { return v >= 4.0; })); // Vacuously true. EXPECT_TRUE( none_of(zero_m_, [](const double v) { return v >= 0.0; })); } // ------------------- // Case T = AutoDiffXd // ------------------- class BoolTestAutoDiffXd : public ::testing::Test { protected: void SetUp() override { m_(0, 0) = AutoDiffXd{1., Eigen::Vector2d{1., 0.}}; m_(0, 1) = AutoDiffXd{0., Eigen::Vector2d{1., 0.}}; m_(1, 0) = AutoDiffXd{0., Eigen::Vector2d{0., 1.}}; m_(1, 1) = AutoDiffXd{1., Eigen::Vector2d{0., 1.}}; } MatrixX<AutoDiffXd> m_{2, 2}; MatrixX<AutoDiffXd> zero_m_{0, 0}; }; TEST_F(BoolTestAutoDiffXd, TypeCheck) { static_assert(std::is_same_v<boolean<AutoDiffXd>, bool>, "boolean<AutoDiffXd> should be bool"); static_assert(std::is_same_v<scalar_predicate<AutoDiffXd>::type, bool>, "scalar_predicate<AutoDiffXd>::type should be bool"); static_assert(scalar_predicate<AutoDiffXd>::is_bool, "scalar_predicate<AutoDiffXd>::is_bool should be true"); } TEST_F(BoolTestAutoDiffXd, AllOf) { EXPECT_TRUE(all_of(m_, [](const AutoDiffXd& v) { return v.derivatives()[0] == 1.0 || v.derivatives()[1] == 1.0; })); EXPECT_FALSE( all_of(m_, [](const AutoDiffXd& v) { return v >= 1.0; })); // Vacuously true. EXPECT_TRUE( all_of(zero_m_, [](const AutoDiffXd& v) { return v >= 1.0; })); } TEST_F(BoolTestAutoDiffXd, AnyOf) { EXPECT_TRUE(any_of(m_, [](const AutoDiffXd& v) { return v.derivatives()[0] == 1.0 && v.derivatives()[1] == 0.0; })); EXPECT_FALSE(any_of(m_, [](const AutoDiffXd& v) { return v.derivatives()[0] == 1.0 && v.derivatives()[1] == 1.0; })); // Vacuously false. EXPECT_FALSE( any_of(zero_m_, [](const AutoDiffXd& v) { return v >= 1.0; })); } TEST_F(BoolTestAutoDiffXd, NoneOf) { EXPECT_TRUE(none_of(m_, [](const AutoDiffXd& v) { return v.derivatives()[0] == 1.0 && v.derivatives()[1] == 1.0; })); EXPECT_FALSE(none_of(m_, [](const AutoDiffXd& v) { return v.derivatives()[0] == 1.0 && v.derivatives()[1] == 0.0; })); // Vacuously true. EXPECT_TRUE( none_of(zero_m_, [](const AutoDiffXd& v) { return v >= 1.0; })); } // ----------------------------- // Case T = symbolic::Expression // ----------------------------- class BoolTestSymbolic : public ::testing::Test { protected: void SetUp() override { // clang-format off m_ << x_, y_, z_, w_; // clang-format on } const Variable x_{"x"}; const Variable y_{"y"}; const Variable z_{"z"}; const Variable w_{"w"}; MatrixX<Expression> m_{2, 2}; MatrixX<Expression> zero_m_{0, 0}; }; TEST_F(BoolTestSymbolic, TypeCheck) { static_assert( std::is_same_v<boolean<Expression>, Formula>, "boolean<Expression> should be Formula"); static_assert( std::is_same_v<scalar_predicate<Expression>::type, Formula>, "scalar_predicate<Expression>::type should be Formula"); static_assert( !scalar_predicate<Expression>::is_bool, "scalar_predicate<Expression>::is_bool should be false"); } TEST_F(BoolTestSymbolic, All) { const MatrixX<Formula> formulae = m_.unaryExpr(&symbolic::isnan); EXPECT_PRED2(FormulaEqual, all(formulae), isnan(x_) && isnan(y_) && isnan(z_) && isnan(w_)); // Vacuously true. EXPECT_TRUE(drake::all(MatrixX<Formula>::Constant(0, 0, Formula::False()))); } TEST_F(BoolTestSymbolic, AllOf) { EXPECT_PRED2( FormulaEqual, all_of(m_, [](const Expression& v) { return !isnan(v); }), !isnan(x_) && !isnan(y_) && !isnan(z_) && !isnan(w_)); // Vacuously true. EXPECT_TRUE( all_of(zero_m_, [](const Expression& v) { return v >= 0.0; })); } TEST_F(BoolTestSymbolic, Any) { const MatrixX<Formula> formulae = m_.unaryExpr(&symbolic::isnan); EXPECT_PRED2(FormulaEqual, any(formulae), isnan(x_) || isnan(y_) || isnan(z_) || isnan(w_)); // Vacuously false. EXPECT_FALSE(any(MatrixX<Formula>::Constant(0, 0, Formula::True()))); } TEST_F(BoolTestSymbolic, AnyOf) { EXPECT_PRED2(FormulaEqual, any_of(m_, [](const Expression& v) { return isnan(v); }), isnan(x_) || isnan(y_) || isnan(z_) || isnan(w_)); // Vacuously false. EXPECT_FALSE( any_of(zero_m_, [](const Expression& v) { return v >= 0.0; })); } TEST_F(BoolTestSymbolic, None) { const MatrixX<Formula> formulae = m_.unaryExpr(&symbolic::isnan); EXPECT_PRED2(FormulaEqual, none(formulae), !isnan(x_) && !isnan(y_) && !isnan(z_) && !isnan(w_)); // Vacuously true. EXPECT_TRUE(none(MatrixX<Formula>::Constant(0, 0, Formula::False()))); } TEST_F(BoolTestSymbolic, NoneOf) { EXPECT_PRED2( FormulaEqual, none_of(m_, [](const Expression& v) { return isnan(v); }), !isnan(x_) && !isnan(y_) && !isnan(z_) && !isnan(w_)); // Vacuously true. EXPECT_TRUE( none_of(zero_m_, [](const Expression& v) { return v >= 0.0; })); } GTEST_TEST(IfThenElseTest, VectorX) { const bool predicate = true; const Eigen::VectorXd a = Eigen::Vector3d(1.0, 2.0, 3.0); const Eigen::VectorXd b = Eigen::Vector3d(4.0, 5.0, 6.0); const Eigen::VectorXd result = if_then_else(predicate, a, b); ASSERT_EQ(result.size(), 3); EXPECT_EQ(result[0], 1.0); EXPECT_EQ(result[1], 2.0); EXPECT_EQ(result[2], 3.0); } GTEST_TEST(IfThenElseTest, Vector3) { const bool predicate = false; const Eigen::Vector3d a = Eigen::Vector3d(1.0, 2.0, 3.0); const Eigen::Vector3d b = Eigen::Vector3d(4.0, 5.0, 6.0); const Eigen::Vector3d result = if_then_else(predicate, a, b); EXPECT_EQ(result[0], 4.0); EXPECT_EQ(result[1], 5.0); EXPECT_EQ(result[2], 6.0); } GTEST_TEST(IfThenElseTest, VectorBad) { const bool predicate = true; const Eigen::VectorXd a = Eigen::VectorXd::Zero(2); const Eigen::VectorXd b = Eigen::VectorXd::Zero(3); EXPECT_THROW(if_then_else(predicate, a, b), std::exception); } } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_atan2_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Atan2) { CHECK_BINARY_FUNCTION_ADS_ADS(atan2, x, y, 0.1); CHECK_BINARY_FUNCTION_ADS_ADS(atan2, x, y, -0.1); CHECK_BINARY_FUNCTION_ADS_ADS(atan2, y, x, 0.4); CHECK_BINARY_FUNCTION_ADS_ADS(atan2, y, x, -0.4); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/copyable_unique_ptr_test.cc
#include "drake/common/copyable_unique_ptr.h" #include <memory> #include <regex> #include <sstream> #include <gtest/gtest.h> #include "drake/common/is_cloneable.h" #include "drake/common/test_utilities/is_dynamic_castable.h" #include "drake/common/unused.h" namespace drake { namespace { using std::make_unique; using std::regex; using std::regex_match; using std::stringstream; using std::unique_ptr; // Convenience alias to keep the test code lines shorter. template <typename T> using cup = copyable_unique_ptr<T>; // -------------------- copy functionality tests ------------------------ // These tests cover the actual copyable semantics. Confirming that the // protocol selecting between Clone and copy constructor is consistent with the // definition and that the implementation invokes the correct copy mechanism // and, when neither exists, recognizes an uncopyable class. // These tests implicitly test copyable_unique_ptr's copy constructor. // Indicator of where a particular instance came from. enum class Origin { UNINITIALIZED, CONSTRUCT, COPY, CLONE }; // A simple base class that stores a value and a construction origin. This only // has a *protected* copy constructor. Child classes can invoke it, but it // won't be considered copyable. struct Base { explicit Base(int v, Origin org = Origin::CONSTRUCT) : origin(org), value(v) {} virtual ~Base() {} Origin origin{Origin::UNINITIALIZED}; int value{-1}; protected: Base(const Base& b) : origin(Origin::COPY), value(b.value) {} }; // A class that is copyable, but has no Clone method. struct CopyOnly : Base { explicit CopyOnly(int v, Origin org = Origin::CONSTRUCT) : Base(v, org) {} CopyOnly(const CopyOnly& b) : Base(b) {} }; // Confirms that a class with only a public copy constructor is considered // copyable and copies appropriately. GTEST_TEST(CopyableUniquePtrTest, CopyOnlySuccess) { cup<CopyOnly> ptr(new CopyOnly(1)); EXPECT_EQ(ptr->origin, Origin::CONSTRUCT); cup<CopyOnly> copy(ptr); EXPECT_EQ(copy->origin, Origin::COPY); EXPECT_EQ(copy->value, ptr->value); ++copy->value; EXPECT_NE(copy->value, ptr->value); } // This class has a private copy constructor but declares copyable_unique_ptr // to be a friend so it should still be copyable. class FriendsWithBenefitsCopy { public: explicit FriendsWithBenefitsCopy(int value) : value_(value) {} int value() const {return value_;} private: friend class copyable_unique_ptr<FriendsWithBenefitsCopy>; FriendsWithBenefitsCopy(const FriendsWithBenefitsCopy&) = default; int value_{0}; }; // This class has no copy constructor and a private Clone() method but declares // copyable_unique_ptr to be a friend so it should still be copyable. class FriendsWithBenefitsClone { public: explicit FriendsWithBenefitsClone(int value) : value_(value) {} int value() const {return value_;} FriendsWithBenefitsClone(const FriendsWithBenefitsClone&) = delete; private: friend class copyable_unique_ptr<FriendsWithBenefitsClone>; std::unique_ptr<FriendsWithBenefitsClone> Clone() const { return std::make_unique<FriendsWithBenefitsClone>(value_); } int value_{0}; }; // Check that a friend declaration works to get copyable_unique_ptr access // to the needed copy constructor or Clone() method. GTEST_TEST(CopyableUniquePtrTest, FriendsWithBenefits) { copyable_unique_ptr<FriendsWithBenefitsCopy> fwb( new FriendsWithBenefitsCopy(10)); EXPECT_EQ(fwb->value(), 10); copyable_unique_ptr<FriendsWithBenefitsCopy> fwb2(fwb); EXPECT_EQ(fwb2->value(), 10); copyable_unique_ptr<FriendsWithBenefitsClone> fwbc( new FriendsWithBenefitsClone(20)); EXPECT_EQ(fwbc->value(), 20); copyable_unique_ptr<FriendsWithBenefitsClone> fwbc2(fwbc); EXPECT_EQ(fwbc2->value(), 20); } // A fully copyable class (has both copy constructor and Clone). Confirms that // in the presence of both, the clone function is preferred. struct FullyCopyable : Base { explicit FullyCopyable(int v, Origin org = Origin::CONSTRUCT) : Base(v, org) {} FullyCopyable(const FullyCopyable& b) : Base(b) {} unique_ptr<FullyCopyable> Clone() const { return make_unique<FullyCopyable>(value, Origin::CLONE); } }; // Confirms that Clone is preferred when both exist. GTEST_TEST(CopyableUniquePtrTest, FullyCopyableSuccess) { cup<FullyCopyable> ptr(new FullyCopyable(1)); EXPECT_EQ(ptr->origin, Origin::CONSTRUCT); cup<FullyCopyable> copy(ptr); EXPECT_EQ(copy->origin, Origin::CLONE); EXPECT_EQ(copy->value, ptr->value); ++copy->value; EXPECT_NE(copy->value, ptr->value); } // A class with only a Clone method. struct CloneOnly : Base { explicit CloneOnly(int v, Origin org = Origin::CONSTRUCT) : Base(v, org) {} unique_ptr<CloneOnly> Clone() const { return unique_ptr<CloneOnly>(DoClone()); } protected: CloneOnly(const CloneOnly& other) : Base(other.value) {} [[nodiscard]] virtual CloneOnly* DoClone() const { return new CloneOnly(value, Origin::CLONE); } }; // Confirms that a class that has a proper implementation of Clone, but no // copy constructor clones itself. GTEST_TEST(CopyableUniquePtrTest, CloneOnlySuccess) { cup<CloneOnly> ptr(new CloneOnly(1)); EXPECT_EQ(ptr->origin, Origin::CONSTRUCT); cup<CloneOnly> copy(ptr); EXPECT_EQ(copy->origin, Origin::CLONE); EXPECT_EQ(copy->value, ptr->value); copy->value++; EXPECT_NE(copy->value, ptr->value); } // A class that derives from a copyable class with no copy constructor. It // provides a Clone method. This can be assigned to a cup<CloneOnly> *and* // supports the cup<CloneOnlyChildWithClone> specialization. Copying an instance // of cup<CloneOnly> which contains a reference to this will produce an instance // of CloneOnlyChildWithClone. struct CloneOnlyChildWithClone : CloneOnly { explicit CloneOnlyChildWithClone(int v, Origin org = Origin::CONSTRUCT) : CloneOnly(v, org) {} CloneOnlyChildWithClone(const CloneOnlyChildWithClone&) = delete; unique_ptr<CloneOnlyChildWithClone> Clone() const { return unique_ptr<CloneOnlyChildWithClone>(DoClone()); } protected: [[nodiscard]] CloneOnlyChildWithClone* DoClone() const override { return new CloneOnlyChildWithClone(value, Origin::CLONE); } }; // A class that derives from a copyable class with no copy constructor. It // provides a copy constructor. This can be assigned to a cup<CloneOnly> *and* // supports the cup<CloneOnlyWithCopy> specialization. It also overrides the // protected DoClone method. Copying an instance of cup<CloneOnly> which // contains a reference to this will produce a copy of // CloneOnlyChildWithCopyVClone. struct CloneOnlyChildWithCopyVClone : CloneOnly { explicit CloneOnlyChildWithCopyVClone(int v, Origin org = Origin::CONSTRUCT) : CloneOnly(v, org) {} CloneOnlyChildWithCopyVClone(const CloneOnlyChildWithCopyVClone&) = default; protected: [[nodiscard]] CloneOnlyChildWithCopyVClone* DoClone() const override { return new CloneOnlyChildWithCopyVClone(value, Origin::CLONE); } }; // A class that derives from a copyable class with no copy constructor. It // provides a copy constructor. This can be assigned to a cup<CloneOnly> *and* // supports the cup<CloneOnlyWithCopy> specialization. This does *not* override // the protected DoClone() method. Copying an instance of cup<CloneOnly> which // contains a reference to this will produce a type-sliced copy of CloneOnly. struct CloneOnlyChildWithCopy : CloneOnly { explicit CloneOnlyChildWithCopy(int v, Origin org = Origin::CONSTRUCT) : CloneOnly(v, org) {} CloneOnlyChildWithCopy(const CloneOnlyChildWithCopy&) = default; }; // A class that derives from a copyable class with no copy constructor. It // provides no copy functions. This can be assigned to a cup<CloneOnly> but does // *not* support the cup<CloneOnlyChildUncopyable> specialization. Copying an // instance of cup<CloneOnly> which contains a reference to this will produce a // type-sliced copy of CloneOnly. struct CloneOnlyChildUncopyable : CloneOnly { explicit CloneOnlyChildUncopyable(int v, Origin org = Origin::CONSTRUCT) : CloneOnly(v, org) {} CloneOnlyChildUncopyable(const CloneOnlyChildUncopyable&) = delete; }; // A class that derives from a copyable class *with* a copy constructor. It // provides its own copy constructor. This can be assigned to a cup<CopyChild> // and supports the cup<CopyChild> specialization. Copying an instance of // cup<FullyCopyable> which contains a reference to a CopyChild will produce a // type-sliced copy of FullyCopyable. struct CopyChild : public FullyCopyable { explicit CopyChild(int v) : FullyCopyable(v) {} CopyChild(const CopyChild& c) = default; }; // Tests the copyability of derived class of a copyable class. In this case, // the base class has *only* a Clone method and no copy constructor. Just // because the base class is copyable does not imply the child is copyable. GTEST_TEST(CopyableUniquePtrTest, PolymorphicCopyability) { // FYI is_cloneable and is_copy_constructible look only for public methods // which is a more stringent condition that copyable_unique_ptr enforces. // Below we'll verify that the presence of an appropriate public method *does* // enable us to use copyable_unique_ptr, by creating one of the appropriate // type and then marking it "unused" to avoid warnings. If this test compiles // then we succeeded. // Case 1) Child with *only* Clone method. EXPECT_TRUE(is_cloneable<CloneOnlyChildWithClone>::value); EXPECT_FALSE(std::is_copy_constructible_v<CloneOnlyChildWithClone>); copyable_unique_ptr<CloneOnlyChildWithClone> ptr_1; // Case 2) Child with *only* Copy method but virtual DoClone(). EXPECT_FALSE(is_cloneable<CloneOnlyChildWithCopyVClone>::value); EXPECT_TRUE(std::is_copy_constructible_v<CloneOnlyChildWithCopyVClone>); copyable_unique_ptr<CloneOnlyChildWithCopyVClone> ptr_2; // Case 3) Child with *only* Copy method. EXPECT_FALSE(is_cloneable<CloneOnlyChildWithCopy>::value); EXPECT_TRUE(std::is_copy_constructible_v<CloneOnlyChildWithCopy>); copyable_unique_ptr<CloneOnlyChildWithCopy> ptr_3; // Case 4) Child with no copy and no clone. EXPECT_FALSE(is_cloneable<CloneOnlyChildUncopyable>::value); EXPECT_FALSE(std::is_copy_constructible_v<CloneOnlyChildUncopyable>); // Can't make a cloneable_unique_ptr<CloneOnlyChildUncopyable>. // Case 5) Child with copy, derived from base with copy. EXPECT_FALSE(is_cloneable<CopyChild>::value); EXPECT_TRUE(std::is_copy_constructible_v<CopyChild>); copyable_unique_ptr<CopyChild> ptr_4; unused(ptr_1, ptr_2, ptr_3, ptr_4); } // Utility test for the CopyTypeSlicing test. It is templated on the sub-class // of CloneOnly. Various implementations in the derived class can lead to // copies that slice the type back to CloneOnly. template <typename T> void TestPolymorphicCopy(bool copy_success) { static_assert(std::is_convertible_v<T*, CloneOnly*>, "This utility method can only be used with classes derived " "from CloneOnly."); cup<CloneOnly> src(new T(1)); cup<CloneOnly> tgt; tgt = src; // Triggers a copy EXPECT_NE(tgt.get(), nullptr); // Confirm actual object assigned. EXPECT_NE(tgt.get(), src.get()); // Confirm different objects. if (copy_success) { EXPECT_TRUE(is_dynamic_castable<T>(tgt.get())); } else { EXPECT_TRUE((std::is_same_v<const CloneOnly*, decltype(tgt.get())>)); EXPECT_FALSE(is_dynamic_castable<T>(tgt.get())); } } // Tests the copy functionality based on polymorphism. Given a // copyable_unique_ptr on a base class, various concrete derived instances are // pushed into the pointer and copied. Some derived classes will be type // sliced and some will have their type preserved. This confirms the behavior. GTEST_TEST(CopyableUniquePtrTest, CopyTypeSlicing) { // Case 1) Child with *only* Clone method. TestPolymorphicCopy<CloneOnlyChildWithClone>(true); // Case 2) Child with *only* Copy method but protected DoClone() override. TestPolymorphicCopy<CloneOnlyChildWithCopyVClone>(true); // Case 3) Child with *only* Copy method. TestPolymorphicCopy<CloneOnlyChildWithCopy>(false); // Case 4) Child with no copy and no clone. TestPolymorphicCopy<CloneOnlyChildUncopyable>(false); // Case 5) Child with copy, derived from base with copy. cup<FullyCopyable> src(new CopyChild(1)); cup<FullyCopyable> tgt; tgt = src; // Triggers a copy EXPECT_NE(tgt.get(), nullptr); // Confirm actual object assigned. EXPECT_NE(tgt.get(), src.get()); // Confirm different objects. EXPECT_TRUE((std::is_same_v<const FullyCopyable*, decltype(tgt.get())>)); EXPECT_FALSE(is_dynamic_castable<CopyChild>(tgt.get())); } // This tests the structure of a class and confirms that the "is_copyable" value // conforms to the stated properties. A class is copyable if it is copy // constructible *or* cloneable. GTEST_TEST(CopyableUniquePtrTest, CopyableAsExpected) { // Examine the 2 x 2 matrix of copy constructible X cloneable with copyable // indicated in parentheses and case numbers in the corners: // // copy constructible // T F // ___________________________ // c |1) |2) | // l | | | // o T | FullyCopyable | CloneOnly | // n | (T) | (T) | // e |_______________|___________| // a |3) |4) | // b | | | // l F | CopyOnly | Base | // e | (T) | (F) | // |_______________|___________| // // Case X) Cloneable || Constructible --> Copyable // Case 1) True || True --> True EXPECT_TRUE(is_cloneable<FullyCopyable>::value); EXPECT_TRUE(std::is_copy_constructible_v<FullyCopyable>); // Case 2) True || False --> True EXPECT_TRUE(is_cloneable<CloneOnly>::value); EXPECT_FALSE(std::is_copy_constructible_v<CloneOnly>); // Case 3) False || True --> True EXPECT_FALSE(is_cloneable<CopyOnly>::value); EXPECT_TRUE(std::is_copy_constructible_v<CopyOnly>); // Case 4) False || False --> False EXPECT_FALSE(is_cloneable<Base>::value); EXPECT_FALSE(std::is_copy_constructible_v<Base>); } // ------------------------ Constructor Tests ------------------------------ // These tests cover construction functionality. // Tests constructor methods that create an empty pointer. This implicitly // relies on the empty() method. GTEST_TEST(CopyableUniquePtrTest, ConstructEmptyPtr) { // Default constructor. cup<CopyOnly> ptr; EXPECT_TRUE(ptr.empty()); // Explicitly null. cup<CopyOnly> ptr2(nullptr); EXPECT_TRUE(ptr2.empty()); } // Test constructor methods that construct a valid copyable_unique_ptr from // compatible non-null pointers. These constructors do *not* invoke any copying. GTEST_TEST(CopyableUniquePtrTest, ConstructOnPtrNoCopy) { CloneOnly* base_ptr; // Case 1: cup<Base> with Base* cup<CloneOnly> ptr(base_ptr = new CloneOnly(1)); EXPECT_EQ(ptr.get(), base_ptr); // Case 2: cup<Base> with Derived* CloneOnlyChildWithClone* co_ptr; cup<CloneOnly> ptr2(co_ptr = new CloneOnlyChildWithClone(2)); // Shows that type is preserved. ASSERT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(ptr2.get())); EXPECT_EQ(ptr2.get(), co_ptr); } // Test copy constructor on copyable_unique_ptr. Copying from three different // types: // copyable_unique_ptr<Base> (containing a Base*) // copyable_unique_ptr<Base> (containing a Derived*) // copyable_unique_ptr<Derived> (containing a Derived*) GTEST_TEST(CopyableUniquePtrTest, CopyConstructFromCopyable) { CloneOnly* base_ptr; cup<CloneOnly> u_ptr(base_ptr = new CloneOnly(1)); EXPECT_EQ(u_ptr.get(), base_ptr); // Copy constructor on copyable_unique-ptr of same specialized class. cup<CloneOnly> cup_ptr(u_ptr); EXPECT_EQ(u_ptr.get(), base_ptr); EXPECT_NE(cup_ptr.get(), base_ptr); EXPECT_NE(cup_ptr.get(), nullptr); EXPECT_EQ(cup_ptr->value, u_ptr->value); CloneOnlyChildWithClone* co_ptr; cup<CloneOnly> u_ptr2(co_ptr = new CloneOnlyChildWithClone(2)); EXPECT_EQ(u_ptr2.get(), co_ptr); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(u_ptr2.get())); // Copy constructor on copyable_unique-ptr of same specialized class, but // contains derived class. cup<CloneOnly> cup_ptr2(u_ptr2); EXPECT_EQ(u_ptr2.get(), co_ptr); EXPECT_NE(cup_ptr2.get(), co_ptr); EXPECT_NE(cup_ptr2.get(), nullptr); EXPECT_EQ(cup_ptr2->value, u_ptr2->value); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(cup_ptr2.get())); // Copy constructor on copyable_unique-ptr of derived specialized class. CloneOnlyChildWithClone* co_ptr3; cup<CloneOnlyChildWithClone> u_ptr3(co_ptr3 = new CloneOnlyChildWithClone(3)); EXPECT_EQ(u_ptr3.get(), co_ptr3); cup<CloneOnly> cup_ptr3(u_ptr3); EXPECT_EQ(u_ptr3.get(), co_ptr3); EXPECT_NE(cup_ptr3.get(), co_ptr3); EXPECT_NE(cup_ptr3.get(), nullptr); EXPECT_EQ(cup_ptr3->value, u_ptr3->value); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(cup_ptr3.get())); } // Test copy constructor on unique_ptr. Copying from three different // types: // copyable_unique_ptr<Base> (containing a Base*) // copyable_unique_ptr<Base> (containing a Derived*) // copyable_unique_ptr<Derived> (containing a Derived*) GTEST_TEST(CopyableUniquePtrTest, CopyConstructFromUniquePtr) { CloneOnly* base_ptr; unique_ptr<CloneOnly> u_ptr(base_ptr = new CloneOnly(1)); EXPECT_EQ(u_ptr.get(), base_ptr); // Copy constructor on copyable_unique-ptr of same specialized class. cup<CloneOnly> cup_ptr(u_ptr); EXPECT_EQ(u_ptr.get(), base_ptr); EXPECT_NE(cup_ptr.get(), base_ptr); EXPECT_NE(cup_ptr.get(), nullptr); EXPECT_EQ(cup_ptr->value, u_ptr->value); CloneOnlyChildWithClone* co_ptr; unique_ptr<CloneOnly> u_ptr2(co_ptr = new CloneOnlyChildWithClone(2)); EXPECT_EQ(u_ptr2.get(), co_ptr); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(u_ptr2.get())); // Copy constructor on copyable_unique-ptr of same specialized class, but // contains derived class. cup<CloneOnly> cup_ptr2(u_ptr2); EXPECT_EQ(u_ptr2.get(), co_ptr); EXPECT_NE(cup_ptr2.get(), co_ptr); EXPECT_NE(cup_ptr2.get(), nullptr); EXPECT_EQ(cup_ptr2->value, u_ptr2->value); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(cup_ptr2.get())); // Copy constructor on copyable_unique-ptr of derived specialized class. CloneOnlyChildWithClone* co_ptr3; unique_ptr<CloneOnlyChildWithClone> u_ptr3( co_ptr3 = new CloneOnlyChildWithClone(3)); EXPECT_EQ(u_ptr3.get(), co_ptr3); cup<CloneOnly> cup_ptr3(u_ptr3); EXPECT_EQ(u_ptr3.get(), co_ptr3); EXPECT_NE(cup_ptr3.get(), co_ptr3); EXPECT_NE(cup_ptr3.get(), nullptr); EXPECT_EQ(cup_ptr3->value, u_ptr3->value); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(cup_ptr3.get())); } // Test move constructor on copyable_unique_ptr. Copying from three different // types: // copyable_unique_ptr<Base> (containing a Base*) // copyable_unique_ptr<Base> (containing a Derived*) // copyable_unique_ptr<Derived> (containing a Derived*) GTEST_TEST(CopyableUniquePtrTest, MoveConstructFromCopyable) { CloneOnly* base_ptr; cup<CloneOnly> u_ptr(base_ptr = new CloneOnly(1)); EXPECT_EQ(u_ptr.get(), base_ptr); // Move constructor on copyable_unique-ptr of same specialized class. cup<CloneOnly> cup_ptr(move(u_ptr)); EXPECT_EQ(u_ptr.get(), nullptr); EXPECT_EQ(cup_ptr.get(), base_ptr); CloneOnlyChildWithClone* co_ptr; cup<CloneOnly> u_ptr2(co_ptr = new CloneOnlyChildWithClone(2)); EXPECT_EQ(u_ptr2.get(), co_ptr); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(u_ptr2.get())); // Copy constructor on copyable_unique-ptr of same specialized class, but // contains derived class. cup<CloneOnly> cup_ptr2(move(u_ptr2)); EXPECT_EQ(u_ptr2.get(), nullptr); EXPECT_EQ(cup_ptr2.get(), co_ptr); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(cup_ptr2.get())); // Copy constructor on copyable_unique-ptr of derived specialized class. CloneOnlyChildWithClone* co_ptr3; cup<CloneOnlyChildWithClone> u_ptr3(co_ptr3 = new CloneOnlyChildWithClone(3)); EXPECT_EQ(u_ptr3.get(), co_ptr3); cup<CloneOnly> cup_ptr3(move(u_ptr3)); EXPECT_EQ(u_ptr3.get(), nullptr); EXPECT_EQ(cup_ptr3.get(), co_ptr3); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(cup_ptr3.get())); } // Test move constructor on unique_ptr. Copying from three different // types: // copyable_unique_ptr<Base> (containing a Base*) // copyable_unique_ptr<Base> (containing a Derived*) // copyable_unique_ptr<Derived> (containing a Derived*) GTEST_TEST(CopyableUniquePtrTest, MoveConstructFromUnique) { CloneOnly* base_ptr; unique_ptr<CloneOnly> u_ptr(base_ptr = new CloneOnly(1)); EXPECT_EQ(u_ptr.get(), base_ptr); // Move constructor on copyable_unique-ptr of same specialized class. cup<CloneOnly> cup_ptr(move(u_ptr)); EXPECT_EQ(u_ptr.get(), nullptr); EXPECT_EQ(cup_ptr.get(), base_ptr); CloneOnlyChildWithClone* co_ptr; unique_ptr<CloneOnly> u_ptr2(co_ptr = new CloneOnlyChildWithClone(2)); EXPECT_EQ(u_ptr2.get(), co_ptr); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(u_ptr2.get())); // Copy constructor on copyable_unique-ptr of same specialized class, but // contains derived class. cup<CloneOnly> cup_ptr2(move(u_ptr2)); EXPECT_EQ(u_ptr2.get(), nullptr); EXPECT_EQ(cup_ptr2.get(), co_ptr); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(cup_ptr2.get())); // Copy constructor on copyable_unique-ptr of derived specialized class. CloneOnlyChildWithClone* co_ptr3; unique_ptr<CloneOnlyChildWithClone> u_ptr3( co_ptr3 = new CloneOnlyChildWithClone(3)); EXPECT_EQ(u_ptr3.get(), co_ptr3); cup<CloneOnly> cup_ptr3(move(u_ptr3)); EXPECT_EQ(u_ptr3.get(), nullptr); EXPECT_EQ(cup_ptr3.get(), co_ptr3); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(cup_ptr3.get())); } // Test the construction from a sample model value. We don't test all varieties // of cloneable types because we know that the model construction uses the same // underlying mechanism as has been tested by all the other constructors. GTEST_TEST(CopyableUniquePtrTest, ConstructByValue) { CloneOnly clone_only(17); cup<CloneOnly> clone_ptr(clone_only); EXPECT_NE(&clone_only, clone_ptr.get()); EXPECT_EQ(clone_only.value, clone_ptr->value); CopyOnly copy_only(2); cup<CopyOnly> copy_ptr(copy_only); EXPECT_NE(&copy_only, copy_ptr.get()); EXPECT_EQ(copy_only.value, copy_ptr->value); } // ------------------------ Destructor Tests ------------------------------ // These tests the various methods that cause the object to be destroyed. // This class allows me to track destruction of instances in copyable_unique_ptr // instances. To use it, set the static member dtor_called to false, and then // perform an operation. If an instance has been destroyed, dtor_called will be // true, otherwise, no destructor was called. struct DestructorTracker : public CloneOnly { explicit DestructorTracker(int v, Origin org = Origin::CONSTRUCT) : CloneOnly(v, org) {} virtual ~DestructorTracker() { dtor_called = true; } DestructorTracker(const DestructorTracker&) = delete; unique_ptr<DestructorTracker> Clone() const { return make_unique<DestructorTracker>(value, Origin::CLONE); } static bool dtor_called; }; bool DestructorTracker::dtor_called = false; // Tests the destruction of the referenced object when the pointer is destroyed. // In this case, destruction is triggered by leaving the scope of the // copyable_unique_ptr. GTEST_TEST(CopyableUniquePtrTest, DestroyOnScopeExit) { // Empty copyable_unique_ptr<T> does not invoke T's destructor. { cup<DestructorTracker> empty; DestructorTracker::dtor_called = false; } EXPECT_FALSE(DestructorTracker::dtor_called); // Non-empty pointer invokes destructor. DestructorTracker* raw_ptr = new DestructorTracker(1); { cup<DestructorTracker> ptr(raw_ptr); EXPECT_EQ(ptr.get(), raw_ptr); DestructorTracker::dtor_called = false; } EXPECT_TRUE(DestructorTracker::dtor_called); } // This tests the various incarnations of reset. GTEST_TEST(CopyableUniquePtrTest, Reset) { cup<DestructorTracker> ptr; EXPECT_TRUE(ptr.empty()); // Confirm initial condition. // Case 1: Resetting an empty pointer invokes no constructor. DestructorTracker* raw_ptr = new DestructorTracker(1); DestructorTracker::dtor_called = false; ptr.reset(raw_ptr); EXPECT_EQ(ptr.get(), raw_ptr); // Previously empty pointer does *not* invoke destructor. EXPECT_FALSE(DestructorTracker::dtor_called); // Case 2: Previous non-null contents *are* destroyed. raw_ptr = new DestructorTracker(2); EXPECT_NE(ptr.get(), raw_ptr); DestructorTracker::dtor_called = false; ptr.reset(raw_ptr); EXPECT_EQ(ptr.get(), raw_ptr); // Previously non-empty pointer *does* invoke destructor. EXPECT_TRUE(DestructorTracker::dtor_called); // Case 3: Previous non-null contents replace by nullptr. DestructorTracker::dtor_called = false; ptr.reset(); EXPECT_EQ(ptr.get(), nullptr); // Previously non-empty pointer *does* invoke destructor. EXPECT_TRUE(DestructorTracker::dtor_called); } // ------------------------ Assignment Tests ------------------------------ // These tests cover assignment operator. // Tests the assignment of a raw pointer to a copyable_unique_ptr. The // copyable_unique_ptr should take ownership. It also confirms that the // previous object is destroyed. Assignment of the following patterns: // // | Target Type | Source | Target State | Dtor? | // |-------------+----------+--------------+-------| // | Base | nullptr | nullptr | N | // | Base | Base* | nullptr | Y | // | Base | Base* | Base* | Y | // | Base | Derived* | nullptr | N | GTEST_TEST(CopyableUniquePtrTest, AssignPointer) { cup<DestructorTracker> ptr; // Do not re-order these tests. Each test implicitly relies on the verified // state at the conclusion of the previous case. // Case 1: Assign nullptr to empty cup. EXPECT_EQ(ptr.get(), nullptr); DestructorTracker::dtor_called = false; ptr = nullptr; EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_EQ(ptr.get(), nullptr); // Case 2: Assign pointer of specialized type to empty cup. DestructorTracker::dtor_called = false; DestructorTracker* raw = new DestructorTracker(421); ptr = raw; EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_EQ(ptr.get(), raw); // Case 3: Assign pointer of specialized type to non-empty cup. DestructorTracker* raw2 = new DestructorTracker(124); DestructorTracker::dtor_called = false; ptr = raw2; EXPECT_TRUE(DestructorTracker::dtor_called); EXPECT_EQ(ptr.get(), raw2); // Case 4: Assign pointer of Derived type to empty cup<Base> cup<CloneOnly> co_ptr; CloneOnlyChildWithClone* derived_raw = new CloneOnlyChildWithClone(13); co_ptr = derived_raw; EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(co_ptr.get())); EXPECT_EQ(co_ptr.get(), derived_raw); } // Tests the assignment of a const reference object to a copyable_unique_ptr. // This should *always* create a copy. It also confirms that the previous object // is destroyed. Assignment of the following patterns: // // | Target Type | Source | Target State | Dtor? | // |-------------+----------+--------------+-------| // | Base | Base& | nullptr | Y | // | Base | Base& | Base* | Y | // | Base | Derived& | nullptr | N | GTEST_TEST(CopyableUniquePtrTest, AssignConstReference) { DestructorTracker ref(421); cup<DestructorTracker> ptr; // Do not re-order these tests. Each test implicitly relies on the verified // state at the conclusion of the previous case. // Case 1: Assign reference of specialized type to empty cup. EXPECT_EQ(ptr.get(), nullptr); DestructorTracker::dtor_called = false; ptr = ref; EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_NE(ptr.get(), &ref); EXPECT_EQ(ptr->value, ref.value); // Case 2: Assign reference of specialized type to non-empty cup. DestructorTracker ref2(124); DestructorTracker::dtor_called = false; ptr = ref2; EXPECT_TRUE(DestructorTracker::dtor_called); EXPECT_NE(ptr.get(), &ref); EXPECT_NE(ptr.get(), &ref2); EXPECT_EQ(ptr->value, ref2.value); // Case 3: Assign reference of Derived type to empty cup<Base> cup<CloneOnly> co_ptr; CloneOnlyChildWithClone derived_ref(132); co_ptr = derived_ref; EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(co_ptr.get())); EXPECT_NE(co_ptr.get(), &derived_ref); EXPECT_EQ(co_ptr->value, derived_ref.value); } // Tests the copy assignment of a copyable_unique_ptr to a copyable_unique_ptr. // This should *always* create a copy. It also confirms that the previous object // is destroyed. Assignment of the following patterns: // // | Target Type | Source | Target State | Dtor? | // |-------------+-----------+--------------+-------| // | Base | empty | nullptr | N | // | Base | <Base> | nullptr | Y | // | Base | <Base> | Base* | Y | // | Base | <Derived> | nullptr | N | GTEST_TEST(CopyableUniquePtrTest, CopyAssignFromCopyableUniquePtr) { DestructorTracker* raw = new DestructorTracker(421); cup<DestructorTracker> src(raw); cup<DestructorTracker> empty; cup<DestructorTracker> tgt; // Do not re-order these tests. Each test implicitly relies on the verified // state at the conclusion of the previous case. // Case 1: Assign empty cup to empty cup. EXPECT_EQ(tgt.get(), nullptr); DestructorTracker::dtor_called = false; tgt = empty; EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_EQ(tgt.get(), nullptr); EXPECT_EQ(empty.get(), nullptr); // Case 2: Assign non-empty cup<Base> to empty cup<Base>. DestructorTracker::dtor_called = false; tgt = src; EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_NE(tgt.get(), src.get()); // Not the same pointer as src. EXPECT_EQ(src.get(), raw); // Src has original value. EXPECT_EQ(tgt->value, src->value); // Src and tgt are copies. // Case 3: Assign non-empty cup<Base> type to non-empty cup<Base>. DestructorTracker* raw2; cup<DestructorTracker> src2(raw2 = new DestructorTracker(124)); DestructorTracker::dtor_called = false; tgt = src2; EXPECT_TRUE(DestructorTracker::dtor_called); EXPECT_NE(tgt.get(), src2.get()); // Not the same pointer as src. EXPECT_EQ(src2.get(), raw2); // Src has original value. EXPECT_EQ(tgt->value, src2->value); // Src and tgt are copies. // Case 4: Assign non-empty cup<Derived> to empty cup<Base> cup<CloneOnly> base_tgt; CloneOnlyChildWithClone* derived_raw; cup<CloneOnlyChildWithClone> derived_src(derived_raw = new CloneOnlyChildWithClone(13)); base_tgt = derived_src; EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(base_tgt.get())); EXPECT_NE(base_tgt.get(), derived_src.get()); EXPECT_EQ(base_tgt->value, derived_src->value); } // Tests the copy assignment of a standard unique_ptr to a copyable_unique_ptr. // This should *always* create a copy. It also confirms that the previous object // is destroyed. Assignment of the following patterns: // // | Target Type | Source | Target State | Dtor? | // |-------------+-----------+--------------+-------| // | Base | empty | nullptr | N | // | Base | <Base> | nullptr | Y | // | Base | <Base> | Base* | Y | // | Base | <Derived> | nullptr | N | GTEST_TEST(CopyableUniquePtrTest, CopyAssignFromUniquePtr) { DestructorTracker* raw = new DestructorTracker(421); unique_ptr<DestructorTracker> src(raw); unique_ptr<DestructorTracker> empty; cup<DestructorTracker> tgt; // Do not re-order these tests. Each test implicitly relies on the verified // state at the conclusion of the previous case. // Case 1: Assign empty unique_ptr to empty cup. EXPECT_EQ(tgt.get(), nullptr); DestructorTracker::dtor_called = false; tgt = empty; EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_EQ(tgt.get(), nullptr); EXPECT_EQ(empty.get(), nullptr); // Case 2: Assign non-empty unique_ptr<Base> to empty cup<Base>. DestructorTracker::dtor_called = false; tgt = src; EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_NE(tgt.get(), src.get()); // Not the same pointer as src. EXPECT_EQ(src.get(), raw); // Src has original value. EXPECT_EQ(tgt->value, src->value); // Src and tgt are copies. // Case 3: Assign non-empty unique_ptr<Base> type to non-empty cup<Base>. DestructorTracker* raw2; cup<DestructorTracker> src2(raw2 = new DestructorTracker(124)); DestructorTracker::dtor_called = false; tgt = src2; EXPECT_TRUE(DestructorTracker::dtor_called); EXPECT_NE(tgt.get(), src2.get()); // Not the same pointer as src. EXPECT_EQ(src2.get(), raw2); // Src has original value. EXPECT_EQ(tgt->value, src2->value); // Src and tgt are copies. // Case 4: Assign non-empty unique_ptr<Derived> to empty cup<Base> cup<CloneOnly> base_tgt; CloneOnlyChildWithClone* derived_raw; unique_ptr<CloneOnlyChildWithClone> derived_src( derived_raw = new CloneOnlyChildWithClone(13)); base_tgt = derived_src; EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(base_tgt.get())); EXPECT_NE(base_tgt.get(), derived_src.get()); EXPECT_EQ(base_tgt->value, derived_src->value); } // Tests the move assignment of a copyable_unique_ptr to a copyable_unique_ptr. // This should reassign ownership changing the target and source. It also // confirms that the previous object is destroyed. Assignment of the following // patterns: // // | Target Type | Source | Target State | Dtor? | // |-------------+-----------+--------------+-------| // | Base | empty | nullptr | N | // | Base | <Base> | nullptr | Y | // | Base | <Base> | Base* | Y | // | Base | <Derived> | nullptr | N | GTEST_TEST(CopyableUniquePtrTest, MoveAssignFromCopyableUniquePtr) { DestructorTracker* raw = new DestructorTracker(421); cup<DestructorTracker> src(raw); cup<DestructorTracker> empty; cup<DestructorTracker> tgt; // Do not re-order these tests. Each test implicitly relies on the verified // state at the conclusion of the previous case. // Case 1: Assign empty unique_ptr to empty cup. EXPECT_EQ(tgt.get(), nullptr); DestructorTracker::dtor_called = false; tgt = move(empty); EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_EQ(tgt.get(), nullptr); EXPECT_EQ(empty.get(), nullptr); // Case 2: Assign non-empty unique_ptr<Base> to empty cup<Base>. DestructorTracker::dtor_called = false; tgt = move(src); EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_EQ(tgt.get(), raw); // Tgt has taken ownership of raw. EXPECT_EQ(src.get(), nullptr); // Src has been cleared. // Case 3: Assign non-empty unique_ptr<Base> type to non-empty cup<Base>. DestructorTracker* raw2; cup<DestructorTracker> src2(raw2 = new DestructorTracker(124)); DestructorTracker::dtor_called = false; tgt = move(src2); EXPECT_TRUE(DestructorTracker::dtor_called); EXPECT_EQ(tgt.get(), raw2); // Tgt has taken ownership of raw. EXPECT_EQ(src2.get(), nullptr); // Src has been cleared. // Case 4: Assign non-empty unique_ptr<Derived> to empty cup<Base> cup<CloneOnly> base_tgt; CloneOnlyChildWithClone* derived_raw; cup<CloneOnlyChildWithClone> derived_src(derived_raw = new CloneOnlyChildWithClone(13)); base_tgt = move(derived_src); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(base_tgt.get())); EXPECT_EQ(base_tgt.get(), derived_raw); // Tgt has taken ownership of raw. EXPECT_EQ(derived_src.get(), nullptr); // Src has been cleared. } // Tests the move assignment of a standard unique_ptr to a copyable_unique_ptr. // This should reassign ownership changing the target and source. It also // confirms that the previous object is destroyed. Assignment of the following // patterns: // // | Target Type | Source | Target State | Dtor? | // |-------------+-----------+--------------+-------| // | Base | empty | nullptr | N | // | Base | <Base> | nullptr | Y | // | Base | <Base> | Base* | Y | // | Base | <Derived> | nullptr | N | GTEST_TEST(CopyableUniquePtrTest, MoveAssignFromUniquePtr) { DestructorTracker* raw = new DestructorTracker(421); unique_ptr<DestructorTracker> src(raw); unique_ptr<DestructorTracker> empty; cup<DestructorTracker> tgt; // Do not re-order these tests. Each test implicitly relies on the verified // state at the conclusion of the previous case. // Case 1: Assign empty unique_ptr to empty cup. EXPECT_EQ(tgt.get(), nullptr); DestructorTracker::dtor_called = false; tgt = move(empty); EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_EQ(tgt.get(), nullptr); EXPECT_EQ(empty.get(), nullptr); // Case 2: Assign non-empty unique_ptr<Base> to empty cup<Base>. DestructorTracker::dtor_called = false; tgt = move(src); EXPECT_FALSE(DestructorTracker::dtor_called); EXPECT_EQ(tgt.get(), raw); // Tgt has taken ownership of raw. EXPECT_EQ(src.get(), nullptr); // Src has been cleared. // Case 3: Assign non-empty unique_ptr<Base> type to non-empty cup<Base>. DestructorTracker* raw2; cup<DestructorTracker> src2(raw2 = new DestructorTracker(124)); DestructorTracker::dtor_called = false; tgt = move(src2); EXPECT_TRUE(DestructorTracker::dtor_called); EXPECT_EQ(tgt.get(), raw2); // Tgt has taken ownership of raw. EXPECT_EQ(src2.get(), nullptr); // Src has been cleared. // Case 4: Assign non-empty unique_ptr<Derived> to empty cup<Base> cup<CloneOnly> base_tgt; CloneOnlyChildWithClone* derived_raw; unique_ptr<CloneOnlyChildWithClone> derived_src( derived_raw = new CloneOnlyChildWithClone(13)); base_tgt = move(derived_src); EXPECT_TRUE(is_dynamic_castable<CloneOnlyChildWithClone>(base_tgt.get())); EXPECT_EQ(base_tgt.get(), derived_raw); // Tgt has taken ownership of raw. EXPECT_EQ(derived_src.get(), nullptr); // Src has been cleared. } // ------------------------ Observer Tests ------------------------------ // These tests cover the introspective functions: determining if the pointer is // empty, acquiring access to the raw pointer, and references. The empty() // method is implicitly tested multiple times in other methods. // Tests the semantics that get() and get_mutable() return const and non-const // pointers respectively. GTEST_TEST(CopyableUniquePtrTest, PointerAccessConstSemantics) { CloneOnly* raw; cup<CloneOnly> ptr(raw = new CloneOnly(1)); // Simply test that they return the right pointer *value*. EXPECT_EQ(ptr.get(), raw); EXPECT_EQ(ptr.get_mutable(), raw); // The extra parentheses prevent the macro from getting confused. // get is const pointer EXPECT_TRUE((std::is_same_v<const CloneOnly*, decltype(ptr.get())>)); // NOTE: is_assignable uses declval<T> to create the lhs. declval<T> creates // an r-value reference (which will *always* fail assignability tests. By // taking an l-value reference of the object, the resulting type becomes // l-value. EXPECT_FALSE((std::is_assignable_v<CloneOnly*&, decltype(ptr.get())>)); // get_mutable is non-const EXPECT_TRUE((std::is_same_v<CloneOnly*, decltype(ptr.get_mutable())>)); EXPECT_TRUE((std::is_assignable_v<CloneOnly*&, decltype(ptr.get_mutable())>)); // Constness of dereferenced result depends on the constness of the smart // pointer. EXPECT_TRUE((std::is_same_v<CloneOnly&, decltype(*ptr)>)); const cup<CloneOnly>& const_ptr_ref = ptr; EXPECT_TRUE((std::is_same_v<const CloneOnly&, decltype(*const_ptr_ref)>)); // Constness of T cannot be undone by non-const pointer container. cup<const CloneOnly> ptr_to_const(new CloneOnly(2)); EXPECT_TRUE( (std::is_same_v<const CloneOnly*, decltype(ptr_to_const.get_mutable())>)); EXPECT_TRUE((std::is_same_v<const CloneOnly&, decltype(*ptr_to_const)>)); } // ------------------------ Core unique_ptr Tests ------------------------------ // This tests the functionality that should be directly inherited from the // unique_ptr class, preserving the idea that, except for copying semantics, // the copyable_unique_ptr *is* a unique_ptr. // This tests that a cup<const T> offers no mutable access to the underlying // // type (via pointer or reference). GTEST_TEST(CopyableUniquePtrTest, ConstSpecializationHasNoMutableAccess) { cup<const CloneOnly> ptr(new CloneOnly(2)); // Being the same as a 'const' type, precludes the possibility of being the // "same" as a non-const type. EXPECT_TRUE((std::is_same_v<const CloneOnly*, decltype(ptr.get())>)); } // This tests the implicit conversion of the pointer to a boolean. It does *not* // confirm that it is only available in "contextual conversions". See: // http://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions GTEST_TEST(CopyableUniquePtrTest, ConverstionToBool) { copyable_unique_ptr<CloneOnly> ptr; EXPECT_FALSE(ptr); ptr.reset(new CloneOnly(1)); EXPECT_TRUE(ptr); } // Tests the two forms of swap (member method and external method). GTEST_TEST(CopyableUniquePtrTest, SwapTest) { DestructorTracker* raw1; DestructorTracker* raw2; cup<DestructorTracker> ptr1(raw1 = new DestructorTracker(1)); cup<DestructorTracker> ptr2(raw2 = new DestructorTracker(2)); EXPECT_EQ(ptr1.get(), raw1); EXPECT_EQ(ptr2.get(), raw2); EXPECT_NE(ptr1.get(), ptr2.get()); // Don't reorder these tests. Results depend on this execution order. // The swap method. DestructorTracker::dtor_called = false; ptr1.swap(ptr2); EXPECT_FALSE(DestructorTracker::dtor_called); // Nothing got destroyed. EXPECT_EQ(ptr1.get(), raw2); EXPECT_EQ(ptr2.get(), raw1); // The swap function. DestructorTracker::dtor_called = false; swap(ptr1, ptr2); EXPECT_FALSE(DestructorTracker::dtor_called); // Nothing got destroyed. EXPECT_EQ(ptr1.get(), raw1); EXPECT_EQ(ptr2.get(), raw2); } // Tests the release method. GTEST_TEST(CopyableUniquePtrTest, ReleaseTest) { cup<DestructorTracker> ptr; EXPECT_EQ(ptr.get(), nullptr); DestructorTracker* raw = nullptr; // Case 1: Release a null ptr. raw = ptr.release(); EXPECT_EQ(ptr.get(), nullptr); EXPECT_EQ(raw, nullptr); // Case 2: Release non-null ptr. DestructorTracker* src; ptr.reset(src = new DestructorTracker(1)); EXPECT_EQ(ptr.get(), src); DestructorTracker::dtor_called = false; raw = ptr.release(); EXPECT_FALSE(DestructorTracker::dtor_called); // Nothing destroyed. EXPECT_EQ(raw, src); delete src; } // Tests the stream value. GTEST_TEST(CopyableUniquePtrTest, FormatterTest) { // Try a null pointer value. cup<CloneOnly> ptr; const void* raw = ptr.get(); EXPECT_EQ(fmt::to_string(ptr), fmt::to_string(raw)); // Try a non-null value. ptr.reset(new CloneOnly(1)); raw = ptr.get(); EXPECT_EQ(fmt::to_string(ptr), fmt::to_string(raw)); } // Tests the == tests between copyable_unique_ptr and other entities. GTEST_TEST(CopyableUniquePtrTest, EqualityTest) { CloneOnlyChildWithClone* raw; // This assigns the same pointer to *two* unique pointers. However, one // releases the pointer before going out of scope. This facilitates equality // testing for truly equal pointers. cup<CloneOnly> ptr(raw = new CloneOnlyChildWithClone(1)); cup<CloneOnlyChildWithClone> child_ptr(raw); cup<CloneOnlyChildWithClone> other_ptr(new CloneOnlyChildWithClone(1)); cup<CloneOnlyChildWithClone> child_null; cup<CloneOnly> parent_null; EXPECT_FALSE(ptr == parent_null); EXPECT_FALSE(ptr == child_null); EXPECT_FALSE(child_ptr == parent_null); EXPECT_FALSE(child_ptr == child_null); EXPECT_TRUE(parent_null == child_null); EXPECT_TRUE(ptr == child_ptr); EXPECT_FALSE(child_ptr == other_ptr); EXPECT_FALSE(ptr == other_ptr); EXPECT_FALSE(nullptr == ptr); EXPECT_FALSE(ptr == nullptr); // Don't try to call destructor twice. child_ptr.release(); } // Tests the != tests between copyable_unique_ptr and other entities. GTEST_TEST(CopyableUniquePtrTest, InEqualityTest) { CloneOnlyChildWithClone* raw; cup<CloneOnly> ptr(raw = new CloneOnlyChildWithClone(1)); cup<CloneOnlyChildWithClone> child_ptr(raw); cup<CloneOnlyChildWithClone> other_ptr(new CloneOnlyChildWithClone(1)); cup<CloneOnlyChildWithClone> child_null; cup<CloneOnly> parent_null; EXPECT_TRUE(ptr != parent_null); EXPECT_TRUE(ptr != child_null); EXPECT_TRUE(child_ptr != parent_null); EXPECT_TRUE(child_ptr != child_null); EXPECT_FALSE(parent_null != child_null); EXPECT_FALSE(ptr != child_ptr); EXPECT_TRUE(child_ptr != other_ptr); EXPECT_TRUE(ptr != other_ptr); EXPECT_TRUE(nullptr != ptr); EXPECT_TRUE(ptr != nullptr); // Don't try to call destructor twice. child_ptr.release(); } // Tests the < and <= tests between copyable_unique_ptr and other entities. GTEST_TEST(CopyableUniquePtrTest, LessThanTest) { CloneOnlyChildWithClone* raw; cup<CloneOnly> ptr(raw = new CloneOnlyChildWithClone(1)); cup<CloneOnlyChildWithClone> child_ptr(raw); cup<CloneOnlyChildWithClone> other_ptr(new CloneOnlyChildWithClone(1)); cup<CloneOnlyChildWithClone> child_null; cup<CloneOnly> parent_null; bool other_less_than_raw = other_ptr.get() < raw; EXPECT_FALSE(ptr < parent_null); EXPECT_FALSE(ptr < child_null); EXPECT_FALSE(child_ptr < parent_null); EXPECT_FALSE(child_ptr < child_null); EXPECT_FALSE(parent_null < child_null); EXPECT_TRUE(nullptr < ptr); EXPECT_FALSE(ptr < nullptr); EXPECT_FALSE(ptr < child_ptr); // I don't know which is actually less a priori. XORing with the counter test // guarantees that these should always evaluate to true in successful tests. EXPECT_TRUE((child_ptr < other_ptr) ^ other_less_than_raw); EXPECT_TRUE((ptr < other_ptr) ^ other_less_than_raw); EXPECT_FALSE(ptr <= parent_null); EXPECT_FALSE(ptr <= child_null); EXPECT_FALSE(child_ptr <= parent_null); EXPECT_FALSE(child_ptr <= child_null); EXPECT_TRUE(parent_null <= child_null); EXPECT_TRUE(nullptr <= ptr); EXPECT_FALSE(ptr <= nullptr); EXPECT_TRUE(ptr <= child_ptr); // I don't know which is actually less a priori. XORing with the counter test // guarantees that these should always evaluate to true in successful tests. EXPECT_TRUE((child_ptr <= other_ptr) ^ other_less_than_raw); EXPECT_TRUE((ptr <= other_ptr) ^ other_less_than_raw); // Don't try to call destructor twice. child_ptr.release(); } // Tests the > and >= tests between copyable_unique_ptr and other entities. GTEST_TEST(CopyableUniquePtrTest, GreaterThanTest) { CloneOnlyChildWithClone* raw; cup<CloneOnly> ptr(raw = new CloneOnlyChildWithClone(1)); cup<CloneOnlyChildWithClone> child_ptr(raw); cup<CloneOnlyChildWithClone> other_ptr(new CloneOnlyChildWithClone(1)); cup<CloneOnlyChildWithClone> child_null; cup<CloneOnly> parent_null; bool other_greater_than_raw = other_ptr.get() > raw; EXPECT_TRUE(ptr > parent_null); EXPECT_TRUE(ptr > child_null); EXPECT_TRUE(child_ptr > parent_null); EXPECT_TRUE(child_ptr > child_null); EXPECT_FALSE(parent_null > child_null); EXPECT_FALSE(nullptr > ptr); EXPECT_TRUE(ptr > nullptr); EXPECT_FALSE(ptr > child_ptr); // I don't know which is actually less a priori. XORing with the counter test // guarantees that these should always evaluate to true in successful tests. EXPECT_TRUE((child_ptr > other_ptr) ^ other_greater_than_raw); EXPECT_TRUE((ptr > other_ptr) ^ other_greater_than_raw); EXPECT_TRUE(ptr >= parent_null); EXPECT_TRUE(ptr >= child_null); EXPECT_TRUE(child_ptr >= parent_null); EXPECT_TRUE(child_ptr >= child_null); EXPECT_TRUE(parent_null >= child_null); EXPECT_FALSE(nullptr >= ptr); EXPECT_TRUE(ptr >= nullptr); EXPECT_TRUE(ptr >= child_ptr); // I don't know which is actually less a priori. XORing with the counter test // guarantees that these should always evaluate to true in successful tests. EXPECT_TRUE((child_ptr >= other_ptr) ^ other_greater_than_raw); EXPECT_TRUE((ptr >= other_ptr) ^ other_greater_than_raw); // Don't try to call destructor twice. child_ptr.release(); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/reset_after_move_test.cc
#include "drake/common/reset_after_move.h" #include <type_traits> #include <gtest/gtest.h> namespace drake { namespace { // A function that helps force an implicit conversion operator to int; without // it, EXPECT_EQ is underspecified whether we are unwrapping the first argument // or converting the second. int ForceInt(int value) { return value; } GTEST_TEST(DefaultValueTest, Constructor) { EXPECT_EQ(reset_after_move<int>(), 0); EXPECT_EQ(reset_after_move<int>(1), 1); } GTEST_TEST(DefaultValueTest, Access) { // Assignment from a RHS of int (versus reset_after_move<int>). reset_after_move<int> x; x = 1; // Conversion operator, non-const value. EXPECT_EQ(x, 1); EXPECT_EQ(ForceInt(x), 1); // Conversion operator, const. const reset_after_move<int>& x_cref = x; EXPECT_EQ(x_cref, 1); EXPECT_EQ(ForceInt(x_cref), 1); // Conversion operator, non-const reference. int& x_value_ref = x; EXPECT_EQ(x_value_ref, 1); EXPECT_EQ(ForceInt(x_value_ref), 1); // All values work okay. x = 2; EXPECT_EQ(x, 2); EXPECT_EQ(ForceInt(x), 2); EXPECT_EQ(x_cref, 2); EXPECT_EQ(ForceInt(x_cref), 2); EXPECT_EQ(x_value_ref, 2); EXPECT_EQ(ForceInt(x_value_ref), 2); } // For the next test. struct Thing { int i{}; }; // Check that the dereferencing operators *ptr and ptr-> work for pointer types. GTEST_TEST(DefaultValueTest, Pointers) { int i = 5; reset_after_move<int*> i_ptr{&i}; reset_after_move<const int*> i_cptr{&i}; EXPECT_EQ(*i_ptr, 5); EXPECT_EQ(*i_cptr, 5); *i_ptr = 6; EXPECT_EQ(*i_ptr, 6); EXPECT_EQ(*i_cptr, 6); reset_after_move<int*> i_ptr2(std::move(i_ptr)); reset_after_move<const int*> i_cptr2(std::move(i_cptr)); EXPECT_EQ(i_ptr2, &i); EXPECT_EQ(i_cptr2, &i); EXPECT_EQ(i_ptr, nullptr); EXPECT_EQ(i_cptr, nullptr); Thing thing; reset_after_move<Thing*> thing_ptr{&thing}; reset_after_move<const Thing*> thing_cptr{&thing}; // Make sure there's no cloning happening. EXPECT_EQ(&*thing_ptr, &thing); thing_ptr->i = 10; EXPECT_EQ(thing_ptr->i, 10); EXPECT_EQ((*thing_ptr).i, 10); } GTEST_TEST(DefaultValueTest, Copy) { reset_after_move<int> x{1}; EXPECT_EQ(x, 1); // Copy-construction (from non-const reference) and lack of aliasing. reset_after_move<int> y{x}; EXPECT_EQ(x, 1); EXPECT_EQ(y, 1); x = 2; EXPECT_EQ(x, 2); EXPECT_EQ(y, 1); // Copy-construction (from const reference) and lack of aliasing. const reset_after_move<int>& x_cref = x; reset_after_move<int> z{x_cref}; x = 3; EXPECT_EQ(x, 3); EXPECT_EQ(y, 1); EXPECT_EQ(z, 2); // Copy-assignment and lack of aliasing. reset_after_move<int> w{22}; w = x; EXPECT_EQ(x, 3); EXPECT_EQ(w, 3); w = 4; EXPECT_EQ(x, 3); EXPECT_EQ(w, 4); } // We need to indirect self-move-assign through this function; doing it // directly in the test code generates a compiler warning. void MoveAssign(reset_after_move<int>* target, reset_after_move<int>* donor) { *target = std::move(*donor); } GTEST_TEST(DefaultValueTest, Move) { reset_after_move<int> x{1}; EXPECT_EQ(x, 1); // Move-construction and lack of aliasing. reset_after_move<int> y{std::move(x)}; EXPECT_EQ(x, 0); EXPECT_EQ(y, 1); x = 2; EXPECT_EQ(x, 2); EXPECT_EQ(y, 1); // Second move-construction and lack of aliasing. reset_after_move<int> z{std::move(x)}; EXPECT_EQ(x, 0); EXPECT_EQ(y, 1); EXPECT_EQ(z, 2); // Move-assignment and lack of aliasing. reset_after_move<int> w{22}; x = 3; w = std::move(x); EXPECT_EQ(x, 0); EXPECT_EQ(y, 1); EXPECT_EQ(z, 2); EXPECT_EQ(w, 3); x = 4; EXPECT_EQ(x, 4); EXPECT_EQ(y, 1); EXPECT_EQ(z, 2); EXPECT_EQ(w, 3); // Self-assignment during move. MoveAssign(&w, &w); EXPECT_EQ(w, 3); } // Make sure that our wrapper is sufficiently nothrow, e.g., so that it can // be moved (not copied) when an STL container is resized. GTEST_TEST(DefaultValueTest, Nothrow) { // Default constructor. EXPECT_TRUE(noexcept(reset_after_move<int>())); // Initialize-from-lvalue constructor. int i{}; EXPECT_TRUE(noexcept(reset_after_move<int>{i})); // Initialize-from-rvalue constructor. EXPECT_TRUE(noexcept(reset_after_move<int>{5})); // Copy constructor & assignment (source must be lvalue). reset_after_move<int> r_int, r_int2; EXPECT_TRUE(noexcept(reset_after_move<int>{r_int})); EXPECT_TRUE(noexcept(r_int = r_int2)); // Move constructor & assignment. EXPECT_TRUE(noexcept(reset_after_move<int>{std::move(r_int)})); EXPECT_TRUE(noexcept(r_int = std::move(r_int2))); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/find_runfiles_stub_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/find_runfiles.h" /* clang-format on */ #include <gtest/gtest.h> namespace drake { namespace { // Checks that find_runfiles_stub successfully compiles and links. GTEST_TEST(FindRunfilesTest, AcceptanceTest) { EXPECT_FALSE(HasRunfiles()); const auto result = FindRunfile("drake/foo"); EXPECT_EQ(result.abspath, ""); EXPECT_NE(result.error, ""); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_asin_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Asin) { CHECK_UNARY_FUNCTION(asin, x, y, 0.1); CHECK_UNARY_FUNCTION(asin, x, y, -0.1); CHECK_UNARY_FUNCTION(asin, y, x, 0.1); CHECK_UNARY_FUNCTION(asin, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/bit_cast_test.cc
#include "drake/common/bit_cast.h" #include <cstdint> #include <gtest/gtest.h> namespace drake { namespace internal { namespace { using std::uint64_t; // Mostly, this just checks for compilation failures. GTEST_TEST(BitCast, BasicTest) { const uint64_t foo = bit_cast<int64_t>(1.0); EXPECT_EQ(foo, 0x3ff0000000000000ull); const double bar = bit_cast<double>(foo); EXPECT_EQ(bar, 1.0); } } // namespace } // namespace internal } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/fmt_test.cc
#include "drake/common/fmt.h" #include <ostream> #include <fmt/ranges.h> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" // This namespace contains example code (i.e., what a user would write) for // formatting a class (or struct) using the "format as" helper. namespace sample { // A simple, non-templated struct. struct Int { int i{}; }; // A template with 1 type argument. template <typename T> struct Wrap { T t{}; }; // A template with 2 type arguments. template <typename T, typename U> struct Pair { T t{}; U u{}; }; } // namespace sample // Tell fmt how to format the sample types. DRAKE_FORMATTER_AS(, sample, Int, x, x.i) DRAKE_FORMATTER_AS(typename T, sample, Wrap<T>, x, x.t) DRAKE_FORMATTER_AS(typename... Ts, sample, Pair<Ts...>, x, std::pair(x.t, x.u)) namespace drake { namespace { // Spot check for the "format as" formatter. GTEST_TEST(FmtTest, FormatAsFormatter) { const sample::Int plain{1}; EXPECT_EQ(fmt::format("{}", plain), "1"); EXPECT_EQ(fmt::format("{:3}", plain), " 1"); EXPECT_EQ(fmt::format("{:<3}", plain), "1 "); const sample::Wrap<double> real{1.1234567e6}; EXPECT_EQ(fmt::format("{}", real), "1123456.7"); EXPECT_EQ(fmt::format("{:.3G}", real), "1.12E+06"); // N.B. The fmt:formatter for std::pair comes from <fmt/ranges.h>. const sample::Pair<int, int> pear{1, 2}; EXPECT_EQ(fmt::format("{}", pear), "(1, 2)"); } // The googletest infrastructure uses fmt's formatters. GTEST_TEST(FmtTest, TestPrinter) { const sample::Int plain{1}; EXPECT_EQ(testing::PrintToString(plain), "1"); const sample::Wrap<double> real{1.1}; EXPECT_EQ(testing::PrintToString(real), "1.1"); const sample::Pair<int, int> pear{1, 2}; EXPECT_EQ(testing::PrintToString(pear), "(1, 2)"); } // Spot check for the floating point formatter. GTEST_TEST(FmtTest, FloatingPoint) { EXPECT_EQ(fmt_floating_point(1.11), "1.11"); EXPECT_EQ(fmt_floating_point(1.1), "1.1"); EXPECT_EQ(fmt_floating_point(1.0), "1.0"); EXPECT_EQ(fmt_floating_point(1.11f), "1.11"); EXPECT_EQ(fmt_floating_point(1.1f), "1.1"); EXPECT_EQ(fmt_floating_point(1.0f), "1.0"); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/find_runfiles_subprocess_test.py
import os import subprocess import unittest class TestFindRunfilesSubprocess(unittest.TestCase): def _check_output(self, env=os.environ): try: output = subprocess.check_output([ "common/find_runfiles_test", "-spdlog_level=trace", "--gtest_filter=FindRunfilesTest.AcceptanceTest", ], stderr=subprocess.STDOUT, env=env) return output.decode("utf-8") except subprocess.CalledProcessError as e: e.output = e.output.decode("utf-8") print(e.output) raise def test_basic_child_process(self): # Check that a C++ program that uses FindRunfiles succeeds when called # from a python binary. output = self._check_output() # Check that the C++ program used the resource paths we wanted it to: # - It used the special-case TEST_SRCDIR mechanism. self.assertIn("FindRunfile mechanism = TEST_SRCDIR", output) # - It used find_runfiles_subprocess_test not find_runfiles_test, i.e., # the runfiles of the parent process were imbued to the subprocess. self.assertIn("find_runfiles_subprocess_test.runfile", output) self.assertNotIn("find_runfiles_test.runfile", output) def test_sans_test_srcdir(self): # Repeat test_basic_child_subprocess but with TEST_SRCDIR unset. # from a python binary. new_env = dict(os.environ) del new_env["TEST_SRCDIR"] output = self._check_output(env=new_env) self.assertIn("FindRunfile mechanism = RUNFILES_{MANIFEST", output) self.assertIn("find_runfiles_subprocess_test.runfile", output) self.assertNotIn("find_runfiles_test.runfile", output) def test_sans_all_env(self): # Repeat test_basic_child_subprocess but with an empty environment. # This covers the "argv0 mechanism" codepaths. try: output = self._check_output(env={}) status = 0 except subprocess.CalledProcessError as e: output = e.output status = e.returncode # If the user-facing binary bazel-bin/common/find_runfiles_test happens # to already exist then the subprocess's AcceptanceTest case passes. # # If instead only bazel-out/k8-opt/bin/common/find_runfiles_test exists # (and it will always exist, because it is a data dependency of this # python test), then the subprocess's AcceptanceTest case fails. # # Either way, should report that its using argv0 and not segfault. self.assertIn("FindRunfile mechanism = argv0", output) self.assertIn(status, (0, 1))
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/hash_test.cc
#include "drake/common/hash.h" #include <vector> #include <gtest/gtest.h> namespace drake { namespace { // A hasher which simply records all of its invocations for later inspection class MockHasher { public: void operator()(const void* data, size_t length) noexcept { const uint8_t* const begin = static_cast<const uint8_t*>(data); const uint8_t* const end = begin + length; record_.emplace_back(begin, end); } std::vector<std::vector<uint8_t>> record() const { return record_; } private: std::vector<std::vector<uint8_t>> record_; }; GTEST_TEST(HashTest, HashAppendOptional) { // Test basic functionality: ensure two equal values get hashed the same way, // and that an empty value and non-empty value are hashed differently // (regardless of whether or not the hashes turn out the same). std::optional<int> nonempty1(99); std::optional<int> nonempty2(99); MockHasher hash_nonempty1; MockHasher hash_nonempty2; hash_append(hash_nonempty1, nonempty1); hash_append(hash_nonempty2, nonempty2); EXPECT_EQ(hash_nonempty1.record(), hash_nonempty2.record()); EXPECT_EQ(hash_nonempty1.record().size(), 2); std::optional<int> empty1; std::optional<int> empty2; MockHasher hash_empty1; MockHasher hash_empty2; hash_append(hash_empty1, empty1); hash_append(hash_empty2, empty2); EXPECT_EQ(hash_empty1.record(), hash_empty2.record()); EXPECT_EQ(hash_empty1.record().size(), 1); // We specifically want to ensure that the hasher is called in a different // way for the empty and non-empty cases. Given that `hash_append` for // `int` and `bool` each invoke the hasher once, the following expectation // on total invocation counts reliably tests this: EXPECT_NE(hash_empty1.record().size(), hash_nonempty1.record().size()); } // This is mostly just a compilation test. If the declarations vs definitions // in the header file are incorrectly ordered, this would fail to compile. GTEST_TEST(HashTest, HashAppendPairOptionals) { const std::pair<std::optional<int>, std::optional<int>> foo{1, 2}; MockHasher foo_hash; hash_append(foo_hash, foo); EXPECT_EQ(foo_hash.record().size(), 4); } GTEST_TEST(HashTest, HashAppendPointer) { const std::pair<int, const int*> foo{22, nullptr}; MockHasher foo_hash; hash_append(foo_hash, foo); MockHasher expected; hash_append(expected, 22); hash_append(expected, std::uintptr_t{}); EXPECT_EQ(foo_hash.record(), expected.record()); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/name_value_test.cc
#include "drake/common/name_value.h" #include <gtest/gtest.h> namespace drake { namespace { GTEST_TEST(NameValueTest, SmokeTest) { int foo{1}; auto dut = DRAKE_NVP(foo); EXPECT_EQ(dut.name(), std::string("foo")); EXPECT_EQ(dut.value(), &foo); EXPECT_EQ(*dut.value(), 1); *dut.value() = 2; EXPECT_EQ(foo, 2); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/resource_tool_installed_test.py
"""Performs tests for resource_tool as used _after_ installation. """ import os from pathlib import Path import unittest import subprocess import sys import install_test_helper class TestResourceTool(unittest.TestCase): def setUp(self): # Establish the path to resource_tool. self._install_dir = Path(install_test_helper.get_install_dir()) self._resource_tool = ( self._install_dir / "share/drake/common/resource_tool") self.assertTrue(self._resource_tool.is_file()) # Establish the path to the sentinel dotfile. self._resource_subfolder = Path("share/drake") self._installed_sentinel = ( self._install_dir / self._resource_subfolder / ".drake-find_resource-sentinel") self.assertTrue(self._installed_sentinel.is_file()) # A valid, well-known resource path. self._resource = "drake/examples/pendulum/Pendulum.urdf" def test_basic_finding(self): """The installed resource_tool uses the installed files by default.""" absolute_path = install_test_helper.check_output( [self._resource_tool, "--print_resource_path", self._resource], stderr=subprocess.STDOUT).strip() self.assertTrue(Path(absolute_path).is_file(), f"Path does not exist: {absolute_path}") @unittest.skipIf( sys.platform == "darwin", "Our scaffolding uses LD_LIBRARY_PATH, which is not a thing on macOS") def test_symlinked_finding(self): # Prepare a copy of resource_tool that loads its library via a symlink. special_bin = self._install_dir / "foo/bar/baz/quux/bin" special_bin.mkdir(parents=True) (special_bin / "libdrake_marker.so").symlink_to( self._install_dir / "lib/libdrake_marker.so") env = {"LD_LIBRARY_PATH": str(special_bin)} special_tool = special_bin / "resource_tool" special_tool.hardlink_to(self._resource_tool) absolute_path = install_test_helper.check_output( [special_tool, "--print_resource_path", self._resource], env=env, stderr=subprocess.STDOUT).strip() self.assertTrue(Path(absolute_path).is_file(), f"Path does not exist: {absolute_path}") def test_ignores_runfiles(self): """The installed resource_tool ignores non-Drake runfiles.""" tool_env = dict(os.environ) tool_env["TEST_SRCDIR"] = "/tmp" absolute_path = install_test_helper.check_output( [self._resource_tool, "--print_resource_path", self._resource], env=tool_env, stderr=subprocess.STDOUT).strip() self.assertTrue(Path(absolute_path).is_file(), f"Path does not exist: {absolute_path}") def test_resource_root_environ(self): """The installed resource_tool obeys DRAKE_RESOURCE_ROOT.""" # Create a resource in the temporary directory. tmp_dir = Path(install_test_helper.create_temporary_dir()) resource_folder = tmp_dir / self._resource_subfolder test_folder = resource_folder / "common/test" test_folder.mkdir(parents=True) # Create sentinel file. sentinel = resource_folder / self._installed_sentinel.name sentinel.symlink_to(self._installed_sentinel) # Create resource file. resource = test_folder / "tmp_resource" resource_data = "tmp_resource" with open(resource, "w") as f: f.write(resource_data) # Cross-check the resource root environment variable name. env_name = "DRAKE_RESOURCE_ROOT" output_name = install_test_helper.check_output( [self._resource_tool, "--print_resource_root_environment_variable_name"]).strip() self.assertEqual(output_name, env_name) # Use the installed resource_tool to find a resource. tool_env = dict(os.environ) tool_env[env_name] = tmp_dir / "share" absolute_path = install_test_helper.check_output( [self._resource_tool, "--print_resource_path", "drake/common/test/tmp_resource"], env=tool_env).strip() with open(absolute_path, 'r') as data: self.assertEqual(data.read(), resource_data) # Use the installed resource_tool to find a resource, but with a bogus # DRAKE_RESOURCE_ROOT that should be ignored. tool_env[env_name] = tmp_dir / "share/drake" full_text = install_test_helper.check_output( [self._resource_tool, "--print_resource_path", self._resource], env=tool_env, stderr=subprocess.STDOUT).strip() warning = full_text.splitlines()[0] absolute_path = full_text.splitlines()[-1] self.assertIn("FindResource ignoring DRAKE_RESOURCE_ROOT", warning) self.assertTrue(Path(absolute_path).is_file(), f"Path does not exist: {absolute_path}") if __name__ == '__main__': unittest.main()
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/pointer_cast_test.cc
#include "drake/common/pointer_cast.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" namespace drake { namespace { struct Base { virtual ~Base() = default; }; struct Derived : public Base {}; struct MoreDerived : public Derived {}; // === Tests for static_pointer_cast<> === // N.B. We can't test failed downcast (types mismatch), because that is // undefined behavior. // Downcasting works. GTEST_TEST(StaticPointerCastTest, Downcast) { std::unique_ptr<Base> u = std::make_unique<Derived>(); std::unique_ptr<Derived> t = static_pointer_cast<Derived>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Casting to the identical type works. GTEST_TEST(StaticPointerCastTest, SameType) { std::unique_ptr<Base> u = std::make_unique<Base>(); std::unique_ptr<Base> t = static_pointer_cast<Base>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Upcasting works. GTEST_TEST(StaticPointerCastTest, Upcast) { std::unique_ptr<Derived> u = std::make_unique<Derived>(); std::unique_ptr<Base> t = static_pointer_cast<Base>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Downcasting while preserving const works. GTEST_TEST(StaticPointerCastTest, DowncastConst) { std::unique_ptr<const Base> u = std::make_unique<const Derived>(); std::unique_ptr<const Derived> t = static_pointer_cast<const Derived>( std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // === Tests for dynamic_pointer_cast<> === // Downcasting works. GTEST_TEST(DynamicPointerCastTest, Downcast) { std::unique_ptr<Base> u = std::make_unique<Derived>(); std::unique_ptr<Derived> t = dynamic_pointer_cast<Derived>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Failed downcast (type mismatch) leaves the original object intact. GTEST_TEST(DynamicPointerCastTest, FailedDowncast) { std::unique_ptr<Base> u = std::make_unique<Derived>(); std::unique_ptr<Derived> t = dynamic_pointer_cast<MoreDerived>(std::move(u)); EXPECT_EQ(!!u, true); EXPECT_EQ(!!t, false); } // Casting to the identical type works. GTEST_TEST(DynamicPointerCastTest, SameType) { std::unique_ptr<Base> u = std::make_unique<Base>(); std::unique_ptr<Base> t = dynamic_pointer_cast<Base>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Upcasting works. GTEST_TEST(DynamicPointerCastTest, Upcast) { std::unique_ptr<Derived> u = std::make_unique<Derived>(); std::unique_ptr<Base> t = dynamic_pointer_cast<Base>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Downcasting while preserving const works. GTEST_TEST(DynamicPointerCastTest, DowncastConst) { std::unique_ptr<const Base> u = std::make_unique<const Derived>(); std::unique_ptr<const Derived> t = dynamic_pointer_cast<const Derived>( std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // === Tests for dynamic_pointer_cast_or_throw<> on unique_ptr === // Downcasting works. GTEST_TEST(DynamicPointerCastOrThrowTest, Downcast) { std::unique_ptr<Base> u = std::make_unique<Derived>(); std::unique_ptr<Derived> t = dynamic_pointer_cast_or_throw<Derived>( std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Failed cast of nullptr. GTEST_TEST(DynamicPointerCastOrThrowTest, FailedCastFromNullptr) { std::unique_ptr<Base> u; DRAKE_EXPECT_THROWS_MESSAGE( dynamic_pointer_cast_or_throw<MoreDerived>(std::move(u)), "Cannot cast a unique_ptr<drake.*Base> containing nullptr " "to unique_ptr<drake.*MoreDerived>."); EXPECT_EQ(!!u, false); } // Failed cast (type mismatch) leaves the original object intact. GTEST_TEST(DynamicPointerCastOrThrowTest, FailedDowncast) { std::unique_ptr<Base> u = std::make_unique<Derived>(); DRAKE_EXPECT_THROWS_MESSAGE( dynamic_pointer_cast_or_throw<MoreDerived>(std::move(u)), "Cannot cast a unique_ptr<drake.*Base> containing an object of type " "drake.*Derived to unique_ptr<drake.*MoreDerived>."); EXPECT_EQ(!!u, true); } // Casting to the identical type works. GTEST_TEST(DynamicPointerCastOrThrowTest, SameType) { std::unique_ptr<Base> u = std::make_unique<Base>(); std::unique_ptr<Base> t = dynamic_pointer_cast_or_throw<Base>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Upcasting works. GTEST_TEST(DynamicPointerCastOrThrowTest, Upcast) { std::unique_ptr<Derived> u = std::make_unique<Derived>(); std::unique_ptr<Base> t = dynamic_pointer_cast_or_throw<Base>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // Downcasting while preserving const works. GTEST_TEST(DynamicPointerCastOrThrowTest, DowncastConst) { std::unique_ptr<const Base> u = std::make_unique<const Derived>(); std::unique_ptr<const Derived> t = dynamic_pointer_cast_or_throw<const Derived>(std::move(u)); EXPECT_EQ(!!u, false); EXPECT_EQ(!!t, true); } // === Tests for dynamic_pointer_cast_or_throw<> on a raw pointer === // Downcasting works. GTEST_TEST(BareDynamicPointerCastOrThrowTest, Downcast) { Derived derived; Base* u = &derived; Derived* t = dynamic_pointer_cast_or_throw<Derived>(u); EXPECT_TRUE(t != nullptr); EXPECT_TRUE(t == u); } // Failed cast of nullptr. GTEST_TEST(BareDynamicPointerCastOrThrowTest, FailedCastFromNullptr) { Base* u = nullptr; DRAKE_EXPECT_THROWS_MESSAGE( dynamic_pointer_cast_or_throw<MoreDerived>(u), "Cannot cast a nullptr drake.*Base. " "to drake.*MoreDerived.."); } // Failed cast (type mismatch). GTEST_TEST(BareDynamicPointerCastOrThrowTest, FailedDowncast) { Derived derived; Base* u = &derived; DRAKE_EXPECT_THROWS_MESSAGE( dynamic_pointer_cast_or_throw<MoreDerived>(u), "Cannot cast a drake.*Base. pointing to an object of type " "drake.*Derived to drake.*MoreDerived.."); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/is_cloneable_test.cc
#include "drake/common/is_cloneable.h" #include <memory> #include <gtest/gtest.h> // This provides concrete examples of the `is_cloneable` function // for showing which classes are considered cloneable and which // aren't. namespace drake { namespace { using std::make_unique; using std::unique_ptr; //----- A Collection of Dummy Classes for tests // A fully copyable class (has both copy constructor and Clone). Also used to // test inheritance of Clone methods. // Cloneable! class Base { public: Base() {} Base(const Base& b) = default; unique_ptr<Base> Clone() const { return make_unique<Base>(); } }; GTEST_TEST(IsCloneableTest, FullyCopyable) { EXPECT_TRUE(is_cloneable<Base>::value); } // A class with no copy constructor, but a valid Clone method. // Cloneable! class CloneOnly { public: CloneOnly() {} CloneOnly(const CloneOnly& f) = delete; unique_ptr<CloneOnly> Clone() const { return make_unique<CloneOnly>(); } }; GTEST_TEST(IsCloneableTest, OnlyCloneable) { EXPECT_TRUE(is_cloneable<CloneOnly>::value); } // Confirms that a const type is still considered cloneable if the type is // cloneable. GTEST_TEST(IsCloneableTest, TestConstType) { EXPECT_TRUE(is_cloneable<const CloneOnly>::value); } // A class with no copy constructor, but has a Clone that returns the parent // class pointer. The parent is representative of *any* ancestor in the // inheritance tree. // Cloneable! class CloneToParent : public Base { public: CloneToParent() {} CloneToParent(const CloneToParent& c) = delete; unique_ptr<Base> Clone() const { return make_unique<CloneToParent>(); } }; // This tests the cloneability of a class that *does* have a const Clone() // method, but the return type is a parent class type. This is not cloneable // because it would amount to: // Base* base_ptr = nullptr; // Derived* ptr = base_ptr; // which is clearly invalid. GTEST_TEST(IsCloneableTest, CloneUsingInheritedMethod) { EXPECT_FALSE(is_cloneable<CloneToParent>::value); } // A class with no copy constructor and a Clone method with the wrong return // type -- no explicit conversion from * to unique_ptr. // NOT CLONEABLE! class BadClone : public Base { public: BadClone() {} BadClone(const BadClone& c) = delete; [[nodiscard]] BadClone* Clone() const { return new BadClone(); } }; GTEST_TEST(IsCloneableTest, BadCloneReturnFail) { EXPECT_FALSE(is_cloneable<BadClone>::value); } // A class with no copy constructor and a non-const Clone method. // NOT CLONEABLE! class NonConstClone : public Base { public: NonConstClone() {} NonConstClone(const NonConstClone& c) = delete; unique_ptr<NonConstClone> Clone() { return make_unique<NonConstClone>(); } }; GTEST_TEST(IsCloneableTest, NonConstCloneFail) { EXPECT_FALSE(is_cloneable<NonConstClone>::value); } // Class with no copy semantics (no copy constructor, no Clone) // NOT CLONEABLE! class CantCopy { public: CantCopy() {} CantCopy(const CantCopy& f) = delete; }; GTEST_TEST(IsCloneableTest, UnCopyableFail) { EXPECT_FALSE(is_cloneable<CantCopy>::value); } // A class with a malformed Clone method, but it has a copy constructor. // NOT CLONEABLE! (But copyable.) class BadCloneCopy { public: BadCloneCopy() {} BadCloneCopy(const BadCloneCopy& f) = default; [[nodiscard]] BadCloneCopy* Clone() const { return new BadCloneCopy(); } }; GTEST_TEST(IsCloneableTest, CopyableWithBadCloneFail) { EXPECT_FALSE(is_cloneable<BadCloneCopy>::value); } // A class with a copy constructor but no clone method. // NOT CLONEABLE! (But copyable.) class NoClone { public: NoClone() {} NoClone(const NoClone& f) {} }; GTEST_TEST(IsCloneableTest, CopyableButNoCloneFail) { EXPECT_FALSE(is_cloneable<NoClone>::value); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/sorted_pair_test.cc
#include "drake/common/sorted_pair.h" #include <sstream> #include <unordered_map> #include <vector> #include <fmt/ranges.h> #include <gtest/gtest.h> namespace drake { namespace { struct NoDefaultCtor { explicit NoDefaultCtor(int value_in) : value(value_in) {} bool operator<(const NoDefaultCtor& other) const { return value < other.value; } int value{}; }; // Verifies behavior of the default constructor. GTEST_TEST(SortedPair, Default) { SortedPair<int> x; EXPECT_EQ(x.first(), 0); EXPECT_EQ(x.second(), 0); SortedPair<double> y; EXPECT_EQ(y.first(), 0.0); EXPECT_EQ(y.second(), 0.0); } // Usable even with non-default-constructible types GTEST_TEST(SortedPair, WithoutDefaultCtor) { NoDefaultCtor a(2); NoDefaultCtor b(1); SortedPair<NoDefaultCtor> x(a, b); EXPECT_EQ(x.first().value, 1); EXPECT_EQ(x.second().value, 2); } // Verifies sorting occurs. GTEST_TEST(SortedPair, Values) { SortedPair<int> x(3, 2); EXPECT_EQ(x.first(), 2); EXPECT_EQ(x.second(), 3); } // Verifies that the type casting copy constructor works as desired. GTEST_TEST(SortedPair, Casting) { SortedPair<double> x = SortedPair<int>(3, 2); EXPECT_EQ(x.first(), 2.0); EXPECT_EQ(x.second(), 3.0); } // Verifies that 'set()' works properly. GTEST_TEST(SortedPair, Set) { SortedPair<double> x; x.set(1.0, 2.0); EXPECT_EQ(x.first(), 1.0); EXPECT_EQ(x.second(), 2.0); x.set(5.0, 3.0); EXPECT_EQ(x.first(), 3.0); EXPECT_EQ(x.second(), 5.0); } // Verifies that the move assignment operator and move constructor work. GTEST_TEST(SortedPair, Move) { auto a = std::make_unique<int>(2); auto b = std::make_unique<int>(1); SortedPair<std::unique_ptr<int>> y(std::move(a), std::move(b)); SortedPair<std::unique_ptr<int>> x; x = std::move(y); EXPECT_TRUE(x.first() < x.second()); EXPECT_EQ(y.first().get(), nullptr); EXPECT_EQ(y.second().get(), nullptr); y = SortedPair<std::unique_ptr<int>>(std::move(x)); EXPECT_TRUE(y.first() < y.second()); EXPECT_EQ(x.first().get(), nullptr); EXPECT_EQ(x.second().get(), nullptr); } // Checks the assignment operator. GTEST_TEST(SortedPair, Assignment) { SortedPair<int> x; SortedPair<int> y(3, 2); EXPECT_EQ(&(x = y), &x); EXPECT_EQ(x.first(), 2.0); EXPECT_EQ(x.second(), 3.0); } // Checks the equality operator. GTEST_TEST(SortedPair, Equality) { SortedPair<int> x(1, 2), y(2, 1); EXPECT_EQ(x, y); } // Checks the comparison operators. GTEST_TEST(SortedPair, Comparison) { SortedPair<int> x(1, 2), y(2, 2); EXPECT_FALSE(x < x); EXPECT_FALSE(x > x); EXPECT_TRUE(x <= x); EXPECT_TRUE(x >= x); EXPECT_TRUE(x < y); } // Checks the swap function. GTEST_TEST(SortedPair, Swap) { SortedPair<int> x(1, 2), y(3, 4); std::swap(x, y); EXPECT_EQ(x.first(), 3); EXPECT_EQ(x.second(), 4); EXPECT_EQ(y.first(), 1); EXPECT_EQ(y.second(), 2); } // Checks hash keys. GTEST_TEST(SortedPair, Hash) { SortedPair<int> x(1, 2), y(2, 4); std::unordered_map<SortedPair<int>, int> hash; hash[x] = 11; hash[y] = 13; EXPECT_EQ(hash[x], 11); EXPECT_EQ(hash[y], 13); } // Checks expansion with STL vector. GTEST_TEST(SortedPair, VectorExp) { std::vector<std::unique_ptr<SortedPair<int>>> v; v.emplace_back(std::make_unique<SortedPair<int>>(1, 2)); v.resize(v.capacity() + 1); EXPECT_EQ(v.front()->first(), 1); EXPECT_EQ(v.front()->second(), 2); } // Tests the MakeSortedPair operator. GTEST_TEST(SortedPair, MakeSortedPair) { EXPECT_EQ(SortedPair<int>(1, 2), MakeSortedPair(1, 2)); } // Tests that formatting support is reasonable. GTEST_TEST(SortedPair, Format) { SortedPair<int> pair{8, 7}; // We don't care exactly what fmt does here, just that it looks sensible. // It's OK to to update this goal string in case fmt changes a bit over time. EXPECT_EQ(fmt::to_string(pair), "(7, 8)"); } GTEST_TEST(SortedPair, StructuredBinding) { SortedPair<int> pair{8, 7}; // Copy access. { auto [a, b] = pair; EXPECT_EQ(a, pair.first()); EXPECT_EQ(b, pair.second()); } // Const reference access. { auto& [a, b] = pair; EXPECT_EQ(&a, &pair.first()); EXPECT_EQ(&b, &pair.second()); } // Access via range iterators. { std::vector<SortedPair<int>> pairs({{1, 2}, {3, 6}}); for (const auto& [a, b] : pairs) { EXPECT_EQ(2 * a, b); } } } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/resource_tool_test.py
"""Performs simple within-sandbox tests for resource_tool, exercising its command-line API through all corner cases. """ import re import subprocess import os import sys import unittest class TestResourceTool(unittest.TestCase): def setUp(self): self._resource_tool_exe, = sys.argv[1:] self.assertTrue( os.path.exists(self._resource_tool_exe), "Could not find " + self._resource_tool_exe) def _check_call(self, args, expected_returncode=0): """Run resource_tool with the given args; return output. """ try: output = subprocess.check_output( [self._resource_tool_exe] + args, stderr=subprocess.STDOUT) returncode = 0 except subprocess.CalledProcessError as e: output = e.output returncode = e.returncode self.assertEqual( returncode, expected_returncode, "Expected returncode %r from %r but got %r with output %r" % ( expected_returncode, args, returncode, output)) return output.decode('utf8') def test_help(self): output = self._check_call([ "--help", ], expected_returncode=1) self.assertTrue("Find Drake-related resources" in output) self.assertGreater(len(output), 1000) def test_no_arguments(self): output = self._check_call([], expected_returncode=1) self.assertGreater(len(output), 1000) def test_too_many_arguments(self): self._check_call([ "--print_resource_root_environment_variable_name", "--print_resource_path", "drake/common/test/resource_tool_test_data.txt", ], expected_returncode=1) def test_resource_root_environment_variable_name(self): output = self._check_call([ "--print_resource_root_environment_variable_name", ], expected_returncode=0).strip() self.assertGreater(len(output), 0) # N.B. This test only confirms that the variable name is printed. The # resource_tool_installed_test.py covers actually setting the variable. def test_print_resource_path_found(self): output = self._check_call([ "--print_resource_path", "drake/common/test/resource_tool_test_data.txt", ], expected_returncode=0) absolute_path = output.strip() with open(absolute_path, 'r') as data: self.assertEqual( data.read(), "Test data for drake/common/test/resource_tool_test.py.\n") def test_print_resource_path_error(self): output = self._check_call([ "--print_resource_path", "drake/no_such_file", ], expected_returncode=1) self.assertIn("Sought 'drake/no_such_file' in runfiles", output) self.assertIn("file does not exist", output) def test_help_example_is_correct(self): # Look at the usage message, and snarf its Pendulum example paths. output = self._check_call([ "--help", ], expected_returncode=1) output = output.replace("\n", " ") m = re.search( (r"-print_resource_path.*`(drake.*)`.*" + r"absolute path.*?`/home/user/(drake/.*?)`"), output) self.assertTrue(m is not None, "Could not match in " + repr(output)) example_relpath, example_abspath = m.groups() self.assertEqual(example_relpath, example_abspath) # Ask for the help message's example and make sure it still works. output = self._check_call([ "--print_resource_path", example_relpath, ], expected_returncode=0) absolute_path = output.strip() self.assertTrue(absolute_path.endswith(example_abspath)) self.assertTrue(os.path.exists(absolute_path))
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/parallelism_test.cc
#include "drake/common/parallelism.h" #include <thread> #include <gtest/gtest.h> namespace drake { namespace internal { namespace { constexpr int kNoneThreads = 1; // This is configured by the test rule, which sets the environment variable. constexpr int kMaxThreads = 2; // Tests that different spellings of no parallelism are equivalent. GTEST_TEST(ParallelismTest, NoneTest) { const Parallelism default_parallelism; EXPECT_EQ(default_parallelism.num_threads(), kNoneThreads); const Parallelism none_parallelism = Parallelism::None(); EXPECT_EQ(none_parallelism.num_threads(), kNoneThreads); const Parallelism false_parallelism(false); EXPECT_EQ(false_parallelism.num_threads(), kNoneThreads); } // Tests that different spellings of max parallelism are equivalent. GTEST_TEST(ParallelismTest, MaxTest) { const Parallelism max_parallelism = Parallelism::Max(); EXPECT_EQ(max_parallelism.num_threads(), kMaxThreads); const Parallelism true_parallelism(true); EXPECT_EQ(true_parallelism.num_threads(), kMaxThreads); } // Tests construction with a specific number of threads. GTEST_TEST(ParallelismTest, NumThreadsTest) { // Valid values for number of threads. for (const int num_threads : {1, 2, 10, 1000}) { EXPECT_EQ(Parallelism(num_threads).num_threads(), num_threads); } // Specified number of threads must be >= 1. EXPECT_THROW(Parallelism(0), std::exception); EXPECT_THROW(Parallelism(-1), std::exception); EXPECT_THROW(Parallelism(-1000), std::exception); } // Tests that conversion and assignment from bool work. GTEST_TEST(ParallelismTest, BoolConversionAssignmentTest) { const Parallelism converted_false = false; EXPECT_EQ(converted_false.num_threads(), kNoneThreads); const Parallelism converted_true = true; EXPECT_EQ(converted_true.num_threads(), kMaxThreads); Parallelism assigned_parallelism; EXPECT_EQ(assigned_parallelism.num_threads(), kNoneThreads); assigned_parallelism = true; EXPECT_EQ(assigned_parallelism.num_threads(), kMaxThreads); assigned_parallelism = false; EXPECT_EQ(assigned_parallelism.num_threads(), kNoneThreads); } // Tests all variety of environment variable string parsing. GTEST_TEST(ParallelismTest, ParsingLogicTest) { // When string parsing fails, this is what we get back. const int fallback = std::thread::hardware_concurrency(); EXPECT_EQ(ConfigureMaxNumThreads(nullptr, nullptr), fallback); // A table of test cases for string value => configured max. std::vector<std::pair<const char*, int>> tests = {{ // Happy values. {"1", 1}, {"2", 2}, // Empty values. {"", fallback}, {" ", fallback}, // Garbage values. {"4,4,4", fallback}, {"1.0", fallback}, {"a", fallback}, {"a1", fallback}, {"0x01", fallback}, {"☃", fallback}, {"1☃", fallback}, // Out-of-bounds values. {"-100", fallback}, {"-1", fallback}, {"0", fallback}, {"999999999", fallback}, }}; for (const auto& [value, expected_max] : tests) { EXPECT_EQ(ConfigureMaxNumThreads(value, nullptr), expected_max) << value; EXPECT_EQ(ConfigureMaxNumThreads(nullptr, value), expected_max) << value; } // When both environment variables are set, the DRAKE one always wins even if // it's unparseable. EXPECT_EQ(ConfigureMaxNumThreads("2", "1"), 2); EXPECT_EQ(ConfigureMaxNumThreads("", "1"), fallback); EXPECT_EQ(ConfigureMaxNumThreads("-1", "1"), fallback); } } // namespace } // namespace internal } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/autodiffxd_atan_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/autodiff.h" #include "drake/common/ad/test/standard_operations_test.h" /* clang-format on */ namespace drake { namespace test { namespace { TEST_F(AutoDiffXdTest, Atan) { CHECK_UNARY_FUNCTION(atan, x, y, 0.1); CHECK_UNARY_FUNCTION(atan, x, y, -0.1); CHECK_UNARY_FUNCTION(atan, y, x, 0.1); CHECK_UNARY_FUNCTION(atan, y, x, -0.1); } } // namespace } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/nice_type_name_test.cc
#include "drake/common/nice_type_name.h" #include <complex> #include <string> #include <utility> #include <vector> #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/autodiff.h" #include "drake/common/identifier.h" #include "drake/common/nice_type_name_override.h" using std::string; namespace drake { namespace { enum class Color { Red, Green, Blue }; // Tests enumeration types. struct ForTesting { enum MyEnum { One, Two, Three }; enum class MyEnumClass { Four, Five, Six }; }; // Test RTTI for inheritance. class Base { public: virtual ~Base() = default; }; class Derived : public Base {}; // Type to have its NiceTypeName be overridden via // `SetNiceTypeNamePtrOverride`. class OverrideName {}; // Test the Identifier pattern. using AId = Identifier<class ATag>; } // namespace namespace { // Can't test much of NiceTypeName::Demangle because its behavior is compiler- // and platform-specific. Everyone should agree on simple types though. GTEST_TEST(NiceTypeNameTest, Demangle) { // NOLINTNEXTLINE(readability/casting) False positive. EXPECT_EQ(NiceTypeName::Demangle(typeid(bool).name()), "bool"); // NOLINTNEXTLINE(readability/casting) False positive. EXPECT_EQ(NiceTypeName::Demangle(typeid(int).name()), "int"); EXPECT_EQ(NiceTypeName::Demangle(typeid(unsigned).name()), "unsigned int"); } // Standalone tests of the method that is used by NiceTypeName::Get<T>::Get() // to clean up the demangled names on various platforms. GTEST_TEST(NiceTypeNameTest, Canonicalize) { // Get rid of extra spaces and useless names like "class". EXPECT_EQ(NiceTypeName::Canonicalize("class std :: vector < double >"), "std::vector<double>"); // OSX's stl like to throw in these extra namespaces. EXPECT_EQ(NiceTypeName::Canonicalize("std:: __1 :: __23 :: set<T>"), "std::set<T>"); // Should leave spaces between words. EXPECT_EQ(NiceTypeName::Canonicalize("lunch bucket"), "lunch bucket"); // And keep funny looking namespaces if they aren't __something. EXPECT_EQ(NiceTypeName::Canonicalize("std::my__1::__23x::resigned char"), "std::my__1::resigned char"); } GTEST_TEST(NiceTypeNameTest, BuiltIns) { EXPECT_EQ(NiceTypeName::Get<bool>(), "bool"); EXPECT_EQ(NiceTypeName::Get<signed char>(), "signed char"); EXPECT_EQ(NiceTypeName::Get<unsigned char>(), "unsigned char"); EXPECT_EQ(NiceTypeName::Get<short>(), "short"); // NOLINT(runtime/int) EXPECT_EQ(NiceTypeName::Get<unsigned short>(), // NOLINT(runtime/int) "unsigned short"); EXPECT_EQ(NiceTypeName::Get<int>(), "int"); EXPECT_EQ(NiceTypeName::Get<unsigned int>(), "unsigned int"); EXPECT_EQ(NiceTypeName::Get<unsigned>(), "unsigned int"); EXPECT_EQ(NiceTypeName::Get<long>(), "long"); // NOLINT(runtime/int) EXPECT_EQ(NiceTypeName::Get<long int>(), "long"); // NOLINT(runtime/int) EXPECT_EQ(NiceTypeName::Get<unsigned long>(), // NOLINT(runtime/int) "unsigned long"); EXPECT_EQ(NiceTypeName::Get<long long>(), // NOLINT(runtime/int) "long long"); EXPECT_EQ(NiceTypeName::Get<long long int>(), // NOLINT(runtime/int) "long long"); EXPECT_EQ(NiceTypeName::Get<unsigned long long>(), // NOLINT(runtime/int) "unsigned long long"); EXPECT_EQ(NiceTypeName::Get<float>(), "float"); EXPECT_EQ(NiceTypeName::Get<double>(), "double"); EXPECT_EQ(NiceTypeName::Get<long double>(), "long double"); EXPECT_EQ(NiceTypeName::Get<std::complex<float>>(), "std::complex<float>"); EXPECT_EQ(NiceTypeName::Get<std::complex<double>>(), "std::complex<double>"); EXPECT_EQ(NiceTypeName::Get<std::complex<long double>>(), "std::complex<long double>"); } GTEST_TEST(NiceTypeNameTest, StdClasses) { EXPECT_EQ(NiceTypeName::Get<std::string>(), "std::string"); EXPECT_EQ(NiceTypeName::Get<string>(), "std::string"); // Shouldn't be fooled by an alias or typedef. using MyStringAlias = std::string; typedef std::string MyStringTypedef; EXPECT_EQ(NiceTypeName::Get<MyStringAlias>(), "std::string"); EXPECT_EQ(NiceTypeName::Get<MyStringTypedef>(), "std::string"); // std::vector with default allocator. EXPECT_EQ(NiceTypeName::Get<std::vector<int>>(), "std::vector<int,std::allocator<int>>"); EXPECT_EQ(NiceTypeName::Get<std::vector<std::string>>(), "std::vector<std::string,std::allocator<std::string>>"); // Try non-standard allocator. using NonStdAlloc = std::vector<unsigned, std::allocator<unsigned>>; EXPECT_EQ(NiceTypeName::Get<NonStdAlloc>(), "std::vector<unsigned int,std::allocator<unsigned int>>"); } GTEST_TEST(NiceTypeNameTest, Eigen) { EXPECT_EQ(NiceTypeName::Get<Eigen::Matrix2d>(), "Eigen::Matrix2d"); EXPECT_EQ(NiceTypeName::Get<Eigen::Matrix3i>(), "Eigen::Matrix3i"); EXPECT_EQ(NiceTypeName::Get<Eigen::Matrix3f>(), "Eigen::Matrix3f"); EXPECT_EQ(NiceTypeName::Get<Eigen::Matrix3d>(), "Eigen::Matrix3d"); EXPECT_EQ(NiceTypeName::Get<Eigen::MatrixXd>(), "Eigen::MatrixXd"); EXPECT_EQ(NiceTypeName::Get<Eigen::Vector2d>(), "Eigen::Vector2d"); EXPECT_EQ(NiceTypeName::Get<Eigen::Vector3i>(), "Eigen::Vector3i"); EXPECT_EQ(NiceTypeName::Get<Eigen::Vector3f>(), "Eigen::Vector3f"); EXPECT_EQ(NiceTypeName::Get<Eigen::Vector3d>(), "Eigen::Vector3d"); EXPECT_EQ(NiceTypeName::Get<Eigen::VectorXd>(), "Eigen::VectorXd"); EXPECT_EQ(NiceTypeName::Get<AutoDiffXd>(), "drake::AutoDiffXd"); using PairType = std::pair<Eigen::Vector2i, Eigen::Vector3d>; EXPECT_EQ(NiceTypeName::Get<PairType>(), "std::pair<Eigen::Vector2i,Eigen::Vector3d>"); } GTEST_TEST(NiceTypeNameTest, Enum) { EXPECT_EQ(NiceTypeName::Get<Color>(), "drake::(anonymous)::Color"); EXPECT_EQ(NiceTypeName::Get<ForTesting>(), "drake::(anonymous)::ForTesting"); EXPECT_EQ(NiceTypeName::Get<ForTesting::MyEnum>(), "drake::(anonymous)::ForTesting::MyEnum"); EXPECT_EQ(NiceTypeName::Get<ForTesting::MyEnumClass>(), "drake::(anonymous)::ForTesting::MyEnumClass"); EXPECT_EQ(NiceTypeName::Get<decltype(ForTesting::One)>(), "drake::(anonymous)::ForTesting::MyEnum"); EXPECT_EQ(NiceTypeName::Get<decltype( ForTesting::MyEnumClass::Four)>(), "drake::(anonymous)::ForTesting::MyEnumClass"); } GTEST_TEST(NiceTypeNameTest, IdentifierTemplate) { EXPECT_EQ(NiceTypeName::Get<AId>(), "drake::(anonymous)::AId"); } // Test the type_info form of NiceTypeName::Get(). GTEST_TEST(NiceTypeNameTest, FromTypeInfo) { EXPECT_EQ(NiceTypeName::Get(typeid(int)), "int"); EXPECT_EQ(NiceTypeName::Get(typeid(Derived)), "drake::(anonymous)::Derived"); } // Test the expression-accepting form of NiceTypeName::Get(). GTEST_TEST(NiceTypeNameTest, Expressions) { const int i = 10; const double d = 3.14; EXPECT_EQ(NiceTypeName::Get(i), "int"); EXPECT_EQ(NiceTypeName::Get(d), "double"); EXPECT_EQ(NiceTypeName::Get(i * d), "double"); Derived derived; Base* base = &derived; // These both have the same name despite different declarations because // they resolve to the same concrete type. EXPECT_EQ(NiceTypeName::Get(derived), "drake::(anonymous)::Derived"); EXPECT_EQ(NiceTypeName::Get(*base), "drake::(anonymous)::Derived"); // OTOH, these differ because we get only the declared types. EXPECT_NE(NiceTypeName::Get<decltype(*base)>(), NiceTypeName::Get<decltype(derived)>()); auto derived_uptr = std::make_unique<Derived>(); auto base_uptr = std::unique_ptr<Base>(new Derived()); EXPECT_EQ(NiceTypeName::Get(*derived_uptr), "drake::(anonymous)::Derived"); EXPECT_EQ(NiceTypeName::Get(*base_uptr), "drake::(anonymous)::Derived"); // unique_ptr is not polymorphic (unlike its contents) so its declared type // and runtime type are the same. EXPECT_EQ(NiceTypeName::Get<decltype(base_uptr)>(), NiceTypeName::Get(base_uptr)); } GTEST_TEST(NiceTypeNameTest, RemoveNamespaces) { EXPECT_EQ(NiceTypeName::RemoveNamespaces("JustAPlainType"), "JustAPlainType"); EXPECT_EQ( NiceTypeName::RemoveNamespaces("drake::(anonymous)::Derived"), "Derived"); // Should ignore nested namespaces. EXPECT_EQ(NiceTypeName::RemoveNamespaces( "std::vector<std::string,std::allocator<std::string>>"), "vector<std::string,std::allocator<std::string>>"); // Should stop at the first templatized segment. EXPECT_EQ(NiceTypeName::RemoveNamespaces( "drake::systems::sensors::RgbdRenderer<T>::Impl"), "RgbdRenderer<T>::Impl"); // Check behavior in odd cases. EXPECT_EQ(NiceTypeName::RemoveNamespaces(""), ""); EXPECT_EQ(NiceTypeName::RemoveNamespaces("::"), "::"); // No final type segment -- should leave unprocessed. EXPECT_EQ(NiceTypeName::RemoveNamespaces("blah::blah2::"), "blah::blah2::"); } // This test must be last. GTEST_TEST(NiceTypeNameTest, Override) { internal::SetNiceTypeNamePtrOverride( [](const internal::type_erased_ptr& ptr) -> std::string { EXPECT_NE(ptr.raw, nullptr); if (ptr.info == typeid(OverrideName)) { return "example_override"; } else { return NiceTypeName::Get(ptr.info); } }); EXPECT_EQ( NiceTypeName::Get<OverrideName>(), "drake::(anonymous)::OverrideName"); const OverrideName obj; EXPECT_EQ(NiceTypeName::Get(obj), "example_override"); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/never_destroyed_test.cc
#include "drake/common/never_destroyed.h" #include <random> #include <unordered_map> #include <gtest/gtest.h> #include "drake/common/drake_copyable.h" namespace drake { namespace { class Boom : public std::exception { }; struct DtorGoesBoom { ~DtorGoesBoom() noexcept(false) { throw Boom(); } }; // Confirm that we see booms by default. GTEST_TEST(NeverDestroyedTest, BoomTest) { try { { DtorGoesBoom foo; } GTEST_FAIL(); } catch (const Boom&) { ASSERT_TRUE(true); } } // Confirm that our wrapper stops the booms. GTEST_TEST(NeverDestroyedTest, NoBoomTest) { try { { never_destroyed<DtorGoesBoom> foo; } ASSERT_TRUE(true); } catch (const Boom& e) { GTEST_FAIL(); } } // This is an example from the class overview API docs; we repeat it here to // ensure it remains valid. class Singleton { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Singleton) static Singleton& getInstance() { static never_destroyed<Singleton> instance; return instance.access(); } private: friend never_destroyed<Singleton>; Singleton() = default; }; GTEST_TEST(NeverDestroyedExampleTest, Singleton) { const Singleton* get1 = &Singleton::getInstance(); const Singleton* get2 = &Singleton::getInstance(); EXPECT_EQ(get1, get2); } // This is an example from the class overview API docs; we repeat it here to // ensure it remains valid. enum class Foo { kBar, kBaz }; Foo ParseFoo(const std::string& foo_string) { using Dict = std::unordered_map<std::string, Foo>; static const drake::never_destroyed<Dict> string_to_enum{ std::initializer_list<Dict::value_type>{ {"bar", Foo::kBar}, {"baz", Foo::kBaz}, } }; return string_to_enum.access().at(foo_string); } GTEST_TEST(NeverDestroyedExampleTest, ParseFoo) { EXPECT_EQ(ParseFoo("bar"), Foo::kBar); EXPECT_EQ(ParseFoo("baz"), Foo::kBaz); } // This is an example from the class overview API docs; we repeat it here to // ensure it remains valid. const std::vector<double>& GetConstantMagicNumbers() { static const drake::never_destroyed<std::vector<double>> result{[]() { std::vector<double> prototype; std::mt19937 random_generator; for (int i = 0; i < 10; ++i) { double new_value = random_generator(); prototype.push_back(new_value); } return prototype; }()}; return result.access(); } GTEST_TEST(NeverDestroyedExampleTest, GetConstantMagicNumbers) { const auto& numbers = GetConstantMagicNumbers(); EXPECT_EQ(numbers.size(), 10); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/identifier_test.cc
#include "drake/common/identifier.h" #include <set> #include <sstream> #include <unordered_map> #include <unordered_set> #include <utility> #include "absl/container/flat_hash_set.h" #include <gtest/gtest.h> #include "drake/common/sorted_pair.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/expect_throws_message.h" namespace drake { namespace { // Creates various dummy index types to test. using std::set; using std::stringstream; using std::unordered_set; using std::unordered_map; using AId = Identifier<class ATag>; using BId = Identifier<class BTag>; class IdentifierTests : public ::testing::Test { protected: // Configuration of test *case* variables (instead of per-test) is important. // The tests can evaluate in any order and run in the same memory space. // Those tests that depend on identifier *value* could easily become invalid // based on execution order. This guarantees a fixed set of identifiers // with known values. static void SetUpTestCase() { a1_ = AId::get_new_id(); // Should have the value 1. a2_ = AId::get_new_id(); // Should have the value 2. a3_ = AId::get_new_id(); // Should have the value 3. b_ = BId::get_new_id(); // Should have the value 1. } static AId a1_; static AId a2_; static AId a3_; static BId b_; }; AId IdentifierTests::a1_; AId IdentifierTests::a2_; AId IdentifierTests::a3_; BId IdentifierTests::b_; // Verifies the copy constructor. This implicitly tests the expected property // of the get_new_id() factory method and the get_value() method. TEST_F(IdentifierTests, Constructor) { EXPECT_EQ(a1_.get_value(), 1); EXPECT_EQ(a2_.get_value(), 2); EXPECT_EQ(a3_.get_value(), 3); AId temp(a2_); EXPECT_EQ(temp.get_value(), 2); AId bad; EXPECT_FALSE(bad.is_valid()); EXPECT_TRUE(a2_.is_valid()); } // Confirms that assignment behaves correctly. This also implicitly tests // equality and inequality. TEST_F(IdentifierTests, AssignmentAndComparison) { EXPECT_TRUE(a2_ != a3_); AId temp = a2_; EXPECT_TRUE(temp == a2_); temp = a3_; EXPECT_TRUE(temp == a3_); } // Check the specialized internal-use compare that can be used on an invalid // Identifier. TEST_F(IdentifierTests, InvalidOrSameComparison) { AId same_as_a1 = a1_; EXPECT_TRUE(same_as_a1.is_same_as_valid_id(a1_)); EXPECT_FALSE(a1_.is_same_as_valid_id(a2_)); AId invalid; EXPECT_FALSE(invalid.is_same_as_valid_id(a1_)); } // Confirms that ids are configured to serve as unique keys in // STL containers. TEST_F(IdentifierTests, ServeAsMapKey) { unordered_set<AId> ids; // This is a *different* id with the *same* value as a1. It should *not* // introduce a new value to the set. AId temp = a1_; EXPECT_EQ(ids.size(), 0); ids.insert(a1_); EXPECT_NE(ids.find(a1_), ids.end()); EXPECT_NE(ids.find(temp), ids.end()); EXPECT_EQ(ids.size(), 1); ids.insert(a2_); EXPECT_EQ(ids.size(), 2); ids.insert(temp); EXPECT_EQ(ids.size(), 2); EXPECT_EQ(ids.find(a3_), ids.end()); } // Checks the abseil-specific hash function. When a class does not provide an // abseil-specific hash function, abseil will fall back to invoking std::hash // on the class to obtain a size_t hash value and then feeding that size_t into // the abseil hasher. This leads to slow and bloated object code. We want to // prove that our abseil-specific hash function is being used; we can do that // by checking which hash value comes out of an absl container hasher. TEST_F(IdentifierTests, AbslHash) { // Compute the hash value used by an absl unordered container. // We'll want to demonstrate that this is the specialized hash value. absl::flat_hash_set<AId>::hasher absl_id_hasher; const size_t absl_hash = absl_id_hasher(a1_); // Compute the unspecialized hash value that would be seen in case absl // delegated to the std hasher. const size_t std_hash = std::hash<AId>{}(a1_); absl::flat_hash_set<size_t>::hasher absl_uint_hasher; const size_t absl_hash_via_std_hash = absl_uint_hasher(std_hash); // To demonstrate that the specialization worked, the specialized hash must // differ from the fallback hash. EXPECT_NE(absl_hash, absl_hash_via_std_hash); } // Confirms that SortedPair<FooId> can serve as a key in STL containers. // This shows that Identifier is not just hashable, but implicitly shows that // it is compatible with the Drake hash mechanism (because it assumes that the // SortedPair is compatible). TEST_F(IdentifierTests, SortedPairAsKey) { unordered_set<SortedPair<AId>> ids; EXPECT_EQ(ids.size(), 0u); ids.insert({a1_, a2_}); EXPECT_EQ(ids.size(), 1u); // An equivalent pair to what was inserted. SortedPair<AId> pair{a1_, a2_}; EXPECT_NE(ids.find(pair), ids.end()); } // Confirms that ids are configured to serve as values in STL containers. TEST_F(IdentifierTests, ServeAsMapValue) { unordered_map<BId, AId> ids; BId b1 = BId::get_new_id(); BId b2 = BId::get_new_id(); BId b3 = BId::get_new_id(); ids.emplace(b1, a1_); ids.emplace(b2, a2_); EXPECT_EQ(ids.find(b3), ids.end()); EXPECT_NE(ids.find(b2), ids.end()); EXPECT_NE(ids.find(b1), ids.end()); ids[b3] = a3_; EXPECT_NE(ids.find(b3), ids.end()); } // Confirms that ids can be put into a set. TEST_F(IdentifierTests, PutInSet) { set<AId> ids; AId a1 = AId::get_new_id(); AId a2 = AId::get_new_id(); EXPECT_EQ(ids.size(), 0u); ids.insert(a1); EXPECT_EQ(ids.size(), 1u); EXPECT_TRUE(ids.contains(a1)); ids.insert(a2); EXPECT_EQ(ids.size(), 2u); EXPECT_TRUE(ids.contains(a2)); ids.insert(a1); EXPECT_EQ(ids.size(), 2u); EXPECT_TRUE(ids.contains(a1)); } // Tests the streaming behavior. TEST_F(IdentifierTests, StreamOperator) { stringstream ss; ss << a2_; EXPECT_EQ(ss.str(), "2"); } // Tests the ability to convert the id to string via std::to_string. TEST_F(IdentifierTests, ToString) { using std::to_string; EXPECT_EQ(to_string(a2_), to_string(a2_.get_value())); } // These tests confirm that behavior that *shouldn't* be compilable isn't. // This code allows us to turn compile-time errors into run-time errors that // we can incorporate in a unit test. The macro simplifies the boilerplate. // This macro confirms binary operations are *valid* between two ids of // the same type, but invalid between an id and objects of *any* other type. // (Although the space of "all other types", is sparsely sampled). // // The use is: // BINARY_TEST( op, op_name ) // It produces the templated method: has_op_name<T, U>(), which returns true // if `t op u` is a valid operation for `T t` and `U u`. // // Examples of invocations: // op | op_name // ---------+------------- // == | equals // < | less_than // + | add #define BINARY_TEST(OP, OP_NAME) \ template <typename T, typename U, \ typename = decltype(std::declval<T>() OP std::declval<U>())> \ bool has_ ## OP_NAME ## _helper(int) { return true; } \ template <typename T, typename U> \ bool has_ ## OP_NAME ## _helper(...) { return false; } \ template <typename T, typename U> \ bool has_ ## OP_NAME() { return has_ ## OP_NAME ## _helper<T, U>(1); } \ TEST_F(IdentifierTests, OP_NAME ## OperatorAvailiblity) { \ EXPECT_FALSE((has_ ## OP_NAME<AId, BId>())); \ EXPECT_TRUE((has_ ## OP_NAME<AId, AId>())); \ EXPECT_FALSE((has_ ## OP_NAME<AId, int>())); \ EXPECT_FALSE((has_ ## OP_NAME<AId, size_t>())); \ EXPECT_FALSE((has_ ## OP_NAME<AId, int64_t>())); \ } BINARY_TEST(==, Equals) BINARY_TEST(!=, NotEquals) BINARY_TEST(=, Assignment) // This test should pass, as long as it compiles. If the Identifier class were // to change and allow conversion between identifiers (or between identifiers // and ints), this would fail to compile. TEST_F(IdentifierTests, Convertible) { static_assert(!std::is_convertible_v<AId, BId>, "Identifiers of different types should not be convertible."); static_assert(!std::is_convertible_v<AId, int>, "Identifiers should not be convertible to ints."); static_assert(!std::is_convertible_v<int, AId>, "Identifiers should not be convertible from ints"); } // Attempting to acquire the value is an error. TEST_F(IdentifierTests, InvalidGetValueCall) { if (kDrakeAssertIsDisarmed) { return; } AId invalid; DRAKE_EXPECT_THROWS_MESSAGE( invalid.get_value(), ".*is_valid.*failed.*"); } // Comparison of invalid ids is an error. TEST_F(IdentifierTests, InvalidEqualityCompare) { if (kDrakeAssertIsDisarmed) { return; } AId invalid; DRAKE_EXPECT_THROWS_MESSAGE(invalid == a1_, ".*is_valid.*failed.*"); } // Comparison of invalid ids is an error. TEST_F(IdentifierTests, InvalidInequalityCompare) { if (kDrakeAssertIsDisarmed) { return; } AId invalid; DRAKE_EXPECT_THROWS_MESSAGE(invalid != a1_, ".*is_valid.*failed.*"); } // Comparison of invalid ids is an error. TEST_F(IdentifierTests, BadInvalidOrSameComparison) { if (kDrakeAssertIsDisarmed) { return; } AId invalid; DRAKE_EXPECT_THROWS_MESSAGE(a1_.is_same_as_valid_id(invalid), ".*is_valid.*failed.*"); } // Hashing an invalid id is *not* an error. TEST_F(IdentifierTests, InvalidHash) { if (kDrakeAssertIsDisarmed) { return; } std::unordered_set<AId> ids; AId invalid; DRAKE_EXPECT_NO_THROW(ids.insert(invalid)); } // Streaming an invalid id is an error. TEST_F(IdentifierTests, InvalidStream) { if (kDrakeAssertIsDisarmed) { return; } AId invalid; std::stringstream ss; DRAKE_EXPECT_THROWS_MESSAGE(ss << invalid, ".*is_valid.*failed.*"); } } // namespace } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/drake_deprecated_test.cc
#include "drake/common/drake_deprecated.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" // This test verifies that the Drake build still succeeds if a deprecated class // or function is in use. namespace { class DRAKE_DEPRECATED("2038-01-19", "Use MyNewClass instead.") MyClass { }; class MyNewClass { }; DRAKE_DEPRECATED("2038-01-19", "Don't use this function; use NewMethod() instead.") int OldMethod(int arg) { return arg; } int NewMethod(int arg) { return arg; } GTEST_TEST(DrakeDeprecatedTest, ClassTest) { MyClass this_is_obsolete; MyNewClass this_is_not; (void)this_is_obsolete; // Avoid "unused" warning. (void)this_is_not; } GTEST_TEST(DrakeDeprecatedTest, FunctionTest) { int obsolete = OldMethod(1); int not_obsolete = NewMethod(1); (void)obsolete; (void)not_obsolete; } // Check that the "warn once" idiom compiles and doesn't crash at runtime. GTEST_TEST(DrakeDeprecatedTest, WarnOnceTest) { static const drake::internal::WarnDeprecated warn_once( "2038-01-19", "The method OldCalc() has been renamed to NewCalc()."); } // When the magic environment variable is set, warnings become errors. GTEST_TEST(DrakeDeprecatedTest, WarnThrowsTest) { constexpr char kEnvName[] = "_DRAKE_DEPRECATION_IS_ERROR"; ASSERT_EQ(::setenv(kEnvName, "1", 1), 0); DRAKE_EXPECT_THROWS_MESSAGE( drake::internal::WarnDeprecated("2038-01-19", "Hello"), "DRAKE DEPRECATED: Hello. The deprecated code will be removed from Drake " "on or after 2038-01-19."); ASSERT_EQ(::unsetenv(kEnvName), 0); } } // namespace
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/resource_tool_test_data.txt
Test data for drake/common/test/resource_tool_test.py.
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/test/value_test.cc
#include "drake/common/value.h" #include <functional> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <vector> #include <gtest/gtest.h> #include "drake/common/drake_copyable.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/systems/framework/test_utilities/my_vector.h" namespace drake { namespace test { // A type with no constructors. struct BareStruct { int data; }; // A copyable type with no default constructor. struct CopyableInt { DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(CopyableInt); explicit CopyableInt(int i) : data{i} {} CopyableInt(int c1, int c2) : data{c1 * c2} {} int data; }; // A clone-only type with no default constructor. struct CloneableInt { DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(CloneableInt); explicit CloneableInt(int i) : data{i} {} std::unique_ptr<CloneableInt> Clone() const { return std::make_unique<CloneableInt>(data); } const int data; }; // A move-or-clone (not copy) type with a default constructor. struct MoveOrCloneInt { MoveOrCloneInt() {} explicit MoveOrCloneInt(int i) : data{i} {} MoveOrCloneInt(MoveOrCloneInt&& other) { std::swap(data, other.data); } MoveOrCloneInt& operator=(MoveOrCloneInt&& other) { std::swap(data, other.data); return *this; } MoveOrCloneInt(const MoveOrCloneInt&) = delete; void operator=(const MoveOrCloneInt&) = delete; std::unique_ptr<MoveOrCloneInt> Clone() const { return std::make_unique<MoveOrCloneInt>(data); } int data{}; }; // Helper for EXPECT_EQ to unwrap the data field. template <typename T> bool operator==(int i, const T& value) { return i == value.data; } using systems::BasicVector; using systems::MyVector2d; // Boilerplate for tests that are identical across different types. Our // TYPED_TESTs will run using all of the below types as the TypeParam. template <typename TypeParam> class TypedValueTest : public ::testing::Test {}; typedef ::testing::Types< int, CopyableInt, CloneableInt, MoveOrCloneInt > Implementations; TYPED_TEST_SUITE(TypedValueTest, Implementations); // Value<T>() should work if and only if T is default-constructible. GTEST_TEST(ValueTest, DefaultConstructor) { const AbstractValue& value_int = Value<int>(); EXPECT_EQ(0, value_int.get_value<int>()); const AbstractValue& value_bare_struct = Value<BareStruct>(); EXPECT_EQ(0, value_bare_struct.get_value<BareStruct>().data); static_assert(!std::is_default_constructible_v<Value<CopyableInt>>, "Value<CopyableInt>() should not work."); static_assert(!std::is_default_constructible_v<Value<CloneableInt>>, "Value<CloneableInt>() should not work."); const AbstractValue& value_move_or_clone_int = Value<MoveOrCloneInt>(); EXPECT_EQ(0, value_move_or_clone_int.get_value<MoveOrCloneInt>().data); } // Value<T>(int) should work (possibly using forwarding). TYPED_TEST(TypedValueTest, ForwardingConstructor) { using T = TypeParam; const AbstractValue& abstract_value = Value<T>(22); EXPECT_EQ(22, abstract_value.get_value<T>()); } // A two-argument constructor should work using forwarding. (The forwarding // test case above is not quite enough, because the Value implementation treats // the first argument and rest of the arguments separately.) GTEST_TEST(ValueTest, ForwardingConstructorTwoArgs) { using T = CopyableInt; const AbstractValue& value = Value<T>(11, 2); EXPECT_EQ(22, value.get_value<T>()); } // Passing a single reference argument to the Value<T> constructor should use // the `(const T&)` constructor, not the forwarding constructor. TYPED_TEST(TypedValueTest, CopyConstructor) { using T = TypeParam; T param{0}; const T const_param{0}; const Value<T> xvalue(T{0}); // Called with `T&&`. const Value<T> lvalue(param); // Called with `T&`. const Value<T> crvalue(const_param); // Called with `const T&`. } // Ditto for BareStruct. GTEST_TEST(ValueTest, BareCopyConstructor) { using T = BareStruct; T param{}; const T const_param{}; const Value<T> xvalue(T{}); // Called with `T&&`. const Value<T> lvalue(param); // Called with `T&`. const Value<T> crvalue(const_param); // Called with `const T&`. } // Passing a unique_ptr<T> to Value<T> should take over the value. TYPED_TEST(TypedValueTest, UniquePtrConstructor) { using T = TypeParam; auto original = std::make_unique<T>(22); const Value<T> value{std::move(original)}; EXPECT_EQ(original.get(), nullptr); EXPECT_EQ(22, value.get_value()); } TYPED_TEST(TypedValueTest, Make) { using T = TypeParam; // TODO(jwnimmer-tri) We should be able to forward this too, and lose the // explicit construction of T{42}. auto abstract_value = AbstractValue::Make<T>(T{42}); EXPECT_EQ(42, abstract_value->template get_value<T>()); } GTEST_TEST(TypedValueTest, MakeDefault) { EXPECT_EQ(0, AbstractValue::Make<int>()->get_value<int>()); EXPECT_EQ("", AbstractValue::Make<std::string>()->get_value<std::string>()); } GTEST_TEST(ValueTest, NiceTypeName) { auto double_value = AbstractValue::Make<double>(3.); auto string_value = AbstractValue::Make<std::string>("hello"); auto base_value = std::make_unique<Value<BasicVector<double>>>(MyVector2d::Make(1., 2.)); EXPECT_EQ(double_value->GetNiceTypeName(), "double"); EXPECT_EQ(string_value->GetNiceTypeName(), "std::string"); // Must return the name of the most-derived type. EXPECT_EQ(base_value->GetNiceTypeName(), "drake::systems::MyVector<double,2>"); } GTEST_TEST(ValueTest, TypeInfo) { auto double_value = AbstractValue::Make<double>(3.); auto string_value = AbstractValue::Make<std::string>("hello"); auto base_value = std::make_unique<Value<BasicVector<double>>>(MyVector2d::Make(1., 2.)); EXPECT_EQ(double_value->static_type_info(), typeid(double)); EXPECT_EQ(double_value->type_info(), typeid(double)); EXPECT_EQ(string_value->static_type_info(), typeid(std::string)); EXPECT_EQ(string_value->type_info(), typeid(std::string)); // The static type is BasicVector, but the runtime type is MyVector2d. EXPECT_EQ(base_value->static_type_info(), typeid(BasicVector<double>)); EXPECT_EQ(base_value->type_info(), typeid(MyVector2d)); } // Check that maybe_get_value() returns nullptr for wrong-type requests, // and returns the correct value for right-type requests. GTEST_TEST(ValueTest, MaybeGetValue) { auto double_value = AbstractValue::Make<double>(3.); auto string_value = AbstractValue::Make<std::string>("hello"); EXPECT_EQ(double_value->maybe_get_value<std::string>(), nullptr); EXPECT_EQ(string_value->maybe_get_value<double>(), nullptr); const double* const double_pointer = double_value->maybe_get_value<double>(); const std::string* const string_pointer = string_value->maybe_get_value<std::string>(); ASSERT_NE(double_pointer, nullptr); ASSERT_NE(string_pointer, nullptr); EXPECT_EQ(*double_pointer, 3.); EXPECT_EQ(*string_pointer, "hello"); } // Check that maybe_get_mutable_value() returns nullptr for wrong-type // requests, and returns the correct value for right-type requests. GTEST_TEST(ValueTest, MaybeGetMutableValue) { auto double_value = AbstractValue::Make<double>(3.); auto string_value = AbstractValue::Make<std::string>("hello"); EXPECT_EQ(double_value->maybe_get_mutable_value<std::string>(), nullptr); EXPECT_EQ(string_value->maybe_get_mutable_value<double>(), nullptr); double* const double_pointer = double_value->maybe_get_mutable_value<double>(); std::string* const string_pointer = string_value->maybe_get_mutable_value<std::string>(); ASSERT_NE(double_pointer, nullptr); ASSERT_NE(string_pointer, nullptr); EXPECT_EQ(*double_pointer, 3.); EXPECT_EQ(*string_pointer, "hello"); *string_pointer = "goodbye"; EXPECT_EQ(string_value->get_value<std::string>(), "goodbye"); } TYPED_TEST(TypedValueTest, Access) { using T = TypeParam; Value<T> value(3); const AbstractValue& erased = value; EXPECT_EQ(3, erased.get_value<T>()); ASSERT_NE(erased.maybe_get_value<T>(), nullptr); EXPECT_EQ(3, *erased.maybe_get_value<T>()); } TYPED_TEST(TypedValueTest, Clone) { using T = TypeParam; Value<T> value(43); const AbstractValue& erased = value; std::unique_ptr<AbstractValue> cloned = erased.Clone(); EXPECT_EQ(43, cloned->get_value<T>()); } TYPED_TEST(TypedValueTest, Mutation) { using T = TypeParam; Value<T> value(3); value.set_value(T{4}); AbstractValue& erased = value; EXPECT_EQ(4, erased.get_value<T>()); erased.set_value<T>(T{5}); EXPECT_EQ(5, erased.get_value<T>()); erased.SetFrom(Value<T>(6)); EXPECT_EQ(6, erased.get_value<T>()); } TYPED_TEST(TypedValueTest, BadCast) { using T = TypeParam; Value<double> value(4); AbstractValue& erased = value; EXPECT_THROW(erased.get_value<T>(), std::logic_error); EXPECT_THROW(erased.get_mutable_value<T>(), std::logic_error); EXPECT_THROW(erased.set_value<T>(T{3}), std::logic_error); EXPECT_THROW(erased.SetFrom(Value<T>(2)), std::logic_error); } class PrintInterface { public: virtual ~PrintInterface() {} virtual std::string print() const = 0; protected: // Allow our subclasses to make these public. DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PrintInterface) PrintInterface() = default; }; // A trivial class that implements a trivial interface. // // N.B. Don't use this precise example in your own code! Normally we would // mark this class `final` in order to avoid the slicing problem during copy, // move, and assignment; however, the unit tests below are specifically // checking for weird corner cases, so we can't mark it as such here. class Point : public PrintInterface { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Point) Point(int x, int y) : x_(x), y_(y) {} virtual ~Point() {} int x() const { return x_; } int y() const { return y_; } void set_x(int x) { x_ = x; } void set_y(int y) { y_ = y; } std::string print() const override { std::ostringstream out; out << x_ << "," << y_; return out.str(); } private: int x_, y_; }; // Tests that classes can be erased in an AbstractValue. GTEST_TEST(ValueTest, ClassType) { Point point(1, 2); Value<Point> value(point); AbstractValue& erased = value; erased.get_mutable_value<Point>().set_x(-1); EXPECT_EQ(-1, erased.get_value<Point>().x()); EXPECT_EQ(2, erased.get_value<Point>().y()); erased.get_mutable_value<Point>().set_y(-2); EXPECT_EQ(-1, erased.get_value<Point>().x()); EXPECT_EQ(-2, erased.get_value<Point>().y()); } class SubclassOfPoint : public Point { public: SubclassOfPoint() : Point(-1, -2) {} }; // Tests that attempting to unerase an AbstractValue to a parent class of the // original class throws std::logic_error. GTEST_TEST(ValueTest, CannotUneraseToParentClass) { SubclassOfPoint point; Value<SubclassOfPoint> value(point); AbstractValue& erased = value; EXPECT_THROW(erased.get_mutable_value<Point>(), std::logic_error); } // A child class of Value<T> that requires T to satisfy PrintInterface, and // also satisfies PrintInterface itself. template <typename T> class PrintableValue : public Value<T>, public PrintInterface { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PrintableValue) explicit PrintableValue(const T& v) : Value<T>(v) {} std::unique_ptr<AbstractValue> Clone() const override { return std::make_unique<PrintableValue<T>>(this->get_value()); } std::string print() const override { const PrintInterface& print_interface = Value<T>::get_value(); return print_interface.print(); } }; // Tests that AbstractValues can be unerased to interfaces implemented by // subclasses of Value<T>. GTEST_TEST(ValueTest, SubclassOfValue) { Point point(3, 4); PrintableValue<Point> printable_value(point); AbstractValue* erased = &printable_value; PrintInterface* printable_erased = dynamic_cast<PrintInterface*>(erased); ASSERT_NE(nullptr, printable_erased); EXPECT_EQ("3,4", printable_erased->print()); } // Tests that even after being cloned, PrintableValue can be unerased to // PrintInterface. GTEST_TEST(ValueTest, SubclassOfValueSurvivesClone) { Point point(5, 6); PrintableValue<Point> printable_value(point); const AbstractValue& erased = printable_value; std::unique_ptr<AbstractValue> cloned = erased.Clone(); PrintInterface* printable_erased = dynamic_cast<PrintInterface*>(cloned.get()); ASSERT_NE(nullptr, printable_erased); EXPECT_EQ("5,6", printable_erased->print()); } // Tests an allowed type, and shows (by commented out examples) that pointers, // arrays, const, volatile, and reference types should be forbidden. GTEST_TEST(ValueTest, AllowedTypesMetaTest) { using T = int; Value<T>{}; // - cvref // Value<const T>{}; // Triggers static assertion; fails without assertion. // Value<volatile T>{}; // Trigger static assertion; works without assertion. // Value<const T&>{}; // Triggers static assertion; fails without assertion. // Value<T&&>{}; // Triggers static assertion; fails without assertion. // - array / pointer // Value<T*>{}; // Triggers static assertion; works without assertion. // Value<T[2]>{}; // Triggers static assertion; fails without assertion. } // Check that TypeHash is extracting exactly the right strings from // __PRETTY_FUNCTION__. template <typename T> void CheckHash(const std::string& name) { internal::FNV1aHasher hasher; hasher(name.data(), name.size()); EXPECT_EQ(internal::TypeHash<T>::value, size_t(hasher)) << " for name\n" << " Which is: " << name << "\n" << " for __PRETTY_FUNCTION__\n" << " Which is: " << __PRETTY_FUNCTION__; } namespace { struct AnonStruct {}; class AnonClass {}; enum class AnonEnum { kFoo, kBar }; // A class with a non-type template argument is not hashable. template <AnonEnum K> class UnadornedAnonEnumTemplate {}; // To enable hashing, the user can add a `using` statement like this. template <AnonEnum K> class NiceAnonEnumTemplate { public: using NonTypeTemplateParameter = std::integral_constant<AnonEnum, K>; }; } // namespace // Apple clang prior to version 13 needs a fixup for inline namespaces. #if defined(__APPLE__) && defined(__clang__) && __clang_major__ < 13 constexpr bool kAppleInlineNamespace = true; #else constexpr bool kAppleInlineNamespace = false; #endif #ifdef __clang__ constexpr bool kClang = true; #else constexpr bool kClang = false; #endif #if __GNUC__ >= 9 constexpr bool kGcc9 = true; #else constexpr bool kGcc9 = false; #endif GTEST_TEST(TypeHashTest, WellKnownValues) { // Simple primitives, structs, and classes. CheckHash<int>("int"); CheckHash<double>("double"); CheckHash<Point>("drake::test::Point"); // Anonymous structs and classes, and an enum class. CheckHash<AnonStruct>("drake::test::{anonymous}::AnonStruct"); CheckHash<AnonClass>("drake::test::{anonymous}::AnonClass"); CheckHash<AnonEnum>("drake::test::{anonymous}::AnonEnum"); // Templated containers without default template arguments. const std::string stdcc = kAppleInlineNamespace ? "std::__1" : "std"; CheckHash<std::shared_ptr<double>>(fmt::format( "{std}::shared_ptr<double>", fmt::arg("std", stdcc))); CheckHash<std::pair<int, double>>(fmt::format( "{std}::pair<int,double>", fmt::arg("std", stdcc))); // Templated classes *with* default template arguments. CheckHash<std::vector<double>>(fmt::format( "{std}::vector<double,{std}::allocator<double>>", fmt::arg("std", stdcc))); CheckHash<std::vector<BasicVector<double>>>(fmt::format( "{std}::vector<" "drake::systems::BasicVector<double>," "{std}::allocator<drake::systems::BasicVector<double>>" ">", fmt::arg("std", stdcc))); // Const-qualified types. CheckHash<std::shared_ptr<const double>>(fmt::format( "{std}::shared_ptr<const double>", fmt::arg("std", stdcc))); // Eigen classes. CheckHash<Eigen::VectorXd>( "Eigen::Matrix<double,int=-1,int=1,int=0,int=-1,int=1>"); CheckHash<Eigen::MatrixXd>( "Eigen::Matrix<double,int=-1,int=-1,int=0,int=-1,int=-1>"); CheckHash<Eigen::Vector3d>( "Eigen::Matrix<double,int=3,int=1,int=0,int=3,int=1>"); CheckHash<Eigen::Matrix3d>( "Eigen::Matrix<double,int=3,int=3,int=0,int=3,int=3>"); // Vectors of Eigens. CheckHash<std::vector<Eigen::VectorXd>>(fmt::format( "{std}::vector<{eigen},{std}::allocator<{eigen}>>", fmt::arg("std", stdcc), fmt::arg("eigen", "Eigen::Matrix<double,int=-1,int=1,int=0,int=-1,int=1>"))); // Everything together at once works. using BigType = std::vector<std::pair< const double, std::shared_ptr<Eigen::Matrix3d>>>; CheckHash<BigType>(fmt::format( "{std}::vector<" "{std}::pair<" "const double," "{std}::shared_ptr<{eigen}>>," "{std}::allocator<{std}::pair<" "const double," "{std}::shared_ptr<{eigen}>>>>", fmt::arg("std", stdcc), fmt::arg("eigen", "Eigen::Matrix<double,int=3,int=3,int=0,int=3,int=3>"))); // Templated on a value, but with the 'using NonTypeTemplateParameter' // decoration so that the hash works. const std::string kfoo = kClang || kGcc9 ? "drake::test::{anonymous}::AnonEnum::kFoo" : "0"; CheckHash<NiceAnonEnumTemplate<AnonEnum::kFoo>>( "drake::test::{anonymous}::NiceAnonEnumTemplate<" "drake::test::{anonymous}::AnonEnum=" + kfoo + ">"); } // Tests that a type mismatched is detected for a mismatched non-type template // parameter, even in Release builds. When the TypeHash fails (is zero), it's // important that AbstractValue fall back to using typeinfo comparison instead. GTEST_TEST(ValueTest, NonTypeTemplateParameter) { // We cannot compute hashes for non-type template parameters when the user // hasn't added a `using` statement to guide us. using T1 = UnadornedAnonEnumTemplate<AnonEnum::kFoo>; using T2 = UnadornedAnonEnumTemplate<AnonEnum::kBar>; ASSERT_EQ(internal::TypeHash<T1>::value, 0); ASSERT_EQ(internal::TypeHash<T2>::value, 0); // However, our getters and setters still catch type mismatches (by using the // std::typeinfo comparison). Value<T1> foo_value; Value<T2> bar_value; AbstractValue& foo = foo_value; DRAKE_EXPECT_NO_THROW(foo.get_value<T1>()); EXPECT_THROW(foo.get_value<T2>(), std::exception); EXPECT_THROW(foo.get_value<int>(), std::exception); EXPECT_THROW(foo.SetFrom(bar_value), std::exception); } // When a cast fails, the error message should report the actual types found // not to match. The request must match the static type of the Value container, // not the dynamic possibly-more-derived type of the contained value. When the // static and dynamic types differ, display both. See #15434. GTEST_TEST(ValueTest, TypesInBadCastMessage) { using MyVector1d = systems::MyVector<double, 1>; { // Make a base-typed value container with a more-derived value inside. auto value = std::make_unique<Value<BasicVector<double>>>(MyVector1d{}); AbstractValue& abstract = *value; // This request looks like it should work, but doesn't. The error message // should indicate why. DRAKE_EXPECT_THROWS_MESSAGE( abstract.get_value<MyVector1d>(), ".*request.*MyVector.*static.*BasicVector.*" "dynamic.*MyVector.*'\\)\\.$"); // This is the proper request type. DRAKE_EXPECT_NO_THROW(abstract.get_value<BasicVector<double>>()); } { // Make a value container that doesn't have the possibility of containing // derived types. Value<int> value; AbstractValue& abstract = value; // The error message in this case can be simpler. Test note: the regular // expression here specifically rejects parentheses near the end of the // line, to exclude the more elaborate error message matched in the case // above. DRAKE_EXPECT_THROWS_MESSAGE( abstract.get_value<double>(), ".*request.*double.*static.*int'\\.$"); } } } // namespace test } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/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_polynomial", srcs = ["benchmark_polynomial.cc"], add_test_rule = True, test_args = [ # When testing, skip over Args() that are >= 100. "--benchmark_filter=-/.00", ], test_timeout = "moderate", deps = [ "//common:add_text_logging_gflags", "//common/symbolic:monomial_util", "//common/symbolic:polynomial", "//tools/performance:fixture_common", "//tools/performance:gflags_main", "@fmt", ], ) drake_py_experiment_binary( name = "polynomial_experiment", googlebench_binary = ":benchmark_polynomial", ) add_lint_tests()
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/benchmarking/benchmark_polynomial.cc
#include <fmt/format.h> #include "drake/common/symbolic/monomial_util.h" #include "drake/common/symbolic/polynomial.h" #include "drake/tools/performance/fixture_common.h" namespace drake { namespace symbolic { namespace { void PolynomialEvaluatePartial(benchmark::State& state) { // NOLINT Eigen::Matrix<symbolic::Variable, 12, 1> x = MakeVectorContinuousVariable(12, "x"); const symbolic::Variables x_set(x); const auto monomial_basis = internal::ComputeMonomialBasis<Eigen::Dynamic>(x_set, 2); MatrixX<symbolic::Variable> S(monomial_basis.rows(), monomial_basis.rows()); VectorX<symbolic::Variable> S_upper((S.rows() + 1) * S.rows() / 2); int upper_count = 0; for (int i = 0; i < monomial_basis.rows(); ++i) { S(i, i) = symbolic::Variable(fmt::format("S({}, {})", i, i)); S_upper(upper_count++) = S(i, i); for (int j = i + 1; j < monomial_basis.rows(); ++j) { S(i, j) = symbolic::Variable(fmt::format("S({}, {})", i, j)); S_upper(upper_count++) = S(i, j); S(j, i) = S(i, j); } } symbolic::Polynomial p; for (int i = 0; i < S.rows(); ++i) { p.AddProduct(S(i, i), symbolic::pow(monomial_basis(i), 2)); for (int j = i + 1; j < S.cols(); ++j) { p.AddProduct(2 * S(i, j), monomial_basis(i) * monomial_basis(j)); } } symbolic::Environment env; // Test with S = 𝟏 (every entry of S is 1). During EvaluatePartial, we will // compute S(i, j) * monomial_basis(i) * monomial_basis(j). Since S(i, j) = 1, // each term will have non-zero coefficient (there won't be two terms // cancelling each other). env.insert(S_upper, Eigen::VectorXd::Ones(S_upper.rows())); for (auto _ : state) { const auto p_evaluate = p.EvaluatePartial(env); } } /* A benchmark for tr(Q @ X); Q's type is double, X's type is Variable. */ void MatrixInnerProduct(benchmark::State& state) { // NOLINT const int n = state.range(0); const bool sparse_Q = state.range(1); Eigen::MatrixXd Q(n, n); if (sparse_Q) { Q.setZero(); for (int i = 0; i < n; ++i) { Q(i, i) = std::sin(i); } } else { for (int i = 0; i < n; ++i) { Q(i, i) = std::sin(i); for (int j = i + 1; j < n; ++j) { Q(i, j) = std::cos(i + 2 * j); Q(j, i) = Q(i, j); } } } MatrixX<symbolic::Variable> X(n, n); for (int i = 0; i < n; ++i) { X(i, i) = symbolic::Variable(fmt::format("X({}, {})", i, i)); for (int j = i + 1; j < n; ++j) { X(i, j) = symbolic::Variable(fmt::format("X({}, {})", i, j)); X(j, i) = X(i, j); } } for (auto _ : state) { symbolic::Polynomial((Q * X).trace()); } } /* Creates a pair of matrices with arbitrary data, and in some cases with some matrix elements populated as variables instead of constants. The data types of the returned matrices are T1 and T2, respectively. @tparam T1 must be either double or Expression. @tparam T2 must be either Variable or Expression. */ template <typename T1, typename T2> std::pair<MatrixX<T1>, MatrixX<T2>> CreateGemmInput(int n) { MatrixX<T1> A(n, n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { int k = i + 2 * j; A(i, j) = std::cos(k); if constexpr (std::is_same_v<T1, double>) { // Nothing more to do. } else { static_assert(std::is_same_v<T1, Expression>); if ((k % 3) == 0) { A(i, j) *= Variable("X"); } } } } MatrixX<T2> B(n, n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if constexpr (std::is_same_v<T2, Variable>) { B(i, j) = Variable("X"); } else { static_assert(std::is_same_v<T2, Expression>); int k = i + 7 * j; B(i, j) = std::cos(k); if ((k % 3) == 0) { B(i, j) *= Variable("X"); } } } } return {std::move(A), std::move(B)}; } // Benchmarking four pairs of types is sufficient to cover all of the // interesting cases of symbolic matrix multiplication. // A benchmark for A @ B where A is T=double and B is T=Variable. void GemmDV(benchmark::State& state) { // NOLINT const int n = state.range(0); const auto& [A, B] = CreateGemmInput<double, Variable>(n); for (auto _ : state) { (A * B).eval(); } } // A benchmark for A @ B where A is T=double and B is T=Expression. void GemmDE(benchmark::State& state) { // NOLINT const int n = state.range(0); const auto& [A, B] = CreateGemmInput<double, Expression>(n); for (auto _ : state) { (A * B).eval(); } } // A benchmark for A @ B where A is T=Variable and B is T=Expression. void GemmVE(benchmark::State& state) { // NOLINT const int n = state.range(0); const auto& [B, A] = CreateGemmInput<Expression, Variable>(n); for (auto _ : state) { (A * B).eval(); } } // A benchmark for A @ B where both matrix types are Expression. void GemmEE(benchmark::State& state) { // NOLINT const int n = state.range(0); const auto& [A, B] = CreateGemmInput<Expression, Expression>(n); for (auto _ : state) { (A * B).eval(); } } BENCHMARK(PolynomialEvaluatePartial)->Unit(benchmark::kMicrosecond); BENCHMARK(MatrixInnerProduct) ->ArgsProduct({{10, 50, 100, 200}, {false, true}}) ->Unit(benchmark::kSecond); BENCHMARK(GemmDV) ->ArgsProduct({{10, 50, 100, 200}}) ->Unit(benchmark::kMillisecond); BENCHMARK(GemmDE) ->ArgsProduct({{10, 50, 100, 200}}) ->Unit(benchmark::kMillisecond); BENCHMARK(GemmVE) ->ArgsProduct({{10, 50, 100, 200}}) ->Unit(benchmark::kMillisecond); BENCHMARK(GemmEE) ->ArgsProduct({{10, 50, 100, 200}}) ->Unit(benchmark::kMillisecond); } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/no_clarabel.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/clarabel_solver.h" /* clang-format on */ #include <stdexcept> namespace drake { namespace solvers { bool ClarabelSolver::is_available() { return false; } void ClarabelSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const { throw std::runtime_error( "The Clarabel bindings were not compiled. You'll need to use a " "different solver."); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/sdpa_free_format.cc
#include "drake/solvers/sdpa_free_format.h" #include <algorithm> #include <fstream> #include <initializer_list> #include <iomanip> #include <limits> #include <stdexcept> #include <unordered_map> #include <vector> #include <Eigen/Core> #include <Eigen/Sparse> #include <Eigen/SparseQR> #include "drake/common/text_logging.h" namespace drake { namespace solvers { namespace internal { const double kInf = std::numeric_limits<double>::infinity(); SdpaFreeFormat::~SdpaFreeFormat() {} void SdpaFreeFormat::DeclareXforPositiveSemidefiniteConstraints( const MathematicalProgram& prog, std::unordered_map<symbolic::Variable::Id, std::vector<EntryInX>>* entries_in_X_for_same_decision_variable) { int num_blocks = 0; for (const auto& binding : prog.positive_semidefinite_constraints()) { // The bound variables are the column-stacked vector of the psd matrix. We // only record the upper-diagonal entries in the psd matrix. int psd_matrix_variable_index = 0; const int matrix_rows = binding.evaluator()->matrix_rows(); X_blocks_.emplace_back(BlockType::kMatrix, matrix_rows); for (int j = 0; j < matrix_rows; ++j) { for (int i = 0; i <= j; ++i) { const symbolic::Variable& psd_ij_var = binding.variables()(psd_matrix_variable_index++); const int psd_ij_var_index = prog.FindDecisionVariableIndex(psd_ij_var); const bool has_var_registered = !(std::holds_alternative<std::nullptr_t>( prog_var_in_sdpa_[psd_ij_var_index])); const EntryInX psd_ij_entry_in_X(num_blocks, i, j, num_X_rows_); if (!has_var_registered) { // This variable has not been registered into X. Now register this // variable, by adding it to prog_var_in_sdpa_ prog_var_in_sdpa_[psd_ij_var_index].emplace<DecisionVariableInSdpaX>( Sign::kPositive, 0, psd_ij_entry_in_X); } else { // This variable has been registered into X. We need to add the // equality constraint between all X entries corresponding to this // variable. // First find if there exists equality constraint on this variable // already. const auto it2 = entries_in_X_for_same_decision_variable->find( psd_ij_var.get_id()); if (it2 == entries_in_X_for_same_decision_variable->end()) { // There does not exist equality constraint on this variable yet. entries_in_X_for_same_decision_variable->emplace_hint( it2, psd_ij_var.get_id(), std::vector<EntryInX>({std::get<DecisionVariableInSdpaX>( prog_var_in_sdpa_[psd_ij_var_index]) .entry_in_X, psd_ij_entry_in_X})); } else { // We found equality constraint on this variable, append the vector // containing all X entries that correspond to this variable. it2->second.push_back(psd_ij_entry_in_X); } } } psd_matrix_variable_index += matrix_rows - j - 1; } num_blocks++; num_X_rows_ += matrix_rows; } } void AddTermToTriplets(const EntryInX& entry_in_X, double coeff, std::vector<Eigen::Triplet<double>>* triplets) { if (entry_in_X.row_index_in_block == entry_in_X.column_index_in_block) { triplets->emplace_back( entry_in_X.X_start_row + entry_in_X.row_index_in_block, entry_in_X.X_start_row + entry_in_X.column_index_in_block, coeff); } else { triplets->emplace_back( entry_in_X.X_start_row + entry_in_X.row_index_in_block, entry_in_X.X_start_row + entry_in_X.column_index_in_block, coeff / 2); triplets->emplace_back( entry_in_X.X_start_row + entry_in_X.column_index_in_block, entry_in_X.X_start_row + entry_in_X.row_index_in_block, coeff / 2); } } void SdpaFreeFormat::AddLinearEqualityConstraint( const std::vector<double>& coeff_prog_vars, const std::vector<int>& prog_vars_indices, const std::vector<double>& coeff_X_entries, const std::vector<EntryInX>& X_entries, const std::vector<double>& coeff_free_vars, const std::vector<FreeVariableIndex>& free_vars_indices, double rhs) { DRAKE_ASSERT(coeff_prog_vars.size() == prog_vars_indices.size()); DRAKE_ASSERT(coeff_X_entries.size() == X_entries.size()); DRAKE_ASSERT(coeff_free_vars.size() == free_vars_indices.size()); const int constraint_index = static_cast<int>(A_triplets_.size()); std::vector<Eigen::Triplet<double>> Ai_triplets; // If the entries are off-diagonal entries of X, then it needs two // coefficients in Ai, for both the upper and lower diagonal part. Ai_triplets.reserve( static_cast<int>(coeff_prog_vars.size() + coeff_X_entries.size()) * 2); g_.conservativeResize(g_.rows() + 1); g_(constraint_index) = rhs; for (int i = 0; i < static_cast<int>(coeff_prog_vars.size()); ++i) { if (coeff_prog_vars[i] != 0) { const int prog_var_index = prog_vars_indices[i]; if (std::holds_alternative<DecisionVariableInSdpaX>( prog_var_in_sdpa_[prog_var_index])) { // This variable is an entry in X. const auto& decision_var_in_X = std::get<DecisionVariableInSdpaX>( prog_var_in_sdpa_[prog_var_index]); g_(constraint_index) -= coeff_prog_vars[i] * decision_var_in_X.offset; const double coeff = decision_var_in_X.coeff_sign == Sign::kPositive ? coeff_prog_vars[i] : -coeff_prog_vars[i]; AddTermToTriplets(decision_var_in_X.entry_in_X, coeff, &Ai_triplets); } else if (std::holds_alternative<double>( prog_var_in_sdpa_[prog_var_index])) { // This variable has a constant value. const double var_value = std::get<double>(prog_var_in_sdpa_[prog_var_index]); g_(constraint_index) -= coeff_prog_vars[i] * var_value; } else if (std::holds_alternative<FreeVariableIndex>( prog_var_in_sdpa_[prog_var_index])) { // This variable is a free variable (no lower nor upper bound). B_triplets_.emplace_back( constraint_index, std::get<FreeVariableIndex>(prog_var_in_sdpa_[prog_var_index]), coeff_prog_vars[i]); } else { throw std::runtime_error( "SdpaFreeFormat::AddLinearEqualityConstraint() : this decision " "variable is not an entry in X or s, and is not a constant."); } } } // Adds coeff_X_entries * X_entries. for (int i = 0; i < static_cast<int>(coeff_X_entries.size()); ++i) { if (coeff_X_entries[i] != 0) { AddTermToTriplets(X_entries[i], coeff_X_entries[i], &Ai_triplets); } } A_triplets_.push_back(Ai_triplets); // Adds coeff_free_vars * free_vars. if (!coeff_X_entries.empty()) { for (int i = 0; i < static_cast<int>(coeff_free_vars.size()); ++i) { B_triplets_.emplace_back(constraint_index, free_vars_indices[i], coeff_free_vars[i]); } } } void SdpaFreeFormat::AddEqualityConstraintOnXEntriesForSameDecisionVariable( const std::unordered_map<symbolic::Variable::Id, std::vector<EntryInX>>& entries_in_X_for_same_decision_variable) { for (const auto& item : entries_in_X_for_same_decision_variable) { const auto& Xentries = item.second; DRAKE_ASSERT(Xentries.size() >= 2); const std::vector<double> a{{1, -1}}; for (int i = 1; i < static_cast<int>(Xentries.size()); ++i) { AddLinearEqualityConstraint({} /* coefficients for prog_vars */, {} /* empty prog_vars */, a, {Xentries[0], Xentries[i]}, {}, {}, 0.0); } } } void SdpaFreeFormat::RegisterSingleMathematicalProgramDecisionVariable( double lower_bound, double upper_bound, int variable_index, int block_index, int* new_X_var_count) { // First check if this variable has either finite lower or upper bound. If // not, then the variable is a free variable in SDPA. if (std::isinf(lower_bound) && std::isinf(upper_bound)) { // This is a free variable. prog_var_in_sdpa_[variable_index].emplace<FreeVariableIndex>( num_free_variables_); num_free_variables_++; } else { if (!std::isinf(lower_bound) && std::isinf(upper_bound)) { // lower <= x. prog_var_in_sdpa_[variable_index].emplace<DecisionVariableInSdpaX>( Sign::kPositive, lower_bound, block_index, *new_X_var_count, *new_X_var_count, num_X_rows_); (*new_X_var_count)++; } else if (std::isinf(lower_bound) && !std::isinf(upper_bound)) { // x <= upper. prog_var_in_sdpa_[variable_index].emplace<DecisionVariableInSdpaX>( Sign::kNegative, upper_bound, block_index, *new_X_var_count, *new_X_var_count, num_X_rows_); (*new_X_var_count)++; } else if (lower_bound == upper_bound) { // x == bound. prog_var_in_sdpa_[variable_index].emplace<double>(lower_bound); } else { // lower <= x <= upper. // x will be replaced with y + lower, where y is an entry in X. prog_var_in_sdpa_[variable_index].emplace<DecisionVariableInSdpaX>( Sign::kPositive, lower_bound, block_index, *new_X_var_count, *new_X_var_count, num_X_rows_); // Add another slack variables z, with the constraint x + z = upper. AddLinearEqualityConstraint({1}, {variable_index}, {1.0}, {EntryInX(block_index, *new_X_var_count + 1, *new_X_var_count + 1, num_X_rows_)}, {}, {}, upper_bound); (*new_X_var_count) += 2; } } } void SdpaFreeFormat::AddBoundsOnRegisteredDecisionVariable( double lower_bound, double upper_bound, int variable_index, int block_index, int* new_X_var_count) { // This variable has been registered as a variable in SDPA. It should have // been registered as an entry in X. if (std::holds_alternative<DecisionVariableInSdpaX>( prog_var_in_sdpa_[variable_index])) { if (std::isinf(lower_bound) && std::isinf(upper_bound)) { // no finite bounds. return; } else if (!std::isinf(lower_bound) && std::isinf(upper_bound)) { // lower <= x. // Adds a slack variable y as a diagonal entry in X, with the // constraint x - y = lower. AddLinearEqualityConstraint({1}, {variable_index}, {-1.0}, {EntryInX(block_index, *new_X_var_count, *new_X_var_count, num_X_rows_)}, {}, {}, lower_bound); (*new_X_var_count)++; } else if (std::isinf(lower_bound) && !std::isinf(upper_bound)) { // x <= upper. // Adds a slack variable y as a diagonal entry in X, with the // constraint x + y = upper. AddLinearEqualityConstraint({1.0}, {variable_index}, {1.0}, {EntryInX(block_index, *new_X_var_count, *new_X_var_count, num_X_rows_)}, {}, {}, upper_bound); (*new_X_var_count)++; } else if (lower_bound == upper_bound) { // Add the constraint x == bound. AddLinearEqualityConstraint({1.0}, {variable_index}, {}, {}, {}, {}, lower_bound); } else { // lower <= x <= upper. // Adds two slack variables y1, y2 in X, with the linear equality // constraint x - y1 = lower and x + y2 <= upper. AddLinearEqualityConstraint({1.0}, {variable_index}, {-1.0}, {EntryInX(block_index, *new_X_var_count, *new_X_var_count, num_X_rows_)}, {}, {}, lower_bound); AddLinearEqualityConstraint( {1.0}, {variable_index}, {1.0}, {EntryInX(block_index, (*new_X_var_count) + 1, (*new_X_var_count) + 1, num_X_rows_)}, {}, {}, upper_bound); (*new_X_var_count) += 2; } } else { throw std::runtime_error( "SdpaFreeFormat::AddBoundsOnRegisteredDecisionVariable(): " "the registered variable should be an entry in X."); } } void SdpaFreeFormat::RegisterMathematicalProgramDecisionVariables( const MathematicalProgram& prog) { // Go through all the decision variables in @p prog. If the decision variable // has not been registered in SDPA, then register it now. Refer to @ref // prog_var_in_sdpa_ for different types. Eigen::VectorXd lower_bound = Eigen::VectorXd::Constant(prog.num_vars(), -kInf); Eigen::VectorXd upper_bound = Eigen::VectorXd::Constant(prog.num_vars(), kInf); for (const auto& bounding_box : prog.bounding_box_constraints()) { for (int i = 0; i < bounding_box.variables().rows(); ++i) { const int variable_index = prog.FindDecisionVariableIndex(bounding_box.variables()(i)); lower_bound(variable_index) = std::max(lower_bound(variable_index), bounding_box.evaluator()->lower_bound()(i)); upper_bound(variable_index) = std::min(upper_bound(variable_index), bounding_box.evaluator()->upper_bound()(i)); } } // Now go through each of the decision variables in prog. const int block_index = static_cast<int>(X_blocks_.size()); int new_X_var_count = 0; for (int i = 0; i < prog.num_vars(); ++i) { // The variable might have been registered when we go through the positive // semidefinite constraint. bool has_var_registered = !std::holds_alternative<std::nullptr_t>(prog_var_in_sdpa_[i]); // First check if this variable has either finite lower or upper bound. If // not, then the variable is a free variable in SDPA. if (!has_var_registered) { RegisterSingleMathematicalProgramDecisionVariable( lower_bound(i), upper_bound(i), i, block_index, &new_X_var_count); } else { AddBoundsOnRegisteredDecisionVariable(lower_bound(i), upper_bound(i), i, block_index, &new_X_var_count); } } if (new_X_var_count > 0) { X_blocks_.emplace_back(BlockType::kDiagonal, new_X_var_count); num_X_rows_ += new_X_var_count; } } void SdpaFreeFormat::AddLinearCostsFromProgram( const MathematicalProgram& prog) { for (const auto& linear_cost : prog.linear_costs()) { for (int i = 0; i < linear_cost.variables().rows(); ++i) { // The negation sign is because in SDPA format, the objective is to // maximize the cost, while in MathematicalProgram, the objective is to // minimize the cost. double coeff = -linear_cost.evaluator()->a()(i); if (coeff != 0) { // Only adds the cost if the cost coefficient is non-zero. const int var_index = prog.FindDecisionVariableIndex(linear_cost.variables()(i)); if (std::holds_alternative<DecisionVariableInSdpaX>( prog_var_in_sdpa_[var_index])) { const auto& decision_var_in_X = std::get<DecisionVariableInSdpaX>(prog_var_in_sdpa_[var_index]); coeff = decision_var_in_X.coeff_sign == Sign::kPositive ? coeff : -coeff; constant_min_cost_term_ += linear_cost.evaluator()->a()(i) * decision_var_in_X.offset; AddTermToTriplets(decision_var_in_X.entry_in_X, coeff, &C_triplets_); } else if (std::holds_alternative<double>( prog_var_in_sdpa_[var_index])) { const double val = std::get<double>(prog_var_in_sdpa_[var_index]); constant_min_cost_term_ += linear_cost.evaluator()->a()(i) * val; } else if (std::holds_alternative<FreeVariableIndex>( prog_var_in_sdpa_[var_index])) { const FreeVariableIndex& s_index = std::get<FreeVariableIndex>(prog_var_in_sdpa_[var_index]); d_triplets_.emplace_back(s_index, 0, coeff); } else { throw std::runtime_error( "SdpaFreeFormat::AddLinearCostFromProgram() only supports " "DecisionVariableInSdpaX, double or FreeVariableIndex."); } } } constant_min_cost_term_ += linear_cost.evaluator()->b(); } } template <typename Constraint> void SdpaFreeFormat::AddLinearConstraintsHelper( const MathematicalProgram& prog, const Binding<Constraint>& linear_constraint, bool is_equality_constraint, int* linear_constraint_slack_entry_in_X_count) { const std::vector<int> var_indices = prog.FindDecisionVariableIndices(linear_constraint.variables()); // Go through each row of the constraint. for (int i = 0; i < linear_constraint.evaluator()->num_constraints(); ++i) { const bool does_lower_equal_upper_in_this_row = is_equality_constraint || linear_constraint.evaluator()->lower_bound()(i) == linear_constraint.evaluator()->upper_bound()(i); std::vector<double> a, b; // If this row's lower and upper bound are the same, then we only need to // append one row to SDPA format, namely tr(Ai * X) + bi' * s = rhs, // Otherwise, we need to append two rows to SDPA format // tr(Ai_lower * X_lower) + bi' * s = lower_bound // tr(Ai_upper * X_upper) + bi' * s = upper_bound // and append two diagonal entries into X as slack variables. a.reserve(var_indices.size()); b.reserve(1); std::vector<int> decision_var_indices_in_X; decision_var_indices_in_X.reserve(var_indices.size()); std::vector<EntryInX> X_entries; X_entries.reserve(1); std::vector<int> s_indices; for (int j = 0; j < linear_constraint.variables().rows(); ++j) { // TODO(Alexandre.Amice) fix this to only access the sparse version of A. if (linear_constraint.evaluator()->GetDenseA()(i, j) != 0) { a.push_back(linear_constraint.evaluator()->GetDenseA()(i, j)); decision_var_indices_in_X.push_back(var_indices[j]); } } // CSDP solver would abort if we pass in an empty constraint (e.g, 0 == 0 or // 1 <= 2). So if this row of constraint is empty (all coefficients are // 0), then we should either ignore the constraint if it is trivially true // (like 0 == 0) or throw an error if it is trivially false (like 1 >= 2). if (a.size() == 0) { if (linear_constraint.evaluator()->lower_bound()(i) <= 0 && linear_constraint.evaluator()->upper_bound()(i) >= 0) { continue; } else { throw std::runtime_error(fmt::format( "SdpaFreeFormat: the problem is infeasible as it contains " "trivially infeasible constraint {} <= 0 <= {}", linear_constraint.evaluator()->lower_bound()(i), linear_constraint.evaluator()->upper_bound()(i))); } } if (does_lower_equal_upper_in_this_row) { // Add the equality constraint. AddLinearEqualityConstraint( a, decision_var_indices_in_X, {}, {}, {}, {}, linear_constraint.evaluator()->lower_bound()(i)); } else { // First add the constraint and slack variable for the lower bound. if (!std::isinf(linear_constraint.evaluator()->lower_bound()(i))) { AddLinearEqualityConstraint( a, decision_var_indices_in_X, {-1}, {EntryInX(static_cast<int>(X_blocks_.size()), *linear_constraint_slack_entry_in_X_count, *linear_constraint_slack_entry_in_X_count, num_X_rows_)}, {}, {}, linear_constraint.evaluator()->lower_bound()(i)); (*linear_constraint_slack_entry_in_X_count)++; } // Now add the constraint and slack variable for the upper bound. if (!std::isinf(linear_constraint.evaluator()->upper_bound()(i))) { AddLinearEqualityConstraint( a, decision_var_indices_in_X, {1}, {EntryInX(static_cast<int>(X_blocks_.size()), *linear_constraint_slack_entry_in_X_count, *linear_constraint_slack_entry_in_X_count, num_X_rows_)}, {}, {}, linear_constraint.evaluator()->upper_bound()(i)); (*linear_constraint_slack_entry_in_X_count)++; } } } } void SdpaFreeFormat::AddLinearConstraintsFromProgram( const MathematicalProgram& prog) { int linear_constraint_slack_entry_in_X_count = 0; for (const auto& linear_eq_constraint : prog.linear_equality_constraints()) { AddLinearConstraintsHelper(prog, linear_eq_constraint, true, &linear_constraint_slack_entry_in_X_count); } for (const auto& linear_constraint : prog.linear_constraints()) { AddLinearConstraintsHelper(prog, linear_constraint, false, &linear_constraint_slack_entry_in_X_count); } if (linear_constraint_slack_entry_in_X_count > 0) { num_X_rows_ += linear_constraint_slack_entry_in_X_count; X_blocks_.emplace_back(BlockType::kDiagonal, linear_constraint_slack_entry_in_X_count); } } void SdpaFreeFormat::AddLinearMatrixInequalityConstraints( const MathematicalProgram& prog) { for (const auto& lmi_constraint : prog.linear_matrix_inequality_constraints()) { const std::vector<int> var_indices = prog.FindDecisionVariableIndices(lmi_constraint.variables()); // Add the constraint that F1 * x1 + ... + Fn * xn - X_slack = -F0 and // X_slack is psd. const std::vector<Eigen::MatrixXd>& F = lmi_constraint.evaluator()->F(); for (int j = 0; j < lmi_constraint.evaluator()->matrix_rows(); ++j) { for (int i = 0; i <= j; ++i) { std::vector<double> a; a.reserve(static_cast<int>(F.size()) - 1); for (int k = 1; k < static_cast<int>(F.size()); ++k) { a.push_back(F[k](i, j)); } AddLinearEqualityConstraint( a, var_indices, {-1}, {EntryInX(static_cast<int>(X_blocks_.size()), i, j, num_X_rows_)}, {}, {}, -F[0](i, j)); } } X_blocks_.emplace_back(BlockType::kMatrix, lmi_constraint.evaluator()->matrix_rows()); num_X_rows_ += lmi_constraint.evaluator()->matrix_rows(); } } // A Lorentz cone constraint z₀ ≥ sqrt(z₁² + ... + zₙ²), where z = A*x+b, can // be rewritten as a positive semidefinite constraint // ⎡ z₀ z₁ ... zₙ ⎤ // ⎢ z₁ z₀ 0 0 ⎥ is positive semidefinite. // ⎢ .... ⎥ // ⎣ zₙ 0 0 z₀ ⎦ void SdpaFreeFormat::AddLorentzConeConstraints( const MathematicalProgram& prog) { for (const auto& lorentz_cone_constraint : prog.lorentz_cone_constraints()) { const int num_block_rows = lorentz_cone_constraint.evaluator()->A().rows(); const int num_decision_vars = lorentz_cone_constraint.variables().rows(); const std::vector<int> prog_vars_indices = prog.FindDecisionVariableIndices(lorentz_cone_constraint.variables()); // Add the linear constraint that all the diagonal terms of the new block // matrix equals to z0. std::vector<double> a; // The last entry in X_entries would be the diagonal term in the new block. a.reserve(num_decision_vars); // We need to impose the linear equality constraint // lorentz_cone_constraint.evaluator()->A().row(0) * // lorentz_cone_constraint.variables() - new_block(i, i) = // -lorentz_cone_constraint.evaluator()->b()(0). // So we first fill in a, b, X_entries and s_indices with the term from // lorentz_cone_constraint.evaluator()->A().row(0) * // lorentz_cone_constraint.variables() for (int i = 0; i < num_decision_vars; ++i) { const double coeff = lorentz_cone_constraint.evaluator()->A_dense()(0, i); a.push_back(coeff); } // For each diagonal entry in the new block matrix, we need to add // -new_block(i, i) to the left-hand side of the equality constraint. for (int i = 0; i < num_block_rows; ++i) { AddLinearEqualityConstraint( a, prog_vars_indices, {-1.0}, {EntryInX(static_cast<int>(X_blocks_.size()), i, i, num_X_rows_)}, {}, {}, -lorentz_cone_constraint.evaluator()->b()(0)); } // Now we add the linear equality constraint arising from the first row of // the new block lorentz_cone_constraint.evaluator()->A().row(i) * // lorentz_cone_constraint.variables() + // lorentz_cone_constraint.evaluator()->b()(i) = new_block(0, i) for i for (int i = 1; i < num_block_rows; ++i) { a.clear(); a.reserve(num_decision_vars); for (int j = 0; j < num_decision_vars; ++j) { const double coeff = lorentz_cone_constraint.evaluator()->A_dense()(i, j); a.push_back(coeff); } // Add the term -new_block(0, i) AddLinearEqualityConstraint( a, prog_vars_indices, {-1}, {EntryInX(static_cast<int>(X_blocks_.size()), 0, i, num_X_rows_)}, {}, {}, -lorentz_cone_constraint.evaluator()->b()(i)); } // Now add the constraint that many entries in this new block is 0. for (int i = 1; i < num_block_rows; ++i) { for (int j = 1; j < i; ++j) { AddLinearEqualityConstraint( {}, {}, {1.0}, {EntryInX(static_cast<int>(X_blocks_.size()), i, j, num_X_rows_)}, {}, {}, 0); } } X_blocks_.emplace_back(BlockType::kMatrix, num_block_rows); num_X_rows_ += num_block_rows; } } // A vector z in rotated Lorentz cone (i.e.,z₀≥0, z₁≥0, z₀z₁≥ sqrt(z₂² + ... // zₙ²), where z = Ax+b ) is equivalent to the following positive semidefinite // constraint // ⎡ z₀ z₂ z₃ ... zₙ ⎤ // ⎢ z₂ z₁ 0 ... 0 ⎥ // ⎢ z₃ 0 z₁ 0 ... 0 ⎥ is positive semidefinite. // ⎢ z₄ 0 0 z₁ 0 0 ⎥ // ⎢ ... ⎥ // ⎢ zₙ₋₁ ... z₁ 0 ⎥ // ⎣ zₙ 0 ... 0 z₁⎦ void SdpaFreeFormat::AddRotatedLorentzConeConstraints( const MathematicalProgram& prog) { for (const auto& rotated_lorentz_constraint : prog.rotated_lorentz_cone_constraints()) { const int z_size = rotated_lorentz_constraint.evaluator()->A().rows(); // The number of rows in the new block matrix const int num_block_rows = z_size - 1; const int num_decision_vars = rotated_lorentz_constraint.variables().rows(); const std::vector<int> prog_vars_indices = prog.FindDecisionVariableIndices( rotated_lorentz_constraint.variables()); // First add the equality constraint arising from the first row of the PSD // constraint. rotated_lorentz_constraint.evaluator()->A().row(j) * // rotated_lorentz_constraint.variables() + // rotated_lorentz_constraint.evaluator()->b()(j) = new_X(0, i); // where j = 0 if i = 0, and j = i + 1 otherwise. for (int i = 0; i < num_block_rows; ++i) { std::vector<double> a; a.reserve(num_decision_vars); const int j = i == 0 ? 0 : i + 1; for (int k = 0; k < num_decision_vars; ++k) { a.push_back(rotated_lorentz_constraint.evaluator()->A_dense()(j, k)); } // Add the term -new_X(0, i) AddLinearEqualityConstraint( a, prog_vars_indices, {-1}, {EntryInX(static_cast<int>(X_blocks_.size()), 0, i, num_X_rows_)}, {}, {}, -rotated_lorentz_constraint.evaluator()->b()(j)); } // Add the linear constraint // rotated_lorentz_constraint.evaluator()->A().row(1) * // rotated_lorentz_constraint.variables() + // rotated_lorentz_constraint.evaluator()->b()(1) = new_X(i, i) for i >= 1 std::vector<double> a; a.reserve(num_decision_vars); for (int i = 0; i < num_decision_vars; ++i) { a.push_back(rotated_lorentz_constraint.evaluator()->A_dense()(1, i)); } for (int i = 1; i < num_block_rows; ++i) { // Add the term -new_block(i, i). AddLinearEqualityConstraint( a, prog_vars_indices, {-1}, {EntryInX(static_cast<int>(X_blocks_.size()), i, i, num_X_rows_)}, {}, {}, -rotated_lorentz_constraint.evaluator()->b()(1)); } // Now add the constraint that new_X(i, j) = 0 for j >= 2 and 1 <= i < j for (int j = 2; j < num_block_rows; ++j) { for (int i = 1; i < j; ++i) { AddLinearEqualityConstraint( {}, {}, {1}, {EntryInX(static_cast<int>(X_blocks_.size()), i, j, num_X_rows_)}, {}, {}, 0); } } X_blocks_.emplace_back(BlockType::kMatrix, num_block_rows); num_X_rows_ += num_block_rows; } } void SdpaFreeFormat::Finalize() { A_.reserve(A_triplets_.size()); for (int i = 0; i < static_cast<int>(A_triplets_.size()); ++i) { A_.emplace_back(num_X_rows_, num_X_rows_); A_.back().setFromTriplets(A_triplets_[i].begin(), A_triplets_[i].end()); } B_.resize(static_cast<int>(A_triplets_.size()), num_free_variables_); B_.setFromTriplets(B_triplets_.begin(), B_triplets_.end()); C_.resize(num_X_rows_, num_X_rows_); C_.setFromTriplets(C_triplets_.begin(), C_triplets_.end()); d_.resize(num_free_variables_, 1); d_.setFromTriplets(d_triplets_.begin(), d_triplets_.end()); } SdpaFreeFormat::SdpaFreeFormat(const MathematicalProgram& prog) { ProgramAttributes solver_capabilities(std::initializer_list<ProgramAttribute>{ ProgramAttribute::kLinearCost, ProgramAttribute::kLinearConstraint, ProgramAttribute::kLinearEqualityConstraint, ProgramAttribute::kLorentzConeConstraint, ProgramAttribute::kRotatedLorentzConeConstraint, ProgramAttribute::kPositiveSemidefiniteConstraint}); if (!AreRequiredAttributesSupported(prog.required_capabilities(), solver_capabilities)) { throw std::invalid_argument( "SdpaFreeFormat(): the program cannot be formulated as an SDP " "in the standard form.\n"); } prog_var_in_sdpa_.reserve(prog.num_vars()); for (int i = 0; i < prog.num_vars(); ++i) { prog_var_in_sdpa_.emplace_back(nullptr); } std::unordered_map<symbolic::Variable::Id, std::vector<EntryInX>> entries_in_X_for_same_decision_variable; DeclareXforPositiveSemidefiniteConstraints( prog, &entries_in_X_for_same_decision_variable); AddEqualityConstraintOnXEntriesForSameDecisionVariable( entries_in_X_for_same_decision_variable); RegisterMathematicalProgramDecisionVariables(prog); AddLinearCostsFromProgram(prog); AddLinearConstraintsFromProgram(prog); AddLinearMatrixInequalityConstraints(prog); AddLorentzConeConstraints(prog); AddRotatedLorentzConeConstraints(prog); Finalize(); } void SdpaFreeFormat::RemoveFreeVariableByNullspaceApproach( Eigen::SparseMatrix<double>* C_hat, std::vector<Eigen::SparseMatrix<double>>* A_hat, Eigen::VectorXd* rhs_hat, Eigen::VectorXd* y_hat, Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>* QR_B) const { DRAKE_ASSERT(this->num_free_variables() != 0); const int num_constraints = static_cast<int>(this->A_triplets().size()); // Do a QR decomposition on B to find the null space of Bᵀ. QR_B->analyzePattern(this->B()); QR_B->factorize(this->B()); if (QR_B->info() != Eigen::Success) { throw std::runtime_error( "SdpaFreeFormat::RemoveFreeVariableByNullspaceApproach(): cannot " "perform QR decomposition of B. Please try the other method " "kTwoSlackVariables."); } // BP = [Q₁ Q₂] * [R; 0], so the nullspace of Bᵀ is Q₂ Eigen::SparseMatrix<double> Q; Q = QR_B->matrixQ(); const Eigen::SparseMatrix<double> N = Q.rightCols(this->B().rows() - QR_B->rank()); *rhs_hat = N.transpose() * this->g(); A_hat->clear(); A_hat->reserve(N.cols()); for (int i = 0; i < N.cols(); ++i) { A_hat->emplace_back(this->num_X_rows(), this->num_X_rows()); A_hat->back().setZero(); for (Eigen::SparseMatrix<double>::InnerIterator it_N(N, i); it_N; ++it_N) { A_hat->back() += it_N.value() * this->A()[it_N.row()]; } } const Eigen::SparseMatrix<double> B_t = this->B().transpose(); Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> qr_B_t; qr_B_t.compute(B_t); if (qr_B_t.info() != Eigen::Success) { throw std::runtime_error( "RemoveFreeVariableByNullspaceApproach():QR " "decomposition on B.transpose() fails\n"); } *y_hat = qr_B_t.solve(Eigen::VectorXd(this->d())); *C_hat = this->C(); for (int i = 0; i < num_constraints; ++i) { *C_hat -= (*y_hat)(i) * this->A()[i]; } } void SdpaFreeFormat::RemoveFreeVariableByTwoSlackVariablesApproach( std::vector<internal::BlockInX>* X_hat_blocks, std::vector<Eigen::SparseMatrix<double>>* A_hat, Eigen::SparseMatrix<double>* C_hat) const { *X_hat_blocks = this->X_blocks(); X_hat_blocks->emplace_back(internal::BlockType::kDiagonal, 2 * this->num_free_variables()); const int num_X_hat_rows = this->num_X_rows() + 2 * this->num_free_variables(); std::vector<std::vector<Eigen::Triplet<double>>> A_hat_triplets = this->A_triplets(); for (int j = 0; j < this->num_free_variables(); ++j) { for (Eigen::SparseMatrix<double>::InnerIterator it(this->B(), j); it; ++it) { const int i = it.row(); // Add the entry in Âᵢ that multiplies with sⱼ. A_hat_triplets[i].emplace_back(this->num_X_rows() + j, this->num_X_rows() + j, it.value()); A_hat_triplets[i].emplace_back( this->num_X_rows() + this->num_free_variables() + j, this->num_X_rows() + this->num_free_variables() + j, -it.value()); } } A_hat->clear(); A_hat->reserve(this->A().size()); for (int i = 0; i < static_cast<int>(this->A().size()); ++i) { A_hat->emplace_back(num_X_hat_rows, num_X_hat_rows); A_hat->back().setFromTriplets(A_hat_triplets[i].begin(), A_hat_triplets[i].end()); } // Add the entry in Ĉ that multiplies with sᵢ std::vector<Eigen::Triplet<double>> C_hat_triplets = this->C_triplets(); for (Eigen::SparseMatrix<double>::InnerIterator it(this->d(), 0); it; ++it) { const int i = it.row(); C_hat_triplets.emplace_back(this->num_X_rows() + i, this->num_X_rows() + i, it.value()); C_hat_triplets.emplace_back( this->num_X_rows() + this->num_free_variables() + i, this->num_X_rows() + this->num_free_variables() + i, -it.value()); } *C_hat = Eigen::SparseMatrix<double>(num_X_hat_rows, num_X_hat_rows); C_hat->setFromTriplets(C_hat_triplets.begin(), C_hat_triplets.end()); } void SdpaFreeFormat::RemoveFreeVariableByLorentzConeSlackApproach( std::vector<internal::BlockInX>* X_hat_blocks, std::vector<Eigen::SparseMatrix<double>>* A_hat, Eigen::VectorXd* rhs_hat, Eigen::SparseMatrix<double>* C_hat) const { *X_hat_blocks = this->X_blocks(); X_hat_blocks->emplace_back(internal::BlockType::kMatrix, this->num_free_variables() + 1); const int num_X_hat_rows = this->num_X_rows() + this->num_free_variables() + 1; std::vector<std::vector<Eigen::Triplet<double>>> A_hat_triplets = this->A_triplets(); // Âᵢ = diag(Aᵢ, B̂ᵢ) // where B̂ᵢ = ⎡0 bᵢᵀ/2⎤ // ⎣bᵢ/2 0⎦ for (int j = 0; j < this->num_free_variables(); ++j) { for (Eigen::SparseMatrix<double>::InnerIterator it(this->B(), j); it; ++it) { const int i = it.row(); // Add the entry in Âᵢ that multiplies with sⱼ. A_hat_triplets[i].emplace_back( this->num_X_rows(), this->num_X_rows() + j + 1, it.value() / 2); A_hat_triplets[i].emplace_back(this->num_X_rows() + j + 1, this->num_X_rows(), it.value() / 2); } } const int num_linear_eq_constr = this->A().size() + (num_free_variables_ * (num_free_variables_ + 1)) / 2; A_hat->clear(); A_hat->reserve(num_linear_eq_constr); for (int i = 0; i < static_cast<int>(this->A().size()); ++i) { A_hat->emplace_back(num_X_hat_rows, num_X_hat_rows); A_hat->back().setFromTriplets(A_hat_triplets[i].begin(), A_hat_triplets[i].end()); } // The new right hand side is the same as the old one, except padding 0's // in the end. *rhs_hat = Eigen::VectorXd::Zero(num_linear_eq_constr); rhs_hat->head(this->A().size()) = this->g(); for (int i = 0; i < num_free_variables_; ++i) { // Append the constraint Y(i + 1, i + 1) = Y(0, 0). std::vector<Eigen::Triplet<double>> triplets; triplets.reserve(2); triplets.emplace_back(num_X_rows_, num_X_rows_, -1); triplets.emplace_back(num_X_rows_ + i + 1, num_X_rows_ + i + 1, 1); A_hat->emplace_back(num_X_hat_rows, num_X_hat_rows); A_hat->back().setFromTriplets(triplets.begin(), triplets.end()); for (int j = i + 1; j < num_free_variables_; ++j) { // Append the constraint Y(i+1, j+1) = 0 triplets.clear(); triplets.reserve(2); triplets.emplace_back(num_X_rows_ + i + 1, num_X_rows_ + j + 1, 0.5); triplets.emplace_back(num_X_rows_ + j + 1, num_X_rows_ + i + 1, 0.5); A_hat->emplace_back(num_X_hat_rows, num_X_hat_rows); A_hat->back().setFromTriplets(triplets.begin(), triplets.end()); } } // Add the entry in Ĉ that multiplies with sᵢ. std::vector<Eigen::Triplet<double>> C_hat_triplets = this->C_triplets(); for (Eigen::SparseMatrix<double>::InnerIterator it(this->d(), 0); it; ++it) { const int i = it.row(); C_hat_triplets.emplace_back(this->num_X_rows(), this->num_X_rows() + i + 1, it.value() / 2); C_hat_triplets.emplace_back(this->num_X_rows() + i + 1, this->num_X_rows(), it.value() / 2); } *C_hat = Eigen::SparseMatrix<double>(num_X_hat_rows, num_X_hat_rows); C_hat->setFromTriplets(C_hat_triplets.begin(), C_hat_triplets.end()); } namespace { bool GenerateSdpaImpl(const std::vector<BlockInX>& X_blocks, const Eigen::SparseMatrix<double>& C, const std::vector<Eigen::SparseMatrix<double>>& A, const Eigen::Ref<const Eigen::VectorXd>& g, const std::string& file_name) { const int num_X_rows = C.rows(); DRAKE_DEMAND(C.cols() == num_X_rows); std::ofstream sdpa_file; sdpa_file.open(file_name + ".dat-s", std::ios::out | std::ios::trunc); if (sdpa_file.is_open()) { // First line, number of constraints. sdpa_file << g.rows() << "\n"; // Second line, number of blocks in X. sdpa_file << X_blocks.size() << "\n"; // Third line, size of each block. for (const auto& X_block : X_blocks) { switch (X_block.block_type) { case internal::BlockType::kMatrix: { sdpa_file << X_block.num_rows; break; } case internal::BlockType::kDiagonal: { // Negative value indates diagonal block according to SDPA format. sdpa_file << -X_block.num_rows; break; } } sdpa_file << " "; } sdpa_file << "\n"; // Fourth line, the right-hand side of the constraint g. for (int i = 0; i < g.size(); ++i) { if (i > 0) { sdpa_file << " "; } // Different versions of fmt disagree on whether to omit the trailing ".0" // when formatting integer-valued floating-point numbers, so we must paper // over it using a helper function. sdpa_file << fmt_floating_point(g[i]); } sdpa_file << "\n"; // block_start_rows[i] records the starting row index of the i'th block in // X. row_to_block_indices[i] records the index of the block that X(i, i) // belongs to. std::vector<int> block_start_rows(X_blocks.size()); std::vector<int> row_to_block_indices(num_X_rows); int X_row_count = 0; for (int i = 0; i < static_cast<int>(X_blocks.size()); ++i) { block_start_rows[i] = X_row_count; for (int j = X_row_count; j < X_row_count + X_blocks[i].num_rows; ++j) { row_to_block_indices[j] = i; } X_row_count += X_blocks[i].num_rows; } // The non-zero entries in C for (int i = 0; i < num_X_rows; ++i) { for (Eigen::SparseMatrix<double>::InnerIterator it(C, i); it; ++it) { if (it.row() <= it.col()) { const int block_start_row = block_start_rows[row_to_block_indices[i]]; sdpa_file << 0 /* 0 for cost matrix C */ << " " << row_to_block_indices[i] + 1 /* block number, starts from 1 */ << " " << it.row() - block_start_row + 1 /* block row index, starts from 1*/ << " " << i - block_start_row + 1 /* block column index, starts from 1*/ << " " << fmt_floating_point(it.value()) << "\n"; } } } // The remaining lines are for A for (int i = 0; i < static_cast<int>(A.size()); ++i) { for (int j = 0; j < num_X_rows; ++j) { for (Eigen::SparseMatrix<double>::InnerIterator it(A[i], j); it; ++it) { if (it.row() <= it.col()) { const int block_start_row = block_start_rows[row_to_block_indices[j]]; sdpa_file << i + 1 /* constraint number, starts from 1 */ << " " << row_to_block_indices[j] + 1 /* block number, starts from 1 */ << " " << it.row() - block_start_row + 1 << " " << j - block_start_row + 1 << " " << fmt_floating_point(it.value()) << "\n"; } } } } } else { drake::log()->warn("GenerateSDPA(): Cannot open the file {}.dat-s", file_name); return false; } sdpa_file.close(); return true; } } // namespace } // namespace internal std::string to_string(const RemoveFreeVariableMethod& x) { switch (x) { case RemoveFreeVariableMethod::kTwoSlackVariables: return "kTwoSlackVariables"; case RemoveFreeVariableMethod::kNullspace: return "kNullspace"; case RemoveFreeVariableMethod::kLorentzConeSlack: return "kLorentzConeSlack"; } DRAKE_UNREACHABLE(); } bool GenerateSDPA(const MathematicalProgram& prog, const std::string& file_name, RemoveFreeVariableMethod method) { const internal::SdpaFreeFormat sdpa_free_format(prog); if (sdpa_free_format.num_free_variables() == 0) { return internal::GenerateSdpaImpl( sdpa_free_format.X_blocks(), sdpa_free_format.C(), sdpa_free_format.A(), sdpa_free_format.g(), file_name); } switch (method) { case RemoveFreeVariableMethod::kNullspace: { Eigen::SparseMatrix<double> C_hat; std::vector<Eigen::SparseMatrix<double>> A_hat; Eigen::VectorXd rhs_hat, y_hat; Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> QR_B; sdpa_free_format.RemoveFreeVariableByNullspaceApproach( &C_hat, &A_hat, &rhs_hat, &y_hat, &QR_B); return internal::GenerateSdpaImpl(sdpa_free_format.X_blocks(), C_hat, A_hat, rhs_hat, file_name); break; } case RemoveFreeVariableMethod::kTwoSlackVariables: { std::vector<internal::BlockInX> X_hat_blocks; std::vector<Eigen::SparseMatrix<double>> A_hat; Eigen::SparseMatrix<double> C_hat; sdpa_free_format.RemoveFreeVariableByTwoSlackVariablesApproach( &X_hat_blocks, &A_hat, &C_hat); return internal::GenerateSdpaImpl(X_hat_blocks, C_hat, A_hat, sdpa_free_format.g(), file_name); } case RemoveFreeVariableMethod::kLorentzConeSlack: { std::vector<internal::BlockInX> X_hat_blocks; std::vector<Eigen::SparseMatrix<double>> A_hat; Eigen::VectorXd rhs_hat; Eigen::SparseMatrix<double> C_hat; sdpa_free_format.RemoveFreeVariableByLorentzConeSlackApproach( &X_hat_blocks, &A_hat, &rhs_hat, &C_hat); return internal::GenerateSdpaImpl(X_hat_blocks, C_hat, A_hat, rhs_hat, file_name); } } return false; } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/mosek_solver.cc
#include "drake/solvers/mosek_solver.h" #include <cmath> #include <optional> #include <stdexcept> #include <unordered_map> #include <utility> #include <vector> #include <Eigen/Core> #include <Eigen/SparseCore> #include <mosek.h> #include "drake/common/scoped_singleton.h" #include "drake/common/text_logging.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/mosek_solver_internal.h" namespace drake { namespace solvers { /* * Implements RAII for a Mosek license / environment. */ class MosekSolver::License { public: License() { if (!MosekSolver::is_enabled()) { throw std::runtime_error( "Could not locate MOSEK license file because MOSEKLM_LICENSE_FILE " "environment variable was not set."); } MSKrescodee rescode = MSK_makeenv(&mosek_env_, nullptr); if (rescode != MSK_RES_OK) { throw std::runtime_error("Could not create MOSEK environment."); } DRAKE_DEMAND(mosek_env_ != nullptr); const int num_tries = 3; rescode = MSK_RES_TRM_INTERNAL; for (int i = 0; i < num_tries && rescode != MSK_RES_OK; ++i) { // Acquire the license for the base MOSEK system so that we can // fail fast if the license file is missing or the server is // unavailable. Any additional features should be checked out // later by MSK_optimizetrm if needed (so there's still the // possibility of later failure at that stage if the desired // feature is unavailable or another error occurs). rescode = MSK_checkoutlicense(mosek_env_, MSK_FEATURE_PTS); } if (rescode != MSK_RES_OK) { throw std::runtime_error( fmt::format("Could not acquire MOSEK license: {}. See " "https://docs.mosek.com/10.1/capi/" "response-codes.html#mosek.rescode for details.", fmt_streamed(rescode))); } } ~License() { MSK_deleteenv(&mosek_env_); mosek_env_ = nullptr; // Fail-fast if accidentally used after destruction. } MSKenv_t mosek_env() const { return mosek_env_; } private: MSKenv_t mosek_env_{nullptr}; }; std::shared_ptr<MosekSolver::License> MosekSolver::AcquireLicense() { // According to // https://docs.mosek.com/8.1/cxxfusion/solving-parallel.html sharing // an env used between threads is safe (not mentioned in 10.0 documentation), // but nothing mentions thread-safety when allocating the environment. We can // safeguard against this ambiguity by using GetScopedSingleton for basic // thread-safety when acquiring / releasing the license. return GetScopedSingleton<MosekSolver::License>(); } bool MosekSolver::is_available() { return true; } void MosekSolver::DoSolve(const MathematicalProgram& prog, const Eigen::VectorXd& initial_guess, const SolverOptions& merged_options, MathematicalProgramResult* result) const { if (!prog.GetVariableScaling().empty()) { static const logging::Warn log_once( "MosekSolver doesn't support the feature of variable scaling."); } // num_decision_vars is the total number of decision variables in @p prog. It // includes both the matrix variables (for psd matrix variables) and // non-matrix variables. const int num_decision_vars = prog.num_vars(); MSKrescodee rescode{MSK_RES_OK}; if (!license_) { license_ = AcquireLicense(); } MSKenv_t env = license_->mosek_env(); internal::MosekSolverProgram impl(prog, env); // The number of non-matrix variables in @p prog. const int num_nonmatrix_vars_in_prog = impl.decision_variable_to_mosek_nonmatrix_variable().size(); // Set the options (parameters). bool print_to_console{false}; std::string print_file_name{}; std::optional<std::string> msk_writedata; if (rescode == MSK_RES_OK) { rescode = impl.UpdateOptions(merged_options, id(), &print_to_console, &print_file_name, &msk_writedata); } // Always check if rescode is MSK_RES_OK before we call any Mosek functions. // If it is not MSK_RES_OK, then bypasses everything and exits. if (rescode == MSK_RES_OK) { rescode = MSK_appendvars(impl.task(), num_nonmatrix_vars_in_prog); } // Add positive semidefinite constraint. This also adds Mosek matrix // variables. // psd_barvar_indices records the index of the bar matrix for this positive // semidefinite constraint. We will use this bar matrix index later, for // example when retrieving the dual solution. std::unordered_map<Binding<PositiveSemidefiniteConstraint>, MSKint32t> psd_barvar_indices; if (rescode == MSK_RES_OK) { rescode = impl.AddPositiveSemidefiniteConstraints(prog, &psd_barvar_indices); } // Add the constraint that Mosek matrix variable entries corresponding to the // same decision variables should all be equal. if (rescode == MSK_RES_OK) { rescode = impl.AddEqualityConstraintBetweenMatrixVariablesForSameDecisionVariable(); // NOLINT } // Add costs if (rescode == MSK_RES_OK) { rescode = impl.AddCosts(prog); } // We store the dual variable indices for each bounding box constraint. // bb_con_dual_indices[constraint] returns the pair (lower_bound_indices, // upper_bound_indices), where lower_bound_indices are the indices of the // lower bound dual variables, and upper_bound_indices are the indices of the // upper bound dual variables. std::unordered_map<Binding<BoundingBoxConstraint>, std::pair<internal::ConstraintDualIndices, internal::ConstraintDualIndices>> bb_con_dual_indices; // Add bounding box constraints on decision variables. if (rescode == MSK_RES_OK) { rescode = impl.AddBoundingBoxConstraints(prog, &bb_con_dual_indices); } // Specify binary variables. bool with_integer_or_binary_variable = false; if (rescode == MSK_RES_OK) { rescode = impl.SpecifyVariableType(prog, &with_integer_or_binary_variable); } // Add linear constraints. std::unordered_map<Binding<LinearConstraint>, internal::ConstraintDualIndices> linear_con_dual_indices; std::unordered_map<Binding<LinearEqualityConstraint>, internal::ConstraintDualIndices> lin_eq_con_dual_indices; if (rescode == MSK_RES_OK) { rescode = impl.AddLinearConstraints(prog, &linear_con_dual_indices, &lin_eq_con_dual_indices); } // Add Lorentz cone constraints. std::unordered_map<Binding<LorentzConeConstraint>, MSKint64t> lorentz_cone_acc_indices; if (rescode == MSK_RES_OK) { rescode = impl.AddConeConstraints(prog, prog.lorentz_cone_constraints(), &lorentz_cone_acc_indices); } // Add rotated Lorentz cone constraints. std::unordered_map<Binding<RotatedLorentzConeConstraint>, MSKint64t> rotated_lorentz_cone_acc_indices; if (rescode == MSK_RES_OK) { rescode = impl.AddConeConstraints(prog, prog.rotated_lorentz_cone_constraints(), &rotated_lorentz_cone_acc_indices); } // Add quadratic constraints. std::unordered_map<Binding<QuadraticConstraint>, MSKint64t> quadratic_constraint_dual_indices; if (rescode == MSK_RES_OK) { rescode = impl.AddQuadraticConstraints(prog, &quadratic_constraint_dual_indices); } // Add linear matrix inequality constraints. std::unordered_map<Binding<LinearMatrixInequalityConstraint>, MSKint64t> lmi_acc_indices; // TODO(hongkai.dai): use lmi_acc_indices to return the dual solution of LMI // constraints. if (rescode == MSK_RES_OK) { rescode = impl.AddLinearMatrixInequalityConstraint(prog, &lmi_acc_indices); } // Add exponential cone constraints. std::unordered_map<Binding<ExponentialConeConstraint>, MSKint64t> exp_cone_acc_indices; if (rescode == MSK_RES_OK) { rescode = impl.AddConeConstraints(prog, prog.exponential_cone_constraints(), &exp_cone_acc_indices); } // Determines the solution type. MSKsoltypee solution_type; if (with_integer_or_binary_variable) { solution_type = MSK_SOL_ITG; } else if (prog.quadratic_costs().empty() && prog.l2norm_costs().empty() && prog.quadratic_constraints().empty() && prog.lorentz_cone_constraints().empty() && prog.rotated_lorentz_cone_constraints().empty() && prog.positive_semidefinite_constraints().empty() && prog.linear_matrix_inequality_constraints().empty() && prog.exponential_cone_constraints().empty()) { // The program is LP. int ipm_basis{}; if (rescode == MSK_RES_OK) { rescode = MSK_getintparam(impl.task(), MSK_IPAR_INTPNT_BASIS, &ipm_basis); } // By default ipm_basis > 0 and Mosek will do a basis identification to // clean up the solution after the interior point method (IPM), then we can // query the basis solution. Otherwise we will only query the IPM solution. if (ipm_basis > 0) { solution_type = MSK_SOL_BAS; } else { solution_type = MSK_SOL_ITR; } } else { solution_type = MSK_SOL_ITR; } // Since Mosek 10, it allows setting the initial guess for both continuous and // integer/binary variables. See // https://docs.mosek.com/latest/rmosek/tutorial-mio-shared.html#specifying-an-initial-solution // for more details. if (initial_guess.array().isFinite().any()) { DRAKE_ASSERT(initial_guess.size() == prog.num_vars()); for (int i = 0; i < prog.num_vars(); ++i) { const auto& map_to_mosek = impl.decision_variable_to_mosek_nonmatrix_variable(); if (auto it = map_to_mosek.find(i); it != map_to_mosek.end()) { if (rescode == MSK_RES_OK) { const MSKrealt initial_guess_i = initial_guess(i); if (!std::isnan(initial_guess_i)) { rescode = MSK_putxxslice(impl.task(), solution_type, it->second, it->second + 1, &initial_guess_i); } } } } } result->set_solution_result(SolutionResult::kSolverSpecificError); // Run optimizer. if (rescode == MSK_RES_OK) { // TODO([email protected]): add trmcode to the returned struct. MSKrescodee trmcode; // termination code rescode = MSK_optimizetrm(impl.task(), &trmcode); // Refer to // https://docs.mosek.com/latest/capi/debugging-tutorials.html#debugging-tutorials // on printing the solution summary. if (print_to_console || !print_file_name.empty()) { if (rescode == MSK_RES_OK) { rescode = MSK_solutionsummary(impl.task(), MSK_STREAM_LOG); } } } if (rescode == MSK_RES_OK && msk_writedata.has_value()) { rescode = MSK_writedata(impl.task(), msk_writedata.value().c_str()); } MSKsolstae solution_status{MSK_SOL_STA_UNKNOWN}; if (rescode == MSK_RES_OK) { rescode = MSK_getsolsta(impl.task(), solution_type, &solution_status); } if (rescode == MSK_RES_OK) { switch (solution_status) { case MSK_SOL_STA_OPTIMAL: case MSK_SOL_STA_INTEGER_OPTIMAL: case MSK_SOL_STA_PRIM_FEAS: { result->set_solution_result(SolutionResult::kSolutionFound); break; } case MSK_SOL_STA_DUAL_INFEAS_CER: { result->set_solution_result(SolutionResult::kDualInfeasible); break; } case MSK_SOL_STA_PRIM_INFEAS_CER: { result->set_solution_result(SolutionResult::kInfeasibleConstraints); break; } default: { result->set_solution_result(SolutionResult::kSolverSpecificError); break; } } MSKint32t num_mosek_vars; rescode = MSK_getnumvar(impl.task(), &num_mosek_vars); DRAKE_ASSERT(rescode == MSK_RES_OK); Eigen::VectorXd mosek_sol_vector(num_mosek_vars); rescode = MSK_getxx(impl.task(), solution_type, mosek_sol_vector.data()); MSKint32t num_bar_x; rescode = MSK_getnumbarvar(impl.task(), &num_bar_x); DRAKE_ASSERT(rescode == MSK_RES_OK); std::vector<Eigen::VectorXd> mosek_bar_x_sol(num_bar_x); for (int i = 0; i < num_bar_x; ++i) { MSKint32t bar_xi_dim; rescode = MSK_getdimbarvarj(impl.task(), i, &bar_xi_dim); DRAKE_ASSERT(rescode == MSK_RES_OK); mosek_bar_x_sol[i].resize(bar_xi_dim * (bar_xi_dim + 1) / 2); rescode = MSK_getbarxj(impl.task(), solution_type, i, mosek_bar_x_sol[i].data()); } DRAKE_ASSERT(rescode == MSK_RES_OK); Eigen::VectorXd sol_vector(num_decision_vars); for (int i = 0; i < num_decision_vars; ++i) { auto it1 = impl.decision_variable_to_mosek_nonmatrix_variable().find(i); if (it1 != impl.decision_variable_to_mosek_nonmatrix_variable().end()) { sol_vector(i) = mosek_sol_vector(it1->second); } else { auto it2 = impl.decision_variable_to_mosek_matrix_variable().find(i); sol_vector(i) = mosek_bar_x_sol[it2->second.bar_matrix_index()]( it2->second.IndexInLowerTrianglePart()); } } if (rescode == MSK_RES_OK) { result->set_x_val(sol_vector); } MSKrealt optimal_cost; rescode = MSK_getprimalobj(impl.task(), solution_type, &optimal_cost); DRAKE_ASSERT(rescode == MSK_RES_OK); if (rescode == MSK_RES_OK) { result->set_optimal_cost(optimal_cost); } rescode = impl.SetDualSolution( solution_type, prog, bb_con_dual_indices, linear_con_dual_indices, lin_eq_con_dual_indices, quadratic_constraint_dual_indices, lorentz_cone_acc_indices, rotated_lorentz_cone_acc_indices, exp_cone_acc_indices, psd_barvar_indices, result); DRAKE_ASSERT(rescode == MSK_RES_OK); } MosekSolverDetails& solver_details = result->SetSolverDetailsType<MosekSolverDetails>(); solver_details.rescode = rescode; solver_details.solution_status = solution_status; if (rescode == MSK_RES_OK) { rescode = MSK_getdouinf(impl.task(), MSK_DINF_OPTIMIZER_TIME, &(solver_details.optimizer_time)); } // rescode is not used after this. If in the future, the user wants to call // more MSK functions after this line, then he/she needs to check if rescode // is OK. But do not modify result->solution_result_ if rescode is not OK // after this line. unused(rescode); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/clarabel_solver.h
#pragma once #include <string> #include "drake/common/drake_copyable.h" #include "drake/solvers/solver_base.h" namespace drake { namespace solvers { /// The Clarabel solver details after calling the Solve() function. The user can /// call MathematicalProgramResult::get_solver_details<ClarabelSolver>() to /// obtain the details. struct ClarabelSolverDetails { /// The solve time inside Clarabel in seconds. double solve_time{}; /// Number of iterations in Clarabel. int iterations{}; /// The status from Clarabel. std::string status{}; }; /// An interface to wrap Clarabel https://github.com/oxfordcontrol/Clarabel.cpp class ClarabelSolver final : public SolverBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ClarabelSolver) /// Type of details stored in MathematicalProgramResult. using Details = ClarabelSolverDetails; ClarabelSolver(); ~ClarabelSolver() final; /// @name Static versions of the instance methods with similar names. //@{ static SolverId id(); static bool is_available(); static bool is_enabled(); static bool ProgramAttributesSatisfied(const MathematicalProgram&); static std::string UnsatisfiedProgramAttributes(const MathematicalProgram&); //@} // A using-declaration adds these methods into our class's Doxygen. using SolverBase::Solve; private: void DoSolve(const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const final; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/clp_solver.cc
#include "drake/solvers/clp_solver.h" #include <limits> #include <unordered_map> #include <utility> #include <vector> #include "ClpSimplex.hpp" #include "drake/common/text_logging.h" #include "drake/solvers/aggregate_costs_constraints.h" namespace drake { namespace solvers { constexpr double kInf = std::numeric_limits<double>::infinity(); namespace { void ConstructClpModel( const std::vector<Eigen::Triplet<double>>& constraint_coeffs, const std::vector<double>& constraint_lower, const std::vector<double>& constraint_upper, const Eigen::VectorXd& xlow, const Eigen::VectorXd& xupp, const Eigen::SparseMatrix<double>& quadratic_matrix, const Eigen::VectorXd& objective_coeff, double constant_cost, ClpModel* model) { Eigen::SparseMatrix<double> constraint_mat(constraint_lower.size(), xlow.rows()); constraint_mat.setFromTriplets(constraint_coeffs.begin(), constraint_coeffs.end()); // Now convert the sparse matrix to Compressed Column Storage format. model->loadProblem(constraint_mat.cols(), constraint_mat.rows(), constraint_mat.outerIndexPtr(), constraint_mat.innerIndexPtr(), constraint_mat.valuePtr(), xlow.data(), xupp.data(), objective_coeff.data(), constraint_lower.data(), constraint_upper.data(), nullptr /* rowObjective=nullptr */); if (quadratic_matrix.nonZeros() > 0) { static const logging::Warn log_once( "Currently CLP solver has a memory issue when solving a QP. The user " "should be aware of this risk."); model->loadQuadraticObjective( quadratic_matrix.cols(), quadratic_matrix.outerIndexPtr(), quadratic_matrix.innerIndexPtr(), quadratic_matrix.valuePtr()); } model->setObjectiveOffset(-constant_cost); } template <typename C> void AddLinearConstraint( const MathematicalProgram& prog, const Binding<C>& linear_constraint, std::vector<Eigen::Triplet<double>>* constraint_coeffs, std::vector<double>* constraint_lower, std::vector<double>* constraint_upper, int* constraint_count, std::unordered_map<Binding<Constraint>, int>* constraint_dual_start_index) { const Binding<Constraint> binding_cast = internal::BindingDynamicCast<Constraint>(linear_constraint); constraint_dual_start_index->emplace(binding_cast, *constraint_count); const Eigen::SparseMatrix<double>& A = linear_constraint.evaluator()->get_sparse_A(); // First loop by column to set the coefficient since A is a column major // matrix. for (int j = 0; j < A.cols(); ++j) { const int var_index = prog.FindDecisionVariableIndex(linear_constraint.variables()(j)); for (Eigen::SparseMatrix<double>::InnerIterator it(A, j); it; ++it) { const int row = it.row(); constraint_coeffs->emplace_back(row + *constraint_count, var_index, it.value()); } } // Now loop by rows of the constraints to set the bounds. for (int i = 0; i < linear_constraint.evaluator()->num_constraints(); ++i) { (*constraint_lower)[*constraint_count + i] = linear_constraint.evaluator()->lower_bound()(i); (*constraint_upper)[*constraint_count + i] = linear_constraint.evaluator()->upper_bound()(i); } *constraint_count += linear_constraint.evaluator()->num_constraints(); } void AddLinearConstraints( const MathematicalProgram& prog, std::vector<Eigen::Triplet<double>>* constraint_coeffs, std::vector<double>* constraint_lower, std::vector<double>* constraint_upper, std::unordered_map<Binding<Constraint>, int>* constraint_dual_start_index) { int num_constraints = 0; int num_nonzero_coeff_max = 0; for (const auto& linear_constraint : prog.linear_constraints()) { num_constraints += linear_constraint.evaluator()->num_constraints(); num_nonzero_coeff_max += linear_constraint.evaluator()->num_constraints() * linear_constraint.variables().rows(); } for (const auto& linear_eq_constraint : prog.linear_equality_constraints()) { num_constraints += linear_eq_constraint.evaluator()->num_constraints(); num_nonzero_coeff_max += linear_eq_constraint.evaluator()->num_constraints() * linear_eq_constraint.variables().rows(); } constraint_lower->resize(num_constraints); constraint_upper->resize(num_constraints); constraint_coeffs->reserve(num_nonzero_coeff_max); int constraint_count = 0; for (const auto& linear_constraint : prog.linear_constraints()) { AddLinearConstraint<LinearConstraint>( prog, linear_constraint, constraint_coeffs, constraint_lower, constraint_upper, &constraint_count, constraint_dual_start_index); } for (const auto& linear_equal_constraint : prog.linear_equality_constraints()) { AddLinearConstraint<LinearEqualityConstraint>( prog, linear_equal_constraint, constraint_coeffs, constraint_lower, constraint_upper, &constraint_count, constraint_dual_start_index); } } // @param lambda The dual solution for the whole problem. This can be obtained // through CLP by calling getRowPrice() or getReducedCost() function. void SetConstraintDualSolution( const Eigen::Map<const Eigen::VectorXd>& lambda, const std::unordered_map<Binding<Constraint>, int>& constraint_dual_start_index, MathematicalProgramResult* result) { for (const auto& [constraint, dual_start_index] : constraint_dual_start_index) { result->set_dual_solution( constraint, lambda.segment(dual_start_index, constraint.evaluator()->num_constraints())); } } void SetBoundingBoxConstraintDualSolution( const Eigen::Map<const Eigen::VectorXd>& column_dual_sol, const std::unordered_map<Binding<BoundingBoxConstraint>, std::pair<std::vector<int>, std::vector<int>>>& bb_con_dual_variable_indices, MathematicalProgramResult* result) { for (const auto& [bb_con, dual_var_indices] : bb_con_dual_variable_indices) { Eigen::VectorXd bb_con_dual_sol = Eigen::VectorXd::Zero(bb_con.evaluator()->num_constraints()); const std::vector<int>& lower_dual_indices = dual_var_indices.first; const std::vector<int>& upper_dual_indices = dual_var_indices.second; for (int k = 0; k < bb_con.evaluator()->num_constraints(); ++k) { // At most one of the bound is active (If both the lower and upper bounds // are active, then these two bounds have to be equal, then the dual // solution for both bounds are the same). if (lower_dual_indices[k] != -1 && column_dual_sol(lower_dual_indices[k]) > 0) { // If the dual solution is positive, then the lower bound is active // (according to the definition of reduced cost). bb_con_dual_sol[k] = column_dual_sol[lower_dual_indices[k]]; } else if (upper_dual_indices[k] != -1 && column_dual_sol(upper_dual_indices[k]) < 0) { // If the dual solution is negative, then the upper bound is active // (according to the definition of reduced cost). bb_con_dual_sol[k] = column_dual_sol[upper_dual_indices[k]]; } } result->set_dual_solution(bb_con, bb_con_dual_sol); } } void SetSolution( const MathematicalProgram& prog, const ClpModel& model, const std::unordered_map<Binding<Constraint>, int>& constraint_dual_start_index, const std::unordered_map<Binding<BoundingBoxConstraint>, std::pair<std::vector<int>, std::vector<int>>>& bb_con_dual_variable_indices, MathematicalProgramResult* result) { ClpSolverDetails& solver_details = result->SetSolverDetailsType<ClpSolverDetails>(); solver_details.clp_version = CLP_VERSION; result->set_x_val(Eigen::Map<const Eigen::VectorXd>(model.getColSolution(), prog.num_vars())); Eigen::Map<const Eigen::VectorXd> lambda(model.dualRowSolution(), model.getNumRows()); SetConstraintDualSolution(lambda, constraint_dual_start_index, result); Eigen::Map<const Eigen::VectorXd> column_dual_sol(model.dualColumnSolution(), model.getNumCols()); SetBoundingBoxConstraintDualSolution(column_dual_sol, bb_con_dual_variable_indices, result); solver_details.status = model.status(); SolutionResult solution_result{SolutionResult::kSolverSpecificError}; switch (solver_details.status) { case -1: { solution_result = SolutionResult::kSolverSpecificError; break; } case 0: { solution_result = SolutionResult::kSolutionFound; break; } case 1: { solution_result = SolutionResult::kInfeasibleConstraints; break; } case 2: { solution_result = SolutionResult::kUnbounded; break; } case 3: { solution_result = SolutionResult::kIterationLimit; break; } default: { // Merging multiple CLP status code into one Drake SolutionResult code. solution_result = SolutionResult::kSolverSpecificError; } } double objective_val{-kInf}; if (solution_result == SolutionResult::kInfeasibleConstraints) { objective_val = kInf; } else if (solution_result == SolutionResult::kUnbounded) { objective_val = -kInf; } else { objective_val = model.getObjValue(); } result->set_solution_result(solution_result); result->set_optimal_cost(objective_val); } // bb_con_dual_indices[bb_con] returns the indices of the dual variable for the // lower/upper bound of this bounding box constraint. If this bounding box // constraint cannot be active (some other bounding box constraint has a tighter // bound than this one), then its dual variable index is -1. // @param xlow The aggregated lower bound for all decision variables across all // bounding box constraints. // @param xupp The aggregated upper bound for all decision variables across all // bounding box constraints. void SetBoundingBoxConstraintDualIndices( const MathematicalProgram& prog, const Binding<BoundingBoxConstraint>& bb_con, const Eigen::VectorXd& xlow, const Eigen::VectorXd& xupp, std::unordered_map<Binding<BoundingBoxConstraint>, std::pair<std::vector<int>, std::vector<int>>>* bbcon_dual_indices) { const int num_vars = bb_con.evaluator()->num_constraints(); std::vector<int> lower_dual_indices(num_vars, -1); std::vector<int> upper_dual_indices(num_vars, -1); for (int k = 0; k < num_vars; ++k) { const int idx = prog.FindDecisionVariableIndex(bb_con.variables()(k)); if (xlow[idx] == bb_con.evaluator()->lower_bound()(k)) { lower_dual_indices[k] = idx; } if (xupp[idx] == bb_con.evaluator()->upper_bound()(k)) { upper_dual_indices[k] = idx; } } bbcon_dual_indices->emplace( bb_con, std::make_pair(lower_dual_indices, upper_dual_indices)); } void ParseModelExceptLinearConstraints( const MathematicalProgram& prog, Eigen::VectorXd* xlow, Eigen::VectorXd* xupp, Eigen::SparseMatrix<double>* quadratic_matrix, Eigen::VectorXd* objective_coeff, double* constant_cost) { // Construct model using loadProblem function. DRAKE_ASSERT(xlow->rows() == prog.num_vars()); DRAKE_ASSERT(xupp->rows() == prog.num_vars()); AggregateBoundingBoxConstraints(prog, xlow, xupp); Eigen::SparseVector<double> linear_coeff; VectorX<symbolic::Variable> quadratic_vars, linear_vars; Eigen::SparseMatrix<double> Q_lower; AggregateQuadraticAndLinearCosts(prog.quadratic_costs(), prog.linear_costs(), &Q_lower, &quadratic_vars, &linear_coeff, &linear_vars, constant_cost); // We need to convert 0.5 * quadratic_var.dot(Q_lower * quadratic_var) to // 0.5 * x.dot(quadratic_matrix * x), where x is the vector of all the // decision variables. To do so, we first map each entry of quadratic_var to // its corresponding entry in x. std::unordered_map<symbolic::Variable::Id, int> quadratic_var_to_index; for (int i = 0; i < quadratic_vars.rows(); ++i) { quadratic_var_to_index.emplace( quadratic_vars(i).get_id(), prog.FindDecisionVariableIndex(quadratic_vars(i))); } std::vector<Eigen::Triplet<double>> quadratic_matrix_triplets; quadratic_matrix_triplets.reserve(Q_lower.nonZeros()); for (int col = 0; col < Q_lower.outerSize(); ++col) { const int x_col_index = quadratic_var_to_index.at(quadratic_vars(col).get_id()); for (Eigen::SparseMatrix<double>::InnerIterator it(Q_lower, col); it; ++it) { const int x_row_index = quadratic_var_to_index.at(quadratic_vars(it.row()).get_id()); quadratic_matrix_triplets.emplace_back(x_row_index, x_col_index, it.value()); } } quadratic_matrix->setFromTriplets(quadratic_matrix_triplets.begin(), quadratic_matrix_triplets.end()); objective_coeff->resize(prog.num_vars()); for (Eigen::SparseVector<double>::InnerIterator it(linear_coeff); it; ++it) { (*objective_coeff)(prog.FindDecisionVariableIndex(linear_vars(it.row()))) = it.value(); } } int ChooseLogLevel(const SolverOptions& options) { if (options.get_print_to_console()) { // Documented as "factorizations plus a bit more" in ClpModel.hpp. return 3; } return 0; } int ChooseScaling(const SolverOptions& options) { const auto& clp_options = options.GetOptionsInt(ClpSolver::id()); auto it = clp_options.find("scaling"); if (it == clp_options.end()) { // Default scaling is 1. return 1; } else { return it->second; } } } // namespace bool ClpSolver::is_available() { return true; } void ClpSolver::DoSolve(const MathematicalProgram& prog, const Eigen::VectorXd& initial_guess, const SolverOptions& merged_options, MathematicalProgramResult* result) const { // TODO(hongkai.dai): use initial guess and more of the merged options. unused(initial_guess); ClpSimplex model; model.setLogLevel(ChooseLogLevel(merged_options)); Eigen::VectorXd xlow(prog.num_vars()); Eigen::VectorXd xupp(prog.num_vars()); Eigen::VectorXd objective_coeff = Eigen::VectorXd::Zero(prog.num_vars()); Eigen::SparseMatrix<double> quadratic_matrix(prog.num_vars(), prog.num_vars()); double constant_cost{0.}; ParseModelExceptLinearConstraints(prog, &xlow, &xupp, &quadratic_matrix, &objective_coeff, &constant_cost); std::vector<Eigen::Triplet<double>> constraint_coeffs; std::vector<double> constraint_lower, constraint_upper; std::unordered_map<Binding<Constraint>, int> constraint_dual_start_index; if (!prog.linear_constraints().empty() || !prog.linear_equality_constraints().empty()) { AddLinearConstraints(prog, &constraint_coeffs, &constraint_lower, &constraint_upper, &constraint_dual_start_index); } ConstructClpModel(constraint_coeffs, constraint_lower, constraint_upper, xlow, xupp, quadratic_matrix, objective_coeff, constant_cost, &model); std::unordered_map<Binding<BoundingBoxConstraint>, std::pair<std::vector<int>, std::vector<int>>> bb_con_dual_variable_indices; for (const auto& bb_con : prog.bounding_box_constraints()) { SetBoundingBoxConstraintDualIndices(prog, bb_con, xlow, xupp, &bb_con_dual_variable_indices); } // As suggested by the CLP author, we should call scaling() to handle tiny (or // huge) number in program data. See https://github.com/coin-or/Clp/issues/217 // for the discussion. model.scaling(ChooseScaling(merged_options)); // Solve model.primal(); // Set the solution SetSolution(prog, model, constraint_dual_start_index, bb_con_dual_variable_indices, result); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/gurobi_solver_common.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/gurobi_solver.h" /* clang-format on */ #include <cstdlib> #include <cstring> #include "drake/common/never_destroyed.h" #include "drake/solvers/aggregate_costs_constraints.h" #include "drake/solvers/mathematical_program.h" // This file contains implementations that are common to both the available and // unavailable flavor of this class. namespace drake { namespace solvers { GurobiSolver::GurobiSolver() : SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied, &UnsatisfiedProgramAttributes) {} GurobiSolver::~GurobiSolver() = default; SolverId GurobiSolver::id() { static const never_destroyed<SolverId> singleton{"Gurobi"}; return singleton.access(); } bool GurobiSolver::is_enabled() { const char* grb_license_file = std::getenv("GRB_LICENSE_FILE"); return ((grb_license_file != nullptr) && (std::strlen(grb_license_file) > 0)); } namespace { // If the program is compatible with this solver, returns true and clears the // explanation. Otherwise, returns false and sets the explanation. In either // case, the explanation can be nullptr in which case it is ignored. bool CheckAttributes(const MathematicalProgram& prog, std::string* explanation) { // TODO(hongkai.dai): Gurobi supports callback. Add callback capability. static const never_destroyed<ProgramAttributes> solver_capabilities( std::initializer_list<ProgramAttribute>{ ProgramAttribute::kLinearCost, ProgramAttribute::kQuadraticCost, ProgramAttribute::kL2NormCost, ProgramAttribute::kLinearConstraint, ProgramAttribute::kLinearEqualityConstraint, ProgramAttribute::kLorentzConeConstraint, ProgramAttribute::kRotatedLorentzConeConstraint, ProgramAttribute::kBinaryVariable}); return internal::CheckConvexSolverAttributes( prog, solver_capabilities.access(), "GurobiSolver", explanation); } } // namespace bool GurobiSolver::ProgramAttributesSatisfied(const MathematicalProgram& prog) { return CheckAttributes(prog, nullptr); } std::string GurobiSolver::UnsatisfiedProgramAttributes( const MathematicalProgram& prog) { std::string explanation; CheckAttributes(prog, &explanation); return explanation; } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/integer_inequality_solver.cc
#include "drake/solvers/integer_inequality_solver.h" #include <algorithm> #include <functional> #include <vector> #include <Eigen/Dense> #include "drake/common/drake_assert.h" namespace drake { namespace solvers { namespace { using IntegerVectorList = std::vector<std::vector<int>>; using SolutionList = Eigen::Matrix<int, -1, -1, Eigen::RowMajor>; bool IsElementwiseNonnegative(const Eigen::MatrixXi& A) { return (A.array() >= 0).all(); } bool IsElementwiseNonpositive(const Eigen::MatrixXi& A) { return (A.array() <= 0).all(); } /* Construct finite-set of admissible values, i.e., an alphabet, for each * coordinate from specified upper and lower bounds, e.g., a lower bound and * upper bound of -1, 2 translates to the alphabet [-1, 0, 1, 2]. This function * exists only to simplify the external interface. */ IntegerVectorList BuildAlphabetFromBounds(const Eigen::VectorXi& lower_bound, const Eigen::VectorXi& upper_bound) { DRAKE_ASSERT(lower_bound.size() == upper_bound.size()); IntegerVectorList alphabet(lower_bound.size()); int cnt = 0; for (auto& col_alphabet : alphabet) { DRAKE_ASSERT(lower_bound(cnt) <= upper_bound(cnt)); for (int i = lower_bound(cnt); i <= upper_bound(cnt); i++) { col_alphabet.push_back(i); } cnt++; } return alphabet; } /* If a column Ai of A is nonnegative (resp. nonpositive), then {Ai*z : z ∈ Qi} * is totally ordered, where Qi is the alphabet for the iᵗʰ component. In other * words, the inequalities Ai z1 ≤ Ai z2 ≤ ... ≤ Ai zm hold for zj ∈ Qi * sorted in ascending (resp. descending) order. This allows for infeasibility * propagation in the recursive enumeration of integer solutions. This function * detects when {Ai z : z ∈ Qi} is totally ordered and then sorts the alphabet * using this ordering. */ enum class ColumnType { Nonnegative, Nonpositive, Indefinite }; std::vector<ColumnType> ProcessInputs(const Eigen::MatrixXi& A, IntegerVectorList* alphabet) { DRAKE_ASSERT(alphabet != nullptr); int cnt = 0; std::vector<ColumnType> column_type(A.cols(), ColumnType::Indefinite); for (auto& col_alphabet : *alphabet) { if (IsElementwiseNonnegative(A.col(cnt))) { std::sort(col_alphabet.begin(), col_alphabet.end()); column_type[cnt] = ColumnType::Nonnegative; } else if (IsElementwiseNonpositive(A.col(cnt))) { std::sort(col_alphabet.begin(), col_alphabet.end(), std::greater<int>()); column_type[cnt] = ColumnType::Nonpositive; } cnt++; } return column_type; } /* Given an integer z and a list of integer vectors V, constructs * the Cartesian product (v, z) for all v ∈ V */ SolutionList CartesianProduct(const SolutionList& V, int z) { SolutionList cart_products(V.rows(), V.cols() + 1); if (V.rows() > 0) { if (V.cols() == 0) { cart_products.setConstant(z); } else { cart_products << V, SolutionList::Constant(V.rows(), 1, z); } } return cart_products; } SolutionList VerticalStack(const SolutionList& A, const SolutionList& B) { DRAKE_ASSERT(A.cols() == B.cols()); if (A.rows() == 0) { return B; } if (B.rows() == 0) { return A; } SolutionList Y(A.rows() + B.rows(), B.cols()); Y << A, B; return Y; } /* Find each solution (x(1), x(2), ..., x(n)) to Ax <= b when x(i) can only take on values in a finite alphabet Qi, e.g., Qi = {1, 2, 3, 8, 9}. We do this by recursively enumerating the solutions to A (x(1), x(2), ..., x(n-1) ) <= (b - A_n x_n) for all values of x(n). If the column vectors {An*z : z ∈ Qn} are totally ordered, we propagate infeasibility: if no solutions exist when x(n) = z, then no solution can exist if x(n) takes on values larger than z (in the ordering). We assume the function "ProcessInputs" was previously called to sort the alphabet in ascending order. */ // TODO(frankpermenter): Update to use preallocated memory SolutionList FeasiblePoints(const Eigen::MatrixXi& A, const Eigen::VectorXi& b, const IntegerVectorList& column_alphabets, const std::vector<ColumnType>& column_type, int last_free_var_pos) { DRAKE_ASSERT((last_free_var_pos >= 0) && (last_free_var_pos < A.cols())); DRAKE_ASSERT(column_type.size() == static_cast<std::vector<ColumnType>::size_type>(A.cols())); SolutionList feasible_points(0, last_free_var_pos + 1); for (const auto& value : column_alphabets[last_free_var_pos]) { SolutionList new_feasible_points; if (last_free_var_pos == 0) { if (IsElementwiseNonnegative(b - A.col(0) * value)) { new_feasible_points.resize(1, 1); new_feasible_points(0, 0) = value; } } else { new_feasible_points = CartesianProduct( FeasiblePoints(A, b - A.col(last_free_var_pos) * value, column_alphabets, column_type, last_free_var_pos - 1), value); } if (new_feasible_points.rows() > 0) { feasible_points = VerticalStack(feasible_points, new_feasible_points); } else { // Propagate infeasibility: if this test passes, then no feasible // points exist for remaining values in the alphabet. if (column_type[last_free_var_pos] != ColumnType::Indefinite) { return feasible_points; } } } return feasible_points; } } // namespace SolutionList EnumerateIntegerSolutions( const Eigen::Ref<const Eigen::MatrixXi>& A, const Eigen::Ref<const Eigen::VectorXi>& b, const Eigen::Ref<const Eigen::VectorXi>& lower_bound, const Eigen::Ref<const Eigen::VectorXi>& upper_bound) { DRAKE_DEMAND(A.rows() == b.rows()); DRAKE_DEMAND(A.cols() == lower_bound.size()); DRAKE_DEMAND(A.cols() == upper_bound.size()); auto variable_alphabets = BuildAlphabetFromBounds(lower_bound, upper_bound); // Returns type (nonnegative, nonpositive, or indefinite) of A's // columns and sorts the variable alphabet accordingly. auto column_type = ProcessInputs(A, &variable_alphabets); return FeasiblePoints(A, b, variable_alphabets, column_type, A.cols() - 1); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/non_convex_optimization_util.cc
#include "drake/solvers/non_convex_optimization_util.h" #include <limits> #include "drake/math/quadratic_form.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solve.h" namespace drake { namespace solvers { std::pair<Eigen::MatrixXd, Eigen::MatrixXd> DecomposeNonConvexQuadraticForm( const Eigen::Ref<const Eigen::MatrixXd>& Q) { if (Q.rows() != Q.cols()) { throw std::runtime_error("Q is not a square matrix."); } // If Q is positive semidefinite, then Q1 = Q and Q2 = 0. // If Q is negative semidefinite, then Q1 = 0 and Q2 = -Q. const Eigen::MatrixXd Q_sym = (Q + Q.transpose()) / 2; Eigen::LDLT<Eigen::MatrixXd> ldlt(Q_sym); if (ldlt.info() == Eigen::Success) { if (ldlt.isPositive()) { Eigen::MatrixXd Q2 = Eigen::MatrixXd::Zero(Q.rows(), Q.rows()); return std::make_pair(Q_sym, Q2); } else if (ldlt.isNegative()) { Eigen::MatrixXd Q1 = Eigen::MatrixXd::Zero(Q.rows(), Q.rows()); return std::make_pair(Q1, -Q_sym); } } MathematicalProgram prog; auto Q1 = prog.NewSymmetricContinuousVariables(Q.rows(), "Q1"); auto Q2 = prog.NewSymmetricContinuousVariables(Q.rows(), "Q2"); symbolic::Variable s = prog.NewContinuousVariables<1>("s")(0); prog.AddPositiveSemidefiniteConstraint(Q1); prog.AddPositiveSemidefiniteConstraint(Q2); prog.AddLinearConstraint(Q1.array() - Q2.array() == Q_sym.array()); prog.AddLinearConstraint(symbolic::Expression(s) >= Q1.cast<symbolic::Expression>().trace()); prog.AddLinearConstraint(symbolic::Expression(s) >= Q2.cast<symbolic::Expression>().trace()); prog.AddCost(s); const MathematicalProgramResult result = Solve(prog); // This problem should always be feasible, since we can choose Q1 to a large // diagonal matrix, and Q2 will also have large diagonal entries. Both Q1 and // Q2 are diagonally dominant, thus they are both positive definite. // Due to positive definiteness, both trace(Q1) and trace(Q2) are // non-negative, so min(max(trace(Q1), trace(Q2)) is lower bounded. Hence, // this optimal cost is not un-bounded. DRAKE_DEMAND(result.is_success()); auto Q1_sol = result.GetSolution(Q1); auto Q2_sol = result.GetSolution(Q2); return std::make_pair(Q1_sol, Q2_sol); } std::tuple<Binding<LinearConstraint>, std::vector<Binding<RotatedLorentzConeConstraint>>, VectorXDecisionVariable> AddRelaxNonConvexQuadraticConstraintInTrustRegion( MathematicalProgram* prog, const Eigen::Ref<const VectorXDecisionVariable>& x, const Eigen::Ref<const Eigen::MatrixXd>& Q1, const Eigen::Ref<const Eigen::MatrixXd>& Q2, const Eigen::Ref<const VectorXDecisionVariable>& y, const Eigen::Ref<const Eigen::VectorXd>& p, double lower_bound, double upper_bound, const Eigen::Ref<const Eigen::VectorXd>& linearization_point, double trust_region_gap) { const auto& x0 = linearization_point; if (Q1.rows() != Q1.cols()) { throw std::runtime_error("Q1 should be a square matrix."); } if (Q2.rows() != Q2.cols()) { throw std::runtime_error("Q2 should be a square matrix."); } if (Q1.rows() != Q2.rows() || Q1.rows() != x0.rows() || Q1.rows() != x.rows() || p.rows() != y.rows()) { throw std::runtime_error( "The dimensions of the inputs are not consistent."); } if (trust_region_gap <= 0) { throw std::runtime_error("trust_region_gap should be positive."); } if (lower_bound > upper_bound) { throw std::runtime_error( "lower_bound should be no larger than upper_bound"); } const bool Q1_is_zero = (Q1.array() == 0).all(); const bool Q2_is_zero = (Q2.array() == 0).all(); // Both Q1 and Q2 are zero. if (Q1_is_zero && Q2_is_zero) { throw std::runtime_error( "Both Q1 and Q2 are zero. The constraint is linear. The user should " "not call this function to relax a linear constraint."); } // Only Q1 is zero. const double psd_tol = 1E-15; if (Q1_is_zero && std::isinf(upper_bound)) { throw std::runtime_error( "Q1 is zero, and upper_bound is infinity. The constraint is convex. " "The user should not call this function to relax a convex " "constraint."); } if (Q2_is_zero && std::isinf(lower_bound)) { throw std::runtime_error( "Q2 is zero, and lower_bound is -infinity. The constraint is convex. " "The user should not call this function to relax a convex constraint."); } if (Q1_is_zero || Q2_is_zero) { const double z_coeff = Q1_is_zero ? -1 : 1; const Eigen::Matrix2d nonzero_Q = Q1_is_zero ? Q2 : Q1; auto z = prog->NewContinuousVariables<1>("z"); Binding<RotatedLorentzConeConstraint> lorentz_cone1 = prog->AddRotatedLorentzConeConstraint(z(0), 1, x.dot(nonzero_Q * x), psd_tol); Eigen::Vector2d linear_lb(x0.dot(nonzero_Q * x0) - trust_region_gap, lower_bound); Eigen::Vector2d linear_ub(std::numeric_limits<double>::infinity(), upper_bound); Vector2<symbolic::Expression> linear_expr(2 * x0.dot(nonzero_Q * x) - z(0), p.dot(y) + z_coeff * z(0)); Binding<LinearConstraint> linear_constraint = prog->AddConstraint(internal::BindingDynamicCast<LinearConstraint>( internal::ParseConstraint(linear_expr, linear_lb, linear_ub))); std::vector<Binding<RotatedLorentzConeConstraint>> lorentz_cones{ {lorentz_cone1}}; return std::make_tuple(linear_constraint, lorentz_cones, z); } // Neither Q1 nor Q2 is zero. auto z = prog->NewContinuousVariables<2>("z"); Vector3<symbolic::Expression> linear_expressions; linear_expressions << z(0) - z(1) + p.dot(y), z(0) - 2 * x0.dot(Q1 * x), z(1) - 2 * x0.dot(Q2 * x); const Eigen::Vector3d linear_lb(lower_bound, -std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity()); const Eigen::Vector3d linear_ub(upper_bound, -x0.dot(Q1 * x0) + trust_region_gap, -x0.dot(Q2 * x0) + trust_region_gap); Binding<LinearConstraint> linear_constraint = prog->AddConstraint(internal::BindingDynamicCast<LinearConstraint>( internal::ParseConstraint(linear_expressions, linear_lb, linear_ub))); const Eigen::MatrixXd A1 = math::DecomposePSDmatrixIntoXtransposeTimesX(Q1, psd_tol); const Eigen::MatrixXd A2 = math::DecomposePSDmatrixIntoXtransposeTimesX(Q2, psd_tol); VectorX<symbolic::Expression> lorentz_cone_expr1(2 + A1.rows()); VectorX<symbolic::Expression> lorentz_cone_expr2(2 + A2.rows()); lorentz_cone_expr1 << 1, z(0), A1 * x; lorentz_cone_expr2 << 1, z(1), A2 * x; Binding<RotatedLorentzConeConstraint> lorentz_cone_constraint1 = prog->AddRotatedLorentzConeConstraint(lorentz_cone_expr1); Binding<RotatedLorentzConeConstraint> lorentz_cone_constraint2 = prog->AddRotatedLorentzConeConstraint(lorentz_cone_expr2); std::vector<Binding<RotatedLorentzConeConstraint>> lorentz_cones{ {lorentz_cone_constraint1, lorentz_cone_constraint2}}; return std::make_tuple(linear_constraint, lorentz_cones, z); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/semidefinite_relaxation.cc
#include "drake/solvers/semidefinite_relaxation.h" #include <algorithm> #include <functional> #include <initializer_list> #include <limits> #include <map> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "drake/common/fmt_eigen.h" #include "drake/math/matrix_util.h" #include "drake/solvers/program_attribute.h" namespace drake { namespace solvers { using Eigen::MatrixXd; using Eigen::SparseMatrix; using Eigen::Triplet; using Eigen::VectorXd; using symbolic::Expression; using symbolic::Variable; using symbolic::Variables; namespace { const double kInf = std::numeric_limits<double>::infinity(); // TODO(AlexandreAmice) Move all these methods to // semidefinite_relaxation_internal. // Validate that we can compute the semidefinite relaxation of prog. void ValidateProgramIsSupported(const MathematicalProgram& prog) { std::string unsupported_message{}; const ProgramAttributes supported_attributes( std::initializer_list<ProgramAttribute>{ ProgramAttribute::kLinearCost, ProgramAttribute::kQuadraticCost, ProgramAttribute::kLinearConstraint, ProgramAttribute::kLinearEqualityConstraint, ProgramAttribute::kQuadraticConstraint}); if (!AreRequiredAttributesSupported(prog.required_capabilities(), supported_attributes, &unsupported_message)) { throw std::runtime_error(fmt::format( "MakeSemidefiniteRelaxation() does not (yet) support this program: {}.", unsupported_message)); } } // Check whether the program prog has any non-convex quadratic costs or // constraints. bool CheckProgramHasNonConvexQuadratics(const MathematicalProgram& prog) { return std::any_of(prog.quadratic_costs().begin(), prog.quadratic_costs().end(), [](const auto& cost) { return !cost.evaluator()->is_convex(); }) || std::any_of(prog.quadratic_constraints().begin(), prog.quadratic_constraints().end(), [](const auto& constraint) { return !constraint.evaluator()->is_convex(); }); } // Given a mapping from decision variables in a program to indices, return all // the indices corresponding to the variable vars. This method is useful as in // DoMakeSemidefiniteRelaxation, we sort the decision variables in the // semidefinite variables (and hence the implied constraints). std::vector<int> FindDecisionVariableIndices( const std::map<Variable, int>& variables_to_sorted_indices, const VectorXDecisionVariable& vars) { std::vector<int> indices; indices.reserve(vars.rows()); for (const auto& v : vars) { indices.emplace_back(variables_to_sorted_indices.at(v)); } return indices; } // Iterate over the quadratic costs and constraints in prog, remove them if // present in the relaxation, and add an equivalent linear cost or constraint on // the semidefinite variable X. The map variables_to_sorted_indices maps the // decision variables in prog to their index in the last column of X. void DoLinearizeQuadraticCostsAndConstraints( const MathematicalProgram& prog, const MatrixXDecisionVariable& X, const std::map<Variable, int>& variables_to_sorted_indices, MathematicalProgram* relaxation) { // Returns the {a, vars} in relaxation, such that a' vars = 0.5*tr(QY). This // assumes Q=Q', which is ensured by QuadraticCost and QuadraticConstraint. auto half_trace_QY = [&X, &variables_to_sorted_indices]( const Eigen::MatrixXd& Q, const VectorXDecisionVariable& binding_vars) -> std::pair<VectorXd, VectorX<Variable>> { const int N = binding_vars.size(); const int num_vars = N * (N + 1) / 2; const std::vector<int> indices = FindDecisionVariableIndices(variables_to_sorted_indices, binding_vars); VectorXd a = VectorXd::Zero(num_vars); VectorX<Variable> y(num_vars); int count = 0; for (int i = 0; i < N; ++i) { for (int j = 0; j <= i; ++j) { // tr(QY) = ∑ᵢ ∑ⱼ Qᵢⱼ Yⱼᵢ. a[count] = ((i == j) ? 0.5 : 1.0) * Q(i, j); y[count] = X(indices[i], indices[j]); ++count; } } return {a, y}; }; // Remove the quadratic cost in relaxation and replace it with a linear cost // on the semidefinite variables i.e. // 0.5 y'Qy + b'y + c => 0.5 tr(QY) + b'y + c for (const auto& binding : prog.quadratic_costs()) { relaxation->RemoveCost(binding); const int N = binding.variables().size(); const int num_vars = N + (N * (N + 1) / 2); std::pair<VectorXd, VectorX<Variable>> quadratic_terms = half_trace_QY(binding.evaluator()->Q(), binding.variables()); VectorXd a(num_vars); VectorX<Variable> vars(num_vars); a << quadratic_terms.first, binding.evaluator()->b(); vars << quadratic_terms.second, binding.variables(); relaxation->AddLinearCost(a, binding.evaluator()->c(), vars); } // Remove the quadratic constraints and replace them with a linear constraint // on the semidefinite varaibles i.e. // lb ≤ 0.5 y'Qy + b'y ≤ ub => lb ≤ 0.5 tr(QY) + b'y ≤ ub for (const auto& binding : prog.quadratic_constraints()) { relaxation->RemoveConstraint(binding); const int N = binding.variables().size(); const int num_vars = N + (N * (N + 1) / 2); std::pair<VectorXd, VectorX<Variable>> quadratic_terms = half_trace_QY(binding.evaluator()->Q(), binding.variables()); VectorXd a(num_vars); VectorX<Variable> vars(num_vars); a << quadratic_terms.first, binding.evaluator()->b(); vars << quadratic_terms.second, binding.variables(); relaxation->AddLinearConstraint(a.transpose(), binding.evaluator()->lower_bound(), binding.evaluator()->upper_bound(), vars); } } // Aggregate all the finite linear constraints in the program into a single // expression Ay ≤ b, which can be expressed as [A, -b][y; 1] ≤ 0. // We add the implied linear constraint [A,-b]X[A,-b]ᵀ ≤ 0 on the variable X to // the relaxation. The map variables_to_sorted_indices maps the // decision variables in prog to their index in the last column of X. void DoAddImpliedLinearConstraints( const MathematicalProgram& prog, const MatrixXDecisionVariable& X, const std::map<Variable, int>& variables_to_sorted_indices, MathematicalProgram* relaxation) { // Assemble one big Ay <= b matrix from all bounding box constraints // and linear constraints // TODO(bernhardpg): Consider special-casing linear equality constraints // that are added as bounding box or linear constraints with lb == ub int num_constraints = 0; int nnz = 0; for (const auto& binding : prog.bounding_box_constraints()) { for (int i = 0; i < binding.evaluator()->num_constraints(); ++i) { if (std::isfinite(binding.evaluator()->lower_bound()[i])) { ++num_constraints; } if (std::isfinite(binding.evaluator()->upper_bound()[i])) { ++num_constraints; } } nnz += binding.evaluator()->get_sparse_A().nonZeros(); } for (const auto& binding : prog.linear_constraints()) { for (int i = 0; i < binding.evaluator()->num_constraints(); ++i) { if (std::isfinite(binding.evaluator()->lower_bound()[i])) { ++num_constraints; } if (std::isfinite(binding.evaluator()->upper_bound()[i])) { ++num_constraints; } } nnz += binding.evaluator()->get_sparse_A().nonZeros(); } std::vector<Triplet<double>> A_triplets; A_triplets.reserve(nnz); SparseMatrix<double> A(num_constraints, prog.num_vars()); VectorXd b(num_constraints); int constraint_idx = 0; for (const auto& binding : prog.bounding_box_constraints()) { const std::vector<int> indices = FindDecisionVariableIndices( variables_to_sorted_indices, binding.variables()); for (int i = 0; i < binding.evaluator()->num_constraints(); ++i) { if (std::isfinite(binding.evaluator()->lower_bound()[i])) { A_triplets.push_back(Triplet<double>(constraint_idx, indices[i], -1.0)); b(constraint_idx++) = -binding.evaluator()->lower_bound()[i]; } if (std::isfinite(binding.evaluator()->upper_bound()[i])) { A_triplets.push_back(Triplet<double>(constraint_idx, indices[i], 1.0)); b(constraint_idx++) = binding.evaluator()->upper_bound()[i]; } } } for (const auto& binding : prog.linear_constraints()) { const std::vector<int> indices = FindDecisionVariableIndices( variables_to_sorted_indices, binding.variables()); // TODO(hongkai-dai): Consider using the SparseMatrix iterators. for (int i = 0; i < binding.evaluator()->num_constraints(); ++i) { if (std::isfinite(binding.evaluator()->lower_bound()[i])) { for (int j = 0; j < binding.evaluator()->num_vars(); ++j) { if (binding.evaluator()->get_sparse_A().coeff(i, j) != 0) { A_triplets.push_back(Triplet<double>( constraint_idx, indices[j], -binding.evaluator()->get_sparse_A().coeff(i, j))); } } b(constraint_idx++) = -binding.evaluator()->lower_bound()[i]; } if (std::isfinite(binding.evaluator()->upper_bound()[i])) { for (int j = 0; j < binding.evaluator()->num_vars(); ++j) { if (binding.evaluator()->get_sparse_A().coeff(i, j) != 0) { A_triplets.push_back(Triplet<double>( constraint_idx, indices[j], binding.evaluator()->get_sparse_A().coeff(i, j))); } } b(constraint_idx++) = binding.evaluator()->upper_bound()[i]; } } } A.setFromTriplets(A_triplets.begin(), A_triplets.end()); // 0 ≤ (Ay-b)(Ay-b)ᵀ, implemented with // -bbᵀ ≤ AYAᵀ - b(Ay)ᵀ - (Ay)bᵀ. // TODO(russt): Avoid the symbolic computation here. // TODO(russt): Avoid the dense matrix. const MatrixX<Expression> AYAT = A * X.topLeftCorner(prog.num_vars(), prog.num_vars()) * A.transpose(); const VectorX<Variable> y = X.col(prog.num_vars()).head(prog.num_vars()); const VectorX<Expression> rhs_flat_tril = math::ToLowerTriangularColumnsFromMatrix(AYAT - b * (A * y).transpose() - A * y * b.transpose()); const VectorXd bbT_flat_tril = math::ToLowerTriangularColumnsFromMatrix(-b * b.transpose()); relaxation->AddLinearConstraint( rhs_flat_tril, bbT_flat_tril, VectorXd::Constant(bbT_flat_tril.size(), kInf)); } // For every equality constraint Ay = b in prog, add the implied linear equality // constraint [A, -b]X = 0 on the semidefinite relaxation variable X to the // relaxation. The map variables_to_sorted_indices maps the decision variables // in prog to their index in the last column of X. void DoAddImpliedLinearEqualityConstraints( const MathematicalProgram& prog, const MatrixXDecisionVariable& X, const std::map<Variable, int>& variables_to_sorted_indices, MathematicalProgram* relaxation) { // Linear equality constraints. // Ay = b => (Ay-b)yᵀ = Ayyᵀ - byᵀ = 0. for (const auto& binding : prog.linear_equality_constraints()) { const int N = binding.variables().size(); const std::vector<int> indices = FindDecisionVariableIndices( variables_to_sorted_indices, binding.variables()); VectorX<Variable> vars(N + 1); // Add the constraints one column at a time: // Ayx_j - bx_j = 0. MatrixX<double> Ab(binding.evaluator()->num_constraints(), N + 1); // TODO(Alexandre.Amice) make this only access the sparse matrix. Ab.leftCols(N) = binding.evaluator()->GetDenseA(); Ab.col(N) = -binding.evaluator()->lower_bound(); // We don't need to do the last column of X. for (int j = 0; j < static_cast<int>(X.cols()) - 1; ++j) { for (int i = 0; i < N; ++i) { vars[i] = X(indices[i], j); } vars[N] = X(prog.num_vars(), j); relaxation->AddLinearEqualityConstraint( Ab, VectorXd::Zero(binding.evaluator()->num_constraints()), vars); } } } // Constructs the semidefinite relaxation of the program prog and adds it to // relaxation. We assume that the program attributes of prog are already // validated and that relaxation already contains all the variables and // constraints of prog. The variable one is already constrained to be equal to // one. This is passed so it can be re-used across semidefinite variables in the // sparse version of MakeSemidefiniteRelaxation. Returns the X matrix of the // semidefinite relaxation. MatrixXDecisionVariable DoMakeSemidefiniteRelaxation( const MathematicalProgram& prog, const Variable& one, MathematicalProgram* relaxation, std::optional<int> group_number = std::nullopt) { // Build a symmetric matrix X of decision variables using the original // program variables (so that GetSolution, etc, works using the original // variables). relaxation->AddDecisionVariables(prog.decision_variables()); MatrixX<Variable> X(prog.num_vars() + 1, prog.num_vars() + 1); // X = xxᵀ; x = [prog.decision_vars(); 1]. std::string name = group_number.has_value() ? fmt::format("Y{}", group_number.value()) : "Y"; X.topLeftCorner(prog.num_vars(), prog.num_vars()) = relaxation->NewSymmetricContinuousVariables(prog.num_vars(), name); // We sort the variables so that the matrix X is ordered in a predictable way. // This makes it easier when using the sparsity groups to make the // semidefinite matrices agree. VectorX<Variable> sorted_variables = prog.decision_variables(); std::sort(sorted_variables.data(), sorted_variables.data() + sorted_variables.size(), std::less<Variable>{}); X.topRightCorner(prog.num_vars(), 1) = sorted_variables; X.bottomLeftCorner(1, prog.num_vars()) = sorted_variables.transpose(); std::map<Variable, int> variables_to_sorted_indices; int i = 0; for (const auto& v : sorted_variables) { variables_to_sorted_indices[v] = i++; } // X(-1,-1) = 1. X(prog.num_vars(), prog.num_vars()) = one; // X ≽ 0. relaxation->AddPositiveSemidefiniteConstraint(X); DoLinearizeQuadraticCostsAndConstraints(prog, X, variables_to_sorted_indices, relaxation); DoAddImpliedLinearConstraints(prog, X, variables_to_sorted_indices, relaxation); DoAddImpliedLinearEqualityConstraints(prog, X, variables_to_sorted_indices, relaxation); return X; } } // namespace std::unique_ptr<MathematicalProgram> MakeSemidefiniteRelaxation( const MathematicalProgram& prog) { ValidateProgramIsSupported(prog); auto relaxation = prog.Clone(); const Variable one("one"); relaxation->AddDecisionVariables(Vector1<Variable>(one)); relaxation->AddLinearEqualityConstraint(one, 1); DoMakeSemidefiniteRelaxation(prog, one, relaxation.get()); return relaxation; } std::unique_ptr<MathematicalProgram> MakeSemidefiniteRelaxation( const MathematicalProgram& prog, const std::vector<symbolic::Variables>& variable_groups) { auto relaxation = prog.Clone(); const Variable one("one"); relaxation->AddDecisionVariables(Vector1<Variable>(one)); relaxation->AddLinearEqualityConstraint(one, 1); // The semidefinite relaxation of each variable group will be computed // individually and any variables which overlap in the programs will later be // made to agree using equality constraints. The container programs in this // map are used to store all the costs and constraints needed to compute the // semidefinite relaxation of each variable group. std::map<symbolic::Variables, solvers::MathematicalProgram> groups_to_container_programs; std::map<symbolic::Variables, MatrixXDecisionVariable> groups_to_psd_variables; for (const auto& group : variable_groups) { groups_to_container_programs.try_emplace(group); VectorXDecisionVariable group_vec(group.size()); int i = 0; for (const auto& v : group) { group_vec(i) = v; ++i; } groups_to_container_programs.at(group).AddDecisionVariables(group_vec); } for (const auto& constraint : prog.GetAllConstraints()) { const Variables constraint_variables{constraint.variables()}; for (const auto& group : variable_groups) { if (constraint_variables.IsSubsetOf(group)) { // There is no need to add constraint_variables to the // container_program, since the variables are a subset of the group and // therefore already in the program. groups_to_container_programs.at(group).AddConstraint(constraint); } } } for (const auto& cost : prog.GetAllCosts()) { const Variables cost_variables{cost.variables()}; for (const auto& group : variable_groups) { if (cost_variables.IsSubsetOf(group)) { groups_to_container_programs.at(group).AddCost(cost); // If the variables in this cost are a subset of multiple variable // groups, then these variables will correspond to submatrices of the // relaxed PSD variables. Since later, we will enforce that all these // submatrices be equal, we only need to add the cost exactly once. break; } } } int group_number = 0; for (const auto& [group, container_program] : groups_to_container_programs) { groups_to_psd_variables.emplace( group, DoMakeSemidefiniteRelaxation(container_program, one, relaxation.get(), group_number)); ++group_number; } // Now constrain the semidefinite variables to agree where they overlap. for (auto it = groups_to_psd_variables.begin(); it != groups_to_psd_variables.end(); ++it) { for (auto it2 = std::next(it); it2 != groups_to_psd_variables.end(); ++it2) { const Variables common_variables = intersect(it->first, it2->first); if (!common_variables.empty()) { auto get_submatrix_of_variables = [&common_variables](const MatrixXDecisionVariable& X) { std::set<int> submatrix_indices; for (const auto& v : common_variables) { for (int i = 0; i < X.rows() - 1; ++i) { if (X(i, X.cols() - 1).equal_to(v)) { submatrix_indices.insert(i); break; } } } return math::ExtractPrincipalSubmatrix(X, submatrix_indices); }; relaxation->AddLinearEqualityConstraint( get_submatrix_of_variables(it->second) == get_submatrix_of_variables(it2->second)); } } } if (CheckProgramHasNonConvexQuadratics(*relaxation)) { throw std::runtime_error( "There is a non-convex cost or constraint in the program whose " "variables do not overlap with any variable groups. Therefore, these " "costs or constraints would not be converted to convex, semidefinite " "constraints and so the returned program would not be convex. Consider " "further specifying the variable groups."); } return relaxation; } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/mixed_integer_optimization_util.h
#pragma once #include <string> #include <utility> #include "drake/common/fmt.h" #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { /** * Return ⌈log₂(n)⌉, namely the minimal integer no smaller than log₂(n), with * base 2. * @param n A positive integer. * @return The minimal integer no smaller than log₂(n). */ constexpr int CeilLog2(int n) { return n == 1 ? 0 : 1 + CeilLog2((n + 1) / 2); } /** * The size of the new binary variables in the compile time, for Special Ordered * Set of type 2 (SOS2) constraint. The SOS2 constraint says that * <pre> * λ(0) + ... + λ(n) = 1 * ∀i. λ(i) ≥ 0 * ∃ j ∈ {0, 1, ..., n-1}, s.t λ(j) + λ(j + 1) = 1 * </pre> * @tparam NumLambda The length of the lambda vector. NumLambda = n + 1. */ template <int NumLambda> struct LogarithmicSos2NewBinaryVariables { static constexpr int Rows = CeilLog2(NumLambda - 1); typedef VectorDecisionVariable<Rows> type; }; template <> struct LogarithmicSos2NewBinaryVariables<Eigen::Dynamic> { typedef VectorXDecisionVariable type; static const int Rows = Eigen::Dynamic; }; /** * Adds the special ordered set 2 (SOS2) constraint, * <pre> * λ(0) + ... + λ(n) = 1 * ∀i. λ(i) ≥ 0 * ∃ j ∈ {0, 1, ..., n-1}, s.t λ(i) = 0 if i ≠ j and i ≠ j + 1 * </pre> * Namely at most two entries in λ can be strictly positive, and these two * entries have to be adjacent. All other λ should be zero. Moreover, the * non-zero λ satisfies * λ(j) + λ(j + 1) = 1. * We will need to add ⌈log₂(n - 1)⌉ binary variables, where n is the number of * rows in λ. For more information, please refer to * Modeling Disjunctive Constraints with a Logarithmic Number of Binary * Variables and Constraints * by J. Vielma and G. Nemhauser, 2011. * @param prog Add the SOS2 constraint to this mathematical program. * @param lambda At most two entries in λ can be strictly positive, and these * two entries have to be adjacent. All other entries are zero. * @return y The newly added binary variables. The assignment of the binary * variable y implies which two λ can be strictly positive. * With a binary assignment on y, and suppose the integer M corresponds to * (y(0), y(1), ..., y(⌈log₂(n - 1)⌉)) in Gray code, then only λ(M) and λ(M + 1) * can be non-zero. For example, if the assignment of y = (1, 1), in Gray code, * (1, 1) represents integer 2, so only λ(2) and λ(3) can be strictly positive. */ template <typename Derived> typename std::enable_if_t< drake::is_eigen_vector_of<Derived, symbolic::Expression>::value, typename LogarithmicSos2NewBinaryVariables< Derived::RowsAtCompileTime>::type> AddLogarithmicSos2Constraint(MathematicalProgram* prog, const Eigen::MatrixBase<Derived>& lambda, const std::string& binary_variable_name = "y") { const int binary_variable_size = CeilLog2(lambda.rows() - 1); const auto y = prog->NewBinaryVariables< LogarithmicSos2NewBinaryVariables<Derived::RowsAtCompileTime>::Rows, 1>( binary_variable_size, 1, binary_variable_name); AddLogarithmicSos2Constraint(prog, lambda, y.template cast<symbolic::Expression>()); return y; } /** Adds the special ordered set 2 (SOS2) constraint, * @see AddLogarithmicSos2Constraint. */ void AddLogarithmicSos2Constraint( MathematicalProgram* prog, const Eigen::Ref<const VectorX<symbolic::Expression>>& lambda, const Eigen::Ref<const VectorX<symbolic::Expression>>& y); /** * Adds the special ordered set 2 (SOS2) constraint. y(i) takes binary values * (either 0 or 1). * <pre> * y(i) = 1 => λ(i) + λ(i + 1) = 1. * </pre> * @see AddLogarithmicSos2Constraint for a complete explanation on SOS2 * constraint. * @param prog The optimization program to which the SOS2 constraint is added. * @param lambda At most two entries in λ can be strictly positive, and these * two entries have to be adjacent. All other entries are zero. Moreover, these * two entries should sum up to 1. * @param y y(i) takes binary value, and determines which two entries in λ can * be strictly positive. Throw a runtime error if y.rows() != lambda.rows() - 1. */ void AddSos2Constraint( MathematicalProgram* prog, const Eigen::Ref<const VectorX<symbolic::Expression>>& lambda, const Eigen::Ref<const VectorX<symbolic::Expression>>& y); /** * Adds the special ordered set of type 1 (SOS1) constraint. Namely * <pre> * λ(0) + ... + λ(n-1) = 1 * λ(i) ≥ 0 ∀i * ∃ j ∈ {0, 1, ..., n-1}, s.t λ(j) = 1 * </pre> * where one and only one of λ(i) is 1, all other λ(j) are 0. * We will need to add ⌈log₂(n)⌉ binary variables, where n is the number of * rows in λ. For more information, please refer to * Modeling Disjunctive Constraints with a Logarithmic Number of Binary * Variables and Constraints * by J. Vielma and G. Nemhauser, 2011. * @param prog The program to which the SOS1 constraint is added. * @param lambda lambda is in SOS1. * @param y The binary variables indicating which λ is positive. For a given * assignment on the binary variable `y`, if (y(0), ..., y(⌈log₂(n)⌉) represents * integer M in `binary_encoding`, then only λ(M) is positive. Namely, if * (y(0), ..., y(⌈log₂(n)⌉) equals to binary_encoding.row(M), then λ(M) = 1 * @param binary_encoding A n x ⌈log₂(n)⌉ matrix. binary_encoding.row(i) * represents integer i. No two rows of `binary_encoding` can be the same. * @throws std::exception if @p binary_encoding has a non-binary entry (0, * 1). */ void AddLogarithmicSos1Constraint( MathematicalProgram* prog, const Eigen::Ref<const VectorX<symbolic::Expression>>& lambda, const Eigen::Ref<const VectorXDecisionVariable>& y, const Eigen::Ref<const Eigen::MatrixXi>& binary_encoding); /** * Adds the special ordered set of type 1 (SOS1) constraint. Namely * <pre> * λ(0) + ... + λ(n-1) = 1 * λ(i) ≥ 0 ∀i * ∃ j ∈ {0, 1, ..., n-1}, s.t λ(j) = 1 * </pre> * where one and only one of λ(i) is 1, all other λ(j) are 0. * We will need to add ⌈log₂(n)⌉ binary variables, where n is the number of * rows in λ. For more information, please refer to * Modeling Disjunctive Constraints with a Logarithmic Number of Binary * Variables and Constraints * by J. Vielma and G. Nemhauser, 2011. * @param prog The program to which the SOS1 constraint is added. * @param num_lambda n in the documentation above. * @return (lambda, y) lambda is λ in the documentation above. Notice that * λ are declared as continuous variables, but they only admit binary * solutions. y are binary variables of size ⌈log₂(n)⌉. * When this sos1 constraint is satisfied, suppose that * λ(i)=1 and λ(j)=0 ∀ j≠i, then y is the Reflected Gray code of i. For example, * suppose n = 8, i = 5, then y is a vector of size ⌈log₂(n)⌉ = 3, and the value * of y is (1, 1, 0) which equals to 5 according to reflected Gray code. */ std::pair<VectorX<symbolic::Variable>, VectorX<symbolic::Variable>> AddLogarithmicSos1Constraint(MathematicalProgram* prog, int num_lambda); /** * For a continuous variable whose range is cut into small intervals, we will * use binary variables to represent which interval the continuous variable is * in. We support two representations, either using logarithmic number of binary * variables, or linear number of binary variables. For more details, @see * AddLogarithmicSos2Constraint and AddSos2Constraint */ enum class IntervalBinning { kLogarithmic, kLinear }; std::string to_string(IntervalBinning interval_binning); std::ostream& operator<<(std::ostream& os, const IntervalBinning& binning); /** * Add constraints to the optimization program, such that the bilinear product * x * y is approximated by w, using Special Ordered Set of Type 2 (sos2) * constraint. * To do so, we assume that the range of x is [x_min, x_max], and the range of y * is [y_min, y_max]. We first consider two arrays φˣ, φʸ, satisfying * ``` * x_min = φˣ₀ < φˣ₁ < ... < φˣₘ = x_max * y_min = φʸ₀ < φʸ₁ < ... < φʸₙ = y_max * ``` * , and divide the range of x into intervals * [φˣ₀, φˣ₁], [φˣ₁, φˣ₂], ... , [φˣₘ₋₁, φˣₘ] * and the range of y into intervals * [φʸ₀, φʸ₁], [φʸ₁, φʸ₂], ... , [φʸₙ₋₁, φʸₙ]. The xy plane is thus cut into * rectangles, with each rectangle as * [φˣᵢ, φˣᵢ₊₁] x [φʸⱼ, φʸⱼ₊₁]. The convex hull of the surface * z = x * y for x, y in each rectangle is a tetrahedron. We then approximate * the bilinear product x * y with w, such that (x, y, w) is in one of the * tetrahedrons. * * We use two different encoding schemes on the binary variables, to determine * which interval is active. We can choose either linear or logarithmic binning. * When using linear binning, for a variable with N intervals, we * use N binary variables, and B(i) = 1 indicates the variable is in the i'th * interval. When using logarithmic binning, we use ⌈log₂(N)⌉ binary variables. * If these binary variables represent integer M in the reflected Gray code, * then the continuous variable is in the M'th interval. * @param prog The program to which the bilinear product constraint is added * @param x The decision variable. * @param y The decision variable. * @param w The expression to approximate x * y * @param phi_x The end points of the intervals for `x`. * @param phi_y The end points of the intervals for `y`. * @param Bx The binary variables for the interval in which x stays encoded as * described above. * @param By The binary variables for the interval in which y stays encoded as * described above. * @param binning Determine whether to use linear binning or * logarithmic binning. * @return lambda The auxiliary continuous variables. * * The constraints we impose are * ``` * x = (φˣ)ᵀ * ∑ⱼ λᵢⱼ * y = (φʸ)ᵀ * ∑ᵢ λᵢⱼ * w = ∑ᵢⱼ φˣᵢ * φʸⱼ * λᵢⱼ * Both ∑ⱼ λᵢⱼ = λ.rowwise().sum() and ∑ᵢ λᵢⱼ = λ.colwise().sum() satisfy SOS2 * constraint. * ``` * * If x ∈ [φx(M), φx(M+1)] and y ∈ [φy(N), φy(N+1)], then only λ(M, N), * λ(M + 1, N), λ(M, N + 1) and λ(M+1, N+1) can be strictly positive, all other * λ(i, j) are zero. * * @note We DO NOT add the constraint * Bx(i) ∈ {0, 1}, By(j) ∈ {0, 1} * in this function. It is the user's responsibility to ensure that these * constraints are enforced. */ template <typename DerivedPhiX, typename DerivedPhiY, typename DerivedBx, typename DerivedBy> typename std::enable_if_t< is_eigen_vector_of<DerivedPhiX, double>::value && is_eigen_vector_of<DerivedPhiY, double>::value && is_eigen_vector_of<DerivedBx, symbolic::Expression>::value && is_eigen_vector_of<DerivedBy, symbolic::Expression>::value, MatrixDecisionVariable<DerivedPhiX::RowsAtCompileTime, DerivedPhiY::RowsAtCompileTime>> AddBilinearProductMcCormickEnvelopeSos2( MathematicalProgram* prog, const symbolic::Variable& x, const symbolic::Variable& y, const symbolic::Expression& w, const DerivedPhiX& phi_x, const DerivedPhiY& phi_y, const DerivedBx& Bx, const DerivedBy& By, IntervalBinning binning) { switch (binning) { case IntervalBinning::kLogarithmic: DRAKE_ASSERT(Bx.rows() == CeilLog2(phi_x.rows() - 1)); DRAKE_ASSERT(By.rows() == CeilLog2(phi_y.rows() - 1)); break; case IntervalBinning::kLinear: DRAKE_ASSERT(Bx.rows() == phi_x.rows() - 1); DRAKE_ASSERT(By.rows() == phi_y.rows() - 1); break; } const int num_phi_x = phi_x.rows(); const int num_phi_y = phi_y.rows(); auto lambda = prog->NewContinuousVariables<DerivedPhiX::RowsAtCompileTime, DerivedPhiY::RowsAtCompileTime>( num_phi_x, num_phi_y, "lambda"); prog->AddBoundingBoxConstraint(0, 1, lambda); symbolic::Expression x_convex_combination{0}; symbolic::Expression y_convex_combination{0}; symbolic::Expression w_convex_combination{0}; for (int i = 0; i < num_phi_x; ++i) { for (int j = 0; j < num_phi_y; ++j) { x_convex_combination += lambda(i, j) * phi_x(i); y_convex_combination += lambda(i, j) * phi_y(j); w_convex_combination += lambda(i, j) * phi_x(i) * phi_y(j); } } prog->AddLinearConstraint(x == x_convex_combination); prog->AddLinearConstraint(y == y_convex_combination); prog->AddLinearConstraint(w == w_convex_combination); switch (binning) { case IntervalBinning::kLogarithmic: AddLogarithmicSos2Constraint( prog, lambda.template cast<symbolic::Expression>().rowwise().sum(), Bx); AddLogarithmicSos2Constraint(prog, lambda.template cast<symbolic::Expression>() .colwise() .sum() .transpose(), By); break; case IntervalBinning::kLinear: AddSos2Constraint( prog, lambda.template cast<symbolic::Expression>().rowwise().sum(), Bx); AddSos2Constraint(prog, lambda.template cast<symbolic::Expression>() .colwise() .sum() .transpose(), By); break; } return lambda; } /** * Add constraints to the optimization program, such that the bilinear product * x * y is approximated by w, using Mixed Integer constraint with "Multiple * Choice" model. * To do so, we assume that the range of x is [x_min, x_max], and the range of y * is [y_min, y_max]. We first consider two arrays φˣ, φʸ, satisfying * ``` * x_min = φˣ₀ < φˣ₁ < ... < φˣₘ = x_max * y_min = φʸ₀ < φʸ₁ < ... < φʸₙ = y_max * ``` * , and divide the range of x into intervals * [φˣ₀, φˣ₁], [φˣ₁, φˣ₂], ... , [φˣₘ₋₁, φˣₘ] * and the range of y into intervals * [φʸ₀, φʸ₁], [φʸ₁, φʸ₂], ... , [φʸₙ₋₁, φʸₙ]. The xy plane is thus cut into * rectangles, with each rectangle as * [φˣᵢ, φˣᵢ₊₁] x [φʸⱼ, φʸⱼ₊₁]. The convex hull of the surface * z = x * y for x, y in each rectangle is a tetrahedron. We then approximate * the bilinear product x * y with w, such that (x, y, w) is in one of the * tetrahedrons. * @param prog The optimization problem to which the constraints will be added. * @param x A variable in the bilinear product. * @param y A variable in the bilinear product. * @param w The expression that approximates the bilinear product x * y. * @param phi_x φˣ in the documentation above. Will be used to cut the range of * x into small intervals. * @param phi_y φʸ in the documentation above. Will be used to cut the range of * y into small intervals. * @param Bx The binary-valued expression indicating which interval x is in. * Bx(i) = 1 => φˣᵢ ≤ x ≤ φˣᵢ₊₁. * @param By The binary-valued expression indicating which interval y is in. * By(i) = 1 => φʸⱼ ≤ y ≤ φʸⱼ₊₁. * * One formulation of the constraint is * ``` * x = ∑ᵢⱼ x̂ᵢⱼ * y = ∑ᵢⱼ ŷᵢⱼ * Bˣʸᵢⱼ = Bˣᵢ ∧ Bʸⱼ * ∑ᵢⱼ Bˣʸᵢⱼ = 1 * φˣᵢ Bˣʸᵢⱼ ≤ x̂ᵢⱼ ≤ φˣᵢ₊₁ Bˣʸᵢⱼ * φʸⱼ Bˣʸᵢⱼ ≤ ŷᵢⱼ ≤ φʸⱼ₊₁ Bˣʸᵢⱼ * w ≥ ∑ᵢⱼ (x̂ᵢⱼ φʸⱼ + φˣᵢ ŷᵢⱼ - φˣᵢ φʸⱼ Bˣʸᵢⱼ) * w ≥ ∑ᵢⱼ (x̂ᵢⱼ φʸⱼ₊₁ + φˣᵢ₊₁ ŷᵢⱼ - φˣᵢ₊₁ φʸⱼ₊₁ Bˣʸᵢⱼ) * w ≤ ∑ᵢⱼ (x̂ᵢⱼ φʸⱼ + φˣᵢ₊₁ ŷᵢⱼ - φˣᵢ₊₁ φʸⱼ Bˣʸᵢⱼ) * w ≤ ∑ᵢⱼ (x̂ᵢⱼ φʸⱼ₊₁ + φˣᵢ ŷᵢⱼ - φˣᵢ φʸⱼ₊₁ Bˣʸᵢⱼ) * ``` * * The "logical and" constraint Bˣʸᵢⱼ = Bˣᵢ ∧ Bʸⱼ can be imposed as * ``` * Bˣʸᵢⱼ ≥ Bˣᵢ + Bʸⱼ - 1 * Bˣʸᵢⱼ ≤ Bˣᵢ * Bˣʸᵢⱼ ≤ Bʸⱼ * 0 ≤ Bˣʸᵢⱼ ≤ 1 * ``` * This formulation will introduce slack variables x̂, ŷ and Bˣʸ, in total * 3 * m * n variables. * * In order to reduce the number of slack variables, we can further simplify * these constraints, by defining two vectors `x̅ ∈ ℝⁿ`, `y̅ ∈ ℝᵐ` as * ``` * x̅ⱼ = ∑ᵢ x̂ᵢⱼ * y̅ᵢ = ∑ⱼ ŷᵢⱼ * ``` * and the constraints above can be re-formulated using `x̅` and `y̅` as * ``` * x = ∑ⱼ x̅ⱼ * y = ∑ᵢ y̅ᵢ * Bˣʸᵢⱼ = Bˣᵢ ∧ Bʸⱼ * ∑ᵢⱼ Bˣʸᵢⱼ = 1 * ∑ᵢ φˣᵢ Bˣʸᵢⱼ ≤ x̅ⱼ ≤ ∑ᵢ φˣᵢ₊₁ Bˣʸᵢⱼ * ∑ⱼ φʸⱼ Bˣʸᵢⱼ ≤ y̅ᵢ ≤ ∑ⱼ φʸⱼ₊₁ Bˣʸᵢⱼ * w ≥ ∑ⱼ( x̅ⱼ φʸⱼ ) + ∑ᵢ( φˣᵢ y̅ᵢ ) - ∑ᵢⱼ( φˣᵢ φʸⱼ Bˣʸᵢⱼ ) * w ≥ ∑ⱼ( x̅ⱼ φʸⱼ₊₁ ) + ∑ᵢ( φˣᵢ₊₁ y̅ᵢ ) - ∑ᵢⱼ( φˣᵢ₊₁ φʸⱼ₊₁ Bˣʸᵢⱼ ) * w ≤ ∑ⱼ( x̅ⱼ φʸⱼ ) + ∑ᵢ( φˣᵢ₊₁ y̅ⱼ ) - ∑ᵢⱼ( φˣᵢ₊₁ φʸⱼ Bˣʸᵢⱼ ) * w ≤ ∑ⱼ( x̅ⱼ φʸⱼ₊₁ ) + ∑ᵢ( φˣᵢ y̅ᵢ ) - ∑ᵢⱼ( φˣᵢ φʸⱼ₊₁ Bˣʸᵢⱼ ). * ``` * In this formulation, we introduce new continuous variables `x̅`, `y̅`, `Bˣʸ`. * The total number of new variables is m + n + m * n. * * In section 3.3 of Mixed-Integer Models for Nonseparable Piecewise Linear * Optimization: Unifying Framework and Extensions by Juan P Vielma, Shabbir * Ahmed and George Nemhauser, this formulation is called "Multiple Choice * Model". * * @note We DO NOT add the constraint * Bx(i) ∈ {0, 1}, By(j) ∈ {0, 1} * in this function. It is the user's responsibility to ensure that these binary * constraints are enforced. The users can also add cutting planes ∑ᵢBx(i) = 1, * ∑ⱼBy(j) = 1. Without these two cutting planes, (x, y, w) is still in the * McCormick envelope of z = x * y, but these two cutting planes "might" improve * the computation speed in the mixed-integer solver. */ void AddBilinearProductMcCormickEnvelopeMultipleChoice( MathematicalProgram* prog, const symbolic::Variable& x, const symbolic::Variable& y, const symbolic::Expression& w, const Eigen::Ref<const Eigen::VectorXd>& phi_x, const Eigen::Ref<const Eigen::VectorXd>& phi_y, const Eigen::Ref<const VectorX<symbolic::Expression>>& Bx, const Eigen::Ref<const VectorX<symbolic::Expression>>& By); } // namespace solvers } // namespace drake DRAKE_FORMATTER_AS(, drake::solvers, IntervalBinning, x, drake::solvers::to_string(x))
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/create_cost.cc
#include "drake/solvers/create_cost.h" #include <algorithm> #include <unordered_map> #include <unordered_set> #include <vector> #include "drake/common/polynomial.h" #include "drake/common/symbolic/decompose.h" #include "drake/common/unused.h" namespace drake { namespace solvers { namespace internal { using std::make_shared; using std::numeric_limits; using std::ostringstream; using std::runtime_error; using std::set; using std::shared_ptr; using std::unordered_map; using std::vector; using symbolic::Expression; using symbolic::Formula; using symbolic::Variable; namespace { Binding<QuadraticCost> DoParseQuadraticCost( const symbolic::Polynomial& poly, const VectorXDecisionVariable& vars_vec, const unordered_map<Variable::Id, int>& map_var_to_index, std::optional<bool> is_convex) { // We want to write the expression e in the form 0.5 * x' * Q * x + b' * x + c // TODO(hongkai.dai): use a sparse matrix to represent Q and b. Eigen::MatrixXd Q(vars_vec.size(), vars_vec.size()); Eigen::VectorXd b(vars_vec.size()); double constant_term; symbolic::DecomposeQuadraticPolynomial(poly, map_var_to_index, &Q, &b, &constant_term); return CreateBinding( make_shared<QuadraticCost>(Q, b, constant_term, is_convex), vars_vec); } Binding<LinearCost> DoParseLinearCost( const Expression& e, const VectorXDecisionVariable& vars_vec, const unordered_map<Variable::Id, int>& map_var_to_index) { Eigen::RowVectorXd c(vars_vec.size()); double constant_term{}; symbolic::DecomposeAffineExpression(e, map_var_to_index, &c, &constant_term); return CreateBinding(make_shared<LinearCost>(c.transpose(), constant_term), vars_vec); } } // namespace Binding<LinearCost> ParseLinearCost(const Expression& e) { auto p = symbolic::ExtractVariablesFromExpression(e); return DoParseLinearCost(e, p.first, p.second); } Binding<QuadraticCost> ParseQuadraticCost(const Expression& e, std::optional<bool> is_convex) { // First build an Eigen vector, that contains all the bound variables. auto p = symbolic::ExtractVariablesFromExpression(e); const auto& vars_vec = p.first; const auto& map_var_to_index = p.second; // Now decomposes the expression into coefficients and monomials. const symbolic::Polynomial poly{e}; return DoParseQuadraticCost(poly, vars_vec, map_var_to_index, is_convex); } Binding<PolynomialCost> ParsePolynomialCost(const symbolic::Expression& e) { if (!e.is_polynomial()) { ostringstream oss; oss << "Expression" << e << " is not a polynomial. ParsePolynomialCost" " only supports polynomial expression.\n"; throw runtime_error(oss.str()); } const symbolic::Variables& vars = e.GetVariables(); const Polynomiald polynomial = Polynomiald::FromExpression(e); vector<Polynomiald::VarType> polynomial_vars(vars.size()); VectorXDecisionVariable var_vec(vars.size()); int polynomial_var_count = 0; for (const auto& var : vars) { polynomial_vars[polynomial_var_count] = var.get_id(); var_vec[polynomial_var_count] = var; ++polynomial_var_count; } return CreateBinding(make_shared<PolynomialCost>( Vector1<Polynomiald>(polynomial), polynomial_vars), var_vec); } Binding<L2NormCost> ParseL2NormCost(const symbolic::Expression& e, double psd_tol, double coefficient_tol) { auto [is_l2norm, A, b, vars] = DecomposeL2NormExpression(e, psd_tol, coefficient_tol); if (!is_l2norm) { throw runtime_error(fmt::format( "Expression {} is not an L2 norm. ParseL2NormCost only supports " "expressions that are the square root of a quadratic.", e)); } return CreateBinding(make_shared<L2NormCost>(A, b), vars); } Binding<Cost> ParseCost(const symbolic::Expression& e) { if (!e.is_polynomial()) { // First try an L2-norm cost. auto [is_l2norm, A, b, vars] = DecomposeL2NormExpression(e); if (is_l2norm) { return CreateBinding(make_shared<L2NormCost>(A, b), vars); } // Otherwise make an ExpressionCost. auto cost = make_shared<ExpressionCost>(e); return CreateBinding(cost, cost->vars()); } const symbolic::Polynomial poly{e}; const int total_degree{poly.TotalDegree()}; auto e_extracted = symbolic::ExtractVariablesFromExpression(e); const VectorXDecisionVariable& vars_vec = e_extracted.first; const auto& map_var_to_index = e_extracted.second; if (total_degree > 2) { return ParsePolynomialCost(e); } else if (total_degree == 2) { return DoParseQuadraticCost(poly, vars_vec, map_var_to_index, std::nullopt); } else { return DoParseLinearCost(e, vars_vec, map_var_to_index); } } } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/gurobi_solver.h
#pragma once #include <functional> #include <memory> #include <string> #include "drake/common/autodiff.h" #include "drake/common/drake_copyable.h" #include "drake/solvers/decision_variable.h" #include "drake/solvers/solver_base.h" namespace drake { namespace solvers { /// The Gurobi solver details after calling Solve() function. The user can call /// MathematicalProgramResult::get_solver_details<GurobiSolver>() to obtain the /// details. struct GurobiSolverDetails { /// The gurobi optimization time. Please refer to /// https://www.gurobi.com/documentation/10.0/refman/runtime.html double optimizer_time{}; /// The error message returned from Gurobi call. Please refer to /// https://www.gurobi.com/documentation/10.0/refman/error_codes.html int error_code{}; /// The status code when the optimize call has returned. Please refer to /// https://www.gurobi.com/documentation/10.0/refman/optimization_status_codes.html int optimization_status{}; /// The best known bound on the optimal objective. This is used in mixed /// integer optimization. Please refer to /// https://www.gurobi.com/documentation/10.0/refman/objbound.html double objective_bound{NAN}; }; /// An implementation of SolverInterface for the commercially-licensed Gurobi /// solver (https://www.gurobi.com/). /// /// The default build of Drake is not configured to use Gurobi, so therefore /// SolverInterface::available() will return false. You must compile Drake /// from source in order to link against Gurobi. For details, refer to the /// documentation at https://drake.mit.edu/bazel.html#proprietary-solvers. /// /// The GRB_LICENSE_FILE environment variable controls whether or not /// SolverInterface::enabled() returns true. If it is set to any non-empty /// value, then the solver is enabled; otherwise, the solver is not enabled. /// /// Gurobi solver supports options/parameters listed in /// https://www.gurobi.com/documentation/10.0/refman/parameters.html. On top of /// these options, we provide the following additional options /// 1. "GRBwrite", set to a file name so that Gurobi solver will write the /// optimization model to this file, check /// https://www.gurobi.com/documentation/10.0/refman/py_model_write.html for /// more details, such as all supported file extensions. Set this option to /// "" if you don't want to write to file. Default is not to write to a file. /// 2. "GRBcomputeIIS", set to 1 to compute an Irreducible Inconsistent /// Subsystem (IIS) when the problem is infeasible. Refer to /// https://www.gurobi.com/documentation/10.0/refman/py_model_computeiis.html /// for more details. Often this method is called together with /// setting GRBwrite to "FILENAME.ilp" to write IIS to a file with extension /// "ilp". Default is not to compute IIS. /// /// If the "Threads" integer solver option has not been set by the user, then /// %GurobiSolver uses environment variable GUROBI_NUM_THREADS (if set) as a /// default value for "Threads". class GurobiSolver final : public SolverBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GurobiSolver) /// Type of details stored in MathematicalProgramResult. using Details = GurobiSolverDetails; GurobiSolver(); ~GurobiSolver() final; /// Contains info returned to a user function that handles /// a Node or Solution callback. /// @see MipNodeCallbackFunction /// @see MipSolCallbackFunction struct SolveStatusInfo { /// Runtime as of this callback. double reported_runtime{}; /// Objective of current solution. double current_objective{}; /// Objective of best solution yet. double best_objective{}; /// Best known objective lower bound. double best_bound{}; /// Number of nodes explored so far. int explored_node_count{}; /// Number of feasible sols found so far. int feasible_solutions_count{}; }; /// Users can supply a callback to be called when the Gurobi solver /// finds an intermediate solution node, which may not be feasible. /// See Gurobi reference manual for more detail on callbacks: /// https://www.gurobi.com/documentation/current/refman/cb_codes.html /// The user may supply a partial solution in the VectorXd and /// VectorXDecisionVariable arguments that will be passed to Gurobi /// as a candidate feasible solution. /// See gurobi_solver_test.cc for an example of using std::bind /// to create a callback of this signature, while allowing /// additional data to be passed through. /// @param MathematicalProgram& The optimization wrapper, whose /// current variable values (accessible via /// MathematicalProgram::GetSolution) will be set to the intermediate /// solution values. /// @param SolveStatusInfo& Intermediate solution status information values /// queried from Gurobi. /// @param VectorXd* User may assign this to be the values of the variable /// assignments. /// @param VectorXDecisionVariable* User may assign this to be the decision /// variables being assigned. Must have the same number of elements as /// the VectorXd assignment. typedef std::function<void(const MathematicalProgram&, const SolveStatusInfo& callback_info, Eigen::VectorXd*, VectorXDecisionVariable*)> MipNodeCallbackFunction; /// Registers a callback to be called at intermediate solutions /// during the solve. /// @param callback User callback function. /// @param user_data Arbitrary data that will be passed to the user /// callback function. void AddMipNodeCallback(const MipNodeCallbackFunction& callback) { mip_node_callback_ = callback; } /// Users can supply a callback to be called when the Gurobi solver /// finds a feasible solution. /// See Gurobi reference manual for more detail on callbacks: /// https://www.gurobi.com/documentation/current/refman/cb_codes.html /// See gurobi_solver_test.cc for an example of using std::bind /// to create a callback of this signature, while allowing /// additional data to be passed through. /// @param MathematicalProgram& The optimization wrapper, whose /// current variable values (accessible via /// MathematicalProgram::GetSolution) will be set to the intermediate /// solution values. /// @param SolveStatusInfo& Intermediate solution status information values /// queried from Gurobi. /// @param void* Arbitrary data supplied during callback registration. typedef std::function<void(const MathematicalProgram&, const SolveStatusInfo& callback_info)> MipSolCallbackFunction; /// Registers a callback to be called at feasible solutions /// during the solve. /// @param callback User callback function. /// @param usrdata Arbitrary data that will be passed to the user /// callback function. void AddMipSolCallback(const MipSolCallbackFunction& callback) { mip_sol_callback_ = callback; } /** * This type contains a valid Gurobi license environment, and is only to be * used from AcquireLicense(). */ class License; /** * This acquires a Gurobi license environment shared among all GurobiSolver * instances. The environment will stay valid as long as at least one * shared_ptr returned by this function is alive. GurobiSolver calls this * method on each Solve(). * * If the license file contains the string `HOSTID`, then we treat this as * confirmation that the license is attached to the local host, and maintain * an internal copy of the shared_ptr for the lifetime of the process. * Otherwise the default behavior is to only hold the license while at least * one GurobiSolver instance is alive. * * Call this method directly and maintain the shared_ptr ONLY if you must use * different MathematicalProgram instances at different instances in time, * and repeatedly acquiring the license is costly (e.g., requires contacting * a license server). * @return A shared pointer to a license environment that will stay valid as * long as any shared_ptr returned by this function is alive. If Gurobi is * not available in your build, this will return a null (empty) shared_ptr. * @throws std::exception if Gurobi is available but a license cannot be * obtained. */ static std::shared_ptr<License> AcquireLicense(); /// @name Static versions of the instance methods with similar names. //@{ static SolverId id(); static bool is_available(); /// Returns true iff the environment variable GRB_LICENSE_FILE has been set /// to a non-empty value. static bool is_enabled(); static bool ProgramAttributesSatisfied(const MathematicalProgram&); static std::string UnsatisfiedProgramAttributes(const MathematicalProgram&); //@} // A using-declaration adds these methods into our class's Doxygen. using SolverBase::Solve; private: void DoSolve(const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const final; // Note that this is mutable to allow latching the allocation of env_ // during the first call of Solve() (which avoids grabbing a Gurobi license // before we know that we actually want one). mutable std::shared_ptr<License> license_; // Callbacks and generic user data to pass through, // or NULL if no callback has been supplied. MipNodeCallbackFunction mip_node_callback_; MipSolCallbackFunction mip_sol_callback_; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/solver_type_converter.h
#pragma once #include <optional> #include "drake/common/drake_copyable.h" #include "drake/solvers/solver_id.h" #include "drake/solvers/solver_type.h" namespace drake { namespace solvers { /// Converts between SolverType and SolverId. This class only exists for /// backwards compatibility, and should not be used in new code. class SolverTypeConverter { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SolverTypeConverter); SolverTypeConverter() = delete; ~SolverTypeConverter() = delete; /// Converts the given type to its matching ID. static SolverId TypeToId(SolverType); /// Converts the given ID to its matching type, iff the type matches one of /// SolverType's known values. static std::optional<SolverType> IdToType(SolverId); }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/ipopt_solver.h
#pragma once #include <ostream> #include <string> #include <Eigen/Core> #include "drake/common/drake_copyable.h" #include "drake/solvers/solver_base.h" namespace drake { namespace solvers { /** * The Ipopt solver details after calling Solve() function. The user can call * MathematicalProgramResult::get_solver_details<IpoptSolver>() to obtain the * details. */ struct IpoptSolverDetails { /** * The final status of the solver. Please refer to section 6 in * Introduction to Ipopt: A tutorial for downloading, installing, and using * Ipopt. * You could also find the meaning of the status as Ipopt::SolverReturn * defined in IpAlgTypes.hpp */ int status{}; /// The final value for the lower bound multiplier. Eigen::VectorXd z_L; /// The final value for the upper bound multiplier. Eigen::VectorXd z_U; /// The final value for the constraint function. Eigen::VectorXd g; /// The final value for the constraint multiplier. Eigen::VectorXd lambda; /** Convert status field to string. This function is useful if you want to * interpret the meaning of status. */ const char* ConvertStatusToString() const; }; class IpoptSolver final : public SolverBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(IpoptSolver) /// Type of details stored in MathematicalProgramResult. using Details = IpoptSolverDetails; IpoptSolver(); ~IpoptSolver() final; /// @name Static versions of the instance methods with similar names. //@{ static SolverId id(); static bool is_available(); static bool is_enabled(); static bool ProgramAttributesSatisfied(const MathematicalProgram&); //@} // A using-declaration adds these methods into our class's Doxygen. using SolverBase::Solve; private: void DoSolve(const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const final; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/constraint.h
#pragma once #include <limits> #include <list> #include <map> #include <memory> #include <optional> #include <stdexcept> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <Eigen/Core> #include <Eigen/SparseCore> #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/common/polynomial.h" #include "drake/common/symbolic/expression.h" #include "drake/solvers/decision_variable.h" #include "drake/solvers/evaluator_base.h" #include "drake/solvers/function.h" #include "drake/solvers/sparse_and_dense_matrix.h" namespace drake { namespace solvers { // TODO(eric.cousineau): Consider enabling the constraint class directly to // specify new slack variables. // TODO(eric.cousineau): Consider parameterized constraints: e.g. the // acceleration constraints in the rigid body dynamics are constraints // on vdot and f, but are "parameterized" by q and v. /** * A constraint is a function + lower and upper bounds. * * Solver interfaces must acknowledge that these constraints are mutable. * Parameters can change after the constraint is constructed and before the * call to Solve(). * * It should support evaluating the constraint, and adding it to an optimization * problem. * * @ingroup solver_evaluators */ class Constraint : public EvaluatorBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Constraint) /** * Constructs a constraint which has `num_constraints` rows, with an input * `num_vars` x 1 vector. * @param num_constraints. The number of rows in the constraint output. * @param num_vars. The number of rows in the input. * If the input dimension is unknown, then set `num_vars` to Eigen::Dynamic. * @param lb Lower bound, which must be a `num_constraints` x 1 vector. * @param ub Upper bound, which must be a `num_constraints` x 1 vector. * @see Eval(...) */ template <typename DerivedLB, typename DerivedUB> Constraint(int num_constraints, int num_vars, const Eigen::MatrixBase<DerivedLB>& lb, const Eigen::MatrixBase<DerivedUB>& ub, const std::string& description = "") : EvaluatorBase(num_constraints, num_vars, description), lower_bound_(lb), upper_bound_(ub) { check(num_constraints); DRAKE_DEMAND(!lower_bound_.array().isNaN().any()); DRAKE_DEMAND(!upper_bound_.array().isNaN().any()); } /** * Constructs a constraint which has `num_constraints` rows, with an input * `num_vars` x 1 vector, with no bounds. * @param num_constraints. The number of rows in the constraint output. * @param num_vars. The number of rows in the input. * If the input dimension is unknown, then set `num_vars` to Eigen::Dynamic. * @see Eval(...) */ Constraint(int num_constraints, int num_vars) : Constraint( num_constraints, num_vars, Eigen::VectorXd::Constant(num_constraints, -std::numeric_limits<double>::infinity()), Eigen::VectorXd::Constant( num_constraints, std::numeric_limits<double>::infinity())) {} /** * Return whether this constraint is satisfied by the given value, `x`. * @param x A `num_vars` x 1 vector. * @param tol A tolerance for bound checking. */ bool CheckSatisfied(const Eigen::Ref<const Eigen::VectorXd>& x, double tol = 1E-6) const { DRAKE_ASSERT(x.rows() == num_vars() || num_vars() == Eigen::Dynamic); return DoCheckSatisfied(x, tol); } bool CheckSatisfied(const Eigen::Ref<const AutoDiffVecXd>& x, double tol = 1E-6) const { DRAKE_ASSERT(x.rows() == num_vars() || num_vars() == Eigen::Dynamic); return DoCheckSatisfied(x, tol); } symbolic::Formula CheckSatisfied( const Eigen::Ref<const VectorX<symbolic::Variable>>& x) const { DRAKE_ASSERT(x.rows() == num_vars() || num_vars() == Eigen::Dynamic); return DoCheckSatisfied(x); } const Eigen::VectorXd& lower_bound() const { return lower_bound_; } const Eigen::VectorXd& upper_bound() const { return upper_bound_; } /** Number of rows in the output constraint. */ int num_constraints() const { return num_outputs(); } protected: /** Updates the lower bound. * @note if the users want to expose this method in a sub-class, do * using Constraint::UpdateLowerBound, as in LinearConstraint. */ void UpdateLowerBound(const Eigen::Ref<const Eigen::VectorXd>& new_lb) { if (new_lb.rows() != num_constraints()) { throw std::logic_error("Lower bound has invalid dimension."); } lower_bound_ = new_lb; } /** Updates the upper bound. * @note if the users want to expose this method in a sub-class, do * using Constraint::UpdateUpperBound, as in LinearConstraint. */ void UpdateUpperBound(const Eigen::Ref<const Eigen::VectorXd>& new_ub) { if (new_ub.rows() != num_constraints()) { throw std::logic_error("Upper bound has invalid dimension."); } upper_bound_ = new_ub; } /** * Set the upper and lower bounds of the constraint. * @param new_lb . A `num_constraints` x 1 vector. * @param new_ub. A `num_constraints` x 1 vector. * @note If the users want to expose this method in a sub-class, do * using Constraint::set_bounds, as in LinearConstraint. */ void set_bounds(const Eigen::Ref<const Eigen::VectorXd>& new_lb, const Eigen::Ref<const Eigen::VectorXd>& new_ub) { UpdateLowerBound(new_lb); UpdateUpperBound(new_ub); } virtual bool DoCheckSatisfied(const Eigen::Ref<const Eigen::VectorXd>& x, const double tol) const { Eigen::VectorXd y(num_constraints()); DoEval(x, &y); return (y.array() >= lower_bound_.array() - tol).all() && (y.array() <= upper_bound_.array() + tol).all(); } virtual bool DoCheckSatisfied(const Eigen::Ref<const AutoDiffVecXd>& x, const double tol) const { AutoDiffVecXd y(num_constraints()); DoEval(x, &y); auto get_value = [](const AutoDiffXd& v) { return v.value(); }; return (y.array().unaryExpr(get_value) >= lower_bound_.array() - tol) .all() && (y.array().unaryExpr(get_value) <= upper_bound_.array() + tol).all(); } virtual symbolic::Formula DoCheckSatisfied( const Eigen::Ref<const VectorX<symbolic::Variable>>& x) const; private: void check(int num_constraints) const; Eigen::VectorXd lower_bound_; Eigen::VectorXd upper_bound_; }; /** * lb ≤ .5 xᵀQx + bᵀx ≤ ub * Without loss of generality, the class stores a symmetric matrix Q. * For a non-symmetric matrix Q₀, we can define Q = (Q₀ + Q₀ᵀ) / 2, since * xᵀQ₀x = xᵀQ₀ᵀx = xᵀ*(Q₀+Q₀ᵀ)/2 *x. The first equality holds because the * transpose of a scalar is the scalar itself. Hence we can always convert * a non-symmetric matrix Q₀ to a symmetric matrix Q. * * @ingroup solver_evaluators */ class QuadraticConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QuadraticConstraint) static const int kNumConstraints = 1; /** Whether the Hessian matrix is positive semidefinite, negative semidefinite, or indefinite. */ enum class HessianType { kPositiveSemidefinite, kNegativeSemidefinite, kIndefinite, }; /** * Construct a quadratic constraint. * @tparam DerivedQ The type for Q. * @tparam Derivedb The type for b. * @param Q0 The square matrix. Notice that Q₀ does not have to be symmetric. * @param b The linear coefficient. * @param lb The lower bound. * @param ub The upper bound. * @param hessian_type (optional) Indicates the type of Hessian matrix Q0. * If hessian_type is not std::nullopt, then the user guarantees the type of * Q0. If hessian_type=std::nullopt, then QuadraticConstraint will check the * type of Q0. To speed up the constructor, set hessian_type != std::nullopt * if you can. If this type is set incorrectly, then the downstream code (for * example the solver) will malfunction. */ template <typename DerivedQ, typename Derivedb> QuadraticConstraint(const Eigen::MatrixBase<DerivedQ>& Q0, const Eigen::MatrixBase<Derivedb>& b, double lb, double ub, std::optional<HessianType> hessian_type = std::nullopt) : Constraint(kNumConstraints, Q0.rows(), drake::Vector1d::Constant(lb), drake::Vector1d::Constant(ub)), Q_((Q0 + Q0.transpose()) / 2), b_(b) { UpdateHessianType(hessian_type); DRAKE_ASSERT(Q_.rows() == Q_.cols()); DRAKE_ASSERT(Q_.cols() == b_.rows()); } ~QuadraticConstraint() override {} /** The symmetric matrix Q, being the Hessian of this constraint. */ virtual const Eigen::MatrixXd& Q() const { return Q_; } virtual const Eigen::VectorXd& b() const { return b_; } [[nodiscard]] HessianType hessian_type() const { return hessian_type_; } /** Returns if this quadratic constraint is convex. */ [[nodiscard]] bool is_convex() const; /** * Updates the quadratic and linear term of the constraint. The new * matrices need to have the same dimension as before. * @param new_Q new quadratic term * @param new_b new linear term * @param hessian_type (optional) Indicates the type of Hessian matrix Q0. * If hessian_type is not std::nullopt, then the user guarantees the type of * Q0. If hessian_type=std::nullopt, then QuadraticConstraint will check the * type of Q0. To speed up the constructor, set hessian_type != std::nullopt * if you can. */ template <typename DerivedQ, typename DerivedB> void UpdateCoefficients( const Eigen::MatrixBase<DerivedQ>& new_Q, const Eigen::MatrixBase<DerivedB>& new_b, std::optional<HessianType> hessian_type = std::nullopt) { if (new_Q.rows() != new_Q.cols() || new_Q.rows() != new_b.rows() || new_b.cols() != 1) { throw std::runtime_error("New constraints have invalid dimensions"); } if (new_b.rows() != b_.rows()) { throw std::runtime_error("Can't change the number of decision variables"); } Q_ = (new_Q + new_Q.transpose()) / 2; b_ = new_b; UpdateHessianType(hessian_type); } private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const; void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::ostream& DoDisplay(std::ostream&, const VectorX<symbolic::Variable>&) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; // Updates hessian_type_ based on Q_; void UpdateHessianType(std::optional<HessianType> hessian_type); Eigen::MatrixXd Q_; Eigen::VectorXd b_; HessianType hessian_type_; }; /** Constraining the linear expression \f$ z=Ax+b \f$ lies within the Lorentz cone. A vector z ∈ ℝ ⁿ lies within Lorentz cone if @f[ z_0 \ge \sqrt{z_1^2+...+z_{n-1}^2} @f] <!--> z₀ ≥ sqrt(z₁² + ... + zₙ₋₁²) <--> where A ∈ ℝ ⁿˣᵐ, b ∈ ℝ ⁿ are given matrices. Ideally this constraint should be handled by a second-order cone solver. In case the user wants to enforce this constraint through general nonlinear optimization, we provide three different formulations on the Lorentz cone constraint 1. [kConvex] g(z) = z₀ - sqrt(z₁² + ... + zₙ₋₁²) ≥ 0 This formulation is not differentiable at z₁=...=zₙ₋₁=0 2. [kConvexSmooth] g(z) = z₀ - sqrt(z₁² + ... + zₙ₋₁²) ≥ 0 but the gradient of g(z) is approximated as ∂g(z)/∂z = [1, -z₁/sqrt(z₁² + ... zₙ₋₁² + ε), ..., -zₙ₋₁/sqrt(z₁²+...+zₙ₋₁²+ε)] where ε is a small positive number. 3. [kNonconvex] z₀²-(z₁²+...+zₙ₋₁²) ≥ 0 z₀ ≥ 0 This constraint is differentiable everywhere, but z₀²-(z₁²+...+zₙ₋₁²) ≥ 0 is non-convex. For more information and visualization, please refer to https://www.epfl.ch/labs/disopt/wp-content/uploads/2018/09/7.pdf and https://docs.mosek.com/modeling-cookbook/cqo.html (Fig 3.1) @ingroup solver_evaluators */ class LorentzConeConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LorentzConeConstraint) /** * We provide three possible Eval functions to represent the Lorentz cone * constraint z₀ ≥ sqrt(z₁² + ... + zₙ₋₁²). For more explanation on the three * formulations, refer to LorentzConeConstraint documentation. */ enum class EvalType { kConvex, ///< The constraint is g(z) = z₀ - sqrt(z₁² + ... + zₙ₋₁²) ≥ 0. ///< Note this formulation is non-differentiable at z₁= ...= ///< zₙ₋₁=0 kConvexSmooth, ///< Same as kConvex, but with approximated gradient that ///< exists everywhere.. kNonconvex ///< Nonconvex constraint z₀²-(z₁²+...+zₙ₋₁²) ≥ 0 and z₀ ≥ 0. ///< Note this formulation is differentiable, but at z₁= ...= ///< zₙ₋₁=0 the gradient is also 0, so a gradient-based ///< nonlinear solver can get stuck. }; LorentzConeConstraint(const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::VectorXd>& b, EvalType eval_type = EvalType::kConvexSmooth); ~LorentzConeConstraint() override {} /** Getter for A. */ const Eigen::SparseMatrix<double>& A() const { return A_; } /** Getter for dense version of A. */ const Eigen::MatrixXd& A_dense() const { return A_dense_; } /** Getter for b. */ const Eigen::VectorXd& b() const { return b_; } /** Getter for eval type. */ EvalType eval_type() const { return eval_type_; } /** * Updates the coefficients, the updated constraint is z=new_A * x + new_b in * the Lorentz cone. * @throws std::exception if the new_A.cols() != A.cols(), namely the variable * size should not change. * @pre `new_A` has to have at least 2 rows and new_A.rows() == new_b.rows(). */ void UpdateCoefficients(const Eigen::Ref<const Eigen::MatrixXd>& new_A, const Eigen::Ref<const Eigen::VectorXd>& new_b); private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const; void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::ostream& DoDisplay(std::ostream&, const VectorX<symbolic::Variable>&) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; Eigen::SparseMatrix<double> A_; // We need to store a dense matrix of A_, so that we can compute the gradient // using AutoDiffXd, and return the gradient as a dense matrix. Eigen::MatrixXd A_dense_; Eigen::VectorXd b_; const EvalType eval_type_; }; /** * Constraining that the linear expression \f$ z=Ax+b \f$ lies within rotated * Lorentz cone. * A vector z ∈ ℝ ⁿ lies within rotated Lorentz cone, if * @f[ * z_0 \ge 0\\ * z_1 \ge 0\\ * z_0 z_1 \ge z_2^2 + z_3^2 + ... + z_{n-1}^2 * @f] * where A ∈ ℝ ⁿˣᵐ, b ∈ ℝ ⁿ are given matrices. * <!--> * z₀ ≥ 0 * z₁ ≥ 0 * z₀ * z₁ ≥ z₂² + z₃² + ... zₙ₋₁² * <--> * For more information and visualization, please refer to * https://docs.mosek.com/modeling-cookbook/cqo.html (Fig 3.1) * * @ingroup solver_evaluators */ class RotatedLorentzConeConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RotatedLorentzConeConstraint) RotatedLorentzConeConstraint(const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::VectorXd>& b) : Constraint( 3, A.cols(), Eigen::Vector3d::Constant(0.0), Eigen::Vector3d::Constant(std::numeric_limits<double>::infinity())), A_(A.sparseView()), A_dense_(A), b_(b) { DRAKE_DEMAND(A_.rows() >= 3); DRAKE_ASSERT(A_.rows() == b_.rows()); } /** Getter for A. */ const Eigen::SparseMatrix<double>& A() const { return A_; } /** Getter for dense version of A. */ const Eigen::MatrixXd& A_dense() const { return A_dense_; } /** Getter for b. */ const Eigen::VectorXd& b() const { return b_; } ~RotatedLorentzConeConstraint() override {} /** * Updates the coefficients, the updated constraint is z=new_A * x + new_b in * the rotated Lorentz cone. * @throw std::exception if the new_A.cols() != A.cols(), namely the variable * size should not change. * @pre new_A.rows() >= 3 and new_A.rows() == new_b.rows(). */ void UpdateCoefficients(const Eigen::Ref<const Eigen::MatrixXd>& new_A, const Eigen::Ref<const Eigen::VectorXd>& new_b); private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const; void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::ostream& DoDisplay(std::ostream&, const VectorX<symbolic::Variable>&) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; Eigen::SparseMatrix<double> A_; // We need to store a dense matrix of A_, so that we can compute the gradient // using AutoDiffXd, and return the gradient as a dense matrix. Eigen::MatrixXd A_dense_; Eigen::VectorXd b_; }; /** * A constraint that may be specified using another (potentially nonlinear) * evaluator. * @tparam EvaluatorType The nested evaluator. * * @ingroup solver_evaluators */ template <typename EvaluatorType = EvaluatorBase> class EvaluatorConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(EvaluatorConstraint) /** * Constructs an evaluator constraint, given the EvaluatorType instance * (which will specify the number of constraints and variables), and will * forward the remaining arguments to the Constraint constructor. * @param evaluator EvaluatorType instance. * @param args Arguments to be forwarded to the constraint constructor. */ template <typename... Args> EvaluatorConstraint(const std::shared_ptr<EvaluatorType>& evaluator, Args&&... args) : Constraint(evaluator->num_outputs(), evaluator->num_vars(), std::forward<Args>(args)...), evaluator_(evaluator) {} using Constraint::set_bounds; using Constraint::UpdateLowerBound; using Constraint::UpdateUpperBound; protected: /** Reference to the nested evaluator. */ const EvaluatorType& evaluator() const { return *evaluator_; } private: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { evaluator_->Eval(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { evaluator_->Eval(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { evaluator_->Eval(x, y); } std::shared_ptr<EvaluatorType> evaluator_; }; /** * A constraint on the values of multivariate polynomials. * * @verbatim * lb[i] ≤ P[i](x, y...) ≤ ub[i], * @endverbatim * where each P[i] is a multivariate polynomial in x, y... * * The Polynomial class uses a different variable naming scheme; thus the * caller must provide a list of Polynomial::VarType variables that correspond * to the members of the MathematicalProgram::Binding (the individual scalar * elements of the given VariableList). * * @ingroup solver_evaluators */ class PolynomialConstraint : public EvaluatorConstraint<PolynomialEvaluator> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PolynomialConstraint) /** * Constructs a polynomial constraint * @param polynomials Polynomial vector, a `num_constraints` x 1 vector. * @param poly_vars Polynomial variables, a `num_vars` x 1 vector. * @param lb Lower bounds, a `num_constraints` x 1 vector. * @param ub Upper bounds, a `num_constraints` x 1 vector. */ PolynomialConstraint(const VectorXPoly& polynomials, const std::vector<Polynomiald::VarType>& poly_vars, const Eigen::VectorXd& lb, const Eigen::VectorXd& ub) : EvaluatorConstraint( std::make_shared<PolynomialEvaluator>(polynomials, poly_vars), lb, ub) {} ~PolynomialConstraint() override {} const VectorXPoly& polynomials() const { return evaluator().polynomials(); } const std::vector<Polynomiald::VarType>& poly_vars() const { return evaluator().poly_vars(); } }; // TODO(bradking): consider implementing DifferentiableConstraint, // TwiceDifferentiableConstraint, ComplementarityConstraint, // IntegerConstraint, ... /** * Implements a constraint of the form @f$ lb <= Ax <= ub @f$ * * @ingroup solver_evaluators */ class LinearConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearConstraint) /** * Construct the linear constraint lb <= A*x <= ub * * Throws if A has any entry which is not finite. * @pydrake_mkdoc_identifier{dense_A} */ LinearConstraint(const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub); /** * Overloads constructor with a sparse A matrix. * Throws if A has any entry which is not finite. * @pydrake_mkdoc_identifier{sparse_A} */ LinearConstraint(const Eigen::SparseMatrix<double>& A, const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub); ~LinearConstraint() override {} const Eigen::SparseMatrix<double>& get_sparse_A() const { return A_.get_as_sparse(); } /** * Get the matrix A as a dense matrix. * @note this might involve memory allocation to convert a sparse matrix to a * dense one, for better performance you should call get_sparse_A() which * returns a sparse matrix. */ const Eigen::MatrixXd& GetDenseA() const; /** * Updates the linear term, upper and lower bounds in the linear constraint. * The updated constraint is: * new_lb <= new_A * x <= new_ub * Note that the size of constraints (number of rows) can change, but the * number of variables (number of cols) cannot. * * Throws if new_A has any entry which is not finite or if new_A, new_lb, and * new_ub don't all have the same number of rows. * * @param new_A new linear term * @param new_lb new lower bound * @param new_up new upper bound * @pydrake_mkdoc_identifier{dense_A} */ void UpdateCoefficients(const Eigen::Ref<const Eigen::MatrixXd>& new_A, const Eigen::Ref<const Eigen::VectorXd>& new_lb, const Eigen::Ref<const Eigen::VectorXd>& new_ub); /** * Overloads UpdateCoefficients but with a sparse A matrix. * * Throws if new_A has any entry which is not finite or if new_A, new_lb, and * new_ub don't all have the same number of rows. * * @pydrake_mkdoc_identifier{sparse_A} */ void UpdateCoefficients(const Eigen::SparseMatrix<double>& new_A, const Eigen::Ref<const Eigen::VectorXd>& new_lb, const Eigen::Ref<const Eigen::VectorXd>& new_ub); /** * Sets A(i, j) to zero if abs(A(i, j)) <= tol. * Oftentimes the coefficient A is computed numerically with round-off errors. * Such small round-off errors can cause numerical issues for certain * optimization solvers. Hence it is recommended to remove the tiny * coefficients to achieve numerical robustness. * @param tol The entries in A with absolute value <= tol will be set to 0. * @note tol>= 0. */ void RemoveTinyCoefficient(double tol); /** Returns true iff this constraint already has a dense representation, i.e, * if GetDenseA() will be cheap. */ bool is_dense_A_constructed() const; using Constraint::set_bounds; using Constraint::UpdateLowerBound; using Constraint::UpdateUpperBound; protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::ostream& DoDisplay(std::ostream&, const VectorX<symbolic::Variable>&) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; internal::SparseAndDenseMatrix A_; private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const; }; /** * Implements a constraint of the form @f$ Ax = b @f$ * * @ingroup solver_evaluators */ class LinearEqualityConstraint : public LinearConstraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearEqualityConstraint) /** * Constructs the linear equality constraint Aeq * x = beq. * * Throws is any entry in Aeq or beq is not finite. * @pydrake_mkdoc_identifier{dense_Aeq} */ LinearEqualityConstraint(const Eigen::Ref<const Eigen::MatrixXd>& Aeq, const Eigen::Ref<const Eigen::VectorXd>& beq) : LinearConstraint(Aeq, beq, beq) { DRAKE_THROW_UNLESS(beq.allFinite()); } /** * Overloads the constructor with a sparse matrix Aeq. * @pydrake_mkdoc_identifier{sparse_Aeq} */ LinearEqualityConstraint(const Eigen::SparseMatrix<double>& Aeq, const Eigen::Ref<const Eigen::VectorXd>& beq) : LinearConstraint(Aeq, beq, beq) { DRAKE_THROW_UNLESS(beq.allFinite()); } /** * Constructs the linear equality constraint a.dot(x) = beq * @pydrake_mkdoc_identifier{row_a} */ LinearEqualityConstraint(const Eigen::Ref<const Eigen::RowVectorXd>& a, double beq) : LinearEqualityConstraint(a, Vector1d(beq)) { DRAKE_THROW_UNLESS(this->lower_bound().allFinite()); } /* * @brief change the parameters of the constraint (A and b), but not the * variable associations. * * Note that A and b can change size in the rows only (representing a * different number of linear constraints, but on the same decision * variables). * * Throws if any entry of beq or Aeq is not finite. */ void UpdateCoefficients(const Eigen::Ref<const Eigen::MatrixXd>& Aeq, const Eigen::Ref<const Eigen::VectorXd>& beq) { DRAKE_THROW_UNLESS(beq.allFinite()); LinearConstraint::UpdateCoefficients(Aeq, beq, beq); } /** * Overloads UpdateCoefficients but with a sparse A matrix. * * Throws if any entry of beq or Aeq is not finite. */ void UpdateCoefficients(const Eigen::SparseMatrix<double>& Aeq, const Eigen::Ref<const Eigen::VectorXd>& beq) { DRAKE_THROW_UNLESS(beq.allFinite()); LinearConstraint::UpdateCoefficients(Aeq, beq, beq); } private: /** * The user should not call this function. Call UpdateCoefficients(Aeq, beq) * instead. */ template <typename DerivedA, typename DerivedL, typename DerivedU> void UpdateCoefficients(const Eigen::MatrixBase<DerivedA>&, const Eigen::MatrixBase<DerivedL>&, const Eigen::MatrixBase<DerivedU>&) { static_assert( !std::is_same_v<DerivedA, DerivedA>, "This method should not be called form `LinearEqualityConstraint`"); } std::ostream& DoDisplay(std::ostream&, const VectorX<symbolic::Variable>&) const override; }; /** * Implements a constraint of the form @f$ lb <= x <= ub @f$ * * Note: the base Constraint class (as implemented at the moment) could * play this role. But this class enforces that it is ONLY a bounding * box constraint, and not something more general. Some solvers use * this information to handle bounding box constraints differently than * general constraints, so use of this form is encouraged. * * @ingroup solver_evaluators */ class BoundingBoxConstraint : public LinearConstraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(BoundingBoxConstraint) BoundingBoxConstraint(const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub); ~BoundingBoxConstraint() override {} private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const; void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::ostream& DoDisplay(std::ostream&, const VectorX<symbolic::Variable>&) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; // This function (inheried from the base LinearConstraint class) should not be // called by BoundingBoxConstraint, so we hide it as a private function. // TODO(hongkai.dai): BoundingBoxConstraint should derive from Constraint, not // from LinearConstraint. void RemoveTinyCoefficient(double tol); }; /** * Implements a constraint of the form: * * <pre> * Mx + q ≥ 0 * x ≥ 0 * x'(Mx + q) == 0 * </pre> * Often this is summarized with the short-hand: * <pre> * 0 ≤ z ⊥ Mz+q ≥ 0 * </pre> * * An implied slack variable complements any 0 component of x. To get * the slack values at a given solution x, use Eval(x). * * @ingroup solver_evaluators */ class LinearComplementarityConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearComplementarityConstraint) template <typename DerivedM, typename Derivedq> LinearComplementarityConstraint(const Eigen::MatrixBase<DerivedM>& M, const Eigen::MatrixBase<Derivedq>& q) : Constraint(q.rows(), M.cols()), M_(M), q_(q) {} ~LinearComplementarityConstraint() override {} const Eigen::MatrixXd& M() const { return M_; } const Eigen::VectorXd& q() const { return q_; } protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; bool DoCheckSatisfied(const Eigen::Ref<const Eigen::VectorXd>& x, const double tol) const override; bool DoCheckSatisfied(const Eigen::Ref<const AutoDiffVecXd>& x, const double tol) const override; symbolic::Formula DoCheckSatisfied( const Eigen::Ref<const VectorX<symbolic::Variable>>& x) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; private: // Return Mx + q (the value of the slack variable). template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const; // TODO(ggould-tri) We are storing what are likely statically sized matrices // in dynamically allocated containers. This probably isn't optimal. Eigen::MatrixXd M_; Eigen::VectorXd q_; }; /** * Implements a positive semidefinite constraint on a symmetric matrix S * @f[\text{ * S is p.s.d * }@f] * namely, all eigen values of S are non-negative. * * @ingroup solver_evaluators */ class PositiveSemidefiniteConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PositiveSemidefiniteConstraint) /** * Impose the constraint that a symmetric matrix with size @p rows x @p rows * is positive semidefinite. * @see MathematicalProgram::AddPositiveSemidefiniteConstraint() for how * to use this constraint on some decision variables. We currently use this * constraint as a place holder in MathematicalProgram, to indicate the * positive semidefiniteness of some decision variables. * @param rows The number of rows (and columns) of the symmetric matrix. * * Example: * @code{.cc} * // Create a MathematicalProgram object. * auto prog = MathematicalProgram(); * * // Add a 2 x 2 symmetric matrix S to optimization program as new decision * // variables. * auto S = prog.NewSymmetricContinuousVariables<2>("S"); * * // Impose a positive semidefinite constraint on S. * std::shared_ptr<PositiveSemidefiniteConstraint> psd_constraint = * prog.AddPositiveSemidefiniteConstraint(S); * * ///////////////////////////////////////////////////////////// * // Add more constraints to make the program more interesting, * // but this is not needed. * * // Add the constraint that S(1, 0) = 1. * prog.AddBoundingBoxConstraint(1, 1, S(1, 0)); * * // Minimize S(0, 0) + S(1, 1). * prog.AddLinearCost(Eigen::RowVector2d(1, 1), {S.diagonal()}); * * ///////////////////////////////////////////////////////////// * * // Now solve the program. * auto result = Solve(prog); * * // Retrieve the solution of matrix S. * auto S_value = GetSolution(S, result); * * // Compute the eigen values of the solution, to see if they are * // all non-negative. * Eigen::Vector4d S_stacked; * S_stacked << S_value.col(0), S_value.col(1); * * Eigen::VectorXd S_eigen_values; * psd_constraint->Eval(S_stacked, S_eigen_values); * * std::cout<<"S solution is: " << S << std::endl; * std::cout<<"The eigen value of S is " << S_eigen_values << std::endl; * @endcode */ explicit PositiveSemidefiniteConstraint(int rows) : Constraint(rows, rows * rows, Eigen::VectorXd::Zero(rows), Eigen::VectorXd::Constant( rows, std::numeric_limits<double>::infinity())), matrix_rows_(rows) {} ~PositiveSemidefiniteConstraint() override {} int matrix_rows() const { return matrix_rows_; } protected: /** * Evaluate the eigen values of the symmetric matrix. * @param x The stacked columns of the symmetric matrix. */ void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; /** * @param x The stacked columns of the symmetric matrix. This function is not * supported yet, since Eigen's eigen value solver does not accept AutoDiffXd. */ void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; /** * @param x The stacked columns of the symmetric matrix. This function is not * supported, since Eigen's eigen value solver does not accept * symbolic::Expression. */ void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; private: int matrix_rows_; // Number of rows in the symmetric matrix being positive // semi-definite. }; /** * Impose the matrix inequality constraint on variable x * <!--> * F₀ + x₁ * F₁ + ... xₙ * Fₙ is p.s.d * <--> * @f[ * F_0 + x_1 F_1 + ... + x_n F_n \text{ is p.s.d} * @f] * where p.s.d stands for positive semidefinite. * @f$ F_0, F_1, ..., F_n @f$ are all given symmetric matrices of the same size. * * @ingroup solver_evaluators */ class LinearMatrixInequalityConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearMatrixInequalityConstraint) /** * @param F Each symmetric matrix F[i] should be of the same size. * @param symmetry_tolerance The precision to determine if the input matrices * Fi are all symmetric. @see math::IsSymmetric(). */ LinearMatrixInequalityConstraint(std::vector<Eigen::MatrixXd> F, double symmetry_tolerance = 1E-10); ~LinearMatrixInequalityConstraint() override {} /* Getter for all given matrices F */ const std::vector<Eigen::MatrixXd>& F() const { return F_; } /// Gets the number of rows in the matrix inequality constraint. Namely /// Fi are all matrix_rows() x matrix_rows() matrices. int matrix_rows() const { return matrix_rows_; } protected: /** * Evaluate the eigen values of the linear matrix. */ void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; /** * This function is not supported, since Eigen's eigen value solver does not * accept AutoDiffXd. */ void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; /** * This function is not supported, since Eigen's eigen value solver does not * accept symbolic::Expression type. */ void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; private: std::vector<Eigen::MatrixXd> F_; const int matrix_rows_{}; }; /** * Impose a generic (potentially nonlinear) constraint represented as a * vector of symbolic Expression. Expression::Evaluate is called on every * constraint evaluation. * * Uses symbolic::Jacobian to provide the gradients to the AutoDiff method. * * @ingroup solver_evaluators */ class ExpressionConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ExpressionConstraint) ExpressionConstraint(const Eigen::Ref<const VectorX<symbolic::Expression>>& v, const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub); /** * @return the list of the variables involved in the vector of expressions, * in the order that they are expected to be received during DoEval. * Any Binding that connects this constraint to decision variables should * pass this list of variables to the Binding. */ const VectorXDecisionVariable& vars() const { return vars_; } /** @return the symbolic expressions. */ const VectorX<symbolic::Expression>& expressions() const { return expressions_; } protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::ostream& DoDisplay(std::ostream&, const VectorX<symbolic::Variable>&) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; private: VectorX<symbolic::Expression> expressions_{0}; MatrixX<symbolic::Expression> derivatives_{0, 0}; // map_var_to_index_[vars_(i).get_id()] = i. VectorXDecisionVariable vars_{0}; std::unordered_map<symbolic::Variable::Id, int> map_var_to_index_; // Only for caching, does not carrying hidden state. mutable symbolic::Environment environment_; }; /** * An exponential cone constraint is a special type of convex cone constraint. * We constrain A * x + b to be in the exponential cone, where A has 3 rows, and * b is in ℝ³, x is the decision variable. * A vector z in ℝ³ is in the exponential cone, if * {z₀, z₁, z₂ | z₀ ≥ z₁ * exp(z₂ / z₁), z₁ > 0}. * Equivalently, this constraint can be refomulated with logarithm function * {z₀, z₁, z₂ | z₂ ≤ z₁ * log(z₀ / z₁), z₀ > 0, z₁ > 0} * * The Eval function implemented in this class is * z₀ - z₁ * exp(z₂ / z₁) >= 0, * z₁ > 0 * where z = A * x + b. * It is not recommended to solve an exponential cone constraint through * generic nonlinear optimization. It is possible that the nonlinear solver * can accidentally set z₁ = 0, where the constraint is not well defined. * Instead, the user should consider to solve the program through conic solvers * that can exploit exponential cone, such as MOSEK™ and SCS. * * @ingroup solver_evaluators */ class ExponentialConeConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ExponentialConeConstraint) /** * Constructor for exponential cone. * Constrains A * x + b to be in the exponential cone. * @pre A has 3 rows. */ ExponentialConeConstraint( const Eigen::Ref<const Eigen::SparseMatrix<double>>& A, const Eigen::Ref<const Eigen::Vector3d>& b); ~ExponentialConeConstraint() override{}; /** Getter for matrix A. */ const Eigen::SparseMatrix<double>& A() const { return A_; } /** Getter for vector b. */ const Eigen::Vector3d& b() const { return b_; } protected: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const; void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; std::string DoToLatex(const VectorX<symbolic::Variable>&, int) const override; private: Eigen::SparseMatrix<double> A_; Eigen::Vector3d b_; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/common_solver_option.cc
#include "drake/solvers/common_solver_option.h" #include "drake/common/drake_assert.h" namespace drake { namespace solvers { std::ostream& operator<<(std::ostream& os, CommonSolverOption common_solver_option) { switch (common_solver_option) { case CommonSolverOption::kPrintFileName: os << "kPrintFileName"; return os; case CommonSolverOption::kPrintToConsole: os << "kPrintToConsole"; return os; default: DRAKE_UNREACHABLE(); } } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/nlopt_solver_common.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/nlopt_solver.h" /* clang-format on */ #include "drake/common/never_destroyed.h" #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { NloptSolver::NloptSolver() : SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied) {} NloptSolver::~NloptSolver() = default; SolverId NloptSolver::id() { static const never_destroyed<SolverId> singleton{"NLopt"}; return singleton.access(); } bool NloptSolver::is_enabled() { return true; } bool NloptSolver::ProgramAttributesSatisfied(const MathematicalProgram& prog) { static const never_destroyed<ProgramAttributes> solver_capabilities( std::initializer_list<ProgramAttribute>{ ProgramAttribute::kGenericConstraint, ProgramAttribute::kLinearEqualityConstraint, ProgramAttribute::kLinearConstraint, ProgramAttribute::kQuadraticConstraint, ProgramAttribute::kLorentzConeConstraint, ProgramAttribute::kRotatedLorentzConeConstraint, ProgramAttribute::kGenericCost, ProgramAttribute::kLinearCost, ProgramAttribute::kQuadraticCost, ProgramAttribute::kCallback}); return AreRequiredAttributesSupported(prog.required_capabilities(), solver_capabilities.access()); } std::string NloptSolver::ConstraintToleranceName() { return "constraint_tol"; } std::string NloptSolver::XRelativeToleranceName() { return "xtol_rel"; } std::string NloptSolver::XAbsoluteToleranceName() { return "xtol_abs"; } std::string NloptSolver::MaxEvalName() { return "max_eval"; } std::string NloptSolver::AlgorithmName() { return "algorithm"; } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/program_attribute.cc
#include "drake/solvers/program_attribute.h" #include <algorithm> #include <deque> #include <sstream> #include <vector> #include <fmt/format.h> namespace drake { namespace solvers { bool AreRequiredAttributesSupported(const ProgramAttributes& required, const ProgramAttributes& supported, std::string* unsupported_message) { // Quick short-circuit if we're guaranteed to fail. if ((required.size() > supported.size()) && (unsupported_message == nullptr)) { return false; } // Check required vs supported. If a mismatch is found and we don't need to // produce a descriptive message, then we can bail immediately. Otherwise, // tally any unsupported attributes to populate the message at the end. std::vector<ProgramAttribute> unsupported_enums; for (const auto& attribute : required) { if (!supported.contains(attribute)) { if (unsupported_message == nullptr) { return false; } else { unsupported_enums.push_back(attribute); } } } // If nothing was missing, then we're all done. if (unsupported_enums.empty()) { if (unsupported_message != nullptr) { unsupported_message->clear(); } return true; } // We need to produce an error message, i.e., // "a FooCost was declared but is not supported" or // "a FooCost and BarCost were declared but are not supported" or // "a FooCost, BarCost, and QuuxCost were declared but are not supported". std::sort(unsupported_enums.begin(), unsupported_enums.end()); const int size = unsupported_enums.size(); std::string noun_phrase; for (int i = 0; i < size; ++i) { if (i >= 1) { if (size == 2) { noun_phrase += " and "; } else if (i == (size - 1)) { noun_phrase += ", and "; } else { noun_phrase += ", "; } } noun_phrase += to_string(unsupported_enums[i]); } *unsupported_message = fmt::format("a {} {} declared but {} not supported", noun_phrase, (size == 1) ? "was" : "were", (size == 1) ? "is" : "are"); return false; } std::string to_string(const ProgramAttribute& attr) { switch (attr) { case ProgramAttribute::kGenericCost: return "GenericCost"; case ProgramAttribute::kGenericConstraint: return "GenericConstraint"; case ProgramAttribute::kQuadraticCost: return "QuadraticCost"; case ProgramAttribute::kQuadraticConstraint: return "QuadraticConstraint"; case ProgramAttribute::kLinearCost: return "LinearCost"; case ProgramAttribute::kLinearConstraint: return "LinearConstraint"; case ProgramAttribute::kLinearEqualityConstraint: return "LinearEqualityConstraint"; case ProgramAttribute::kLinearComplementarityConstraint: return "LinearComplementarityConstraint"; case ProgramAttribute::kLorentzConeConstraint: return "LorentzConeConstraint"; case ProgramAttribute::kRotatedLorentzConeConstraint: return "RotatedLorentzConeConstraint"; case ProgramAttribute::kPositiveSemidefiniteConstraint: return "PositiveSemidefiniteConstraint"; case ProgramAttribute::kExponentialConeConstraint: return "ExponentialConeConstraint"; case ProgramAttribute::kL2NormCost: return "L2NormCost"; case ProgramAttribute::kBinaryVariable: return "BinaryVariable"; case ProgramAttribute::kCallback: return "Callback"; } DRAKE_UNREACHABLE(); } std::ostream& operator<<(std::ostream& os, const ProgramAttribute& attr) { os << to_string(attr); return os; } std::string to_string(const ProgramAttributes& attrs) { std::ostringstream result; result << attrs; return result.str(); } std::ostream& operator<<(std::ostream& os, const ProgramAttributes& attrs) { std::deque<ProgramAttribute> sorted(attrs.begin(), attrs.end()); std::sort(sorted.begin(), sorted.end()); os << "{ProgramAttributes: "; if (sorted.empty()) { os << "empty"; } else { os << sorted.front(); sorted.pop_front(); for (const auto& attr : sorted) { os << ", " << attr; } } os << "}"; return os; } std::string to_string(const ProgramType& program_type) { switch (program_type) { case ProgramType::kLP: return "linear programming"; case ProgramType::kQP: return "quadratic programming"; case ProgramType::kSOCP: return "second order cone programming"; case ProgramType::kSDP: return "semidefinite programming"; case ProgramType::kGP: return "geometric programming"; case ProgramType::kCGP: return "conic geometric programming"; case ProgramType::kMILP: return "mixed-integer linear programming"; case ProgramType::kMIQP: return "mixed-integer quadratic programming"; case ProgramType::kMISOCP: return "mixed-integer second order cone programming"; case ProgramType::kMISDP: return "mixed-integer semidefinite programming"; case ProgramType::kQuadraticCostConicConstraint: return "conic-constrained quadratic programming"; case ProgramType::kNLP: return "nonlinear programming"; case ProgramType::kLCP: return "linear complementarity programming"; case ProgramType::kUnknown: return "uncategorized mathematical programming type"; } DRAKE_UNREACHABLE(); } std::ostream& operator<<(std::ostream& os, const ProgramType& program_type) { os << to_string(program_type); return os; } } // namespace solvers } // namespace drake
0