repo_id
stringclasses 205
values | file_path
stringlengths 33
141
| content
stringlengths 1
307k
| __index_level_0__
int64 0
0
|
---|---|---|---|
/home/johnshepherd/drake/common/symbolic/expression | /home/johnshepherd/drake/common/symbolic/expression/test/ostream_test.cc | // Drake never uses operator<< for Eigen::Matix data, but we'd like users to be
// able to do so at their discretion. Therefore, we test it here to ensure that
// our NumTraits specialization is sufficient for this purpose.
#undef EIGEN_NO_IO
#include <sstream>
#include <gtest/gtest.h>
#include "drake/common/symbolic/expression/all.h"
namespace drake {
namespace symbolic {
namespace {
using std::ostringstream;
// Provides common variables and matrices that are used by the
// following tests.
class VariableOverloadingTest : public ::testing::Test {
protected:
const Variable x_{"x"};
const Variable y_{"y"};
const Variable z_{"z"};
const Variable w_{"w"};
Eigen::Matrix<Variable, 2, 2> var_mat_;
Eigen::Matrix<Expression, 2, 2> expr_mat_;
void SetUp() override {
// clang-format off
var_mat_ << x_, y_,
z_, w_;
expr_mat_ << (x_ + z_), (x_ + w_),
(y_ + z_), (y_ + w_);
// clang-format on
}
};
// XXX Mat<var> as well.
TEST_F(VariableOverloadingTest, EigenExpressionMatrixOutputStream) {
// The following fails if we do not provide
// `Eigen::NumTraits<drake::symbolic::DerivedA>`
ostringstream oss1;
oss1 << expr_mat_;
ostringstream oss2;
oss2 << " (x + z) (x + w)\n"
<< " (y + z) (y + w)";
EXPECT_EQ(oss1.str(), oss2.str());
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic/expression | /home/johnshepherd/drake/common/symbolic/expression/test/expression_differentiation_test.cc | /* clang-format off to disable clang-format-includes */
#include "drake/common/symbolic/expression/all.h"
/* clang-format on */
#include <cmath>
#include <exception>
#include <tuple>
#include <vector>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
namespace {
using std::domain_error;
using std::exception;
using std::get;
using std::tuple;
using std::vector;
using test::ExprEqual;
class SymbolicDifferentiationTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
};
// Given a function f and a variable x_i, returns newton's difference quotient
// of f :
//
// f(x1, ..., x_i + delta, ..., x_n) - f(x_1, ..., x_i, ..., x_n)
// ---------------------------------------------------------------
// delta
//
// where delta = sqrt(2.2e-16) * env[x_i]. See "Numerical Recipes in C", Chapter
// 5.7 to find more details about this choice of delta.
//
// We use this expression to check the correctness of Expression::Differentiate
// method numerically.
Expression DifferenceQuotient(const Expression& f, const Variable& x,
const Environment& env) {
const double delta{std::sqrt(2.2e-16) * Expression{x}.Evaluate(env)};
return (f.Substitute(x, x + delta) - f) / delta;
}
TEST_F(SymbolicDifferentiationTest, SymbolicBaseCases) {
const Expression& x{var_x_};
const Expression& y{var_y_};
const Expression& z{var_z_};
vector<tuple<Expression, Variable, Expression>> check_list;
// β/βx (0) = 0
check_list.emplace_back(0.0, var_x_, 0);
// β/βx (1) = 0
check_list.emplace_back(1.0, var_x_, 0);
// β/βx (x) = 1
check_list.emplace_back(x, var_x_, 1);
// β/βx (2 + x + y + z) = 1
check_list.emplace_back(2 + x + y + z, var_x_, 1);
// β/βx (2 + 3*x) = 3
check_list.emplace_back(2 + 3 * x, var_x_, 3);
// β/βx (1/x) = -1 / x^2
check_list.emplace_back(1 / x, var_x_, -1 / pow(x, 2));
// β/βx log(x) = 1 / x
check_list.emplace_back(log(x), var_x_, 1 / x);
// β/βx exp(x) = exp(x)
check_list.emplace_back(exp(x), var_x_, exp(x));
// β/βx sqrt(x) = 1 / (2 * sqrt(x))
check_list.emplace_back(sqrt(x), var_x_, 1 / (2 * sqrt(x)));
// β/βx pow(x, 5) = 5 * pow(x, 4)
check_list.emplace_back(pow(x, 5), var_x_, 5 * pow(x, 4));
// β/βx pow(5, x) = pow(5, x) * log(5)
check_list.emplace_back(pow(5, x), var_x_, pow(5, x) * log(5));
// β/βx pow(x, y) = y * pow(x, y - 1)
check_list.emplace_back(pow(x, y), var_x_, y * pow(x, y - 1));
// β/βy pow(x, y) = pow(x, y) * log(x)
check_list.emplace_back(pow(x, y), var_y_, pow(x, y) * log(x));
// β/βx sin(x) = cos(x)
check_list.emplace_back(sin(x), var_x_, cos(x));
// β/βx cos(x) = -sin(x)
check_list.emplace_back(cos(x), var_x_, -sin(x));
// β/βx tan(x) = sec^2(x) = 1 / cos(x)^2
check_list.emplace_back(tan(x), var_x_, 1 / (cos(x) * cos(x)));
// β/βx asin(x) = 1 / (sqrt(1-x^2))
check_list.emplace_back(asin(x), var_x_, 1 / (sqrt(1 - pow(x, 2))));
// β/βx acos(x) = -1 / (sqrt(1-x^2))
check_list.emplace_back(acos(x), var_x_, -1 / (sqrt(1 - pow(x, 2))));
// β/βx atan(x) = 1 / (x^2 + 1)
check_list.emplace_back(atan(x), var_x_, 1 / (pow(x, 2) + 1));
// β/βx atan2(x, y) = y / (x^2 + y^2)
check_list.emplace_back(atan2(x, y), var_x_, y / (pow(x, 2) + pow(y, 2)));
// β/βy atan2(x, y) = -x / (x^2 + y^2)
check_list.emplace_back(atan2(x, y), var_y_, -x / (pow(x, 2) + pow(y, 2)));
// β/βx sinh x = cosh(x)
check_list.emplace_back(sinh(x), var_x_, cosh(x));
// β/βx cosh(x) = sinh(x)
check_list.emplace_back(cosh(x), var_x_, sinh(x));
// β/βx tanh(x) = 1 / (pow(cosh(x), 2))
check_list.emplace_back(tanh(x), var_x_, 1 / (pow(cosh(x), 2)));
for (const tuple<Expression, Variable, Expression>& item : check_list) {
const Expression& expr{get<0>(item)};
const Variable& var{get<1>(item)};
const Expression& diff_result{get<2>(item)};
EXPECT_PRED2(ExprEqual, expr.Differentiate(var), diff_result);
}
}
TEST_F(SymbolicDifferentiationTest, SymbolicCompoundCases) {
const Expression& x{var_x_};
const Expression& y{var_y_};
const Expression& z{var_z_};
vector<tuple<Expression, Variable, Expression>> check_list;
// β/βx (5 + x + 2 * x^2 + 3 * x^3) = 1 + 4x + 9x^2
check_list.emplace_back(5 + x + 2 * x * x + 3 * pow(x, 3), var_x_,
1 + 4 * x + 9 * x * x);
// β/βx (-2 - 3 * x + 6 * x^2 - 4 * x^5) = -3 + 12 x - 20 x^4
check_list.emplace_back(-2 - 3 * x + 6 * pow(x, 2) - 4 * pow(x, 5), var_x_,
-3 + 12 * x - 20 * pow(x, 4));
// β/βx (3 * (x^3 -x)^3) = 9 * (x^3 -x)^2 * (3x^2 -1)
check_list.emplace_back(3 * pow(pow(x, 3) - x, 3), var_x_,
9 * pow(pow(x, 3) - x, 2) * (3 * pow(x, 2) - 1));
// β/βx [(x^3 + 2) / (x^2 - 3)]
// = [(x^2 - 3) * 3x^2 - (x^3 + 2) * 2x] / (x^2 - 3)^2
check_list.emplace_back(
(pow(x, 3) + 2) / (pow(x, 2) - 3), var_x_,
((pow(x, 2) - 3) * 3 * pow(x, 2) - (pow(x, 3) + 2) * 2 * x) /
pow(pow(x, 2) - 3, 2));
// β/βx x^3yz + xy + z + 3 = 3x^2yz + y
check_list.emplace_back(pow(x, 3) * y * z + x * y + z + 3, var_x_,
3 * pow(x, 2) * y * z + y);
// β/βy x^3yz + xy + z + 3 = x^3z + x
check_list.emplace_back(pow(x, 3) * y * z + x * y + z + 3, var_y_,
pow(x, 3) * z + x);
// β/βz x^3yz + xy + z + 3 = 3x^2y + 1
check_list.emplace_back(pow(x, 3) * y * z + x * y + z + 3, var_z_,
pow(x, 3) * y + 1);
// β/βx sin(xy) + cos(x) = y * cos(xy) - sin(x)
check_list.emplace_back(sin(x * y) + cos(x), var_x_, y * cos(x * y) - sin(x));
// β/βy sin(xy) + cos(x) = x * cos(xy)
check_list.emplace_back(sin(x * y) + cos(x), var_y_, x * cos(x * y));
// β/βx x * exp(xy) = exp(xy) + xy * exp(xy)
check_list.emplace_back(x * exp(x * y), var_x_,
exp(x * y) + (x * y) * exp(x * y));
// β/βy x * exp(xy) = x^2 exp(xy)
check_list.emplace_back(x * exp(x * y), var_y_, pow(x, 2) * exp(x * y));
// β/βx log(x^2 + 2y) = 2x / (x^2 + y)
check_list.emplace_back(log(pow(x, 2) + 2 * y), var_x_,
2 * x / (pow(x, 2) + 2 * y));
// β/βx log(x^2 + 2y) = 2 / (x^2 + 2 * y)
check_list.emplace_back(log(pow(x, 2) + 2 * y), var_y_,
2 / (pow(x, 2) + 2 * y));
// β/βx x * sin(x - y) = x * cos(x - y) + sin(x - y)
check_list.emplace_back(x * sin(x - y), var_x_, x * cos(x - y) + sin(x - y));
// β/βy x * sin(x - y) = -x * cos(x - y)
check_list.emplace_back(x * sin(x - y), var_y_, -x * cos(x - y));
// β/βx sin(y * cos(x)) = -y sin(x) cos(y cos(x))
check_list.emplace_back(sin(y * cos(x)), var_x_,
-y * sin(x) * cos(y * cos(x)));
// β/βy sin(y * cos(x)) = cos(x) cos(y cos(x))
check_list.emplace_back(sin(y * cos(x)), var_y_, cos(x) * cos(y * cos(x)));
// β/βx tan(x + y^2) = 1 / cos^2(x + y^2)
check_list.emplace_back(tan(x + pow(y, 2)), var_x_,
1 / (pow(cos(x + pow(y, 2)), 2)));
// β/βy tan(x + y^2) = 2y / cos^2(x + y^2)
check_list.emplace_back(tan(x + pow(y, 2)), var_y_,
2 * y / (pow(cos(x + pow(y, 2)), 2)));
// β/βx asin(x + 2y) = 1 / sqrt(1 - (x + y)^2)
check_list.emplace_back(asin(x + 2 * y), var_x_,
1 / sqrt(1 - pow(x + 2 * y, 2)));
// β/βy asin(x + 2y) = 2 / sqrt(1 - (x + y)^2)
check_list.emplace_back(asin(x + 2 * y), var_y_,
2 / sqrt(1 - pow(x + 2 * y, 2)));
// β/βx atan(3x + 2y) = 3 / ((3x + 2y)^2 + 1)
check_list.emplace_back(atan(3 * x + 2 * y), var_x_,
3 / (pow(3 * x + 2 * y, 2) + 1));
// β/βy atan(3x + 2y) = 2 / ((3x + 2y)^2 + 1)
check_list.emplace_back(atan(3 * x + 2 * y), var_y_,
2 / (pow(3 * x + 2 * y, 2) + 1));
// β/βx atan2(2x, 3y) = 6y / (4x^2 + 9y^2)
check_list.emplace_back(atan2(2 * x, 3 * y), var_x_,
6 * y / (pow(2 * x, 2) + pow(3 * y, 2)));
// β/βy atan2(2x, 3y) = -6x / (4x^2 + 9y^2)
check_list.emplace_back(atan2(2 * x, 3 * y), var_y_,
-6 * x / (pow(2 * x, 2) + pow(3 * y, 2)));
// β/βx sinh(2x + 3y) = 2 cosh(2x + 3y)
check_list.emplace_back(sinh(2 * x + 3 * y), var_x_, 2 * cosh(2 * x + 3 * y));
// β/βy sinh(2x + 3y) = 3 cosh(2x + 3y)
check_list.emplace_back(sinh(2 * x + 3 * y), var_y_, 3 * cosh(2 * x + 3 * y));
// β/βx cosh(2x + 3y) = 2 sinh(2x + 3y)
check_list.emplace_back(cosh(2 * x + 3 * y), var_x_, 2 * sinh(2 * x + 3 * y));
// β/βy cosh(2x + 3y) = 2 sinh(2x + 3y)
check_list.emplace_back(cosh(2 * x + 3 * y), var_y_, 3 * sinh(2 * x + 3 * y));
// β/βx tanh(2x + 3y) = 2 / (cosh^2(2x + 3y))
check_list.emplace_back(tanh(2 * x + 3 * y), var_x_,
2 / (pow(cosh(2 * x + 3 * y), 2)));
// β/βy tanh(2x + 3y) = 3 / (cosh^2(2x + 3y))
check_list.emplace_back(tanh(2 * x + 3 * y), var_y_,
3 / (pow(cosh(2 * x + 3 * y), 2)));
for (const tuple<Expression, Variable, Expression>& item : check_list) {
const Expression& expr{get<0>(item)};
const Variable& var{get<1>(item)};
const Expression& diff_result{get<2>(item)};
EXPECT_PRED2(ExprEqual, expr.Differentiate(var).Expand(),
diff_result.Expand());
}
}
TEST_F(SymbolicDifferentiationTest, NotDifferentiable) {
const Expression& x{var_x_};
const Expression& y{var_y_};
Expression dummy;
Environment env{{var_x_, 0}, {var_y_, 1}};
// if_then_else is differentiable on relational expressions where the
// arms of the relation are unequal.
EXPECT_ANY_THROW(
if_then_else(x == 0, y + 1, y).Differentiate(var_x_).Evaluate(env));
EXPECT_NO_THROW(
if_then_else(x == 1, y + 1, y).Differentiate(var_x_).Evaluate(env));
// abs, min, max, ceil, and floor are not differentiable with respect to a
// variable if an argument includes the variable and if the argument is at
// the function's corner/discontinuity.
EXPECT_ANY_THROW(abs(x).Differentiate(var_x_).Evaluate(env));
EXPECT_NO_THROW(abs(x + 1).Differentiate(var_x_).Evaluate(env));
EXPECT_ANY_THROW(ceil(x).Differentiate(var_x_).Evaluate(env));
EXPECT_NO_THROW(ceil(x + 0.5).Differentiate(var_x_).Evaluate(env));
EXPECT_ANY_THROW(floor(x).Differentiate(var_x_).Evaluate(env));
EXPECT_NO_THROW(floor(x + 0.5).Differentiate(var_x_).Evaluate(env));
EXPECT_ANY_THROW(dummy = min(x + 1, y).Differentiate(var_y_).Evaluate(env));
EXPECT_NO_THROW(dummy = min(x, y).Differentiate(var_x_).Evaluate(env));
EXPECT_ANY_THROW(dummy = max(x + 1, y).Differentiate(var_x_).Evaluate(env));
EXPECT_NO_THROW(dummy = max(x, y).Differentiate(var_y_).Evaluate(env));
// Those functions are all differentiable if the variable for
// differentiation does not occur in the function body.
EXPECT_EQ(abs(x).Differentiate(var_y_), 0.0);
EXPECT_EQ(ceil(x).Differentiate(var_y_), 0.0);
EXPECT_EQ(floor(x).Differentiate(var_y_), 0.0);
EXPECT_EQ(min(x, y).Differentiate(var_z_), 0.0);
EXPECT_EQ(max(x, y).Differentiate(var_z_), 0.0);
EXPECT_EQ(if_then_else(x > y - 1, x, y).Differentiate(var_z_), 0.0);
}
// It tests if the evaluation result of a symbolic differentiation is close to
// the evaluation of newton's difference quotient. Note that this test,
// NumericalTests1, only includes functions which are well-defined over Real.
TEST_F(SymbolicDifferentiationTest, NumericalTests1) {
const Expression& x{var_x_};
const Expression& y{var_y_};
const Expression& z{var_z_};
// Set up functions to test
vector<Expression> fns;
fns.push_back(3.0);
fns.push_back(7 + -3 * x + 5 * y - 7 * z);
fns.push_back(-2.0 + 2 * x * y - 3 * y * z + 0.5 * z * x);
fns.push_back(x / y);
fns.push_back(y / x);
fns.push_back(1 / x * y * z);
fns.push_back(exp(x));
fns.push_back(sin(x));
fns.push_back(cos(x));
fns.push_back(tan(x));
fns.push_back(atan(x));
fns.push_back(atan2(x, y));
fns.push_back(atan2(y, x));
fns.push_back(sinh(x));
fns.push_back(cosh(x));
fns.push_back(tanh(x));
fns.push_back(exp(cos(x) / 10 + tan(y) / 10));
fns.push_back(sin(x * y + z));
fns.push_back(cos(x / y + z));
fns.push_back(tan(x * z - y));
fns.push_back(atan(0.1 * (x + y - z)));
fns.push_back(atan2(x * y, y * z));
fns.push_back(atan2(y * z, x * z));
fns.push_back(sinh((x * x + y * y + z * z) / 100));
fns.push_back(cosh((x * x + y * y + z * z) / 100));
fns.push_back(tanh((x * x + y * y + z * z) / 100));
// Set up environments to test
vector<Environment> envs;
envs.push_back({{var_x_, 0.3}, {var_y_, 0.2}, {var_z_, 0.2}});
envs.push_back({{var_x_, 1.4}, {var_y_, -0.1}, {var_z_, 3.1}});
envs.push_back({{var_x_, 2.2}, {var_y_, 3.0}, {var_z_, 2.3}});
envs.push_back({{var_x_, -5.7}, {var_y_, 4.9}, {var_z_, -5.4}});
envs.push_back({{var_x_, 3.1}, {var_y_, -0.8}, {var_z_, 2.5}});
envs.push_back({{var_x_, 2.8}, {var_y_, -5.7}, {var_z_, 3.6}});
// Set up variables for differentiation to test
const Variables vars{var_x_, var_y_, var_z_};
const double eps{1e-5}; // This choice of eps is arbitrary.
for (const Expression& f : fns) {
for (const Environment& env : envs) {
for (const Variable& var : vars) {
const double grad{f.Differentiate(var).Evaluate(env)};
const double diff{DifferenceQuotient(f, var, env).Evaluate(env)};
EXPECT_NEAR(grad, diff, eps);
}
}
}
}
// It tests if the evaluation result of a symbolic differentiation is close to
// the evaluation of newton's difference quotient. Note that this test,
// NumericalTests2, only includes functions whose domains are restricted. We've
// tailored the environments so that no domain_error occurs during the test.
TEST_F(SymbolicDifferentiationTest, NumericalTests2) {
const Expression& x{var_x_};
const Expression& y{var_y_};
const Expression& z{var_z_};
// Set up functions to test
vector<Expression> fns;
fns.push_back(log(x)); //
fns.push_back(log(sin(x) + cos(x) + 2));
fns.push_back(sqrt(x)); //
fns.push_back(pow(x, y));
fns.push_back(pow(y, x));
fns.push_back(asin(x / 10));
fns.push_back(acos(x / 10));
fns.push_back(asin(0.1 * (x + y - z)));
fns.push_back(acos(0.1 * (x + y - z)));
fns.push_back(pow(x + y, y / x / 10));
fns.push_back(pow(y * z, (x + z) / 5));
// Set up environments to test
vector<Environment> envs;
envs.push_back({{var_x_, 0.3}, {var_y_, 1}, {var_z_, 0.2}});
envs.push_back({{var_x_, 1.4}, {var_y_, 2}, {var_z_, 3.1}});
envs.push_back({{var_x_, 2.2}, {var_y_, 4}, {var_z_, 2.3}});
envs.push_back({{var_x_, 4.7}, {var_y_, 3}, {var_z_, 3.4}});
envs.push_back({{var_x_, 3.1}, {var_y_, 3}, {var_z_, 2.5}});
envs.push_back({{var_x_, 2.8}, {var_y_, 2}, {var_z_, 2.6}});
// Set up variables for differentiation to test
const Variables vars{var_x_, var_y_, var_z_};
const double eps{1e-5}; // This choice of eps is arbitrary.
for (const Expression& f : fns) {
for (const Environment& env : envs) {
for (const Variable& var : vars) {
const double grad{f.Differentiate(var).Evaluate(env)};
const double diff{DifferenceQuotient(f, var, env).Evaluate(env)};
EXPECT_NEAR(grad, diff, eps);
}
}
}
}
TEST_F(SymbolicDifferentiationTest, UninterpretedFunction) {
const Expression uf{uninterpreted_function("uf", {var_x_, var_y_})};
Expression dummy;
EXPECT_THROW(dummy = uf.Differentiate(var_x_), std::runtime_error);
EXPECT_THROW(dummy = uf.Differentiate(var_y_), std::runtime_error);
EXPECT_PRED2(ExprEqual, uf.Differentiate(var_z_), Expression::Zero());
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic/expression | /home/johnshepherd/drake/common/symbolic/expression/test/variables_test.cc | /* clang-format off to disable clang-format-includes */
#include "drake/common/symbolic/expression/all.h"
/* clang-format on */
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
namespace drake {
namespace symbolic {
namespace {
template <typename T>
size_t get_std_hash(const T& item) {
return std::hash<T>{}(item);
}
// Provides common variables that are used by the following tests.
class VariablesTest : public ::testing::Test {
protected:
const Variable x_{"x"};
const Variable y_{"y"};
const Variable z_{"z"};
const Variable w_{"w"};
const Variable v_{"v"};
};
TEST_F(VariablesTest, ConstructFromVariableVector) {
const Eigen::Matrix<symbolic::Variable, 3, 1> v1(x_, y_, z_);
const Variables vars1(v1); // vars1 = {x, y, z}
EXPECT_EQ(vars1.size(), 3u);
EXPECT_TRUE(vars1.include(x_));
EXPECT_TRUE(vars1.include(y_));
EXPECT_TRUE(vars1.include(z_));
VectorX<Variable> v2(3);
v2 << x_, x_, y_;
const Variables vars2(v2); // vars2 = {x, y}
EXPECT_EQ(vars2.size(), 2u);
EXPECT_TRUE(vars2.include(x_));
EXPECT_TRUE(vars2.include(y_));
EXPECT_FALSE(vars2.include(z_));
}
TEST_F(VariablesTest, HashEq) {
const Variables vars1{x_, y_, z_};
const Variables vars2{z_, y_, x_};
EXPECT_EQ(get_std_hash(vars1), get_std_hash(vars2));
EXPECT_EQ(vars1, vars2);
}
TEST_F(VariablesTest, InsertSize) {
Variables vars1{x_, y_, z_};
EXPECT_EQ(vars1.size(), 3u);
vars1.insert(x_);
vars1.insert(y_);
vars1.insert(z_);
EXPECT_EQ(vars1.size(), 3u);
}
TEST_F(VariablesTest, Plus) {
Variables vars1{x_, y_, z_};
EXPECT_EQ(vars1.size(), 3u);
EXPECT_TRUE(vars1.include(x_));
EXPECT_TRUE(vars1.include(y_));
EXPECT_TRUE(vars1.include(z_));
vars1 = vars1 + x_;
vars1 += y_;
vars1 += z_;
EXPECT_EQ(vars1.size(), 3u);
vars1 = vars1 + w_;
EXPECT_EQ(vars1.size(), 4u);
EXPECT_TRUE(vars1.include(w_));
vars1 += v_;
EXPECT_EQ(vars1.size(), 5u);
EXPECT_TRUE(vars1.include(z_));
}
TEST_F(VariablesTest, Erase) {
Variables vars1{x_, y_, z_};
Variables vars2{y_, z_, w_};
EXPECT_EQ(vars1.size(), 3u);
vars1.erase(y_);
EXPECT_EQ(vars1.size(), 2u);
EXPECT_FALSE(vars1.include(y_));
vars1.erase(vars2);
EXPECT_EQ(vars1.size(), 1u);
EXPECT_TRUE(vars1.include(x_));
EXPECT_FALSE(vars1.include(y_));
EXPECT_FALSE(vars1.include(z_));
}
TEST_F(VariablesTest, Minus) {
Variables vars1{x_, y_, z_};
EXPECT_EQ(vars1.size(), 3u);
EXPECT_TRUE(vars1.include(x_));
EXPECT_TRUE(vars1.include(y_));
EXPECT_TRUE(vars1.include(z_));
EXPECT_TRUE(vars1.include(x_));
vars1 = vars1 - x_;
EXPECT_EQ(vars1.size(), 2u);
EXPECT_FALSE(vars1.include(x_));
vars1 -= y_;
EXPECT_FALSE(vars1.include(y_));
vars1 -= z_;
EXPECT_FALSE(vars1.include(z_));
EXPECT_EQ(vars1.size(), 0u);
Variables vars2{x_, y_, z_};
const Variables vars3{y_, z_, w_};
EXPECT_EQ(vars2.size(), 3u);
vars2 -= vars3;
EXPECT_EQ(vars2.size(), 1u);
EXPECT_TRUE(vars2.include(x_));
}
TEST_F(VariablesTest, IsSubsetOf) {
const Variables vars1{x_, y_, z_, w_, v_};
const Variables vars2{x_, y_};
const Variables vars3{x_, y_, z_};
const Variables vars4{z_, w_, v_};
const Variables vars5{w_, v_};
// vars1 = {x, y, z, w, v}
EXPECT_TRUE(vars1.IsSubsetOf(vars1));
EXPECT_FALSE(vars1.IsSubsetOf(vars2));
EXPECT_FALSE(vars1.IsSubsetOf(vars3));
EXPECT_FALSE(vars1.IsSubsetOf(vars4));
EXPECT_FALSE(vars1.IsSubsetOf(vars5));
// vars2 = {x, y}
EXPECT_TRUE(vars2.IsSubsetOf(vars1));
EXPECT_TRUE(vars2.IsSubsetOf(vars2));
EXPECT_TRUE(vars2.IsSubsetOf(vars3));
EXPECT_FALSE(vars2.IsSubsetOf(vars4));
EXPECT_FALSE(vars2.IsSubsetOf(vars5));
// vars3 = {x_, y_, z_}
EXPECT_TRUE(vars3.IsSubsetOf(vars1));
EXPECT_FALSE(vars3.IsSubsetOf(vars2));
EXPECT_TRUE(vars3.IsSubsetOf(vars3));
EXPECT_FALSE(vars3.IsSubsetOf(vars4));
EXPECT_FALSE(vars3.IsSubsetOf(vars5));
// vars4 = {z, w, v}
EXPECT_TRUE(vars4.IsSubsetOf(vars1));
EXPECT_FALSE(vars4.IsSubsetOf(vars2));
EXPECT_FALSE(vars4.IsSubsetOf(vars3));
EXPECT_TRUE(vars4.IsSubsetOf(vars4));
EXPECT_FALSE(vars4.IsSubsetOf(vars5));
// vars5 = {w, v}
EXPECT_TRUE(vars5.IsSubsetOf(vars1));
EXPECT_FALSE(vars5.IsSubsetOf(vars2));
EXPECT_FALSE(vars5.IsSubsetOf(vars3));
EXPECT_TRUE(vars5.IsSubsetOf(vars4));
EXPECT_TRUE(vars5.IsSubsetOf(vars5));
}
TEST_F(VariablesTest, IsStrictSubsetOf) {
const Variables vars1{x_, y_, z_, w_, v_};
const Variables vars2{x_, y_};
const Variables vars3{x_, y_, z_};
const Variables vars4{z_, w_, v_};
const Variables vars5{w_, v_};
// vars1 = {x, y, z, w, v}
EXPECT_FALSE(vars1.IsStrictSubsetOf(vars1));
EXPECT_FALSE(vars1.IsStrictSubsetOf(vars2));
EXPECT_FALSE(vars1.IsStrictSubsetOf(vars3));
EXPECT_FALSE(vars1.IsStrictSubsetOf(vars4));
EXPECT_FALSE(vars1.IsStrictSubsetOf(vars5));
// vars2 = {x, y}
EXPECT_TRUE(vars2.IsStrictSubsetOf(vars1));
EXPECT_FALSE(vars2.IsStrictSubsetOf(vars2));
EXPECT_TRUE(vars2.IsStrictSubsetOf(vars3));
EXPECT_FALSE(vars2.IsStrictSubsetOf(vars4));
EXPECT_FALSE(vars2.IsStrictSubsetOf(vars5));
// vars3 = {x_, y_, z_}
EXPECT_TRUE(vars3.IsStrictSubsetOf(vars1));
EXPECT_FALSE(vars3.IsStrictSubsetOf(vars2));
EXPECT_FALSE(vars3.IsStrictSubsetOf(vars3));
EXPECT_FALSE(vars3.IsStrictSubsetOf(vars4));
EXPECT_FALSE(vars3.IsStrictSubsetOf(vars5));
// vars4 = {z, w, v}
EXPECT_TRUE(vars4.IsStrictSubsetOf(vars1));
EXPECT_FALSE(vars4.IsStrictSubsetOf(vars2));
EXPECT_FALSE(vars4.IsStrictSubsetOf(vars3));
EXPECT_FALSE(vars4.IsStrictSubsetOf(vars4));
EXPECT_FALSE(vars4.IsStrictSubsetOf(vars5));
// vars5 = {w, v}
EXPECT_TRUE(vars5.IsStrictSubsetOf(vars1));
EXPECT_FALSE(vars5.IsStrictSubsetOf(vars2));
EXPECT_FALSE(vars5.IsStrictSubsetOf(vars3));
EXPECT_TRUE(vars5.IsStrictSubsetOf(vars4));
EXPECT_FALSE(vars5.IsStrictSubsetOf(vars5));
}
TEST_F(VariablesTest, IsSuperSetOf) {
const Variables vars1{x_, y_, z_, w_, v_};
const Variables vars2{x_, y_};
const Variables vars3{x_, y_, z_};
const Variables vars4{z_, w_, v_};
const Variables vars5{w_, v_};
// vars1 = {x, y, z, w, v}
EXPECT_TRUE(vars1.IsSupersetOf(vars1));
EXPECT_TRUE(vars1.IsSupersetOf(vars2));
EXPECT_TRUE(vars1.IsSupersetOf(vars3));
EXPECT_TRUE(vars1.IsSupersetOf(vars4));
EXPECT_TRUE(vars1.IsSupersetOf(vars5));
// vars2 = {x, y}
EXPECT_FALSE(vars2.IsSupersetOf(vars1));
EXPECT_TRUE(vars2.IsSupersetOf(vars2));
EXPECT_FALSE(vars2.IsSupersetOf(vars3));
EXPECT_FALSE(vars2.IsSupersetOf(vars4));
EXPECT_FALSE(vars2.IsSupersetOf(vars5));
// vars3 = {x_, y_, z_}
EXPECT_FALSE(vars3.IsSupersetOf(vars1));
EXPECT_TRUE(vars3.IsSupersetOf(vars2));
EXPECT_TRUE(vars3.IsSupersetOf(vars3));
EXPECT_FALSE(vars3.IsSupersetOf(vars4));
EXPECT_FALSE(vars3.IsSupersetOf(vars5));
// vars4 = {z, w, v}
EXPECT_FALSE(vars4.IsSupersetOf(vars1));
EXPECT_FALSE(vars4.IsSupersetOf(vars2));
EXPECT_FALSE(vars4.IsSupersetOf(vars3));
EXPECT_TRUE(vars4.IsSupersetOf(vars4));
EXPECT_TRUE(vars4.IsSupersetOf(vars5));
// vars5 = {w, v}
EXPECT_FALSE(vars5.IsSupersetOf(vars1));
EXPECT_FALSE(vars5.IsSupersetOf(vars2));
EXPECT_FALSE(vars5.IsSupersetOf(vars3));
EXPECT_FALSE(vars5.IsSupersetOf(vars4));
EXPECT_TRUE(vars5.IsSupersetOf(vars5));
}
TEST_F(VariablesTest, IsStrictSuperSetOf) {
const Variables vars1{x_, y_, z_, w_, v_};
const Variables vars2{x_, y_};
const Variables vars3{x_, y_, z_};
const Variables vars4{z_, w_, v_};
const Variables vars5{w_, v_};
// vars1 = {x, y, z, w, v}
EXPECT_FALSE(vars1.IsStrictSupersetOf(vars1));
EXPECT_TRUE(vars1.IsStrictSupersetOf(vars2));
EXPECT_TRUE(vars1.IsStrictSupersetOf(vars3));
EXPECT_TRUE(vars1.IsStrictSupersetOf(vars4));
EXPECT_TRUE(vars1.IsStrictSupersetOf(vars5));
// vars2 = {x, y}
EXPECT_FALSE(vars2.IsStrictSupersetOf(vars1));
EXPECT_FALSE(vars2.IsStrictSupersetOf(vars2));
EXPECT_FALSE(vars2.IsStrictSupersetOf(vars3));
EXPECT_FALSE(vars2.IsStrictSupersetOf(vars4));
EXPECT_FALSE(vars2.IsStrictSupersetOf(vars5));
// vars3 = {x_, y_, z_}
EXPECT_FALSE(vars3.IsStrictSupersetOf(vars1));
EXPECT_TRUE(vars3.IsStrictSupersetOf(vars2));
EXPECT_FALSE(vars3.IsStrictSupersetOf(vars3));
EXPECT_FALSE(vars3.IsStrictSupersetOf(vars4));
EXPECT_FALSE(vars3.IsStrictSupersetOf(vars5));
// vars4 = {z, w, v}
EXPECT_FALSE(vars4.IsStrictSupersetOf(vars1));
EXPECT_FALSE(vars4.IsStrictSupersetOf(vars2));
EXPECT_FALSE(vars4.IsStrictSupersetOf(vars3));
EXPECT_FALSE(vars4.IsStrictSupersetOf(vars4));
EXPECT_TRUE(vars4.IsStrictSupersetOf(vars5));
// vars5 = {w, v}
EXPECT_FALSE(vars5.IsStrictSupersetOf(vars1));
EXPECT_FALSE(vars5.IsStrictSupersetOf(vars2));
EXPECT_FALSE(vars5.IsStrictSupersetOf(vars3));
EXPECT_FALSE(vars5.IsStrictSupersetOf(vars4));
EXPECT_FALSE(vars5.IsStrictSupersetOf(vars5));
}
TEST_F(VariablesTest, Intersection) {
const Variables vars1{x_, y_, z_, w_, v_};
const Variables vars2{x_, y_};
const Variables vars3{x_, y_, z_};
const Variables vars4{z_, w_, v_};
const Variables vars5{w_, v_};
EXPECT_EQ(intersect(vars1, vars1), vars1);
EXPECT_EQ(intersect(vars1, vars2), vars2);
EXPECT_EQ(intersect(vars1, vars3), vars3);
EXPECT_EQ(intersect(vars1, vars4), vars4);
EXPECT_EQ(intersect(vars1, vars5), vars5);
EXPECT_EQ(intersect(vars2, vars1), vars2);
EXPECT_EQ(intersect(vars2, vars2), vars2);
EXPECT_EQ(intersect(vars2, vars3), vars2);
EXPECT_EQ(intersect(vars2, vars4), Variables{});
EXPECT_EQ(intersect(vars2, vars5), Variables{});
EXPECT_EQ(intersect(vars3, vars1), vars3);
EXPECT_EQ(intersect(vars3, vars2), vars2);
EXPECT_EQ(intersect(vars3, vars3), vars3);
EXPECT_EQ(intersect(vars3, vars4), Variables({z_}));
EXPECT_EQ(intersect(vars3, vars5), Variables{});
EXPECT_EQ(intersect(vars4, vars1), vars4);
EXPECT_EQ(intersect(vars4, vars2), Variables{});
EXPECT_EQ(intersect(vars4, vars3), Variables({z_}));
EXPECT_EQ(intersect(vars4, vars4), vars4);
EXPECT_EQ(intersect(vars4, vars5), vars5);
EXPECT_EQ(intersect(vars5, vars1), vars5);
EXPECT_EQ(intersect(vars5, vars2), Variables{});
EXPECT_EQ(intersect(vars5, vars3), Variables{});
EXPECT_EQ(intersect(vars5, vars4), vars5);
EXPECT_EQ(intersect(vars5, vars5), vars5);
}
TEST_F(VariablesTest, ToString) {
const Variables vars0{};
const Variables vars1{x_, y_, z_, w_, v_};
const Variables vars2{x_, y_};
const Variables vars3{x_, y_, z_};
const Variables vars4{z_, w_, v_};
const Variables vars5{w_, v_};
EXPECT_EQ(vars0.to_string(), "{}");
EXPECT_EQ(vars1.to_string(), "{x, y, z, w, v}");
EXPECT_EQ(vars2.to_string(), "{x, y}");
EXPECT_EQ(vars3.to_string(), "{x, y, z}");
EXPECT_EQ(vars4.to_string(), "{z, w, v}");
EXPECT_EQ(vars5.to_string(), "{w, v}");
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic/expression | /home/johnshepherd/drake/common/symbolic/expression/test/expression_array_test.cc | /* clang-format off to disable clang-format-includes */
#include "drake/common/symbolic/expression/all.h"
/* clang-format on */
#include <functional>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
namespace {
using test::FormulaEqual;
class SymbolicExpressionArrayTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
const Expression x_{var_x_};
const Expression y_{var_y_};
const Expression z_{var_z_};
const Expression zero_{0.0};
const Expression one_{1.0};
const Expression two_{2.0};
const Expression neg_one_{-1.0};
const Expression pi_{3.141592};
const Expression neg_pi_{-3.141592};
const Expression e_{2.718};
Eigen::Matrix<Expression, 3, 2, Eigen::DontAlign> A_;
Eigen::Matrix<Expression, 2, 3, Eigen::DontAlign> B_;
Eigen::Matrix<Expression, 3, 2, Eigen::DontAlign> C_;
Eigen::Array<Expression, 2, 2, Eigen::DontAlign> array_expr_1_;
Eigen::Array<Expression, 2, 2, Eigen::DontAlign> array_expr_2_;
Eigen::Array<Variable, 2, 2, Eigen::DontAlign> array_var_1_;
Eigen::Array<Variable, 2, 2, Eigen::DontAlign> array_var_2_;
Eigen::Array<double, 2, 2, Eigen::DontAlign> array_double_;
void SetUp() override {
// clang-format off
A_ << x_, one_, // [x 1]
y_, neg_one_, // [y -1]
z_, pi_; // [z 3.141592]
B_ << x_, y_, z_, // [x y z]
e_, pi_, two_; // [2.718 3.141592 2]
C_ << z_, two_, // [z 2]
x_, e_, // [x -2.718]
y_, pi_; // [y 3.141592]
array_expr_1_ << x_, y_,
z_, x_;
array_expr_2_ << z_, x_,
y_, z_;
array_var_1_ << var_x_, var_y_,
var_z_, var_x_;
array_var_2_ << var_y_, var_z_,
var_x_, var_x_;
array_double_ << 1.0, 2.0,
3.0, 4.0;
// clang-format on
}
};
// Given two Eigen arrays a1 and a2, it checks if a1 == a2 returns an array
// whose (i, j) element is a formula a1(i, j) == a2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<DerivedA>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<typename Eigen::internal::traits<DerivedB>::XprKind,
Eigen::ArrayXpr>,
bool>
CheckArrayOperatorEq(const DerivedA& a1, const DerivedB& a2) {
const auto arr = (a1 == a2);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a1(i, j) == a2(i, j))) {
return false;
}
}
}
return true;
}
// Given a scalar-type object @p v and an Eigen array @p a, it checks if v == a
// returns an array whose (i, j)-element is a formula v == a(i, j).
template <typename ScalarType, typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(ScalarType() == typename Derived::Scalar()),
Formula>,
bool>
CheckArrayOperatorEq(const ScalarType& v, const Derived& a) {
const Eigen::Array<Formula, Derived::RowsAtCompileTime,
Derived::ColsAtCompileTime>
arr = (v == a);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(v == a(i, j))) {
return false;
}
}
}
return true;
}
// Given an Eigen array @p a and a scalar-type object @p v, it checks if a == v
// returns an array whose (i, j)-element is a formula a(i, j) == v.
template <typename Derived, typename ScalarType>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(typename Derived::Scalar() == ScalarType()),
Formula>,
bool>
CheckArrayOperatorEq(const Derived& a, const ScalarType& v) {
const Eigen::Array<Formula, Derived::RowsAtCompileTime,
Derived::ColsAtCompileTime>
arr = (a == v);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a(i, j) == v)) {
return false;
}
}
}
return true;
}
// Given two Eigen matrices m1 and m2, it checks if m1.array() == m2.array()
// returns an array whose (i, j) element is a formula m1(i, j) == m2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<DerivedA>::XprKind,
Eigen::MatrixXpr> &&
std::is_same_v<typename Eigen::internal::traits<DerivedB>::XprKind,
Eigen::MatrixXpr>,
bool>
CheckArrayOperatorEq(const DerivedA& m1, const DerivedB& m2) {
return CheckArrayOperatorEq(m1.array(), m2.array());
}
// Given two Eigen arrays a1 and a2, it checks if a1 <= a2 returns an array
// whose (i, j) element is a formula a1(i, j) <= a2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_base_of_v<Eigen::ArrayBase<DerivedA>, DerivedA> &&
std::is_base_of_v<Eigen::ArrayBase<DerivedB>, DerivedB>,
bool>
CheckArrayOperatorLte(const DerivedA& a1, const DerivedB& a2) {
const auto arr = (a1 <= a2);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a1(i, j) <= a2(i, j))) {
return false;
}
}
}
return true;
}
// Given a scalar-type object @p v and an Eigen array @p a, it checks if v <= a
// returns an array whose (i, j)-element is a formula v <= a(i, j).
template <typename ScalarType, typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(ScalarType() <= typename Derived::Scalar()),
Formula>,
bool>
CheckArrayOperatorLte(const ScalarType& v, const Derived& a) {
const auto arr = (v <= a);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(v <= a(i, j))) {
return false;
}
}
}
return true;
}
// Given an Eigen array @p a and a scalar-type object @p v, it checks if a <= v
// returns an array whose (i, j)-element is a formula a(i, j) <= v.
template <typename Derived, typename ScalarType>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(typename Derived::Scalar() <= ScalarType()),
Formula>,
bool>
CheckArrayOperatorLte(const Derived& a, const ScalarType& v) {
const auto arr = (a <= v);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a(i, j) <= v)) {
return false;
}
}
}
return true;
}
// Given two Eigen matrices m1 and m2, it checks if m1.array() <= m2.array()
// returns an array whose (i, j) element is a formula m1(i, j) <= m2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<DerivedA>::XprKind,
Eigen::MatrixXpr> &&
std::is_same_v<typename Eigen::internal::traits<DerivedB>::XprKind,
Eigen::MatrixXpr>,
bool>
CheckArrayOperatorLte(const DerivedA& m1, const DerivedB& m2) {
return CheckArrayOperatorLte(m1.array(), m2.array());
}
// Given two Eigen arrays a1 and a2, it checks if a1 < a2 returns an array whose
// (i, j) element is a formula a1(i, j) < a2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_base_of_v<Eigen::ArrayBase<DerivedA>, DerivedA> &&
std::is_base_of_v<Eigen::ArrayBase<DerivedB>, DerivedB>,
bool>
CheckArrayOperatorLt(const DerivedA& a1, const DerivedB& a2) {
const auto arr = (a1 < a2);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a1(i, j) < a2(i, j))) {
return false;
}
}
}
return true;
}
// Given a scalar-type object @p v and an Eigen array @p a, it checks if v < a
// returns an array whose (i, j)-element is a formula v < a(i, j).
template <typename ScalarType, typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(ScalarType() < typename Derived::Scalar()),
Formula>,
bool>
CheckArrayOperatorLt(const ScalarType& v, const Derived& a) {
const auto arr = (v < a);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(v < a(i, j))) {
return false;
}
}
}
return true;
}
// Given an Eigen array @p a and a scalar-type object @p v, it checks if a < v
// returns an array whose (i, j)-element is a formula a(i, j) < v.
template <typename Derived, typename ScalarType>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(typename Derived::Scalar() < ScalarType()),
Formula>,
bool>
CheckArrayOperatorLt(const Derived& a, const ScalarType& v) {
const auto arr = (a < v);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a(i, j) < v)) {
return false;
}
}
}
return true;
}
// Given two Eigen matrices m1 and m2, it checks if m1.array() < m2.array()
// returns an array whose (i, j) element is a formula m1(i, j) < m2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<DerivedA>::XprKind,
Eigen::MatrixXpr> &&
std::is_same_v<typename Eigen::internal::traits<DerivedB>::XprKind,
Eigen::MatrixXpr>,
bool>
CheckArrayOperatorLt(const DerivedA& m1, const DerivedB& m2) {
return CheckArrayOperatorLt(m1.array(), m2.array());
}
// Given two Eigen arrays a1 and a2, it checks if a1 >= a2 returns an array
// whose (i, j) element is a formula a1(i, j) >= a2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_base_of_v<Eigen::ArrayBase<DerivedA>, DerivedA> &&
std::is_base_of_v<Eigen::ArrayBase<DerivedB>, DerivedB>,
bool>
CheckArrayOperatorGte(const DerivedA& a1, const DerivedB& a2) {
const auto arr = (a1 >= a2);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a1(i, j) >= a2(i, j))) {
return false;
}
}
}
return true;
}
// Given a scalar-type object @p v and an Eigen array @p a, it checks if v >= a
// returns an array whose (i, j)-element is a formula a(i, j) <= v.
template <typename ScalarType, typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(ScalarType() >= typename Derived::Scalar()),
Formula>,
bool>
CheckArrayOperatorGte(const ScalarType& v, const Derived& a) {
const auto arr = (v >= a);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
// Note that arr(i, j) should be `a(i, j) <= v` instead of `v >= a(i, j)`.
if (!arr(i, j).EqualTo(a(i, j) <= v)) {
return false;
}
}
}
return true;
}
// Given an Eigen array @p a and a scalar-type object @p v, it checks if a >= v
// returns an array whose (i, j)-element is a formula a(i, j) >= v.
template <typename Derived, typename ScalarType>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(typename Derived::Scalar() >= ScalarType()),
Formula>,
bool>
CheckArrayOperatorGte(const Derived& a, const ScalarType& v) {
const auto arr = (a >= v);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
// TODO(soonho): Add note here.
if (!arr(i, j).EqualTo(a(i, j) >= v)) {
return false;
}
}
}
return true;
}
// Given two Eigen matrices m1 and m2, it checks if m1.array() >= m2.array()
// returns an array whose (i, j) element is a formula m1(i, j) >= m2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<DerivedA>::XprKind,
Eigen::MatrixXpr> &&
std::is_same_v<typename Eigen::internal::traits<DerivedB>::XprKind,
Eigen::MatrixXpr>,
bool>
CheckArrayOperatorGte(const DerivedA& m1, const DerivedB& m2) {
return CheckArrayOperatorGte(m1.array(), m2.array());
}
// Given two Eigen arrays a1 and a2, it checks if a1 > a2 returns an array whose
// (i, j) element is a formula a1(i, j) > a2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_base_of_v<Eigen::ArrayBase<DerivedA>, DerivedA> &&
std::is_base_of_v<Eigen::ArrayBase<DerivedB>, DerivedB>,
bool>
CheckArrayOperatorGt(const DerivedA& a1, const DerivedB& a2) {
const auto arr = (a1 > a2);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a1(i, j) > a2(i, j))) {
return false;
}
}
}
return true;
}
// Given a scalar-type object @p v and an Eigen array @p a, it checks if v > a
// returns an array whose (i, j)-element is a formula a(i, j) < v.
template <typename ScalarType, typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(ScalarType() > typename Derived::Scalar()),
Formula>,
bool>
CheckArrayOperatorGt(const ScalarType& v, const Derived& a) {
const auto arr = (v > a);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
// Note that arr(i, j) should be `a(i, j) < v` instead of `v > a(i, j)`.
if (!arr(i, j).EqualTo(a(i, j) < v)) {
return false;
}
}
}
return true;
}
// Given an Eigen array @p a and a scalar-type object @p v, it checks if a > v
// returns an array whose (i, j)-element is a formula a(i, j) > v.
template <typename Derived, typename ScalarType>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(typename Derived::Scalar() > ScalarType()),
Formula>,
bool>
CheckArrayOperatorGt(const Derived& a, const ScalarType& v) {
const auto arr = (a > v);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a(i, j) > v)) {
return false;
}
}
}
return true;
}
// Given two Eigen matrices m1 and m2, it checks if m1.array() > m2.array()
// returns an array whose (i, j) element is a formula m1(i, j) > m2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<DerivedA>::XprKind,
Eigen::MatrixXpr> &&
std::is_same_v<typename Eigen::internal::traits<DerivedB>::XprKind,
Eigen::MatrixXpr>,
bool>
CheckArrayOperatorGt(const DerivedA& m1, const DerivedB& m2) {
return CheckArrayOperatorGt(m1.array(), m2.array());
}
// Given two Eigen arrays a1 and a2, it checks if a1 != a2 returns an array
// whose (i, j) element is a formula a1(i, j) != a2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_base_of_v<Eigen::ArrayBase<DerivedA>, DerivedA> &&
std::is_base_of_v<Eigen::ArrayBase<DerivedB>, DerivedB>,
bool>
CheckArrayOperatorNeq(const DerivedA& a1, const DerivedB& a2) {
const auto arr = (a1 != a2);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a1(i, j) != a2(i, j))) {
return false;
}
}
}
return true;
}
// Given a scalar-type object @p v and an Eigen array @p a, it checks if v != a
// returns an array whose (i, j)-element is a formula v != a(i, j).
template <typename ScalarType, typename Derived>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(ScalarType() != typename Derived::Scalar()),
Formula>,
bool>
CheckArrayOperatorNeq(const ScalarType& v, const Derived& a) {
const auto arr = (v != a);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(v != a(i, j))) {
return false;
}
}
}
return true;
}
// Given an Eigen array @p a and a scalar-type object @p v, it checks if a != v
// returns an array whose (i, j)-element is a formula a(i, j) != v.
template <typename Derived, typename ScalarType>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind,
Eigen::ArrayXpr> &&
std::is_same_v<decltype(typename Derived::Scalar() != ScalarType()),
Formula>,
bool>
CheckArrayOperatorNeq(const Derived& a, const ScalarType& v) {
const auto arr = (a != v);
for (int i = 0; i < arr.rows(); ++i) {
for (int j = 0; j < arr.cols(); ++j) {
if (!arr(i, j).EqualTo(a(i, j) != v)) {
return false;
}
}
}
return true;
}
// Given two Eigen matrices m1 and m2, it checks if m1.array() != m2.array()
// returns an array whose (i, j) element is a formula m1(i, j) != m2(i, j).
template <typename DerivedA, typename DerivedB>
typename std::enable_if_t<
std::is_same_v<typename Eigen::internal::traits<DerivedA>::XprKind,
Eigen::MatrixXpr> &&
std::is_same_v<typename Eigen::internal::traits<DerivedB>::XprKind,
Eigen::MatrixXpr>,
bool>
CheckArrayOperatorNeq(const DerivedA& m1, const DerivedB& m2) {
return CheckArrayOperatorNeq(m1.array(), m2.array());
}
TEST_F(SymbolicExpressionArrayTest, ArrayExprEqArrayExpr) {
const Eigen::Array<Formula, 3, 2> a1{A_.array() == A_.array()};
const Eigen::Array<Formula, 2, 3> a2{B_.array() == B_.array()};
const Eigen::Array<Formula, 3, 2> a3{C_.array() == C_.array()};
auto is_true_lambda = [](const Formula& f) {
return is_true(f);
};
EXPECT_TRUE(a1.unaryExpr(is_true_lambda).all());
EXPECT_TRUE(a2.unaryExpr(is_true_lambda).all());
EXPECT_TRUE(a3.unaryExpr(is_true_lambda).all());
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Expression>
// and Array<Expression>.
TEST_F(SymbolicExpressionArrayTest, ArrayExprRopArrayExpr) {
EXPECT_TRUE(CheckArrayOperatorEq(A_, C_));
EXPECT_TRUE(CheckArrayOperatorEq(B_ * A_, B_ * C_));
EXPECT_TRUE(CheckArrayOperatorLte(A_, C_));
EXPECT_TRUE(CheckArrayOperatorLte(B_ * A_, B_ * C_));
EXPECT_TRUE(CheckArrayOperatorLt(A_, C_));
EXPECT_TRUE(CheckArrayOperatorLt(B_ * A_, B_ * C_));
EXPECT_TRUE(CheckArrayOperatorGte(A_, C_));
EXPECT_TRUE(CheckArrayOperatorGte(B_ * A_, B_ * C_));
EXPECT_TRUE(CheckArrayOperatorGt(A_, C_));
EXPECT_TRUE(CheckArrayOperatorGt(B_ * A_, B_ * C_));
EXPECT_TRUE(CheckArrayOperatorNeq(A_, C_));
EXPECT_TRUE(CheckArrayOperatorNeq(B_ * A_, B_ * C_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Expression>
// and Array<Variable>
TEST_F(SymbolicExpressionArrayTest, ArrayExprRopArrayVar) {
EXPECT_TRUE(CheckArrayOperatorEq(array_expr_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorEq(array_var_2_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorLte(array_expr_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorLte(array_var_2_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorLt(array_expr_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorLt(array_var_2_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorGte(array_expr_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorGte(array_var_2_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorGt(array_expr_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorGt(array_var_2_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_expr_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_var_2_, array_expr_1_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Expression>
// and Array<double>
TEST_F(SymbolicExpressionArrayTest, ArrayExprRopArrayDouble) {
EXPECT_TRUE(CheckArrayOperatorEq(array_expr_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorEq(array_double_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorLte(array_expr_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorLte(array_double_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorLt(array_expr_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorLt(array_double_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorGte(array_expr_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorGte(array_double_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorGt(array_expr_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorGt(array_double_, array_expr_1_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_expr_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_double_, array_expr_1_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Variable>
// and Array<double>
TEST_F(SymbolicExpressionArrayTest, ArrayVarRopArrayDouble) {
EXPECT_TRUE(CheckArrayOperatorEq(array_var_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorEq(array_double_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLte(array_var_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorLte(array_double_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLt(array_var_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorLt(array_double_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGte(array_var_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorGte(array_double_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGt(array_var_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorGt(array_double_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_var_1_, array_double_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_double_, array_var_1_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Variable>
// and Array<Variable>
TEST_F(SymbolicExpressionArrayTest, ArrayVarRopArrayVar) {
EXPECT_TRUE(CheckArrayOperatorEq(array_var_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorEq(array_var_2_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLte(array_var_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorLte(array_var_2_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLt(array_var_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorLt(array_var_2_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGte(array_var_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorGte(array_var_2_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGt(array_var_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorGt(array_var_2_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_var_1_, array_var_2_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_var_2_, array_var_1_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Expression>
// and Expression.
TEST_F(SymbolicExpressionArrayTest, ArrayExprRopExpr) {
EXPECT_TRUE(CheckArrayOperatorEq(A_.array(), Expression{0.0}));
EXPECT_TRUE(CheckArrayOperatorEq(x_ + y_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorLte(A_.array(), Expression{0.0}));
EXPECT_TRUE(CheckArrayOperatorLte(x_ + y_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorLt(A_.array(), Expression{0.0}));
EXPECT_TRUE(CheckArrayOperatorLt(x_ + y_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorGte(A_.array(), Expression{0.0}));
EXPECT_TRUE(CheckArrayOperatorGte(x_ + y_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorGt(A_.array(), Expression{0.0}));
EXPECT_TRUE(CheckArrayOperatorGt(x_ + y_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorNeq(A_.array(), Expression{0.0}));
EXPECT_TRUE(CheckArrayOperatorNeq(x_ + y_, (B_ * C_).array()));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Expression>
// and Variable.
TEST_F(SymbolicExpressionArrayTest, ArrayExprRopVar) {
EXPECT_TRUE(CheckArrayOperatorEq(A_.array(), var_x_));
EXPECT_TRUE(CheckArrayOperatorEq(var_x_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorLte(A_.array(), var_x_));
EXPECT_TRUE(CheckArrayOperatorLte(var_x_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorLt(A_.array(), var_x_));
EXPECT_TRUE(CheckArrayOperatorLt(var_x_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorGte(A_.array(), var_x_));
EXPECT_TRUE(CheckArrayOperatorGte(var_x_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorGt(A_.array(), var_x_));
EXPECT_TRUE(CheckArrayOperatorGt(var_x_, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorNeq(A_.array(), var_x_));
EXPECT_TRUE(CheckArrayOperatorNeq(var_x_, (B_ * C_).array()));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Expression>
// and double.
TEST_F(SymbolicExpressionArrayTest, ArrayExprRopDouble) {
EXPECT_TRUE(CheckArrayOperatorEq(A_.array(), 0.0));
EXPECT_TRUE(CheckArrayOperatorEq(1.0, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorLte(A_.array(), 0.0));
EXPECT_TRUE(CheckArrayOperatorLte(1.0, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorLt(A_.array(), 0.0));
EXPECT_TRUE(CheckArrayOperatorLt(1.0, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorGte(A_.array(), 0.0));
EXPECT_TRUE(CheckArrayOperatorGte(1.0, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorGt(A_.array(), 0.0));
EXPECT_TRUE(CheckArrayOperatorGt(1.0, (B_ * C_).array()));
EXPECT_TRUE(CheckArrayOperatorNeq(A_.array(), 0.0));
EXPECT_TRUE(CheckArrayOperatorNeq(1.0, (B_ * C_).array()));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Variable>
// and Expression.
TEST_F(SymbolicExpressionArrayTest, ArraryVarRopExpr) {
EXPECT_TRUE(CheckArrayOperatorEq(array_var_1_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorEq(x_ + y_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLte(array_var_1_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorLte(x_ + y_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLt(array_var_1_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorLt(x_ + y_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGte(array_var_1_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorGte(x_ + y_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGt(array_var_1_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorGt(x_ + y_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_var_1_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorNeq(x_ + y_, array_var_1_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Variable>
// and Variable.
TEST_F(SymbolicExpressionArrayTest, ArraryVarRopVar) {
EXPECT_TRUE(CheckArrayOperatorEq(array_var_1_, var_x_));
EXPECT_TRUE(CheckArrayOperatorEq(var_x_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLte(array_var_1_, var_x_));
EXPECT_TRUE(CheckArrayOperatorLte(var_x_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLt(array_var_1_, var_x_));
EXPECT_TRUE(CheckArrayOperatorLt(var_x_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGte(array_var_1_, var_x_));
EXPECT_TRUE(CheckArrayOperatorGte(var_x_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGt(array_var_1_, var_x_));
EXPECT_TRUE(CheckArrayOperatorGt(var_x_, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_var_1_, var_x_));
EXPECT_TRUE(CheckArrayOperatorNeq(var_x_, array_var_1_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<Variable>
// and double.
TEST_F(SymbolicExpressionArrayTest, ArraryVarRopDouble) {
EXPECT_TRUE(CheckArrayOperatorEq(array_var_1_, 3.0));
EXPECT_TRUE(CheckArrayOperatorEq(3.0, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLte(array_var_1_, 3.0));
EXPECT_TRUE(CheckArrayOperatorLte(3.0, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorLt(array_var_1_, 3.0));
EXPECT_TRUE(CheckArrayOperatorLt(3.0, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGte(array_var_1_, 3.0));
EXPECT_TRUE(CheckArrayOperatorGte(3.0, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorGt(array_var_1_, 3.0));
EXPECT_TRUE(CheckArrayOperatorGt(3.0, array_var_1_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_var_1_, 3.0));
EXPECT_TRUE(CheckArrayOperatorNeq(3.0, array_var_1_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<double>
// and Expression.
TEST_F(SymbolicExpressionArrayTest, ArraryDoubleRopExpr) {
EXPECT_TRUE(CheckArrayOperatorEq(array_double_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorEq(x_ + y_, array_double_));
EXPECT_TRUE(CheckArrayOperatorLte(array_double_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorLte(x_ + y_, array_double_));
EXPECT_TRUE(CheckArrayOperatorLt(array_double_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorLt(x_ + y_, array_double_));
EXPECT_TRUE(CheckArrayOperatorGte(array_double_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorGte(x_ + y_, array_double_));
EXPECT_TRUE(CheckArrayOperatorGt(array_double_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorGt(x_ + y_, array_double_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_double_, x_ + y_));
EXPECT_TRUE(CheckArrayOperatorNeq(x_ + y_, array_double_));
}
// Checks relational operators (==, !=, <=, <, >=, >) between Array<double>
// and Variable.
TEST_F(SymbolicExpressionArrayTest, ArraryDoubleRopVar) {
EXPECT_TRUE(CheckArrayOperatorEq(array_double_, var_x_));
EXPECT_TRUE(CheckArrayOperatorEq(var_x_, array_double_));
EXPECT_TRUE(CheckArrayOperatorLte(array_double_, var_x_));
EXPECT_TRUE(CheckArrayOperatorLte(var_x_, array_double_));
EXPECT_TRUE(CheckArrayOperatorLt(array_double_, var_x_));
EXPECT_TRUE(CheckArrayOperatorLt(var_x_, array_double_));
EXPECT_TRUE(CheckArrayOperatorGte(array_double_, var_x_));
EXPECT_TRUE(CheckArrayOperatorGte(var_x_, array_double_));
EXPECT_TRUE(CheckArrayOperatorGt(array_double_, var_x_));
EXPECT_TRUE(CheckArrayOperatorGt(var_x_, array_double_));
EXPECT_TRUE(CheckArrayOperatorNeq(array_double_, var_x_));
EXPECT_TRUE(CheckArrayOperatorNeq(var_x_, array_double_));
}
TEST_F(SymbolicExpressionArrayTest, ArrayOperatorReturnType) {
Eigen::Array<Variable, 2, Eigen::Dynamic> m1(2, 2);
Eigen::Array<Variable, Eigen::Dynamic, 2> m2(2, 2);
EXPECT_TRUE(
(std::is_same_v<decltype(m1 == m2), Eigen::Array<Formula, 2, 2>>));
EXPECT_TRUE(
(std::is_same_v<decltype(m1 != m2), Eigen::Array<Formula, 2, 2>>));
EXPECT_TRUE(
(std::is_same_v<decltype(m1 <= m2), Eigen::Array<Formula, 2, 2>>));
EXPECT_TRUE((std::is_same_v<decltype(m1 < m2), Eigen::Array<Formula, 2, 2>>));
EXPECT_TRUE(
(std::is_same_v<decltype(m1 >= m2), Eigen::Array<Formula, 2, 2>>));
EXPECT_TRUE((std::is_same_v<decltype(m1 > m2), Eigen::Array<Formula, 2, 2>>));
}
TEST_F(SymbolicExpressionArrayTest, ExpressionArraySegment) {
Eigen::Array<Expression, 5, 1> v;
v << x_, 1, y_, x_, 1;
const auto s1 = v.segment(0, 2); // [x, 1]
const auto s2 = v.segment<2>(1); // [1, y]
const auto s3 = v.segment(3, 2); // [x, 1]
const auto a1 = (s1 == s2); // [x = 1, 1 = y]
const auto a2 = (s1 == s3); // [True, True]
EXPECT_PRED2(FormulaEqual, a1(0), x_ == 1);
EXPECT_PRED2(FormulaEqual, a1(1), 1 == y_);
EXPECT_TRUE(is_true(a2(0)));
EXPECT_TRUE(is_true(a2(1)));
}
TEST_F(SymbolicExpressionArrayTest, ExpressionArrayBlock) {
Eigen::Array<Expression, 3, 3> m;
// clang-format off
m << x_, y_, z_,
y_, 1, 2,
z_, 3, 4;
// clang-format on
// b1 = [x, y]
// [y, 1]
const auto b1 = m.block<2, 2>(0, 0);
// b2 = [1, 2]
// [3, 4]
const auto b2 = m.block(1, 1, 2, 2);
// a = [x = 1, y = 2]
// [y = 3, False]
const auto a = (b1 == b2);
EXPECT_PRED2(FormulaEqual, a(0, 0), x_ == 1);
EXPECT_PRED2(FormulaEqual, a(0, 1), y_ == 2);
EXPECT_PRED2(FormulaEqual, a(1, 0), y_ == 3);
EXPECT_TRUE(is_false(a(1, 1)));
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic/expression | /home/johnshepherd/drake/common/symbolic/expression/test/sparse_test.cc | /* clang-format off to disable clang-format-includes */
#include "drake/common/symbolic/expression/all.h"
/* clang-format on */
#include <vector>
#include <Eigen/Sparse>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
namespace {
using test::ExprEqual;
// This is a regression test for drake#18218.
GTEST_TEST(SymbolicMatricesTest, SparseMatrices) {
const Variable x("x");
std::vector<Eigen::Triplet<Expression>> triplets;
triplets.push_back(Eigen::Triplet<Expression>(1, 1, 1.1));
triplets.push_back(Eigen::Triplet<Expression>(2, 2, x * 2.0));
Eigen::SparseMatrix<Expression> M(3, 3);
M.setFromTriplets(triplets.begin(), triplets.end());
EXPECT_PRED2(ExprEqual, M.coeff(0, 0), 0.0);
EXPECT_PRED2(ExprEqual, M.coeff(1, 1), 1.1);
EXPECT_PRED2(ExprEqual, M.coeff(2, 2), x * 2.0);
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic/expression | /home/johnshepherd/drake/common/symbolic/expression/test/substitution_test.cc | /* clang-format off to disable clang-format-includes */
#include "drake/common/symbolic/expression/all.h"
/* clang-format on */
#include <functional>
#include <stdexcept>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/symbolic_test_util.h"
using std::exception;
using std::function;
using std::pair;
using std::vector;
namespace drake {
namespace symbolic {
namespace {
using test::ExprEqual;
using test::FormulaEqual;
// Checks if 'Expression::Substitute(const Variable&, const Expression&)' is
// a homomorphism. That is, we check if the following holds:
//
// f(v).Substitute(v, e) = f(e)
//
void CheckHomomorphism(const function<Expression(const Expression&)>& f,
const Variable& var, const Expression& expr) {
Expression apply_subst{0.0};
try {
apply_subst = f(Expression{var}).Substitute(var, expr);
} catch (const exception&) {
// If apply_subst throws an exception, then subst_apply should
// throws an exception as well.
EXPECT_ANY_THROW(f(expr));
return;
}
// Otherwise, we check if we have apply_subst = subst_apply.
const Expression subst_apply{f(expr)};
EXPECT_PRED2(ExprEqual, apply_subst, subst_apply);
// If the expression was a constant then the substitution is a partial
// evaluation, so this is a convenient place to add unit tests for the
// EvaluatePartial function as well.
if (is_constant(expr)) {
const Expression apply{f(Expression{expr})};
const double value = get_constant_value(expr);
const Expression eval_partial{apply.EvaluatePartial({{var, value}})};
EXPECT_PRED2(ExprEqual, eval_partial, f(expr));
}
}
// Checks if 'Expression::Substitute(const Substitution&)' is a homomorphism.
// That is, we check if the following holds:
//
// f({x_1, ..., x_n}).Substitute(s) = f({e_1, ..., e_n})
//
// where we have x_i.Substitute(s) = e_i by a given substitution s.
void CheckHomomorphism(const function<Expression(const vector<Expression>&)>& f,
const Substitution& s) {
vector<Expression> args1; // {x_1, ..., x_n}
vector<Expression> args2; // {e_1, ..., e_n}
for (const pair<const Variable, Expression>& p : s) {
args1.emplace_back(p.first);
args2.push_back(p.second);
}
Expression apply_subst{0.0};
try {
apply_subst = f(args1).Substitute(s);
} catch (const exception&) {
// If apply_subst throws an exception, then subst_apply should
// throws an exception as well.
EXPECT_ANY_THROW(f(args2));
return;
}
// Otherwise, we check if we have apply_subst = subst_apply.
const Expression subst_apply{f(args2)};
EXPECT_PRED2(ExprEqual, apply_subst, subst_apply);
// If every expression was a constant then the substitution is a partial
// evaluation, so this is a convenient place to add unit tests for the
// EvaluatePartial function as well.
if (std::all_of(args2.begin(), args2.end(), [](const Expression& e) {
return is_constant(e);
})) {
const Expression apply{f(args1)};
Environment env;
for (const auto& [subst_var, subst_expr] : s) {
env.insert(subst_var, get_constant_value(subst_expr));
}
const Expression eval_partial{apply.EvaluatePartial(env)};
EXPECT_PRED2(ExprEqual, eval_partial, f(args2));
}
}
// Checks if 'Formula::Substitute(const Variable&, const Expression&)' is
// a homomorphism. That is, we check if the following holds:
//
// f(v).Substitute(v, e) = f(e)
//
// Note that the above assertion holds only if f is a quantifier-free
// formula. We have a separate tests which covers the quantified case.
void CheckHomomorphism(const function<Formula(const Expression&)>& f,
const Variable& var, const Expression& expr) {
Formula apply_subst{Formula::True()};
try {
apply_subst = f(Expression{var}).Substitute(var, expr);
} catch (const exception&) {
// If apply_subst throws an exception, then subst_apply should
// throws an exception as well.
EXPECT_ANY_THROW(f(expr));
return;
}
// Otherwise, we check if we have apply_subst = subst_apply.
const Formula subst_apply{f(expr)};
EXPECT_PRED2(FormulaEqual, apply_subst, subst_apply);
}
// Checks if 'Formula::Substitute(const Substitution&)' is a homomorphism.
// That is, we check if the following holds:
//
// f({x_1, ..., x_n}).Substitute(s) = f({e_1, ..., e_n})
//
// where we have x_i.Substitute(s) = e_i by a given substitution s.
//
// Note that the above assertion holds only if f is a quantifier-free
// formula. We have a separate tests which covers the quantified case.
void CheckHomomorphism(const function<Formula(const vector<Expression>&)>& f,
const Substitution& s) {
vector<Expression> args1; // {x_1, ..., x_n}
vector<Expression> args2; // {e_1, ..., e_n}
for (const pair<const Variable, Expression>& p : s) {
args1.emplace_back(p.first);
args2.push_back(p.second);
}
Formula apply_subst{Formula::True()};
try {
apply_subst = f(args1).Substitute(s);
} catch (const exception&) {
// If apply_subst throws an exception, then subst_apply should
// throws an exception as well.
EXPECT_ANY_THROW(f(args2));
return;
}
// Otherwise, we check if we have apply_subst = subst_apply.
const Formula subst_apply{f(args2)};
EXPECT_PRED2(FormulaEqual, apply_subst, subst_apply);
}
class SymbolicSubstitutionTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
const Expression x_{var_x_};
const Expression y_{var_y_};
const Expression z_{var_z_};
};
TEST_F(SymbolicSubstitutionTest, CheckHomomorphismExpressionVarExpr) {
using F = function<Expression(const Expression&)>;
// clang-format off
vector<F> fns;
fns.push_back([](const Expression& x) { return 3.0; });
fns.push_back([](const Expression& x) { return x; });
fns.push_back([](const Expression& x) { return 2 * x; });
fns.push_back([](const Expression& x) { return -x; });
fns.push_back([](const Expression& x) { return -3 * x; });
fns.push_back([&](const Expression& x) { return 5.0 + x + y_; });
fns.push_back([&](const Expression& x) { return 5.0 + y_ + x; });
fns.push_back([&](const Expression& x) { return 7.0 - x - y_; });
fns.push_back([&](const Expression& x) { return 7.0 - y_ - x; });
fns.push_back([&](const Expression& x) { return 3.0 * x * z_; });
fns.push_back([&](const Expression& x) { return 3.0 * z_ * x; });
fns.push_back([&](const Expression& x) { return x / y_; });
fns.push_back([&](const Expression& x) { return y_ / x; });
fns.push_back([](const Expression& x) { return log(x); });
fns.push_back([](const Expression& x) { return abs(x); });
fns.push_back([](const Expression& x) { return exp(x); });
fns.push_back([](const Expression& x) { return sqrt(x); });
fns.push_back([&](const Expression& x) { return pow(x, y_); });
fns.push_back([&](const Expression& x) { return pow(y_, x); });
fns.push_back([](const Expression& x) { return sin(x); });
fns.push_back([](const Expression& x) { return cos(x); });
fns.push_back([](const Expression& x) { return tan(x); });
fns.push_back([](const Expression& x) { return asin(x); });
fns.push_back([](const Expression& x) { return acos(x); });
fns.push_back([](const Expression& x) { return atan(x); });
fns.push_back([&](const Expression& x) { return atan2(x, y_); });
fns.push_back([&](const Expression& x) { return atan2(y_, x); });
fns.push_back([](const Expression& x) { return sinh(x); });
fns.push_back([](const Expression& x) { return cosh(x); });
fns.push_back([](const Expression& x) { return tanh(x); });
fns.push_back([&](const Expression& x) { return min(x, y_); });
fns.push_back([&](const Expression& x) { return min(y_, x); });
fns.push_back([&](const Expression& x) { return max(x, z_); });
fns.push_back([&](const Expression& x) { return max(z_, x); });
fns.push_back([](const Expression& x) { return ceil(x); });
fns.push_back([](const Expression& x) { return floor(x); });
fns.push_back([&](const Expression& x) {
return if_then_else(x > y_ && x > z_, x * y_, x / z_);
});
fns.push_back([&](const Expression& x) {
return if_then_else(x > y_ || z_ > x, x * y_, x / z_);
});
// clang-format on
vector<pair<Variable, Expression>> substs;
substs.emplace_back(var_x_, x_);
substs.emplace_back(var_x_, 1.0);
substs.emplace_back(var_x_, -1.0);
substs.emplace_back(var_x_, 20.0);
substs.emplace_back(var_x_, -30.0);
substs.emplace_back(var_x_, 7.0 + x_ + y_);
substs.emplace_back(var_x_, -3.0 + y_ + z_);
substs.emplace_back(var_x_, x_ - y_);
substs.emplace_back(var_x_, y_ - z_);
substs.emplace_back(var_x_, x_ * y_);
substs.emplace_back(var_x_, y_ * z_);
substs.emplace_back(var_x_, x_ / y_);
substs.emplace_back(var_x_, y_ / z_);
substs.emplace_back(var_x_, x_ - y_);
substs.emplace_back(var_x_, y_ - z_);
for (const F& f : fns) {
for (const pair<Variable, Expression>& s : substs) {
const Variable& var{s.first};
const Expression& expr{s.second};
CheckHomomorphism(f, var, expr);
}
}
}
TEST_F(SymbolicSubstitutionTest, CheckHomomorphismExpressionSubstitution) {
using F = function<Expression(const vector<Expression>&)>;
// clang-format off
vector<F> fns;
fns.push_back([](const vector<Expression>& v) { return 3.0; });
fns.push_back([](const vector<Expression>& v) { return v[0]; });
fns.push_back([](const vector<Expression>& v) { return 2 * v[0]; });
fns.push_back([](const vector<Expression>& v) { return -v[0]; });
fns.push_back([](const vector<Expression>& v) { return -3 * v[0]; });
fns.push_back([](const vector<Expression>& v) { return 3.0 + v[0] + v[1]; });
fns.push_back([](const vector<Expression>& v) { return -3.0 + v[1] - v[2]; });
fns.push_back([](const vector<Expression>& v) { return v[0] * v[2]; });
fns.push_back([](const vector<Expression>& v) { return v[0] / v[1]; });
fns.push_back([](const vector<Expression>& v) { return log(v[0]); });
fns.push_back([](const vector<Expression>& v) { return abs(v[1]); });
fns.push_back([](const vector<Expression>& v) { return exp(v[2]); });
fns.push_back([](const vector<Expression>& v) { return sqrt(v[0]); });
fns.push_back([](const vector<Expression>& v) { return pow(v[0], v[1]); });
fns.push_back([](const vector<Expression>& v) { return sin(v[1]); });
fns.push_back([](const vector<Expression>& v) { return cos(v[2]); });
fns.push_back([](const vector<Expression>& v) { return tan(v[0]); });
fns.push_back([](const vector<Expression>& v) { return asin(v[0]); });
fns.push_back([](const vector<Expression>& v) { return acos(v[1]); });
fns.push_back([](const vector<Expression>& v) { return atan(v[2]); });
fns.push_back([](const vector<Expression>& v) { return atan2(v[0], v[1]); });
fns.push_back([](const vector<Expression>& v) { return sinh(v[1]); });
fns.push_back([](const vector<Expression>& v) { return cosh(v[0]); });
fns.push_back([](const vector<Expression>& v) { return tanh(v[2]); });
fns.push_back([](const vector<Expression>& v) { return min(v[0], v[1]); });
fns.push_back([](const vector<Expression>& v) { return max(v[1], v[2]); });
fns.push_back([](const vector<Expression>& v) { return ceil(v[0]); });
fns.push_back([](const vector<Expression>& v) { return floor(v[1]); });
fns.push_back([&](const vector<Expression>& v) {
return fns[9](v) * fns[17](v) / fns[5](v) - fns[19](v);
});
fns.push_back([&](const vector<Expression>& v) {
return fns[6](v) * fns[20](v) / fns[2](v) + fns[12](v);
});
fns.push_back([](const vector<Expression>& v) {
return if_then_else(v[0] > v[1], v[1] * v[2], v[0] - v[2]);
});
// clang-format on
vector<Substitution> substs;
substs.push_back({{var_x_, 1.0}, {var_y_, 1.0}, {var_z_, 2.0}});
substs.push_back({{var_x_, -2.0}, {var_y_, 1.0}, {var_z_, z_}});
substs.push_back({{var_x_, 0.0}, {var_y_, 0.0}, {var_z_, 5.0}});
substs.push_back({{var_x_, -10.0}, {var_y_, 10.0}, {var_z_, 0.0}});
substs.push_back({{var_x_, y_}, {var_y_, z_}, {var_z_, x_}});
substs.push_back({{var_x_, x_ + y_}, {var_y_, y_ + z_}, {var_z_, z_ + x_}});
substs.push_back({{var_x_, pow(x_, y_)},
{var_y_, sin(y_) + cos(z_)},
{var_z_, sqrt(x_ * y_ * z_)}});
substs.push_back({{var_x_, pow(x_, y_)},
{var_y_, sin(y_) + cos(z_)},
{var_z_, log(pow(x_, y_) * z_)}});
for (const F& f : fns) {
for (const Substitution& s : substs) {
CheckHomomorphism(f, s);
}
}
}
TEST_F(SymbolicSubstitutionTest, CheckHomomorphismFormulaVarExpr) {
using F = function<Formula(const Expression&)>;
// clang-format off
vector<F> fns;
fns.push_back([](const Expression& x) { return Formula::True(); });
fns.push_back([](const Expression& x) { return Formula::False(); });
fns.push_back([&](const Expression& x) { return (x + y_) == (y_ * z_); });
fns.push_back([&](const Expression& x) { return (y_ + z_) == (x * z_); });
fns.push_back([&](const Expression& x) { return (x + y_) != (y_ * z_); });
fns.push_back([&](const Expression& x) { return (y_ + z_) != (x * z_); });
fns.push_back([&](const Expression& x) { return (x + y_) > (y_ * z_); });
fns.push_back([&](const Expression& x) { return (y_ + z_) > (x * z_); });
fns.push_back([&](const Expression& x) { return (x + y_) >= (y_ * z_); });
fns.push_back([&](const Expression& x) { return (y_ + z_) >= (x * z_); });
fns.push_back([&](const Expression& x) { return (x + y_) < (y_ * z_); });
fns.push_back([&](const Expression& x) { return (y_ + z_) < (x * z_); });
fns.push_back([&](const Expression& x) { return (x + y_) <= (y_ * z_); });
fns.push_back([&](const Expression& x) { return (y_ + z_) <= (x * z_); });
fns.push_back([&](const Expression& x) { return fns[5](x) && fns[7](x); });
fns.push_back([&](const Expression& x) { return fns[2](x) || fns[6](x); });
fns.push_back([&](const Expression& x) { return !fns[14](x); });
fns.push_back([&](const Expression& x) { return !fns[15](x); });
fns.push_back([&](const Expression& x) {
Eigen::Matrix<Expression, 2, 2> m;
m << (x * y_), 2.0,
2.0, (x * y_);
return positive_semidefinite(m);
});
// clang-format on
vector<pair<Variable, Expression>> substs;
substs.emplace_back(var_x_, x_);
substs.emplace_back(var_x_, 1.0);
substs.emplace_back(var_x_, -1.0);
substs.emplace_back(var_x_, 20.0);
substs.emplace_back(var_x_, -30.0);
substs.emplace_back(var_x_, x_ + y_);
substs.emplace_back(var_x_, y_ + z_);
substs.emplace_back(var_x_, x_ - y_);
substs.emplace_back(var_x_, y_ - z_);
substs.emplace_back(var_x_, x_ * y_);
substs.emplace_back(var_x_, y_ * z_);
substs.emplace_back(var_x_, x_ / y_);
substs.emplace_back(var_x_, y_ / z_);
substs.emplace_back(var_x_, x_ - y_);
substs.emplace_back(var_x_, y_ - z_);
for (const F& f : fns) {
for (const pair<Variable, Expression>& s : substs) {
const Variable& var{s.first};
const Expression& expr{s.second};
CheckHomomorphism(f, var, expr);
}
}
}
TEST_F(SymbolicSubstitutionTest, CheckHomomorphismFormulaSubstitution) {
using F = function<Formula(const vector<Expression>&)>;
vector<F> fns;
fns.push_back([](const vector<Expression>& v) {
return Formula::True();
});
fns.push_back([](const vector<Expression>& v) {
return Formula::False();
});
fns.push_back([](const vector<Expression>& v) {
return (v[0] + v[1]) == (v[1] * v[2]);
});
fns.push_back([](const vector<Expression>& v) {
return (v[0] + v[1]) != (v[1] * v[2]);
});
fns.push_back([](const vector<Expression>& v) {
return (v[0] + v[1]) > (v[1] * v[2]);
});
fns.push_back([](const vector<Expression>& v) {
return (v[0] + v[1]) >= (v[1] * v[2]);
});
fns.push_back([](const vector<Expression>& v) {
return (v[0] + v[1]) < (v[1] * v[2]);
});
fns.push_back([](const vector<Expression>& v) {
return (v[0] + v[1]) <= (v[1] * v[2]);
});
fns.push_back([&](const vector<Expression>& v) {
return fns[5](v) && fns[7](v);
});
fns.push_back([&](const vector<Expression>& v) {
return fns[2](v) || fns[4](v);
});
fns.push_back([&](const vector<Expression>& v) {
return !fns[8](v);
});
fns.push_back([&](const vector<Expression>& v) {
return !fns[9](v);
});
fns.push_back([](const vector<Expression>& v) {
Eigen::Matrix<Expression, 2, 2> m;
// clang-format off
m << (v[0] + v[1]), (v[1] * 2 - 3.5),
(v[1] * 2 - 3.5), (v[0] + v[1]);
// clang-format on
return positive_semidefinite(m);
});
vector<Substitution> substs;
substs.push_back({{var_x_, 1.0}, {var_y_, 1.0}, {var_z_, 2.0}});
substs.push_back({{var_x_, -2.0}, {var_y_, 1.0}, {var_z_, z_}});
substs.push_back({{var_x_, 0.0}, {var_y_, 0.0}, {var_z_, 5.0}});
substs.push_back({{var_x_, -10.0}, {var_y_, 10.0}, {var_z_, 0.0}});
substs.push_back({{var_x_, y_}, {var_y_, z_}, {var_z_, x_}});
substs.push_back({{var_x_, x_ + y_}, {var_y_, y_ + z_}, {var_z_, z_ + x_}});
substs.push_back({{var_x_, pow(x_, y_)},
{var_y_, sin(y_) + cos(z_)},
{var_z_, sqrt(x_ * y_ * z_)}});
substs.push_back({{var_x_, pow(x_, y_)},
{var_y_, sin(y_) + cos(z_)},
{var_z_, log(pow(x_, y_) * z_)}});
for (const F& f : fns) {
for (const Substitution& s : substs) {
CheckHomomorphism(f, s);
}
}
}
TEST_F(SymbolicSubstitutionTest, UninterpretedFunction) {
const Expression uf1{uninterpreted_function("uf1", {})};
const Expression uf2{uninterpreted_function("uf2", {var_x_, var_y_})};
const Substitution s1{{var_x_, 1.0}, {var_y_, x_ + y_}};
const Substitution s2{{var_x_, y_}, {var_y_, z_}};
const Substitution s3{{var_x_, 3.0}, {var_y_, 4.0}};
// uf1 has no variables inside and substitution has no effect as a result.
EXPECT_PRED2(ExprEqual, uf1.Substitute(s1), uf1);
EXPECT_PRED2(ExprEqual, uf1.Substitute(s2), uf1);
EXPECT_PRED2(ExprEqual, uf1.Substitute(s3), uf1);
// (uf2(x, y)).Substitute(x β¦ 1.0, y β¦ x + y)
// = uf2(1.0, x + y)
EXPECT_PRED2(ExprEqual, uf2.Substitute(s1),
uninterpreted_function("uf2", {1.0, x_ + y_}));
// (uf2(x, y)).Substitute(x β¦ y, y β¦ z)
// = uf2(y, z)
EXPECT_PRED2(ExprEqual, uf2.Substitute(s2),
uninterpreted_function("uf2", {y_, z_}));
// (uf2(x, y)).Substitute(x β¦ 3.0, y β¦ 4.0)
// = uf2(3.0, 4.0)
EXPECT_PRED2(ExprEqual, uf2.Substitute(s3),
uninterpreted_function("uf2", {3.0, 4.0}));
// (uf2(x, y)).EvaluatePartial(x β¦ 5.0)
// = uf2(5.0, y)
EXPECT_PRED2(ExprEqual, uf2.EvaluatePartial({{var_x_, 5.0}}),
uninterpreted_function("uf2", {5.0, var_y_}));
}
TEST_F(SymbolicSubstitutionTest, MatrixWithSubstitution) {
Eigen::Matrix<Expression, 2, 2> m;
// clang-format off
// | x + y + z x * y * z |
// | x / y / z xΚΈ * z |
m << x_ + y_ + z_, x_ * y_ * z_,
x_ / y_ * z_, pow(x_, y_) * z_;
// clang-format on
const Substitution subst{{var_x_, 1.0}, {var_y_, 2.0}};
const auto substituted{Substitute(m, subst)};
EXPECT_PRED2(ExprEqual, substituted(0, 0), m(0, 0).Substitute(subst));
EXPECT_PRED2(ExprEqual, substituted(1, 0), m(1, 0).Substitute(subst));
EXPECT_PRED2(ExprEqual, substituted(0, 1), m(0, 1).Substitute(subst));
EXPECT_PRED2(ExprEqual, substituted(1, 1), m(1, 1).Substitute(subst));
}
TEST_F(SymbolicSubstitutionTest, MatrixWithVariableAndExpression) {
Eigen::Matrix<Expression, 2, 2> m;
// clang-format off
// | x + y + z x * y * z |
// | x / y / z xΚΈ * z |
m << x_ + y_ + z_, x_ * y_ * z_,
x_ / y_ * z_, pow(x_, y_) * z_;
// clang-format on
const auto substituted{Substitute(m, var_x_, 3.0)};
EXPECT_PRED2(ExprEqual, substituted(0, 0), m(0, 0).Substitute(var_x_, 3.0));
EXPECT_PRED2(ExprEqual, substituted(1, 0), m(1, 0).Substitute(var_x_, 3.0));
EXPECT_PRED2(ExprEqual, substituted(0, 1), m(0, 1).Substitute(var_x_, 3.0));
EXPECT_PRED2(ExprEqual, substituted(1, 1), m(1, 1).Substitute(var_x_, 3.0));
}
class ForallFormulaSubstitutionTest : public SymbolicSubstitutionTest {
protected:
const Expression e_{x_ + y_ + z_};
const Formula f1_{x_ + y_ > z_};
const Formula f2_{x_ * y_ < 5 * z_};
const Formula f3_{x_ / y_ < 5 * z_};
const Formula f4_{x_ - y_ < 5 * z_};
const Formula f5_{e_ == 0.0};
const Formula f6_{e_ != 0.0};
const Formula f7_{e_ < 0.0};
const Formula f8_{e_ <= 0.0};
const Formula f9_{e_ > 0.0};
const Formula f10_{e_ >= 0.0};
const Formula f11_{f1_ && f2_};
const Formula f12_{f1_ || f2_};
const Formula f13_{!f11_};
const Formula f14_{!f12_};
const vector<Formula> formulas_{f1_, f2_, f3_, f4_, f5_, f6_, f7_,
f8_, f9_, f10_, f11_, f12_, f13_, f14_};
const Formula forall_x_1_{forall({var_x_}, f1_)};
const Formula forall_x_2_{forall({var_x_}, f2_)};
const Formula forall_x_3_{forall({var_x_}, f3_)};
const Formula forall_x_4_{forall({var_x_}, f4_)};
const Formula forall_x_5_{forall({var_x_}, f5_)};
const Formula forall_x_6_{forall({var_x_}, f6_)};
const Formula forall_x_7_{forall({var_x_}, f7_)};
const Formula forall_x_8_{forall({var_x_}, f8_)};
const Formula forall_x_9_{forall({var_x_}, f9_)};
const Formula forall_x_10_{forall({var_x_}, f10_)};
const Formula forall_x_11_{forall({var_x_}, f11_)};
const Formula forall_x_12_{forall({var_x_}, f12_)};
const Formula forall_x_13_{forall({var_x_}, f13_)};
const Formula forall_x_14_{forall({var_x_}, f14_)};
const vector<Formula> forall_formulas_{
forall_x_1_, forall_x_2_, forall_x_3_, forall_x_4_, forall_x_5_,
forall_x_6_, forall_x_7_, forall_x_8_, forall_x_9_, forall_x_10_,
forall_x_11_, forall_x_12_, forall_x_13_, forall_x_14_};
};
TEST_F(ForallFormulaSubstitutionTest, VarExpr1) {
vector<pair<Variable, Expression>> substs;
substs.emplace_back(var_x_, 1.0);
substs.emplace_back(var_x_, x_);
substs.emplace_back(var_x_, 5 * x_);
substs.emplace_back(var_x_, -x_);
substs.emplace_back(var_x_, -2 * x_);
substs.emplace_back(var_x_, y_);
substs.emplace_back(var_x_, z_);
for (const auto& f : forall_formulas_) {
EXPECT_TRUE(is_forall(f));
const Variables& vars{get_quantified_variables(f)};
for (const auto& s : substs) {
const Variable& var{s.first};
const Expression& e{s.second};
EXPECT_TRUE(vars.include(var));
// var is a quantified variable, so Substitute doesn't change
// anything.
EXPECT_PRED2(FormulaEqual, f, f.Substitute(var, e));
}
}
}
TEST_F(ForallFormulaSubstitutionTest, VarExpr2) {
vector<pair<Variable, Expression>> substs;
substs.emplace_back(var_y_, 1.0);
substs.emplace_back(var_y_, y_);
substs.emplace_back(var_y_, 5 * x_);
substs.emplace_back(var_y_, -y_);
substs.emplace_back(var_y_, -2 * x_);
substs.emplace_back(var_y_, y_);
substs.emplace_back(var_y_, z_);
for (const auto& f : forall_formulas_) {
EXPECT_TRUE(is_forall(f));
const Variables& vars{get_quantified_variables(f)};
const Formula& nested_f{get_quantified_formula(f)};
for (const auto& s : substs) {
const Variable& var{s.first};
const Expression& e{s.second};
EXPECT_FALSE(vars.include(var));
// var is not a quantified variable, so the substitution goes inside
// of the quantifier block. As a result, the following holds:
//
// forall({v_1, ..., v_n}, f).subst(var, e) -- (1)
// = forall({v_1, ..., v_n}, f.subst(var, e)) -- (2)
//
Formula f1{Formula::True()};
try {
f1 = {f.Substitute(var, e)};
} catch (const exception&) {
// If (1) throws an exception, then (2) should throws an exception
// as well.
EXPECT_ANY_THROW(forall(vars, nested_f.Substitute(var, e)));
continue;
}
const Formula& f2{forall(vars, nested_f.Substitute(var, e))};
EXPECT_PRED2(FormulaEqual, f1, f2);
}
}
}
TEST_F(ForallFormulaSubstitutionTest, VarExprSubstitution) {
vector<Substitution> substs;
substs.push_back({{var_x_, 1.0}, {var_y_, 1.0}, {var_z_, 2.0}});
substs.push_back({{var_x_, -2.0}, {var_y_, 1.0}, {var_z_, z_}});
substs.push_back({{var_x_, 0.0}, {var_y_, 0.0}, {var_z_, 5.0}});
substs.push_back({{var_x_, -10.0}, {var_y_, 10.0}, {var_z_, 0.0}});
substs.push_back({{var_x_, y_}, {var_y_, z_}, {var_z_, x_}});
substs.push_back({{var_x_, x_ + y_}, {var_y_, y_ + z_}, {var_z_, z_ + x_}});
substs.push_back({{var_x_, pow(x_, y_)},
{var_y_, sin(y_) + cos(z_)},
{var_z_, sqrt(x_ * y_ * z_)}});
substs.push_back({{var_x_, pow(x_, y_)},
{var_y_, sin(y_) + cos(z_)},
{var_z_, log(pow(x_, y_) * z_)}});
// In general, we have the following property:
//
// forall(vars, f).subst(s) -- (1)
// = forall(vars, f.subst(sβvars)) -- (2)
//
// where vars = {v_1, ..., v_n} and sβvars denotes a substitution which
// includes the entries (v, e) β s but v β dom(s).
//
for (const auto& f : forall_formulas_) {
EXPECT_TRUE(is_forall(f));
const Variables& vars{get_quantified_variables(f)};
const Formula& nested_f{get_quantified_formula(f)};
for (const auto& s : substs) {
Substitution s_minus_vars{s};
for (const Variable& quantified_var : vars) {
s_minus_vars.erase(quantified_var);
}
Formula f1{Formula::True()};
try {
f1 = {f.Substitute(s)};
} catch (const exception&) {
// If (1) throws an exception, then (2) should throws an exception
// as well.
EXPECT_ANY_THROW(forall(vars, nested_f.Substitute(s_minus_vars)));
continue;
}
const Formula& f2{forall(vars, nested_f.Substitute(s_minus_vars))};
EXPECT_PRED2(FormulaEqual, f1, f2);
}
}
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic/expression | /home/johnshepherd/drake/common/symbolic/expression/test/environment_test.cc | /* clang-format off to disable clang-format-includes */
#include "drake/common/symbolic/expression/all.h"
/* clang-format on */
#include <cmath>
#include <stdexcept>
#include <string>
#include <gtest/gtest.h>
namespace drake {
namespace symbolic {
namespace {
using std::runtime_error;
using std::string;
// Provides common variables that are used by the following tests.
class EnvironmentTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
const Variable var_w_{"w"};
const Variable var_v_{"v"};
};
TEST_F(EnvironmentTest, EmptySize) {
const Environment env1{};
EXPECT_TRUE(env1.empty());
EXPECT_EQ(env1.size(), 0u);
const Environment env2{{var_x_, 2}, {var_y_, 3}, {var_z_, 4}};
EXPECT_FALSE(env2.empty());
EXPECT_EQ(env2.size(), 3u);
}
TEST_F(EnvironmentTest, InitWithNan) {
EXPECT_THROW((Environment{{var_x_, 10}, {var_y_, NAN}}), runtime_error);
}
TEST_F(EnvironmentTest, InitializerListWithoutValues) {
const Environment env{var_x_, var_y_, var_z_};
for (const auto& p : env) {
EXPECT_EQ(p.second, 0.0);
}
}
TEST_F(EnvironmentTest, InitWithMap) {
Environment::map m;
m.emplace(var_x_, 3.0);
m.emplace(var_y_, 4.0);
const Expression e{var_x_ + var_y_};
EXPECT_EQ(e.Evaluate(Environment{m}), 7.0);
}
TEST_F(EnvironmentTest, InitWithMapExceptionNan) {
Environment::map m;
m.emplace(var_x_, NAN);
EXPECT_THROW(Environment{m}, runtime_error);
}
TEST_F(EnvironmentTest, InsertFind) {
Environment env1{{var_x_, 2}, {var_y_, 3}, {var_z_, 4}};
const Environment env2{env1};
env1.insert(var_w_, 5);
EXPECT_EQ(env1.size(), 4u);
EXPECT_EQ(env2.size(), 3u);
const auto it1(env1.find(var_w_));
ASSERT_TRUE(it1 != env1.end());
EXPECT_EQ(it1->second, 5);
const auto it2(env1.find(var_v_));
EXPECT_TRUE(it2 == env1.end());
env1.insert(var_v_, 6);
EXPECT_EQ(env1.size(), 5u);
}
TEST_F(EnvironmentTest, InsertMultipleItemsFind) {
const auto x = MakeMatrixContinuousVariable<3, 4>("x");
Eigen::Matrix<double, 3, 4> v;
v << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0;
Environment env;
env.insert(x, v);
EXPECT_EQ(env.size(), 12);
for (int j = 0; j < 4; ++j) {
for (int i = 0; i < 3; ++i) {
const auto it(env.find(x(i, j)));
ASSERT_TRUE(it != env.end());
EXPECT_EQ(it->second, v(i, j));
}
}
}
TEST_F(EnvironmentTest, InsertMultipleItemsFindSizeMismatch) {
const auto x = MakeMatrixContinuousVariable<4, 3>("x");
Eigen::Matrix<double, 3, 4> v;
v << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0;
Environment env;
// size of x : 4 x 3.
// size of v : 3 x 4.
EXPECT_THROW(env.insert(x, v), std::runtime_error);
}
TEST_F(EnvironmentTest, domain) {
const Environment env1{};
const Environment env2{{var_x_, 2}, {var_y_, 3}, {var_z_, 4}};
EXPECT_EQ(env1.domain(), Variables{});
EXPECT_EQ(env2.domain(), Variables({var_x_, var_y_, var_z_}));
}
TEST_F(EnvironmentTest, ToString) {
const Environment env{{var_x_, 2}, {var_y_, 3}, {var_z_, 3}};
const string out{env.to_string()};
EXPECT_TRUE(out.find("x -> 2") != string::npos);
EXPECT_TRUE(out.find("y -> 3") != string::npos);
EXPECT_TRUE(out.find("z -> 3") != string::npos);
}
TEST_F(EnvironmentTest, LookupOperator) {
Environment env{{var_x_, 2}};
const Environment const_env{{var_x_, 2}};
EXPECT_EQ(env[var_x_], 2);
EXPECT_EQ(const_env[var_x_], 2);
EXPECT_EQ(env[var_y_], 0);
EXPECT_THROW(const_env[var_y_], runtime_error);
EXPECT_EQ(env.size(), 2u);
EXPECT_EQ(const_env.size(), 1u);
}
TEST_F(EnvironmentTest, PopulateRandomVariables) {
const Variable uni{"uni", Variable::Type::RANDOM_UNIFORM};
const Variable gau{"gau", Variable::Type::RANDOM_GAUSSIAN};
const Variable exp{"exp", Variable::Type::RANDOM_EXPONENTIAL};
const Environment env1{{var_x_, 2}};
RandomGenerator g{};
// PopulateRandomVariables should add entries for the three random variables.
const Environment env2{
PopulateRandomVariables(env1, {var_x_, uni, gau, exp}, &g)};
EXPECT_EQ(env2.size(), 4);
EXPECT_TRUE(env2.find(uni) != env1.end());
EXPECT_TRUE(env2.find(gau) != env1.end());
EXPECT_TRUE(env2.find(exp) != env1.end());
// PopulateRandomVariables should add entries for the unassigned random
// variables, gau and exp. But it should keep the original assignment `uni β¦
// 10.0`.
const Environment env3{{var_x_, 2}, {uni, 10.0}};
const Environment env4{
PopulateRandomVariables(env3, {var_x_, uni, gau, exp}, &g)};
EXPECT_EQ(env4.size(), 4);
EXPECT_TRUE(env4.find(uni) != env1.end());
EXPECT_TRUE(env4.find(gau) != env1.end());
EXPECT_TRUE(env4.find(exp) != env1.end());
EXPECT_EQ(env4[uni], 10.0);
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/monomial_util_test.cc | #include "drake/common/symbolic/monomial_util.h"
#include <unordered_set>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.h"
namespace drake {
namespace symbolic {
void CheckCalcMonomialBasisOrderUpToOne(const drake::symbolic::Variables& t) {
// First compute the unsorted vector of monomial basis.
const auto basis_unsorted = CalcMonomialBasisOrderUpToOne(t, false);
const int basis_size_expected =
static_cast<int>(std::pow(2, static_cast<int>(t.size())));
EXPECT_EQ(basis_unsorted.rows(), basis_size_expected);
std::unordered_set<Monomial> basis_set;
basis_set.reserve(basis_size_expected);
for (int i = 0; i < basis_unsorted.rows(); ++i) {
for (const Variable& ti : t) {
EXPECT_LE(basis_unsorted(i).degree(ti), 1);
}
basis_set.insert(basis_unsorted(i));
}
// Make sure basis_set has the same size as basis_unsorted. Hence each element
// inside basis_unsorted is unique.
EXPECT_EQ(basis_set.size(), basis_size_expected);
// Now compute the sorted vector of monomial basis.
const auto basis_sorted = CalcMonomialBasisOrderUpToOne(t, true);
EXPECT_EQ(basis_sorted.rows(), basis_size_expected);
for (int i = 0; i < basis_sorted.rows(); ++i) {
EXPECT_TRUE(basis_set.contains(basis_sorted(i)));
}
// Make sure that basis_sorted is actually in the graded lexicographic order.
for (int i = 0; i < basis_sorted.rows() - 1; ++i) {
EXPECT_TRUE(GradedReverseLexOrder<std::less<Variable>>()(
basis_sorted(i), basis_sorted(i + 1)));
}
}
class CalcMonomialBasisTest : public ::testing::Test {
protected:
Variable t1_{"t1"};
Variable t2_{"t2"};
Variable t3_{"t3"};
Variable t4_{"t4"};
};
TEST_F(CalcMonomialBasisTest, CalcMonomialBasisOrderUpToOne) {
CheckCalcMonomialBasisOrderUpToOne(Variables({t1_}));
CheckCalcMonomialBasisOrderUpToOne(Variables({t1_, t2_}));
CheckCalcMonomialBasisOrderUpToOne(Variables({t1_, t2_, t3_}));
CheckCalcMonomialBasisOrderUpToOne(Variables({t1_, t2_, t3_, t4_}));
const Vector4<symbolic::Monomial> monomial12 =
CalcMonomialBasisOrderUpToOne(Variables({t1_, t2_}), true);
ASSERT_TRUE(std::less<Variable>()(t1_, t2_));
EXPECT_EQ(monomial12[0], Monomial(t1_ * t2_));
EXPECT_EQ(monomial12[1], Monomial(t2_));
EXPECT_EQ(monomial12[2], Monomial(t1_));
EXPECT_EQ(monomial12[3], Monomial(1));
}
GTEST_TEST(MonomialBasis, TestMultipleVariables) {
// Test overloaded MonomialBasis function with argument
// unordered_map<Variables, int>
const Variable x0("x0");
const Variable x1("x1");
const Variable x2("x2");
const Variable y0("y0");
const Variable y1("y1");
const Variable z0("z0");
const Variable w0("w0");
const Variable w1("w1");
const Variables x_set({x0, x1, x2});
const Variables y_set({y0, y1});
const Variables z_set({z0});
const Variables w_set({w0, w1});
const VectorX<Monomial> monomials =
MonomialBasis({{x_set, 2}, {y_set, 1}, {z_set, 3}, {w_set, 0}});
// There are 10 monomials in MonomialBasis(x_set, 2)
// 3 monomials in MonomialBasis(y_set, 1)
// 4 monomials in MonomialBasis(z_set, 3).
// 1 monomial in MonomialBasis(w_set, 0).
// So in total we should have 10 * 3 * 4 * 1 = 120 monomials.
EXPECT_EQ(monomials.rows(), 120);
// Compute the total degree of a monomial `m` in the variables `var`.
auto degree_in_vars = [](const Monomial& m, const Variables& vars) {
return std::accumulate(vars.begin(), vars.end(), 0,
[&m](int degree, const Variable& v) {
return degree + m.degree(v);
});
};
for (int i = 0; i < monomials.rows(); ++i) {
if (i != 0) {
EXPECT_NE(monomials(i), monomials(i - 1));
EXPECT_TRUE(GradedReverseLexOrder<std::less<Variable>>()(monomials(i - 1),
monomials(i)));
}
EXPECT_LE(degree_in_vars(monomials(i), x_set), 2);
EXPECT_LE(degree_in_vars(monomials(i), y_set), 1);
EXPECT_LE(degree_in_vars(monomials(i), z_set), 3);
EXPECT_LE(degree_in_vars(monomials(i), w_set), 0);
}
// Test overlapping variables in the input.
DRAKE_EXPECT_THROWS_MESSAGE(
MonomialBasis({{Variables({x0, x1}), 2}, {Variables({x0, y0}), 1}}),
".* x0 shows up more than once .*");
}
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/decompose_test.cc | #include "drake/common/symbolic/decompose.h"
#include <limits>
#include <stdexcept>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
namespace drake {
namespace symbolic {
namespace {
using std::runtime_error;
using std::unordered_map;
using MapVarToIndex = unordered_map<Variable::Id, int>;
constexpr double kEps = std::numeric_limits<double>::epsilon();
class SymbolicDecomposeTest : public ::testing::Test {
public:
SymbolicDecomposeTest() = default;
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SymbolicDecomposeTest)
protected:
void SetUp() override {
// clang-format off
M_ << 1, 0, 3,
-4, 5, 0,
7, 0, 9;
v_ << 3,
-7,
2;
x_ << x0_, x1_, x2_;
// clang-format on
}
const Variable x0_{"x0"};
const Variable x1_{"x1"};
const Variable x2_{"x2"};
VectorX<Variable> x_{3};
const Variable a_{"a"};
const Variable b_{"b"};
const Variable c_{"c"};
// M and v matrices that we pass to decompose functions as input. We mix
// static-sized and dynamic-sized matrices intentionally.
Eigen::Matrix3d M_;
Eigen::Vector3d v_;
// Expected values for M and v.
Eigen::Matrix3d M_expected_static_;
Eigen::MatrixXd M_expected_dynamic_{3, 3};
Eigen::Vector3d v_expected_static_;
Eigen::VectorXd v_expected_dynamic_{3};
// Extra terms that we add to test exceptional cases.
Eigen::Matrix<Expression, 3, 1> extra_terms_;
};
TEST_F(SymbolicDecomposeTest, IsAffine) {
Expression a{a_};
Expression x0{x0_};
Eigen::Matrix<Expression, 2, 2> M;
// clang-format off
M << a*a * x0, x0,
2 * x0, 3 * x0 + 1;
// clang-format on
// M is affine in {x0}.
EXPECT_TRUE(IsAffine(M, {x0_}));
// However, M is *not* affine in {a, x0}.
EXPECT_FALSE(IsAffine(M));
}
TEST_F(SymbolicDecomposeTest, DecomposeLinearExpressionsDynamic) {
DecomposeLinearExpressions(M_ * x_, x_, &M_expected_dynamic_);
EXPECT_EQ(M_expected_dynamic_, M_);
}
TEST_F(SymbolicDecomposeTest, DecomposeLinearExpressionsStatic) {
DecomposeLinearExpressions(M_ * x_, x_, &M_expected_static_);
EXPECT_EQ(M_expected_static_, M_);
}
// Adds quadratic terms to check if we have an exception.
TEST_F(SymbolicDecomposeTest, DecomposeLinearExpressionsExceptionNonLinear) {
// clang-format off
extra_terms_ << x0_ * x0_,
x1_ * x1_,
x2_ * x2_;
// clang-format on
DRAKE_EXPECT_THROWS_MESSAGE(
DecomposeLinearExpressions(M_ * x_ + extra_terms_, x_,
&M_expected_static_),
".*we detected a non-linear expression.*");
}
// Adds nonlinear terms to check if we have an exception.
TEST_F(SymbolicDecomposeTest,
DecomposeLinearExpressionsExceptionNonPolynomial) {
// clang-format off
extra_terms_ << sin(x0_),
cos(x1_),
log(x2_);
// clang-format on
DRAKE_EXPECT_THROWS_MESSAGE(
DecomposeLinearExpressions(M_ * x_ + extra_terms_, x_,
&M_expected_static_),
".*we detected a non-polynomial expression.*");
}
// Adds terms with non-const coefficients to check if we have an exception.
TEST_F(SymbolicDecomposeTest,
DecomposeLinearExpressionsExceptionNonConstCoefficient) {
// clang-format off
extra_terms_ << a_ * x0_,
b_ * x1_,
c_ * x2_;
// clang-format on
DRAKE_EXPECT_THROWS_MESSAGE(
DecomposeLinearExpressions(M_ * x_ + extra_terms_, x_,
&M_expected_static_),
".*we detected a non-constant expression.*");
}
// Adds constant terms to check if we have an exception.
TEST_F(SymbolicDecomposeTest, DecomposeLinearExpressionsExceptionAffine) {
// clang-format off
extra_terms_ << -1,
1,
M_PI;
// clang-format on
EXPECT_THROW(DecomposeLinearExpressions(M_ * x_ + extra_terms_, x_,
&M_expected_static_),
runtime_error);
}
TEST_F(SymbolicDecomposeTest, DecomposeAffineExpressionsDynamic) {
DecomposeAffineExpressions(M_ * x_ + v_, x_, &M_expected_dynamic_,
&v_expected_dynamic_);
EXPECT_EQ(M_expected_dynamic_, M_);
EXPECT_EQ(v_expected_dynamic_, v_);
}
TEST_F(SymbolicDecomposeTest, DecomposeAffineExpressionsStatic) {
DecomposeAffineExpressions(M_ * x_ + v_, x_, &M_expected_static_,
&v_expected_static_);
EXPECT_EQ(M_expected_static_, M_);
EXPECT_EQ(v_expected_static_, v_);
}
TEST_F(SymbolicDecomposeTest, DecomposeAffineExpressionsBlock) {
Eigen::Matrix4d M_expected;
auto block = M_expected.block(0, 0, 3, 3);
DecomposeAffineExpressions(M_ * x_ + v_, x_, &block, &v_expected_static_);
EXPECT_EQ(M_expected.block(0, 0, 3, 3), M_);
EXPECT_EQ(v_expected_static_, v_);
}
// Adds quadratic terms to check if we have an exception.
TEST_F(SymbolicDecomposeTest, DecomposeAffineExpressionsExceptionNonlinear) {
// clang-format off
extra_terms_ << x0_ * x0_,
x1_ * x1_,
x2_ * x2_;
// clang-format on
EXPECT_THROW(
DecomposeAffineExpressions(M_ * x_ + v_ + extra_terms_, x_,
&M_expected_static_, &v_expected_static_),
runtime_error);
}
// Adds terms with non-const coefficients to check if we have an exception.
TEST_F(SymbolicDecomposeTest,
DecomposeAffineExpressionsExceptionNonConstCoefficient) {
// clang-format off
extra_terms_ << a_ * x0_,
b_ * x1_,
c_ * x2_;
// clang-format on
EXPECT_THROW(
DecomposeAffineExpressions(M_ * x_ + v_ + extra_terms_, x_,
&M_expected_static_, &v_expected_static_),
runtime_error);
}
// Adds nonlinear terms to check if we have an exception.
TEST_F(SymbolicDecomposeTest,
DecomposeAffineExpressionsExceptionNonPolynomial) {
// clang-format off
extra_terms_ << sin(x0_),
cos(x1_),
log(x2_);
// clang-format on
EXPECT_THROW(
DecomposeAffineExpressions(M_ * x_ + v_ + extra_terms_, x_,
&M_expected_static_, &v_expected_static_),
runtime_error);
}
// Check expected invariance
void ExpectValidMapVarToIndex(const VectorX<Variable>& vars,
const MapVarToIndex& map_var_to_index) {
EXPECT_EQ(vars.size(), map_var_to_index.size());
for (int i = 0; i < vars.size(); ++i) {
const auto& var = vars(i);
EXPECT_EQ(i, map_var_to_index.at(var.get_id()));
}
}
GTEST_TEST(SymbolicExtraction, ExtractVariables1) {
// Test ExtractVariablesFromExpression with a single expression.
const Variable x("x");
const Variable y("y");
Expression e = x + y;
VectorX<Variable> vars_expected(2);
vars_expected << x, y;
VectorX<Variable> vars;
MapVarToIndex map_var_to_index;
std::tie(vars, map_var_to_index) = ExtractVariablesFromExpression(e);
EXPECT_EQ(vars_expected, vars);
ExpectValidMapVarToIndex(vars, map_var_to_index);
const Variable z("z");
e += x * (z - y);
const int vars_size = vars_expected.rows();
vars_expected.conservativeResize(vars_size + 1, Eigen::NoChange);
vars_expected(vars_size) = z;
ExtractAndAppendVariablesFromExpression(e, &vars, &map_var_to_index);
EXPECT_EQ(vars_expected, vars);
ExpectValidMapVarToIndex(vars, map_var_to_index);
}
GTEST_TEST(SymbolicExtraction, ExtractVariables2) {
// TestExtractVariablesFromExpression with a vector of expressions.
const Variable x("x");
const Variable y("y");
const Variable z("z");
Vector3<symbolic::Expression> expressions(x + y, y + 1, x + z);
VectorX<Variable> vars;
MapVarToIndex map_var_to_index;
std::tie(vars, map_var_to_index) =
ExtractVariablesFromExpression(expressions);
EXPECT_EQ(symbolic::Variables(vars), symbolic::Variables({x, y, z}));
ExpectValidMapVarToIndex(vars, map_var_to_index);
std::tie(vars, map_var_to_index) =
ExtractVariablesFromExpression(expressions.tail<2>());
EXPECT_EQ(symbolic::Variables(vars), symbolic::Variables({x, y, z}));
ExpectValidMapVarToIndex(vars, map_var_to_index);
std::tie(vars, map_var_to_index) =
ExtractVariablesFromExpression(expressions.head<2>());
EXPECT_EQ(symbolic::Variables(vars), symbolic::Variables({x, y}));
ExpectValidMapVarToIndex(vars, map_var_to_index);
}
// Make off-diagonal terms symmetric for a given input matrix
template <typename Derived>
void AverageOffDiagonalTerms(const Eigen::MatrixBase<Derived>& Q_asym,
Eigen::MatrixBase<Derived>* pQ_sym) {
DRAKE_ASSERT(Q_asym.rows() == Q_asym.cols());
Derived& Q_sym = pQ_sym->derived();
Q_sym = Q_asym;
int size = Q_sym.rows();
for (int r = 0; r < size - 1; ++r) {
for (int c = r + 1; c < size; ++c) {
Q_sym(r, c) = 0.5 * (Q_asym(r, c) + Q_asym(c, r));
Q_sym(c, r) = Q_sym(r, c);
}
}
}
GTEST_TEST(SymbolicExtraction, DecomposeQuadraticExpression) {
const int num_variables = 3;
const Variable x("x");
const Variable y("y");
const Variable z("z");
const Vector3<Variable> vars_expected(x, y, z);
Eigen::Matrix3d Q_diagonal, Q_symmetric, Q_asymmetric;
Q_diagonal.setZero().diagonal() = Eigen::Vector3d(1, 2, 3);
Q_symmetric << 3, 2, 1, 2, 4, 5, 1, 5, 6;
Q_asymmetric << 3, 2, 1, 4, 6, 5, 7, 8, 9;
const Eigen::Vector3d b_expected(10, 11, 12);
const double c_expected = 13;
for (const Eigen::Matrix3d& Q_in : {Q_diagonal, Q_symmetric, Q_asymmetric}) {
const Expression e =
vars_expected.dot(0.5 * Q_in * vars_expected + b_expected) + c_expected;
const auto pair = ExtractVariablesFromExpression(e);
const VectorX<Variable>& vars = pair.first;
const MapVarToIndex& map_var_to_index = pair.second;
EXPECT_EQ(vars_expected, vars);
const symbolic::Polynomial poly{e};
Eigen::MatrixXd Q(num_variables, num_variables);
Eigen::VectorXd b(num_variables);
double c;
DecomposeQuadraticPolynomial(poly, map_var_to_index, &Q, &b, &c);
Eigen::Matrix3d Q_expected;
AverageOffDiagonalTerms(Q_in, &Q_expected);
EXPECT_TRUE(CompareMatrices(Q_expected, Q, kEps));
EXPECT_TRUE(CompareMatrices(b_expected, b, kEps));
EXPECT_EQ(c_expected, c);
}
}
// Return scalar value from an effectively scalar Eigen expression
template <typename Derived>
const typename Derived::Scalar& AsScalar(const Eigen::EigenBase<Derived>& X) {
DRAKE_ASSERT(X.rows() == 1 && X.cols() == 1);
return X.derived().coeffRef(0, 0);
}
GTEST_TEST(SymbolicExtraction, DecomposeAffineExpression) {
const int num_variables = 3;
const Variable x("x");
const Variable y("y");
const Variable z("z");
const Vector3<Variable> vars_expected(x, y, z);
// Scalar value case
{
Eigen::MatrixXd coeffs_expected(1, num_variables);
coeffs_expected << 1, 2, 3;
double c_expected = 4;
Expression e = AsScalar(coeffs_expected * vars_expected) + c_expected;
const auto pair = ExtractVariablesFromExpression(e);
const VectorX<Variable>& vars = pair.first;
const MapVarToIndex& map_var_to_index = pair.second;
EXPECT_EQ(vars_expected, vars);
Eigen::RowVectorXd coeffs(num_variables);
double c;
DecomposeAffineExpression(e, map_var_to_index, &coeffs, &c);
EXPECT_TRUE(CompareMatrices(coeffs_expected, coeffs, kEps));
EXPECT_EQ(c_expected, c);
c_expected = 0;
e = AsScalar(coeffs_expected * vars_expected) + c_expected;
DecomposeAffineExpression(e, map_var_to_index, &coeffs, &c);
EXPECT_TRUE(CompareMatrices(coeffs_expected, coeffs, kEps));
EXPECT_EQ(c_expected, c);
// Now test a new expression with different coefficients and we pass in the
// same variable `coeffs`. This tests whether DecomposeAffineExpression
// reset coeffs (when the input coeffs stores some value).
coeffs_expected << 0, 0, 5;
c_expected = 2;
e = AsScalar(coeffs_expected * vars_expected) + c_expected;
DecomposeAffineExpression(e, map_var_to_index, &coeffs, &c);
EXPECT_TRUE(CompareMatrices(coeffs_expected, coeffs, kEps));
EXPECT_EQ(c_expected, c);
}
// Vector value case
{
const int num_eq = 3;
Eigen::MatrixXd coeffs_expected(num_eq, num_variables);
coeffs_expected << 1, 2, 3, 4, 5, 6, 7, 8, 9;
Eigen::VectorXd c_expected(num_eq);
c_expected << 10, 11, 12;
const VectorX<Expression> ev = coeffs_expected * vars_expected + c_expected;
Eigen::MatrixXd coeffs(num_eq, num_variables);
Eigen::VectorXd c(num_eq);
VectorX<Variable> vars;
DecomposeAffineExpressions(ev, &coeffs, &c, &vars);
EXPECT_EQ(vars_expected, vars);
EXPECT_TRUE(CompareMatrices(coeffs_expected, coeffs, kEps));
EXPECT_TRUE(CompareMatrices(c_expected, c, kEps));
}
}
GTEST_TEST(SymbolicExtraction, DecomposeLumpedParameters) {
const Variable x("x");
const Variable y("y");
const Variable a("a");
const Variable b("b");
const Variable c("c");
{
// e = a + x, params = {a,b,c} should give
// W = [1], Ξ± = [a], w0 = [x]
const Expression e = a + x;
const auto [W, alpha, w0] = DecomposeLumpedParameters(
Vector1<Expression>(e), Vector3<Variable>{a, b, c});
EXPECT_EQ(W, Vector1<Expression>{1});
EXPECT_EQ(alpha, Vector1<Expression>{a});
EXPECT_EQ(w0, Vector1<Expression>{x});
}
{
// e = a*c*x*y, params = {a,b,c} should give
// W = [x*y], Ξ± = [a*c], w0 = [0]
const Expression e = a * c * x * y;
const auto [W, alpha, w0] = DecomposeLumpedParameters(
Vector1<Expression>(e), Vector3<Variable>{a, b, c});
EXPECT_EQ(W, Vector1<Expression>{x * y});
EXPECT_EQ(alpha, Vector1<Expression>{a * c});
EXPECT_EQ(w0, Vector1<Expression>{0});
}
{
// e = [a + x, a*x], params = {a,b,c} should give
// W = [1; x], Ξ± = [a], w0 = [x; 0]
const Vector2<Expression> f(a + x, a * x);
const auto [W, alpha, w0] =
DecomposeLumpedParameters(f, Vector3<Variable>{a, b, c});
EXPECT_EQ(W, Vector2<Expression>(1, x));
EXPECT_EQ(alpha, Vector1<Expression>(a));
EXPECT_EQ(w0, Vector2<Expression>(x, 0));
}
{
// e = a*x*x, params = {a,b,c} should give
// W = [x*x], Ξ± = [a], w0 = [0]
const Expression e = a * x * x;
const auto [W, alpha, w0] = DecomposeLumpedParameters(
Vector1<Expression>(e), Vector3<Variable>{a, b, c});
EXPECT_EQ(W, Vector1<Expression>{x * x});
EXPECT_EQ(alpha, Vector1<Expression>{a});
EXPECT_EQ(w0, Vector1<Expression>{0});
}
{
// ax + bx + acy + acyΒ² + 2, params = {a,b,c} should give
// W = [x, y+yΒ²], Ξ± = [a+b, ac], w0 = [2]
const Expression e = a * x + b * x + a * c * y + a * c * y * y + 2;
const auto [W, alpha, w0] = DecomposeLumpedParameters(
Vector1<Expression>(e), Vector3<Variable>{a, b, c});
EXPECT_EQ(W, RowVector2<Expression>(x, y + y * y));
EXPECT_EQ(alpha, Vector2<Expression>(a + b, a * c));
EXPECT_EQ(w0, Vector1<Expression>(2));
}
{
// Test non-polynomials.
// e = sin(a)*cos(x)+tanh(y), params = {a,b,c} should give
// W = [cos(x)], Ξ± = [sin(a)], w0 = [tanh(x)]
const Expression e = sin(a) * cos(x) + tanh(x);
const auto [W, alpha, w0] = DecomposeLumpedParameters(
Vector1<Expression>(e), Vector3<Variable>{a, b, c});
EXPECT_EQ(W, Vector1<Expression>(cos(x)));
EXPECT_EQ(alpha, Vector1<Expression>(sin(a)));
EXPECT_EQ(w0, Vector1<Expression>(tanh(x)));
}
{
// Test a case that takes a power of a mixed expression.
// e = (a*x*sin(b))**2, params = {a,b,c} should give
// W = [x*x], alpha = [a*a*sin(b)*sin(b)], w0 = [0].
const Expression e = pow(a * sin(b) * x, 2);
const auto [W, alpha, w0] = DecomposeLumpedParameters(
Vector1<Expression>(e), Vector3<Variable>{a, b, c});
EXPECT_EQ(W, Vector1<Expression>(x * x));
EXPECT_EQ(alpha, Vector1<Expression>(a * a * sin(b) * sin(b)));
EXPECT_EQ(w0, Vector1<Expression>(0));
}
{
// Test a case that is not decomposable.
// e = sin(a*x), params = {a,b,c} should give
const Expression e = sin(a * x);
EXPECT_THROW(DecomposeLumpedParameters(Vector1<Expression>(e),
Vector3<Variable>{a, b, c}),
std::exception);
}
{
// Test additional symbolic elements.
const Expression e = x / y + abs(x) + log(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);
// Note: if_then_else(x>0, x, y) doesn't work because Expand is not
// implemented yet for ifthenelse.
const auto [W, alpha, w0] = DecomposeLumpedParameters(
Vector1<Expression>(e), Vector3<Variable>{a, b, c});
EXPECT_EQ(W.size(), 0);
EXPECT_EQ(alpha.size(), 0);
EXPECT_EQ(w0, Vector1<Expression>(e));
}
}
GTEST_TEST(SymbolicExtraction, DecomposeL2Norm) {
auto x = MakeVectorVariable<3>("x");
auto xe = x.template cast<Expression>();
const Expression e = sqrt(xe.dot(xe));
const auto [is_l2norm, A, b, vars] = DecomposeL2NormExpression(e);
EXPECT_TRUE(is_l2norm);
EXPECT_TRUE(CompareMatrices(A, Eigen::MatrixXd::Identity(3, 3)));
EXPECT_TRUE(CompareMatrices(b, Eigen::VectorXd::Zero(3)));
EXPECT_EQ(vars, x);
}
GTEST_TEST(SymbolicExtraction, DecomposeL2Norm2) {
auto x = MakeVectorVariable<2>("x");
Eigen::Matrix2d A_expected;
A_expected << 1, 2, 3, 4;
const Eigen::Vector2d b_expected(5, 6);
const Expression e = (A_expected * x + b_expected).norm();
const auto [is_l2norm, A, b, vars] = DecomposeL2NormExpression(e);
EXPECT_TRUE(is_l2norm);
// The decomposition is not unique, so we can only check that the resulting
// quadratic form is a match.
EXPECT_TRUE(CompareMatrices(A.transpose() * A,
A_expected.transpose() * A_expected, 1e-12));
EXPECT_TRUE(CompareMatrices(A.transpose() * b,
A_expected.transpose() * b_expected, 1e-12));
EXPECT_EQ(vars, x);
}
GTEST_TEST(SymbolicExtraction, DecomposeL2NormNonSquareMatrix) {
auto x = MakeVectorVariable<3>("x");
Eigen::MatrixXd A_expected(2, 3);
// clang-format off
A_expected << 1, 2, 3,
4, 5, 6;
// clang-format on
const Eigen::Vector2d b_expected(7, 8);
const Expression e = (A_expected * x + b_expected).norm();
const auto [is_l2norm, A, b, vars] = DecomposeL2NormExpression(e);
EXPECT_TRUE(is_l2norm);
// The decomposition is not unique, so we can only check that the resulting
// quadratic form is a match.
EXPECT_TRUE(CompareMatrices(A.transpose() * A,
A_expected.transpose() * A_expected, 1e-12));
EXPECT_TRUE(CompareMatrices(A.transpose() * b,
A_expected.transpose() * b_expected, 1e-12));
EXPECT_EQ(vars, x);
}
GTEST_TEST(SymbolicExtraction, DecomposeL2NormNonSquareMatrix2) {
auto x = MakeVectorVariable<2>("x");
Eigen::MatrixXd A_expected(3, 2);
// clang-format off
A_expected << 1, 2,
3, 4,
5, 6;
// clang-format on
const Eigen::Vector3d b_expected(7, 8, 9);
const Expression e = (A_expected * x + b_expected).norm();
const auto [is_l2norm, A, b, vars] = DecomposeL2NormExpression(e);
EXPECT_TRUE(is_l2norm);
// The decomposition is not unique, so we can only check that the resulting
// quadratic form is a match.
EXPECT_TRUE(CompareMatrices(A.transpose() * A,
A_expected.transpose() * A_expected, 1e-12));
EXPECT_TRUE(CompareMatrices(A.transpose() * b,
A_expected.transpose() * b_expected, 1e-12));
EXPECT_EQ(vars, x);
}
GTEST_TEST(SymbolicExtraction, DecomposeL2NormFalse) {
auto x = MakeVectorVariable<3>("x");
auto xe = x.template cast<Expression>();
// Not a sqrt.
Expression e = xe.dot(xe);
auto [is_l2norm, A, b, vars] = DecomposeL2NormExpression(e);
EXPECT_FALSE(is_l2norm);
// Not a polynomial inside the sqrt.
e = sqrt(sin(x[0]));
std::tie(is_l2norm, A, b, vars) = DecomposeL2NormExpression(e);
EXPECT_FALSE(is_l2norm);
// Not a quadratic form inside the sqrt.
e = sqrt(x[0] * x[0] * x[0]);
std::tie(is_l2norm, A, b, vars) = DecomposeL2NormExpression(e);
EXPECT_FALSE(is_l2norm);
// Not a positive quadratic form inside the sqrt.
e = sqrt(-1 * x[0] * x[0]);
std::tie(is_l2norm, A, b, vars) = DecomposeL2NormExpression(e);
EXPECT_FALSE(is_l2norm);
// Confirm that psd tolerance controls this threshold.
// This passes the psd check but results in an empty A matrix.
std::tie(is_l2norm, A, b, vars) = DecomposeL2NormExpression(e, 2.0);
EXPECT_FALSE(is_l2norm);
// This passes the psd check and results in a smaller A matrix.
e = sqrt(-1 * x[0] * x[0] + 4 * x[1] * x[1]);
std::tie(is_l2norm, A, b, vars) = DecomposeL2NormExpression(e, 2.0);
EXPECT_TRUE(is_l2norm);
EXPECT_TRUE(CompareMatrices(A, Eigen::RowVector2d(0, 2), 1e-12));
// The quadratic form can't be written as (Ax+b)'(Ax+b), because r is not in
// the range of A'.
e = sqrt(x[0] * x[0] + x[0] + x[1] + 0.25);
std::tie(is_l2norm, A, b, vars) = DecomposeL2NormExpression(e);
EXPECT_FALSE(is_l2norm);
// The quadratic form can't be written as (Ax+b)'(Ax+b).
e = sqrt(xe.dot(xe) + 1);
std::tie(is_l2norm, A, b, vars) = DecomposeL2NormExpression(e);
EXPECT_FALSE(is_l2norm);
// Confirm that constant term tolerance controls this threshold.
std::tie(is_l2norm, A, b, vars) = DecomposeL2NormExpression(e, 1e-8, 2.0);
EXPECT_TRUE(is_l2norm);
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/monomial_test.cc | #include <exception>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/hash.h"
#include "drake/common/symbolic/monomial_util.h"
#include "drake/common/symbolic/polynomial.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
using std::map;
using std::pair;
using std::runtime_error;
using std::unordered_map;
using std::vector;
namespace drake {
namespace symbolic {
namespace {
using test::ExprEqual;
using test::VarLess;
class MonomialTest : public ::testing::Test {
protected:
const Variable var_w_{"w"};
const Variable var_z_{"z"};
const Variable var_y_{"y"};
const Variable var_x_{"x"};
const Expression w_{var_w_};
const Expression z_{var_z_};
const Expression y_{var_y_};
const Expression x_{var_x_};
vector<Monomial> monomials_;
void SetUp() override {
monomials_ = {
Monomial{}, // 1.0
Monomial{var_x_, 1}, // x^1
Monomial{var_y_, 1}, // y^1
Monomial{var_z_, 1}, // z^1
Monomial{var_x_, 2}, // x^2
Monomial{var_y_, 3}, // y^3
Monomial{var_z_, 4}, // z^4
Monomial{{{var_x_, 1}, {var_y_, 2}}}, // xy^2
Monomial{{{var_y_, 2}, {var_z_, 5}}}, // y^2z^5
Monomial{{{var_x_, 1}, {var_y_, 2}, {var_z_, 3}}}, // xy^2z^3
Monomial{{{var_x_, 2}, {var_y_, 4}, {var_z_, 3}}}, // x^2y^4z^3
};
EXPECT_PRED2(VarLess, var_y_, var_x_);
EXPECT_PRED2(VarLess, var_z_, var_y_);
EXPECT_PRED2(VarLess, var_w_, var_z_);
}
// Helper function to extract Substitution (Variable -> Expression) from a
// symbolic environment.
Substitution ExtractSubst(const Environment& env) {
Substitution subst;
subst.reserve(env.size());
for (const pair<const Variable, double>& p : env) {
subst.emplace(p.first, p.second);
}
return subst;
}
// Checks if Monomial::Evaluate corresponds to Expression::Evaluate.
//
// ToExpression
// Monomial ------------> Expression
// || ||
// Monomial::Evaluate || || Expression::Evaluate
// || ||
// \/ \/
// double (result2) == double (result1)
//
// In one direction (left-to-right), we convert a Monomial to an Expression
// and evaluate it to a double value (result1). In another direction
// (top-to-bottom), we directly evaluate a Monomial to double (result2). The
// two result1 and result2 should be the same.
//
// Also confirms that expression always is declared to be pre-expanded.
void CheckEvaluate(const Monomial& m, const Environment& env) {
SCOPED_TRACE(fmt::format("m = {}; env = {}", m, env));
const Expression e{m.ToExpression()};
EXPECT_TRUE(e.is_expanded());
const double result1{e.Evaluate(env)};
const double result2{m.Evaluate(env)};
EXPECT_EQ(result1, result2);
}
// Checks if Monomial::EvaluatePartial corresponds to Expression's
// EvaluatePartial.
//
// ToExpression
// Monomial ------------> Expression
// || ||
// EvaluatePartial || || EvaluatePartial
// || ||
// \/ \/
// double * Monomial (e2) == Expression (e1)
//
// In one direction (left-to-right), first we convert a Monomial to an
// Expression using Monomial::ToExpression and call
// Expression::EvaluatePartial to have an Expression (e1). In another
// direction (top-to-bottom), we call Monomial::EvaluatePartial which returns
// a pair of double (coefficient part) and Monomial. We obtain e2 by
// multiplying the two. Then, we check if e1 and e2 are structurally equal.
void CheckEvaluatePartial(const Monomial& m, const Environment& env) {
SCOPED_TRACE(fmt::format("m = {}; env = {}", m, env));
const Expression e1{m.ToExpression().EvaluatePartial(env)};
const auto [coeff, m2] = m.EvaluatePartial(env);
const Expression e2{coeff * m2.ToExpression()};
EXPECT_PRED2(ExprEqual, e1, e2);
}
};
// Tests that default constructor and EIGEN_INITIALIZE_MATRICES_BY_ZERO
// constructor both create the same value.
TEST_F(MonomialTest, DefaultConstructors) {
const Monomial m_default;
const Monomial m_zero(0);
EXPECT_EQ(m_default.total_degree(), 0);
EXPECT_EQ(m_zero.total_degree(), 0);
}
TEST_F(MonomialTest, ConstructFromVariable) {
const Monomial m1{var_x_};
const std::map<Variable, int> powers{m1.get_powers()};
// Checks that powers = {x β¦ 1}.
ASSERT_EQ(powers.size(), 1u);
EXPECT_EQ(powers.begin()->first, var_x_);
EXPECT_EQ(powers.begin()->second, 1);
}
TEST_F(MonomialTest, ConstructFromVariablesAndExponents) {
// [] * [] => 1.
const VectorX<Variable> vars(0);
const VectorX<int> exponents(0);
const Monomial one{Monomial{Expression::One()}};
EXPECT_EQ(Monomial(vars, exponents), one);
const Vector3<Variable> vars_xyz{var_x_, var_y_, var_z_};
// [x, y, z] * [0, 0, 0] => 1.
const Monomial m1{vars_xyz, Eigen::Vector3i{0, 0, 0}};
EXPECT_EQ(m1, one);
// [x, y, z] * [1, 1, 1] => xyz.
const Monomial m2{vars_xyz, Eigen::Vector3i{1, 1, 1}};
const Monomial m2_expected{x_ * y_ * z_};
EXPECT_EQ(m2, m2_expected);
// [x, y, z] * [2, 0, 3] => xΒ²zΒ³.
const Monomial m3{vars_xyz, Eigen::Vector3i{2, 0, 3}};
const Monomial m3_expected{pow(x_, 2) * pow(z_, 3)};
EXPECT_EQ(m3, m3_expected);
// [x, y, z] * [2, 0, -1] => Exception!
DRAKE_EXPECT_THROWS_MESSAGE(Monomial(vars_xyz, Eigen::Vector3i(2, 0, -1)),
"The exponent is negative.");
}
TEST_F(MonomialTest, GetVariables) {
const Monomial m0{};
EXPECT_EQ(m0.GetVariables(), Variables{});
const Monomial m1{var_z_, 4};
EXPECT_EQ(m1.GetVariables(), Variables({var_z_}));
const Monomial m2{{{var_x_, 1}, {var_y_, 2}}};
EXPECT_EQ(m2.GetVariables(), Variables({var_x_, var_y_}));
const Monomial m3{{{var_x_, 1}, {var_y_, 2}, {var_z_, 3}}};
EXPECT_EQ(m3.GetVariables(), Variables({var_x_, var_y_, var_z_}));
}
// Checks we can have an Eigen matrix of Monomials without compilation
// errors. No assertions in the test.
TEST_F(MonomialTest, EigenMatrixOfMonomials) {
Eigen::Matrix<Monomial, 2, 2> M;
// M = | 1 x |
// | yΒ² xΒ²zΒ³ |
// clang-format off
M << Monomial{}, Monomial{var_x_},
Monomial{{{var_y_, 2}}}, Monomial{{{var_x_, 2}, {var_z_, 3}}};
// clang-format on
}
TEST_F(MonomialTest, MonomialOne) {
// Compares monomials all equal to 1, but with different variables.
Monomial m1{};
Monomial m2({{var_x_, 0}});
Monomial m3({{var_x_, 0}, {var_y_, 0}});
EXPECT_EQ(m1, m2);
EXPECT_EQ(m1, m3);
EXPECT_EQ(m2, m3);
}
TEST_F(MonomialTest, MonomialWithZeroExponent) {
// Compares monomials containing zero exponent, such as x^0 * y^2
Monomial m1({{var_y_, 2}});
Monomial m2({{var_x_, 0}, {var_y_, 2}});
EXPECT_EQ(m1, m2);
EXPECT_EQ(m2.get_powers().size(), 1);
std::map<Variable, int> power_expected;
power_expected.emplace(var_y_, 2);
EXPECT_EQ(m2.get_powers(), power_expected);
}
TEST_F(MonomialTest, MonomialBasisX0) {
const drake::VectorX<Monomial> basis1{MonomialBasis({var_x_}, 0)};
const auto basis2 = MonomialBasis<1, 0>({var_x_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 1);
drake::Vector1<Monomial> expected;
// MonomialBasis({x}, 0) = {xβ°} = {1}.
expected << Monomial{};
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, MonomialBasisX2) {
const drake::VectorX<Monomial> basis1{MonomialBasis({var_x_}, 2)};
const auto basis2 = MonomialBasis<1, 2>({var_x_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 3);
drake::Vector3<Monomial> expected;
// MonomialBasis({x}, 2) = {xΒ², x, 1}.
// clang-format off
expected << Monomial{var_x_, 2},
Monomial{var_x_},
Monomial{};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, MonomialBasisXY0) {
const drake::VectorX<Monomial> basis1{MonomialBasis({var_x_, var_y_}, 0)};
const auto basis2 = MonomialBasis<2, 0>({var_x_, var_y_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 1);
drake::Vector1<Monomial> expected;
// MonomialBasis({x, y}, 0) = {1}.
expected << Monomial{{{var_x_, 0}, {var_y_, 0}}}; // = {1}.
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, MonomialBasisXY1) {
const drake::VectorX<Monomial> basis1{MonomialBasis({var_x_, var_y_}, 1)};
const auto basis2 = MonomialBasis<2, 1>({var_x_, var_y_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 3);
drake::Vector3<Monomial> expected;
// MonomialBasis({x, y}, 1) = {x, y, 1}.
// clang-format off
expected << Monomial{var_x_},
Monomial{var_y_},
Monomial{};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, MonomialBasisXY2) {
const drake::VectorX<Monomial> basis1{MonomialBasis({var_x_, var_y_}, 2)};
const auto basis2 = MonomialBasis<2, 2>({var_x_, var_y_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 6);
drake::Vector6<Monomial> expected;
// MonomialBasis({x, y}, 2) = {xΒ², xy, yΒ², x, y, 1}.
// clang-format off
expected << Monomial{var_x_, 2},
Monomial{{{var_x_, 1}, {var_y_, 1}}},
Monomial{var_y_, 2},
Monomial{var_x_},
Monomial{var_y_},
Monomial{};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, MonomialBasisXY3) {
const drake::VectorX<Monomial> basis1{MonomialBasis({var_x_, var_y_}, 3)};
const auto basis2 = MonomialBasis<2, 3>({var_x_, var_y_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 10);
Eigen::Matrix<Monomial, 10, 1> expected;
// MonomialBasis({x, y}, 3) = {xΒ³, xΒ²y, xyΒ², yΒ³, xΒ², xy, yΒ², x, y, 1}.
// clang-format off
expected << Monomial{var_x_, 3},
Monomial{{{var_x_, 2}, {var_y_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 2}}},
Monomial{var_y_, 3},
Monomial{var_x_, 2},
Monomial{{{var_x_, 1}, {var_y_, 1}}},
Monomial{var_y_, 2},
Monomial{var_x_},
Monomial{var_y_},
Monomial{};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, MonomialBasisXYZ2) {
const drake::VectorX<Monomial> basis1{
MonomialBasis({var_x_, var_y_, var_z_}, 2)};
const auto basis2 = MonomialBasis<3, 2>({var_x_, var_y_, var_z_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 10);
Eigen::Matrix<Monomial, 10, 1> expected;
// MonomialBasis({x, y, z}, 2)
// clang-format off
expected << Monomial{var_x_, 2},
Monomial{{{var_x_, 1}, {var_y_, 1}}},
Monomial{var_y_, 2},
Monomial{{{var_x_, 1}, {var_z_, 1}}},
Monomial{{{var_y_, 1}, {var_z_, 1}}},
Monomial{var_z_, 2},
Monomial{var_x_},
Monomial{var_y_},
Monomial{var_z_},
Monomial{};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, MonomialBasisXYZ3) {
const drake::VectorX<Monomial> basis1{
MonomialBasis({var_x_, var_y_, var_z_}, 3)};
const auto basis2 = MonomialBasis<3, 3>({var_x_, var_y_, var_z_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 20);
Eigen::Matrix<Monomial, 20, 1> expected;
// MonomialBasis({x, y, z}, 3)
// = {xΒ³, xΒ²y, xyΒ², yΒ³, xΒ²z, xyz, yΒ²z, xzΒ², yzΒ²,
// zΒ³, xΒ², xy, yΒ², xz, yz, zΒ², x, y, z, 1}
// clang-format off
expected << Monomial{var_x_, 3},
Monomial{{{var_x_, 2}, {var_y_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 2}}},
Monomial{var_y_, 3},
Monomial{{{var_x_, 2}, {var_z_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 1}, {var_z_, 1}}},
Monomial{{{var_y_, 2}, {var_z_, 1}}},
Monomial{{{var_x_, 1}, {var_z_, 2}}},
Monomial{{{var_y_, 1}, {var_z_, 2}}},
Monomial{var_z_, 3},
Monomial{var_x_, 2},
Monomial{{{var_x_, 1}, {var_y_, 1}}},
Monomial{var_y_, 2},
Monomial{{{var_x_, 1}, {var_z_, 1}}},
Monomial{{{var_y_, 1}, {var_z_, 1}}},
Monomial{var_z_, 2},
Monomial{var_x_},
Monomial{var_y_},
Monomial{var_z_},
Monomial{};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, MonomialBasisXYZW3) {
const drake::VectorX<Monomial> basis1{
MonomialBasis({var_x_, var_y_, var_z_, var_w_}, 3)};
const auto basis2 = MonomialBasis<4, 3>({var_x_, var_y_, var_z_, var_w_});
EXPECT_EQ(decltype(basis2)::RowsAtCompileTime, 35);
Eigen::Matrix<Monomial, 35, 1> expected;
// MonomialBasis({x, y, z, w}, 3)
// clang-format off
expected << Monomial{var_x_, 3},
Monomial{{{var_x_, 2}, {var_y_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 2}}},
Monomial{var_y_, 3},
Monomial{{{var_x_, 2}, {var_z_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 1}, {var_z_, 1}}},
Monomial{{{var_y_, 2}, {var_z_, 1}}},
Monomial{{{var_x_, 1}, {var_z_, 2}}},
Monomial{{{var_y_, 1}, {var_z_, 2}}},
Monomial{var_z_, 3},
Monomial{{{var_x_, 2}, {var_w_, 1}}},
Monomial{{{var_y_, 1}, {var_x_, 1}, {var_w_, 1}}},
Monomial{{{var_y_, 2}, {var_w_, 1}}},
Monomial{{{var_z_, 1}, {var_x_, 1}, {var_w_, 1}}},
Monomial{{{var_z_, 1}, {var_y_, 1}, {var_w_, 1}}},
Monomial{{{var_z_, 2}, {var_w_, 1}}},
Monomial{{{var_x_, 1}, {var_w_, 2}}},
Monomial{{{var_y_, 1}, {var_w_, 2}}},
Monomial{{{var_z_, 1}, {var_w_, 2}}},
Monomial{var_w_, 3},
Monomial{var_x_, 2},
Monomial{{{var_x_, 1}, {var_y_, 1}}},
Monomial{var_y_, 2},
Monomial{{{var_x_, 1}, {var_z_, 1}}},
Monomial{{{var_y_, 1}, {var_z_, 1}}},
Monomial{var_z_, 2},
Monomial{{{var_x_, 1}, {var_w_, 1}}},
Monomial{{{var_y_, 1}, {var_w_, 1}}},
Monomial{{{var_z_, 1}, {var_w_, 1}}},
Monomial{var_w_, 2},
Monomial{var_x_},
Monomial{var_y_},
Monomial{var_z_},
Monomial{var_w_},
Monomial{};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, EvenDegreeMonomialBasisX2) {
const drake::VectorX<Monomial> basis1{EvenDegreeMonomialBasis({var_x_}, 2)};
drake::Vector2<Monomial> expected;
// EvenDegreeMonomialBasis({x}, 2) = {xΒ², 1}.
// clang-format off
expected << Monomial{var_x_, 2},
Monomial{};
// clang-format on
EXPECT_EQ(basis1, expected);
}
TEST_F(MonomialTest, EvenDegreeMonomialBasisXY01) {
const drake::VectorX<Monomial> basis1{
EvenDegreeMonomialBasis({var_x_, var_y_}, 0)};
const drake::VectorX<Monomial> basis2{
EvenDegreeMonomialBasis({var_x_, var_y_}, 1)};
drake::Vector1<Monomial> expected;
// EvenDegreeMonomialBasis({x, y}, 0) = {1}.
expected << Monomial{{{var_x_, 0}, {var_y_, 0}}}; // = {1}.
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, EvenDegreeMonomialBasisXY23) {
const drake::VectorX<Monomial> basis1{
EvenDegreeMonomialBasis({var_x_, var_y_}, 2)};
const drake::VectorX<Monomial> basis2{
EvenDegreeMonomialBasis({var_x_, var_y_}, 3)};
drake::Vector4<Monomial> expected;
// EvenDegreeMonomialBasis({x, y}, 2) = {xΒ², xy, yΒ², 1}.
// clang-format off
expected << Monomial{{{var_x_, 2}, {var_y_, 0}}},
Monomial{{{var_x_, 1}, {var_y_, 1}}},
Monomial{{{var_x_, 0}, {var_y_, 2}}},
Monomial{{{var_x_, 0}, {var_y_, 0}}};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, EvenDegreeMonomialBasisXYZ45) {
const drake::VectorX<Monomial> basis1{
EvenDegreeMonomialBasis({var_x_, var_y_, var_z_}, 4)};
const drake::VectorX<Monomial> basis2{
EvenDegreeMonomialBasis({var_x_, var_y_, var_z_}, 5)};
Eigen::Matrix<Monomial, 22, 1> expected;
// EvenDegreeMonomialBasis({x, y, z}, 4) = {xβ΄, xΒ³y, xΒ²yΒ², xyΒ³, yβ΄, xΒ³z, xΒ²yz,
// xyΒ²z, yΒ³z, xΒ²zΒ², xyzΒ², yΒ²zΒ², xzΒ³, yzΒ³, zβ΄, xΒ², xy, yΒ², xz, yz, zΒ², 1}
// clang-format off
expected << Monomial{{{var_x_, 4}, {var_y_, 0}, {var_z_, 0}}},
Monomial{{{var_x_, 3}, {var_y_, 1}, {var_z_, 0}}},
Monomial{{{var_x_, 2}, {var_y_, 2}, {var_z_, 0}}},
Monomial{{{var_x_, 1}, {var_y_, 3}, {var_z_, 0}}},
Monomial{{{var_x_, 0}, {var_y_, 4}, {var_z_, 0}}},
Monomial{{{var_x_, 3}, {var_y_, 0}, {var_z_, 1}}},
Monomial{{{var_x_, 2}, {var_y_, 1}, {var_z_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 2}, {var_z_, 1}}},
Monomial{{{var_x_, 0}, {var_y_, 3}, {var_z_, 1}}},
Monomial{{{var_x_, 2}, {var_y_, 0}, {var_z_, 2}}},
Monomial{{{var_x_, 1}, {var_y_, 1}, {var_z_, 2}}},
Monomial{{{var_x_, 0}, {var_y_, 2}, {var_z_, 2}}},
Monomial{{{var_x_, 1}, {var_y_, 0}, {var_z_, 3}}},
Monomial{{{var_x_, 0}, {var_y_, 1}, {var_z_, 3}}},
Monomial{{{var_x_, 0}, {var_y_, 0}, {var_z_, 4}}},
Monomial{{{var_x_, 2}, {var_y_, 0}, {var_z_, 0}}},
Monomial{{{var_x_, 1}, {var_y_, 1}, {var_z_, 0}}},
Monomial{{{var_x_, 0}, {var_y_, 2}, {var_z_, 0}}},
Monomial{{{var_x_, 1}, {var_y_, 0}, {var_z_, 1}}},
Monomial{{{var_x_, 0}, {var_y_, 1}, {var_z_, 1}}},
Monomial{{{var_x_, 0}, {var_y_, 0}, {var_z_, 2}}},
Monomial{{{var_x_, 0}, {var_y_, 0}, {var_z_, 0}}};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, OddDegreeMonomialBasisX3) {
const drake::VectorX<Monomial> basis1{OddDegreeMonomialBasis({var_x_}, 3)};
drake::Vector2<Monomial> expected;
// OddDegreeMonomialBasis({x}, 3) = {xΒ³, 1}.
// clang-format off
expected << Monomial{var_x_, 3},
Monomial{var_x_, 1};
// clang-format on
EXPECT_EQ(basis1, expected);
}
TEST_F(MonomialTest, OddDegreeMonomialBasisXY12) {
const drake::VectorX<Monomial> basis1{
OddDegreeMonomialBasis({var_x_, var_y_}, 1)};
const drake::VectorX<Monomial> basis2{
OddDegreeMonomialBasis({var_x_, var_y_}, 2)};
drake::Vector2<Monomial> expected;
// OddDegreeMonomialBasis({x, y}, 1) = {x, y}.
expected << Monomial{{{var_x_, 1}, {var_y_, 0}}},
Monomial{{{var_x_, 0}, {var_y_, 1}}};
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, OddDegreeMonomialBasisXY34) {
const drake::VectorX<Monomial> basis1{
OddDegreeMonomialBasis({var_x_, var_y_}, 3)};
const drake::VectorX<Monomial> basis2{
OddDegreeMonomialBasis({var_x_, var_y_}, 4)};
drake::Vector6<Monomial> expected;
// OddDegreeMonomialBasis({x, y}, 3) = {xΒ³, xΒ²y, xyΒ², yΒ³, x, y}
// clang-format off
expected << Monomial{{{var_x_, 3}, {var_y_, 0}}},
Monomial{{{var_x_, 2}, {var_y_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 2}}},
Monomial{{{var_x_, 0}, {var_y_, 3}}},
Monomial{{{var_x_, 1}, {var_y_, 0}}},
Monomial{{{var_x_, 0}, {var_y_, 1}}};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
TEST_F(MonomialTest, OddDegreeMonomialBasisXYZ34) {
const drake::VectorX<Monomial> basis1{
OddDegreeMonomialBasis({var_x_, var_y_, var_z_}, 3)};
const drake::VectorX<Monomial> basis2{
OddDegreeMonomialBasis({var_x_, var_y_, var_z_}, 4)};
Eigen::Matrix<Monomial, 13, 1> expected;
// OddDegreeMonomialBasis({x, y, z}, 3) = {xΒ³, xΒ²y, xyΒ², yΒ³, xΒ²z, xyz, yΒ²z,
// xzΒ², yzΒ², zΒ³, x, y, z}
// clang-format off
expected << Monomial{{{var_x_, 3}, {var_y_, 0}, {var_z_, 0}}},
Monomial{{{var_x_, 2}, {var_y_, 1}, {var_z_, 0}}},
Monomial{{{var_x_, 1}, {var_y_, 2}, {var_z_, 0}}},
Monomial{{{var_x_, 0}, {var_y_, 3}, {var_z_, 0}}},
Monomial{{{var_x_, 2}, {var_y_, 0}, {var_z_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 1}, {var_z_, 1}}},
Monomial{{{var_x_, 0}, {var_y_, 2}, {var_z_, 1}}},
Monomial{{{var_x_, 1}, {var_y_, 0}, {var_z_, 2}}},
Monomial{{{var_x_, 0}, {var_y_, 1}, {var_z_, 2}}},
Monomial{{{var_x_, 0}, {var_y_, 0}, {var_z_, 3}}},
Monomial{{{var_x_, 1}, {var_y_, 0}, {var_z_, 0}}},
Monomial{{{var_x_, 0}, {var_y_, 1}, {var_z_, 0}}},
Monomial{{{var_x_, 0}, {var_y_, 0}, {var_z_, 1}}};
// clang-format on
EXPECT_EQ(basis1, expected);
EXPECT_EQ(basis2, expected);
}
// This test shows that we can have a std::unordered_map whose key is of
// Monomial.
TEST_F(MonomialTest, UnorderedMapOfMonomial) {
unordered_map<Monomial, double> monomial_to_coeff_map;
Monomial x_3{var_x_, 3};
Monomial y_5{var_y_, 5};
// Add 2 * x^3
monomial_to_coeff_map.emplace(x_3, 2);
// Add -7 * y^5
monomial_to_coeff_map.emplace(y_5, -7);
const auto it1 = monomial_to_coeff_map.find(x_3);
ASSERT_TRUE(it1 != monomial_to_coeff_map.end());
EXPECT_EQ(it1->second, 2);
const auto it2 = monomial_to_coeff_map.find(y_5);
ASSERT_TRUE(it2 != monomial_to_coeff_map.end());
EXPECT_EQ(it2->second, -7);
}
// Converts a constant to monomial.
TEST_F(MonomialTest, ToMonomial0) {
Monomial expected;
EXPECT_EQ(Monomial(1), expected);
EXPECT_EQ(Monomial(pow(x_, 0)), expected);
EXPECT_THROW(Monomial(2), std::exception);
}
// Converts expression x to monomial.
TEST_F(MonomialTest, ToMonomial1) {
Monomial expected(var_x_, 1);
EXPECT_EQ(Monomial(x_), expected);
}
// Converts expression x * y to monomial.
TEST_F(MonomialTest, ToMonomial2) {
std::map<Variable, int> powers;
powers.emplace(var_x_, 1);
powers.emplace(var_y_, 1);
Monomial expected(powers);
EXPECT_EQ(Monomial(x_ * y_), expected);
}
// Converts expression x^3 to monomial.
TEST_F(MonomialTest, ToMonomial3) {
Monomial expected(var_x_, 3);
EXPECT_EQ(Monomial(pow(x_, 3)), expected);
EXPECT_EQ(Monomial(pow(x_, 2) * x_), expected);
}
// Converts expression x^3 * y to monomial.
TEST_F(MonomialTest, ToMonomial4) {
std::map<Variable, int> powers;
powers.emplace(var_x_, 3);
powers.emplace(var_y_, 1);
Monomial expected(powers);
EXPECT_EQ(Monomial(pow(x_, 3) * y_), expected);
EXPECT_EQ(Monomial(pow(x_, 2) * y_ * x_), expected);
}
// Converts expression x*(y+z) - x*y to monomial
TEST_F(MonomialTest, ToMonomial5) {
std::map<Variable, int> powers({{var_x_, 1}, {var_z_, 1}});
Monomial expected(powers);
EXPECT_EQ(Monomial(x_ * z_), expected);
EXPECT_EQ(Monomial(x_ * (y_ + z_) - x_ * y_), expected);
}
// `pow(x * y, 2) * pow(x^2 * y^2, 3)` is a monomial (x^8 * y^8).
TEST_F(MonomialTest, ToMonomial6) {
const Monomial m1{pow(x_ * y_, 2) * pow(x_ * x_ * y_ * y_, 3)};
const Monomial m2{{{var_x_, 8}, {var_y_, 8}}};
EXPECT_EQ(m1, m2);
}
// x^0 is a monomial (1).
TEST_F(MonomialTest, ToMonomial7) {
const Monomial m1(var_x_, 0);
const Monomial m2{Expression{1.0}};
const Monomial m3{pow(x_, 0.0)};
EXPECT_EQ(m1, m2);
EXPECT_EQ(m1, m3);
EXPECT_EQ(m2, m3);
}
// `2 * x` is not a monomial because of its coefficient `2`.
TEST_F(MonomialTest, ToMonomialException1) {
EXPECT_THROW(Monomial{2 * x_}, runtime_error);
}
// `x + y` is not a monomial.
TEST_F(MonomialTest, ToMonomialException2) {
EXPECT_THROW(Monomial{x_ + y_}, runtime_error);
}
// `x / 2.0` is not a monomial.
TEST_F(MonomialTest, ToMonomialException3) {
EXPECT_THROW(Monomial{x_ / 2.0}, runtime_error);
}
// `x ^ -1` is not a monomial.
TEST_F(MonomialTest, ToMonomialException4) {
// Note: Parentheses are required around macro argument containing braced
// initializer list.
DRAKE_EXPECT_THROWS_MESSAGE((Monomial{{{var_x_, -1}}}),
"The exponent is negative.");
}
TEST_F(MonomialTest, Multiplication) {
// mβ = xyΒ²
const Monomial m1{{{var_x_, 1}, {var_y_, 2}}};
// mβ = yΒ²zβ΅
const Monomial m2{{{var_y_, 2}, {var_z_, 5}}};
// mβ = mβ * mβ = xyβ΄zβ΅
const Monomial m3{{{var_x_, 1}, {var_y_, 4}, {var_z_, 5}}};
EXPECT_EQ(m1 * m2, m3);
// mβ = mβ * y = xyΒ³
const Monomial m4{{{var_x_, 1}, {var_y_, 3}}};
// Check using Monomial * Variable (and vice versa).
EXPECT_EQ(m1 * var_y_, m4);
EXPECT_EQ(var_y_ * m1, m4);
// Check using Monomial * Expression (and vice versa).
EXPECT_PRED2(ExprEqual, m1 * y_, m4.ToExpression());
EXPECT_PRED2(ExprEqual, y_ * m1, m4.ToExpression());
Monomial m{m1}; // m = mβ
m *= m2; // m = mβ * mβ
EXPECT_EQ(m, m1 * m2);
}
TEST_F(MonomialTest, Pow) {
// mβ = xyΒ²
const Monomial m1{{{var_x_, 1}, {var_y_, 2}}};
// mβ = yΒ²zβ΅
const Monomial m2{{{var_y_, 2}, {var_z_, 5}}};
// pow(mβ, 0) = 1.0
EXPECT_EQ(pow(m1, 0), Monomial{});
// pow(mβ, 0) = 1.0
EXPECT_EQ(pow(m2, 0), Monomial{});
// pow(mβ, 1) = mβ
EXPECT_EQ(pow(m1, 1), m1);
// pow(mβ, 1) = mβ
EXPECT_EQ(pow(m2, 1), m2);
// pow(mβ, 3) = xΒ³yβΆ
const Monomial m1_cube = pow(m1, 3);
EXPECT_EQ(m1_cube, Monomial{pow(x_, 3) * pow(y_, 6)});
EXPECT_EQ(m1_cube.total_degree(), 9);
// pow(mβ, 4) = yβΈzΒ²β°
const Monomial m2_4th_power = pow(m2, 4);
EXPECT_EQ(m2_4th_power, Monomial{pow(y_, 8) * pow(z_, 20)});
EXPECT_EQ(m2_4th_power.total_degree(), 28);
// pow(mβ, -1) throws an exception.
EXPECT_THROW(pow(m1, -1), runtime_error);
// pow(mβ, -5) throws an exception.
EXPECT_THROW(pow(m2, -5), runtime_error);
}
TEST_F(MonomialTest, PowInPlace) {
// mβ = xyΒ²
Monomial m1{{{var_x_, 1}, {var_y_, 2}}};
const Monomial m1_copy{m1};
EXPECT_EQ(m1, m1_copy);
// mβ.pow_in_place modifies mβ.
m1.pow_in_place(2);
EXPECT_NE(m1, m1_copy);
EXPECT_EQ(m1, Monomial({{var_x_, 2}, {var_y_, 4}}));
EXPECT_EQ(m1.total_degree(), 6);
// mβ gets mββ°, which is 1.
m1.pow_in_place(0);
EXPECT_EQ(m1, Monomial());
EXPECT_EQ(m1.total_degree(), 0);
}
TEST_F(MonomialTest, Evaluate) {
const vector<Environment> environments{
{{var_x_, 1.0}, {var_y_, 2.0}, {var_z_, 3.0}}, // + + +
{{var_x_, -1.0}, {var_y_, 2.0}, {var_z_, 3.0}}, // - + +
{{var_x_, 1.0}, {var_y_, -2.0}, {var_z_, 3.0}}, // + - +
{{var_x_, 1.0}, {var_y_, 2.0}, {var_z_, -3.0}}, // + + -
{{var_x_, -1.0}, {var_y_, -2.0}, {var_z_, 3.0}}, // - - +
{{var_x_, 1.0}, {var_y_, -2.0}, {var_z_, -3.0}}, // + - -
{{var_x_, -1.0}, {var_y_, 2.0}, {var_z_, -3.0}}, // - + -
{{var_x_, -1.0}, {var_y_, -2.0}, {var_z_, -3.0}}, // - - -
};
for (const Monomial& m : monomials_) {
for (const Environment& env : environments) {
CheckEvaluate(m, env);
}
}
}
TEST_F(MonomialTest, EvaluateException) {
const Monomial m{{{var_x_, 1}, {var_y_, 2}}}; // xy^2
const Environment env{{{var_x_, 1.0}}};
EXPECT_THROW(m.Evaluate(env), runtime_error);
}
void CheckEvaluateBatch(
const Monomial& dut,
const Eigen::Ref<const VectorX<symbolic::Variable>>& vars,
const Eigen::Ref<const Eigen::MatrixXd>& vars_val) {
const Eigen::VectorXd monomial_vals = dut.Evaluate(vars, vars_val);
EXPECT_EQ(monomial_vals.rows(), vars_val.cols());
for (int i = 0; i < vars_val.cols(); ++i) {
symbolic::Environment env;
env.insert(vars, vars_val.col(i));
EXPECT_EQ(monomial_vals(i), dut.Evaluate(env));
}
}
TEST_F(MonomialTest, EvaluateBatch) {
// Test Evaluate for a batch of data.
const symbolic::Monomial monomial({{var_x_, 2}, {var_y_, 3}});
// vars1 contains exactly the same variables as in monomial.
Vector2<symbolic::Variable> vars1(var_y_, var_x_);
Eigen::Matrix<double, 2, 3> vars1_val;
// clang-format off
vars1_val << 2, 3, 4,
5, 6, 7;
// clang-format on
CheckEvaluateBatch(monomial, vars1, vars1_val);
CheckEvaluateBatch(monomial, vars1, Eigen::Vector2d(2, 3));
// vars2 contains more variables than monomial.
Vector3<symbolic::Variable> vars2(var_y_, var_x_, var_z_);
Eigen::Matrix<double, 3, 4> vars2_val;
// clang-format off
vars2_val << 2, 3, 4, 5,
-6, -7, 8, 9,
-1, -3, 2, 4;
// clang-format on
CheckEvaluateBatch(monomial, vars2, vars2_val);
}
TEST_F(MonomialTest, EvaluateBatchException) {
// Test Evaluate for a batch of data with exception.
const symbolic::Monomial monomial({{var_x_, 2}, {var_y_, 3}});
DRAKE_EXPECT_THROWS_MESSAGE(
monomial.Evaluate(Vector3<symbolic::Variable>(var_x_, var_x_, var_y_),
Eigen::Vector3d(1, 2, 3)),
".* vars contains repeated variables.");
DRAKE_EXPECT_THROWS_MESSAGE(
monomial.Evaluate(Vector2<symbolic::Variable>(var_x_, var_z_),
Eigen::Vector2d(2, 3)),
".* y is not present in vars");
}
TEST_F(MonomialTest, EvaluatePartial) {
const vector<Environment> environments{
{{var_x_, 2.0}},
{{var_y_, 3.0}},
{{var_z_, 4.0}},
{{var_x_, 2.0}, {var_y_, -2.0}},
{{var_y_, -4.0}, {var_z_, 2.5}},
{{var_x_, -2.3}, {var_z_, 2.6}},
{{var_x_, -1.0}, {var_y_, 2.0}, {var_z_, 3.0}},
};
for (const Monomial& m : monomials_) {
for (const Environment& env : environments) {
CheckEvaluatePartial(m, env);
}
}
}
TEST_F(MonomialTest, DegreeVariable) {
EXPECT_EQ(Monomial().degree(var_x_), 0);
EXPECT_EQ(Monomial().degree(var_y_), 0);
EXPECT_EQ(Monomial(var_x_).degree(var_x_), 1);
EXPECT_EQ(Monomial(var_x_).degree(var_y_), 0);
EXPECT_EQ(Monomial(var_x_, 4).degree(var_x_), 4);
EXPECT_EQ(Monomial(var_x_, 4).degree(var_y_), 0);
EXPECT_EQ(Monomial({{var_x_, 1}, {var_y_, 2}}).degree(var_x_), 1);
EXPECT_EQ(Monomial({{var_x_, 1}, {var_y_, 2}}).degree(var_y_), 2);
}
TEST_F(MonomialTest, TotalDegree) {
EXPECT_EQ(Monomial().total_degree(), 0);
EXPECT_EQ(Monomial(var_x_).total_degree(), 1);
EXPECT_EQ(Monomial(var_x_, 1).total_degree(), 1);
EXPECT_EQ(Monomial(var_x_, 4).total_degree(), 4);
EXPECT_EQ(Monomial({{var_x_, 1}, {var_y_, 2}}).total_degree(), 3);
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/latex_test.cc | #include "drake/common/symbolic/latex.h"
#include <vector>
#include <fmt/format.h>
#include <gtest/gtest.h>
#include "drake/common/symbolic/expression.h"
#include "drake/common/test_utilities/expect_throws_message.h"
namespace drake {
namespace symbolic {
namespace {
GTEST_TEST(SymbolicLatex, BasicTest) {
Variable x{"x"}, y{"y"};
Variable b("b", Variable::Type::BOOLEAN);
const double kInf = std::numeric_limits<double>::infinity();
// Expressions
EXPECT_EQ(ToLatex(x), "x");
EXPECT_EQ(ToLatex(0.0), "0");
EXPECT_EQ(ToLatex(1.0), "1");
EXPECT_EQ(ToLatex(1.0, 1), "1");
EXPECT_EQ(ToLatex(1.01), "1.010");
EXPECT_EQ(ToLatex(1.01, 1), "1.0");
EXPECT_EQ(ToLatex(4e9), "4000000000");
EXPECT_EQ(ToLatex(kInf - kInf), "\\text{NaN}");
EXPECT_EQ(ToLatex(kInf), "\\infty");
EXPECT_EQ(ToLatex(-kInf), "-\\infty");
EXPECT_EQ(ToLatex(M_PI), "\\pi");
EXPECT_EQ(ToLatex(-M_PI), "-\\pi");
EXPECT_EQ(ToLatex(14.0 * M_PI), "14\\pi");
EXPECT_EQ(ToLatex(0 * M_PI), "0");
EXPECT_EQ(ToLatex(M_PI + 1e-16, 3), "\\pi");
EXPECT_EQ(ToLatex(M_PI + 1e-13, 3), "3.142");
EXPECT_EQ(ToLatex(M_PI - 1e-16, 3), "\\pi");
EXPECT_EQ(ToLatex(M_PI - 1e-13, 3), "3.142");
EXPECT_EQ(ToLatex(-7.0 * M_E), "-7e");
EXPECT_EQ(ToLatex(x + y), "(x + y)");
EXPECT_EQ(ToLatex(x + 2.3), "(2.300 + x)");
EXPECT_EQ(ToLatex(x - y), "(x - y)");
EXPECT_EQ(ToLatex(x - 2 * y), "(x - 2y)");
EXPECT_EQ(ToLatex(2 * x + 3 * x + 4 * y), "(5x + 4y)");
EXPECT_EQ(ToLatex(2.1 * x + 3.2 * y * y, 1), "(2.1x + 3.2y^{2})");
EXPECT_EQ(ToLatex(x * pow(y, 2)), "x y^{2}");
EXPECT_EQ(ToLatex(2 * x * y), "2 x y");
EXPECT_EQ(ToLatex(pow(x, 3)), "x^{3}");
EXPECT_EQ(ToLatex(pow(x, 3.1)), "x^{3.100}");
EXPECT_EQ(ToLatex(x / y), R"""(\frac{x}{y})""");
EXPECT_EQ(ToLatex(abs(x)), "|x|");
EXPECT_EQ(ToLatex(log(x)), R"""(\log{x})""");
EXPECT_EQ(ToLatex(exp(x)), "e^{x}");
EXPECT_EQ(ToLatex(sqrt(x)), R"""(\sqrt{x})""");
EXPECT_EQ(ToLatex(sin(x)), R"""(\sin{x})""");
EXPECT_EQ(ToLatex(cos(x)), R"""(\cos{x})""");
EXPECT_EQ(ToLatex(tan(x)), R"""(\tan{x})""");
EXPECT_EQ(ToLatex(asin(x)), R"""(\asin{x})""");
EXPECT_EQ(ToLatex(acos(x)), R"""(\acos{x})""");
EXPECT_EQ(ToLatex(atan(x)), R"""(\atan{x})""");
EXPECT_EQ(ToLatex(atan2(y, x)), R"""(\atan{\frac{y}{x}})""");
EXPECT_EQ(ToLatex(sinh(x)), R"""(\sinh{x})""");
EXPECT_EQ(ToLatex(cosh(x)), R"""(\cosh{x})""");
EXPECT_EQ(ToLatex(tanh(x)), R"""(\tanh{x})""");
EXPECT_EQ(ToLatex(min(x, y)), R"""(\min\{x, y\})""");
EXPECT_EQ(ToLatex(max(x, y)), R"""(\max\{x, y\})""");
EXPECT_EQ(ToLatex(ceil(x)), R"""(\lceil x \rceil)""");
EXPECT_EQ(ToLatex(floor(x)), R"""(\lfloor x \rfloor)""");
EXPECT_EQ(ToLatex(if_then_else(x > y, 2 * x, 3)),
R"""(\begin{cases} 2 x & \text{if } x > y, \\)"""
R"""( 3 & \text{otherwise}.\end{cases})""");
DRAKE_EXPECT_THROWS_MESSAGE(
ToLatex(uninterpreted_function("myfunc", std::vector<Expression>())),
"ToLatex does not support uninterpreted functions.");
// Formulas
EXPECT_EQ(ToLatex(Formula::False()), R"""(\text{false})""");
EXPECT_EQ(ToLatex(Formula::True()), R"""(\text{true})""");
EXPECT_EQ(ToLatex(Formula(b)), "b");
EXPECT_EQ(ToLatex(x == y), R"""(x = y)""");
EXPECT_EQ(ToLatex(2.5 * x == y, 2), R"""(2.50 x = y)""");
EXPECT_EQ(ToLatex(2 * x != y), R"""(2 x \neq y)""");
EXPECT_EQ(ToLatex(2 * x > y), R"""(2 x > y)""");
EXPECT_EQ(ToLatex(2 * x >= y), R"""(2 x \ge y)""");
EXPECT_EQ(ToLatex(2 * x < y), R"""(2 x < y)""");
EXPECT_EQ(ToLatex(2 * x <= y), R"""(2 x \le y)""");
EXPECT_EQ(ToLatex(x == y && x * y > x), R"""(x = y \land x y > x)""");
EXPECT_EQ(ToLatex(!(x == y && x * y > x)), R"""(x \neq y \lor x y \le x)""");
EXPECT_EQ(ToLatex(x == y || x * y < x), R"""(x = y \lor x y < x)""");
EXPECT_EQ(ToLatex(!(x == y || x * y < x)), R"""(x \neq y \land x y \ge x)""");
EXPECT_EQ(ToLatex(!(x == y)), R"""(x \neq y)""");
EXPECT_EQ(ToLatex(forall({x, y}, x > y)), R"""(\forall x, y: (x > y))""");
EXPECT_EQ(ToLatex(isnan(x)), R"""(\text{isnan}(x))""");
EXPECT_EQ(ToLatex(!isnan(x)), R"""(\neg \text{isnan}(x))""");
// Matrix<double>
Eigen::Matrix<double, 2, 2> M;
M << 1.2, 3, 4.56, 7;
EXPECT_EQ(ToLatex(M, 1),
R"""(\begin{bmatrix} 1.2 & 3 \\ 4.6 & 7 \end{bmatrix})""");
// Matrix<Expression>
Eigen::Matrix<Expression, 2, 2> Me;
Me << x, 2.3 * y, 2.3 * y, x + y;
EXPECT_EQ(
ToLatex(Me, 1),
R"""(\begin{bmatrix} x & 2.3 y \\ 2.3 y & (x + y) \end{bmatrix})""");
// Formula with a PSD Matrix.
EXPECT_EQ(ToLatex(positive_semidefinite(Me), 1),
R"""(\begin{bmatrix} x & 2.3 y \\ 2.3 y & (x + y) \end{bmatrix})"""
R"""( \succeq 0)""");
}
GTEST_TEST(SymbolicLatex, MatrixSubscripts) {
const VectorX<Variable> x = MakeVectorVariable(2, "x");
const Vector2<Variable> y = MakeVectorVariable<2>("y");
const MatrixX<Variable> A = MakeMatrixVariable(2, 2, "A");
EXPECT_EQ(ToLatex(x[0]), "x_{0}");
EXPECT_EQ(ToLatex(x[1]), "x_{1}");
EXPECT_EQ(ToLatex(y[0]), "y_{0}");
EXPECT_EQ(ToLatex(y[1]), "y_{1}");
EXPECT_EQ(ToLatex(A(0, 0)), "A_{0, 0}");
EXPECT_EQ(ToLatex(A(0, 1)), "A_{0, 1}");
EXPECT_EQ(ToLatex(A(1, 0)), "A_{1, 0}");
EXPECT_EQ(ToLatex(A(1, 1)), "A_{1, 1}");
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/polynomial_test.cc | #include "drake/common/symbolic/polynomial.h"
#include <string>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "drake/common/symbolic/monomial_util.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
#include "drake/common/unused.h"
namespace drake {
namespace symbolic {
namespace {
using std::pair;
using std::runtime_error;
using std::to_string;
using std::vector;
using test::ExprEqual;
using test::PolyEqual;
class SymbolicPolynomialTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
const Variables indeterminates_{var_x_, var_y_, var_z_};
const Variable var_a_{"a"};
const Variable var_b_{"b"};
const Variable var_c_{"c"};
const Variables var_xy_{var_x_, var_y_};
const Variables var_xyz_{var_x_, var_y_, var_z_};
const Variables var_abc_{var_a_, var_b_, var_c_};
const drake::VectorX<symbolic::Monomial> monomials_{
MonomialBasis(var_xyz_, 3)};
const vector<double> doubles_{-9999.0, -5.0, -1.0, 0.0, 1.0, 5.0, 9999.0};
const Expression x_{var_x_};
const Expression y_{var_y_};
const Expression z_{var_z_};
const Expression a_{var_a_};
const Expression b_{var_b_};
const Expression c_{var_c_};
const Expression xy_{var_x_ + var_y_};
const Expression xyz_{var_x_ + var_y_ + var_z_};
const vector<Expression> exprs_{
0,
-1,
3,
x_,
5 * x_,
-3 * x_,
y_,
x_* y_,
2 * x_* x_,
2 * x_* x_,
6 * x_* y_,
3 * x_* x_* y_ + 4 * pow(y_, 3) * z_ + 2,
y_ * (3 * x_ * x_ + 4 * y_ * y_ * z_) + 2,
6 * pow(x_, 3) * pow(y_, 2),
2 * pow(x_, 3) * 3 * pow(y_, 2),
pow(x_, 3) - 4 * x_* y_* y_ + 2 * x_* x_* y_ - 8 * pow(y_, 3),
pow(x_ + 2 * y_, 2) * (x_ - 2 * y_),
(x_ + 2 * y_) * (x_ * x_ - 4 * y_ * y_),
(x_ * x_ + 4 * x_ * y_ + 4 * y_ * y_) * (x_ - 2 * y_),
pow(x_ + y_ + 1, 4),
pow(x_ + y_ + 1, 3),
1 + x_* x_ + 2 * (y_ - 0.5 * x_ * x_ - 0.5),
Expression(5.0) / 2.0, // constant / constant
x_ / 3.0, // var / constant
pow(x_, 2) / 2, // pow / constant
pow(x_* y_ / 3.0, 2) / 2, // pow / constant
(x_ + y_) / 2.0, // sum / constant
(x_* y_* z_ * 3) / 2.0, // product / constant
(x_* y_ / -5.0) / 2.0, // div / constant
};
};
// Tests that default constructor and EIGEN_INITIALIZE_MATRICES_BY_ZERO
// constructor both create the same value.
TEST_F(SymbolicPolynomialTest, DefaultConstructors) {
const Polynomial p;
EXPECT_TRUE(p.monomial_to_coefficient_map().empty());
const Polynomial p_zero(0);
EXPECT_TRUE(p_zero.monomial_to_coefficient_map().empty());
}
TEST_F(SymbolicPolynomialTest, ConstructFromMapType1) {
Polynomial::MapType map;
map.emplace(Monomial{var_x_}, -2.0 * a_); // x β¦ -2a
map.emplace(Monomial{{{var_y_, 3.0}}}, 4.0 * b_); // yΒ³ β¦ 4b
const Polynomial p{map}; // p = -2ax + 4byΒ³
EXPECT_EQ(p.monomial_to_coefficient_map(), map);
EXPECT_EQ(p.ToExpression(), -2 * a_ * x_ + 4 * b_ * pow(y_, 3));
EXPECT_EQ(p.decision_variables(), Variables({var_a_, var_b_}));
EXPECT_EQ(p.indeterminates(), Variables({var_x_, var_y_}));
}
TEST_F(SymbolicPolynomialTest, ConstructFromMapType2) {
Polynomial::MapType p_map;
for (int i = 0; i < monomials_.size(); ++i) {
p_map.emplace(monomials_[i], 1);
}
EXPECT_EQ(Polynomial{p_map}.monomial_to_coefficient_map(), p_map);
}
TEST_F(SymbolicPolynomialTest, ConstructFromMapType3) {
Polynomial::MapType map;
map.emplace(Monomial{var_x_}, -2.0 * a_); // x β¦ -2a
map.emplace(Monomial{{{var_a_, 2.0}}}, 4.0 * b_); // aΒ² β¦ 4b
// We cannot construct a polynomial from the `map` because variable a is used
// as a decision variable (x β¦ -2a) and an indeterminate (aΒ² β¦ 4b) at the same
// time.
if (kDrakeAssertIsArmed) {
EXPECT_THROW(Polynomial{map}, runtime_error);
}
}
TEST_F(SymbolicPolynomialTest, ConstructFromMapType4) {
// map has some coefficient being 0.
Polynomial::MapType map;
map.emplace(Monomial{var_x_}, 0);
symbolic::Polynomial p{map};
EXPECT_TRUE(p.monomial_to_coefficient_map().empty());
map.emplace(Monomial{var_y_}, 2 * a_);
p = symbolic::Polynomial{map};
EXPECT_EQ(p.monomial_to_coefficient_map().size(), 1u);
EXPECT_EQ(p.monomial_to_coefficient_map().at(Monomial{var_y_}), 2 * a_);
}
TEST_F(SymbolicPolynomialTest, ConstructFromMonomial) {
for (int i = 0; i < monomials_.size(); ++i) {
const Polynomial p{monomials_[i]};
for (const std::pair<const Monomial, Expression>& map :
p.monomial_to_coefficient_map()) {
EXPECT_EQ(map.first, monomials_[i]);
EXPECT_EQ(map.second, 1);
}
}
}
TEST_F(SymbolicPolynomialTest, ConstructFromExpression) {
// Expression -------------------> Polynomial
// | .Expand() | .ToExpression()
// \/ \/
// Expanded Expression == Expression
for (const Expression& e : exprs_) {
const Expression expanded_expr{e.Expand()};
const Expression expr_from_polynomial{Polynomial{e}.ToExpression()};
EXPECT_PRED2(ExprEqual, expanded_expr, expr_from_polynomial);
}
}
TEST_F(SymbolicPolynomialTest, ConstructorFromExpressionAndIndeterminates1) {
const Polynomial p1{1.0, var_xyz_}; // pβ = 1.0,
EXPECT_EQ(p1.monomial_to_coefficient_map(),
Polynomial::MapType({{Monomial{}, Expression(1.0)}}));
// pβ = ax + by + cz + 10
const Polynomial p2{a_ * x_ + b_ * y_ + c_ * z_ + 10, var_xyz_};
EXPECT_EQ(p2.monomial_to_coefficient_map(),
Polynomial::MapType({{Monomial{var_x_}, a_},
{Monomial{var_y_}, b_},
{Monomial{var_z_}, c_},
{Monomial{}, 10}}));
// pβ = 3abΒ²*xΒ²y -bc*zΒ³
const Polynomial p3{
3 * a_ * pow(b_, 2) * pow(x_, 2) * y_ - b_ * c_ * pow(z_, 3), var_xyz_};
EXPECT_EQ(p3.monomial_to_coefficient_map(),
Polynomial::MapType(
// xΒ²y β¦ 3abΒ²
{{Monomial{{{var_x_, 2}, {var_y_, 1}}}, 3 * a_ * pow(b_, 2)},
// zΒ³ β¦ -bc
{Monomial{{{var_z_, 3}}}, -b_ * c_}}));
// pβ = 3abΒ²*xΒ²y - bc*xΒ³
const Polynomial p4{
3 * a_ * pow(b_, 2) * pow(x_, 2) * y_ - b_ * c_ * pow(x_, 3), var_xyz_};
EXPECT_EQ(p4.monomial_to_coefficient_map(),
Polynomial::MapType(
{{Monomial{{{var_x_, 2}, {var_y_, 1}}}, 3 * a_ * pow(b_, 2)},
{Monomial{{{var_x_, 3}}}, -b_ * c_}}));
}
TEST_F(SymbolicPolynomialTest, ConstructorFromExpressionAndIndeterminates2) {
const Expression e{x_ * x_ + y_ * y_}; // e = xΒ² + yΒ².
// Show that providing a set of indeterminates {x, y, z} which is a super-set
// of what appeared in `e`, {x, y}, doesn't change the constructed polynomial
// .
const Polynomial p1{e, {var_x_, var_y_}};
const Polynomial p2{e, {var_x_, var_y_, var_z_}};
EXPECT_EQ(p1, p2);
}
TEST_F(SymbolicPolynomialTest, ConstructorFromExpressionAndIndeterminates3) {
// The expression has some coefficient being 0. Show that the constructed
// polynomial removed the 0-coefficient term.
const symbolic::Expression e1{0};
const symbolic::Polynomial p1{e1, {var_x_}};
EXPECT_TRUE(p1.monomial_to_coefficient_map().empty());
}
TEST_F(SymbolicPolynomialTest, ConstructFromVariable) {
// Variable -------------------> Polynomial
// | Expression() | .ToExpression()
// \/ \/
// Expanded Expression == Expression
for (const Variable& v : var_xyz_) {
const Expression expr{v};
const Expression expr_from_polynomial{Polynomial{v}.ToExpression()};
EXPECT_PRED2(ExprEqual, expr, expr_from_polynomial);
}
}
TEST_F(SymbolicPolynomialTest, IndeterminatesAndDecisionVariables) {
// p = 3abΒ²*xΒ²y -bc*zΒ³
const Polynomial p{
3 * a_ * pow(b_, 2) * pow(x_, 2) * y_ - b_ * c_ * pow(z_, 3), var_xyz_};
EXPECT_EQ(p.indeterminates(), var_xyz_);
EXPECT_EQ(p.decision_variables(), var_abc_);
}
TEST_F(SymbolicPolynomialTest, DegreeAndTotalDegree) {
// p = 3abΒ²*xΒ²y -bc*zΒ³
const Polynomial p{
3 * a_ * pow(b_, 2) * pow(x_, 2) * y_ - b_ * c_ * pow(z_, 3), var_xyz_};
EXPECT_EQ(p.Degree(var_x_), 2);
EXPECT_EQ(p.Degree(var_y_), 1);
EXPECT_EQ(p.Degree(var_z_), 3);
EXPECT_EQ(p.TotalDegree(), 3);
}
TEST_F(SymbolicPolynomialTest, AdditionPolynomialPolynomial) {
// (Polynomial(eβ) + Polynomial(eβ)).ToExpression() = (eβ + eβ).Expand()
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
EXPECT_PRED2(ExprEqual, (Polynomial{e1} + Polynomial{e2}).ToExpression(),
(e1 + e2).Expand());
}
}
// Test Polynomial& operator+=(Polynomial& c);
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
Polynomial p{e1};
p += Polynomial{e2};
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e1 + e2).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, AdditionPolynomialMonomial) {
// (Polynomial(e) + m).ToExpression() = (e + m.ToExpression()).Expand()
// (m + Polynomial(e)).ToExpression() = (m.ToExpression() + e).Expand()
for (const Expression& e : exprs_) {
const symbolic::Polynomial p{e};
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
const symbolic::Polynomial sum1 = p + m;
const symbolic::Polynomial sum2 = m + p;
EXPECT_PRED2(ExprEqual, sum1.ToExpression(),
(e + m.ToExpression()).Expand());
EXPECT_PRED2(ExprEqual, sum2.ToExpression(),
(m.ToExpression() + e).Expand());
EXPECT_EQ(sum1.indeterminates(), p.indeterminates() + m.GetVariables());
EXPECT_EQ(sum2.indeterminates(), p.indeterminates() + m.GetVariables());
EXPECT_EQ(sum1.decision_variables(), p.decision_variables());
EXPECT_EQ(sum2.decision_variables(), p.decision_variables());
}
}
// Test Polynomial& operator+=(const Monomial& m);
for (const Expression& e : exprs_) {
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
Polynomial p{e};
const symbolic::Variables e_indeterminates = p.indeterminates();
const symbolic::Variables e_decision_variables = p.decision_variables();
p += m;
EXPECT_PRED2(ExprEqual, p.ToExpression(),
(e + m.ToExpression()).Expand());
EXPECT_EQ(p.indeterminates(), e_indeterminates + m.GetVariables());
EXPECT_EQ(p.decision_variables(), e_decision_variables);
}
}
}
TEST_F(SymbolicPolynomialTest, AdditionPolynomialDouble) {
// (Polynomial(e) + c).ToExpression() = (e + c).Expand()
// (c + Polynomial(e)).ToExpression() = (c + e).Expand()
for (const Expression& e : exprs_) {
for (const double c : doubles_) {
EXPECT_PRED2(ExprEqual, (Polynomial(e) + c).ToExpression(),
(e + c).Expand());
EXPECT_PRED2(ExprEqual, (c + Polynomial(e)).ToExpression(),
(c + e).Expand());
}
}
// Test Polynomial& operator+=(double c).
for (const Expression& e : exprs_) {
for (const double c : doubles_) {
Polynomial p{e};
p += c;
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e + c).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, AdditionMonomialMonomial) {
// (m1 + m2).ToExpression() = m1.ToExpression() + m2.ToExpression()
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m_i{monomials_[i]};
for (int j = 0; j < monomials_.size(); ++j) {
const Monomial& m_j{monomials_[j]};
EXPECT_PRED2(ExprEqual, (m_i + m_j).ToExpression(),
m_i.ToExpression() + m_j.ToExpression());
}
}
}
TEST_F(SymbolicPolynomialTest, AdditionMonomialDouble) {
// (m + c).ToExpression() = m.ToExpression() + c
// (c + m).ToExpression() = c + m.ToExpression()
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
for (const double c : doubles_) {
EXPECT_PRED2(ExprEqual, (m + c).ToExpression(), m.ToExpression() + c);
EXPECT_PRED2(ExprEqual, (c + m).ToExpression(), c + m.ToExpression());
}
}
}
TEST_F(SymbolicPolynomialTest, AdditionPolynomialExpression) {
// (Polynomial(eβ) + eβ).Expand() = (eβ + eβ).Expand() = (Polynomial(eβ) +
// Polynomial(eβ).ToExpression()).Expand()
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
const Polynomial p1{e1};
const Polynomial p2{e2};
EXPECT_PRED2(ExprEqual, (p1 + e2).Expand(), (e1 + e2).Expand());
EXPECT_PRED2(ExprEqual, (e1 + p2).Expand(), (e1 + e2).Expand());
// Tests that the return of Polynomial + Expression is the correct
// Polynomial
EXPECT_PRED2(PolyEqual, Polynomial{p1 + e2}, p1 + p2);
}
}
}
TEST_F(SymbolicPolynomialTest, SubtractionPolynomialPolynomial) {
// (Polynomial(eβ) - Polynomial(eβ)).ToExpression() = (eβ - eβ).Expand()
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
EXPECT_PRED2(ExprEqual, (Polynomial{e1} - Polynomial{e2}).ToExpression(),
(e1 - e2).Expand());
}
}
// Test Polynomial& operator-=(Polynomial& c);
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
Polynomial p{e1};
p -= Polynomial{e2};
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e1 - e2).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, SubtractionPolynomialMonomial) {
// (Polynomial(e) - m).ToExpression() = (e - m.ToExpression()).Expand()
// (m - Polynomial(e)).ToExpression() = (m.ToExpression() - e).Expand()
for (const Expression& e : exprs_) {
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
EXPECT_PRED2(ExprEqual, (Polynomial(e) - m).ToExpression(),
(e - m.ToExpression()).Expand());
EXPECT_PRED2(ExprEqual, (m - Polynomial(e)).ToExpression(),
(m.ToExpression() - e).Expand());
}
}
// Test Polynomial& operator-=(const Monomial& m);
for (const Expression& e : exprs_) {
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
Polynomial p{e};
p -= m;
EXPECT_PRED2(ExprEqual, p.ToExpression(),
(e - m.ToExpression()).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, SubtractionPolynomialDouble) {
// (Polynomial(e) - c).ToExpression() = (e - c).Expand()
// (c - Polynomial(e)).ToExpression() = (c - e).Expand()
for (const Expression& e : exprs_) {
for (const double c : doubles_) {
EXPECT_PRED2(ExprEqual, (Polynomial(e) - c).ToExpression(),
(e - c).Expand());
EXPECT_PRED2(ExprEqual, (c - Polynomial(e)).ToExpression(),
(c - e).Expand());
}
}
// Test Polynomial& operator-=(double c).
for (const Expression& e : exprs_) {
for (const double c : doubles_) {
Polynomial p{e};
p -= c;
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e - c).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, SubtractionMonomialMonomial) {
// (m1 - m2).ToExpression() = m1.ToExpression() - m2.ToExpression()
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m_i{monomials_[i]};
for (int j = 0; j < monomials_.size(); ++j) {
const Monomial& m_j{monomials_[j]};
EXPECT_PRED2(ExprEqual, (m_i - m_j).ToExpression(),
m_i.ToExpression() - m_j.ToExpression());
}
}
}
TEST_F(SymbolicPolynomialTest, SubtractionMonomialDouble) {
// (m - c).ToExpression() = m.ToExpression() - c
// (c - m).ToExpression() = c - m.ToExpression()
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
for (const double c : doubles_) {
EXPECT_PRED2(ExprEqual, (m - c).ToExpression(), m.ToExpression() - c);
EXPECT_PRED2(ExprEqual, (c - m).ToExpression(), c - m.ToExpression());
}
}
}
TEST_F(SymbolicPolynomialTest, SubtractionPolynomialExpression) {
// (Polynomial(eβ) - eβ).Expand() = (eβ - eβ).Expand() = (Polynomial(eβ) -
// Polynomial(eβ).ToExpression()).Expand()
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
const Polynomial p1{e1};
const Polynomial p2{e2};
EXPECT_PRED2(ExprEqual, (p1 - e2).Expand(), (e1 - e2).Expand());
EXPECT_PRED2(ExprEqual, (e1 - p2).Expand(), (e1 - e2).Expand());
// Tests that the return of Polynomial - Expression is the correct
// Polynomial
EXPECT_PRED2(PolyEqual, Polynomial{p1 - e2}, p1 - p2);
}
}
}
TEST_F(SymbolicPolynomialTest, UnaryMinus) {
// (-Polynomial(e)).ToExpression() = -(e.Expand())
for (const Expression& e : exprs_) {
EXPECT_PRED2(ExprEqual, (-Polynomial(e)).ToExpression(), -(e.Expand()));
}
}
TEST_F(SymbolicPolynomialTest, MultiplicationPolynomialPolynomial1) {
// (Polynomial(eβ) * Polynomial(eβ)).ToExpression() = (eβ * eβ).Expand()
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
const symbolic::Polynomial p1{e1};
const symbolic::Polynomial p2{e2};
const symbolic::Polynomial product = p1 * p2;
EXPECT_PRED2(ExprEqual, product.ToExpression(),
(e1.Expand() * e2.Expand()).Expand());
// After multiplication, the product's indeterminates should be the union
// of p1's indeterminates and p2's indeterminates. Same for the decision
// variables.
EXPECT_EQ(product.indeterminates(),
p1.indeterminates() + p2.indeterminates());
EXPECT_EQ(product.decision_variables(),
p1.decision_variables() + p2.decision_variables());
}
}
// Test Polynomial& operator*=(Polynomial& c);
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
Polynomial p{e1};
const symbolic::Variables e1_indeterminates = p.indeterminates();
const symbolic::Variables e1_decision_variables = p.decision_variables();
const symbolic::Polynomial p2{e2};
p *= p2;
EXPECT_PRED2(ExprEqual, p.ToExpression(),
(e1.Expand() * e2.Expand()).Expand());
EXPECT_EQ(p.indeterminates(), e1_indeterminates + p2.indeterminates());
EXPECT_EQ(p.decision_variables(),
e1_decision_variables + p2.decision_variables());
}
}
}
TEST_F(SymbolicPolynomialTest, MultiplicationPolynomialMonomial) {
// (Polynomial(e) * m).ToExpression() = (e * m.ToExpression()).Expand()
// (m * Polynomial(e)).ToExpression() = (m.ToExpression() * e).Expand()
for (const Expression& e : exprs_) {
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
const symbolic::Polynomial p{e};
const symbolic::Polynomial product1 = p * m;
const symbolic::Polynomial product2 = m * p;
EXPECT_PRED2(ExprEqual, product1.ToExpression(),
(e * m.ToExpression()).Expand());
EXPECT_PRED2(ExprEqual, product2.ToExpression(),
(m.ToExpression() * e).Expand());
EXPECT_EQ(product1.indeterminates(),
p.indeterminates() + m.GetVariables());
EXPECT_EQ(product2.indeterminates(),
p.indeterminates() + m.GetVariables());
EXPECT_EQ(product1.decision_variables(), p.decision_variables());
EXPECT_EQ(product2.decision_variables(), p.decision_variables());
}
}
// Test Polynomial& operator*=(const Monomial& m);
for (const Expression& e : exprs_) {
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
Polynomial p{e};
p *= m;
EXPECT_PRED2(ExprEqual, p.ToExpression(),
(e * m.ToExpression()).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, MultiplicationPolynomialDouble) {
// (Polynomial(e) * c).ToExpression() = (e * c).Expand()
// (c * Polynomial(e)).ToExpression() = (c * e).Expand()
for (const Expression& e : exprs_) {
for (const double c : doubles_) {
EXPECT_PRED2(ExprEqual, (Polynomial(e) * c).ToExpression(),
(e * c).Expand());
EXPECT_PRED2(ExprEqual, (c * Polynomial(e)).ToExpression(),
(c * e).Expand());
}
}
// Test Polynomial& operator*=(double c).
for (const Expression& e : exprs_) {
for (const double c : doubles_) {
Polynomial p{e};
p *= c;
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e * c).Expand());
}
Polynomial p{e};
p *= 0;
EXPECT_TRUE(p.monomial_to_coefficient_map().empty());
}
}
TEST_F(SymbolicPolynomialTest, MultiplicationMonomialDouble) {
// (m * c).ToExpression() = (m.ToExpression() * c).Expand()
// (c * m).ToExpression() = (c * m.ToExpression()).Expand()
for (int i = 0; i < monomials_.size(); ++i) {
const Monomial& m{monomials_[i]};
for (const double c : doubles_) {
EXPECT_PRED2(ExprEqual, (m * c).ToExpression(),
(m.ToExpression() * c).Expand());
EXPECT_PRED2(ExprEqual, (c * m).ToExpression(),
(c * m.ToExpression()).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, MultiplicationPolynomialPolynomial2) {
// Evaluates (1 + x) * (1 - x) to confirm that the cross term 0 * x is
// erased from the product.
const Polynomial p1(1 + x_);
const Polynomial p2(1 - x_);
Polynomial::MapType product_map_expected{};
product_map_expected.emplace(Monomial(), 1);
product_map_expected.emplace(Monomial(var_x_, 2), -1);
EXPECT_EQ(product_map_expected, (p1 * p2).monomial_to_coefficient_map());
}
TEST_F(SymbolicPolynomialTest, MultiplicationPolynomialExpression) {
// (Polynomial(eβ) * eβ).Expand() = (eβ * eβ).Expand() = (Polynomial(eβ) *
// Polynomial(eβ).ToExpression()).Expand()
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
const Polynomial computed_left_product{Polynomial(e1) * e2};
const Polynomial computed_right_product{e1 * Polynomial(e2)};
const Polynomial expected{e1 * e2};
const double tol = 1e-12;
// Use PolynomialEqual rather than ExprEqual to be able to use floating
// point rather than exact equality.
EXPECT_TRUE(test::PolynomialEqual(computed_left_product, expected, tol));
EXPECT_TRUE(test::PolynomialEqual(computed_right_product, expected, tol));
}
}
}
TEST_F(SymbolicPolynomialTest, BinaryOperationBetweenPolynomialAndVariable) {
// p = 2aΒ²xΒ² + 3ax + 7.
const Polynomial p{2 * pow(a_, 2) * pow(x_, 2) + 3 * a_ * x_ + 7, {var_x_}};
const Monomial m_x_cube{var_x_, 3};
const Monomial m_x_sq{var_x_, 2};
const Monomial m_x{var_x_, 1};
const Monomial m_one;
// Checks addition.
{
const Polynomial result1{p + var_a_};
const Polynomial result2{var_a_ + p};
// result1 = 2aΒ²xΒ² + 3ax + (7 + a).
EXPECT_TRUE(result1.EqualTo(result2));
EXPECT_EQ(result1.monomial_to_coefficient_map().size(), 3);
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_PRED2(ExprEqual, result1.monomial_to_coefficient_map().at(m_one),
7 + a_);
const Polynomial result3{p + var_x_};
const Polynomial result4{var_x_ + p};
// result3 = 2aΒ²xΒ² + (3a + 1)x + 7.
EXPECT_TRUE(result3.EqualTo(result4));
EXPECT_EQ(result3.monomial_to_coefficient_map().size(), 3);
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_PRED2(ExprEqual, result3.monomial_to_coefficient_map().at(m_x),
3 * a_ + 1);
}
// Checks subtraction.
{
const Polynomial result1{p - var_a_};
// result1 = 2aΒ²xΒ² + 3ax + (7 - a).
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_EQ(result1.monomial_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual, result1.monomial_to_coefficient_map().at(m_one),
7 - a_);
const Polynomial result2{var_a_ - p};
EXPECT_TRUE((-result2).EqualTo(result1));
const Polynomial result3{p - var_x_};
// result3 = 2aΒ²xΒ² + (3a - 1)x + 7.
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_EQ(result3.monomial_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual, result3.monomial_to_coefficient_map().at(m_x),
3 * a_ - 1);
const Polynomial result4{var_x_ - p};
EXPECT_TRUE((-result4).EqualTo(result3));
}
// Checks multiplication.
{
const Polynomial result1{p * var_a_};
// result1 = 2aΒ³xΒ² + 3aΒ²x + 7a.
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_EQ(result1.monomial_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual, result1.monomial_to_coefficient_map().at(m_x_sq),
2 * pow(a_, 3));
EXPECT_PRED2(ExprEqual, result1.monomial_to_coefficient_map().at(m_x),
3 * pow(a_, 2));
EXPECT_PRED2(ExprEqual, result1.monomial_to_coefficient_map().at(m_one),
7 * a_);
const Polynomial result2{var_a_ * p};
EXPECT_TRUE(result2.EqualTo(result1));
const Polynomial result3{p * var_x_};
// result3 = 2aΒ²xΒ³ + 3axΒ² + 7x.
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_EQ(result3.monomial_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual, result3.monomial_to_coefficient_map().at(m_x_cube),
2 * pow(a_, 2));
EXPECT_PRED2(ExprEqual, result3.monomial_to_coefficient_map().at(m_x_sq),
3 * a_);
EXPECT_PRED2(ExprEqual, result3.monomial_to_coefficient_map().at(m_x), 7);
const Polynomial result4{var_x_ * p};
EXPECT_TRUE(result4.EqualTo(result3));
// var_b_ doesn't show up in p, p * b will have b in the
// decision_variables(). result5 = 2aΒ²bxΒ²+3abx+7b
EXPECT_FALSE(p.decision_variables().include(var_b_));
EXPECT_FALSE(p.indeterminates().include(var_b_));
const symbolic::Polynomial result5 = var_b_ * p;
EXPECT_EQ(result5.indeterminates(), symbolic::Variables({var_x_}));
EXPECT_EQ(result5.decision_variables(),
symbolic::Variables({var_a_, var_b_}));
EXPECT_EQ(result5.monomial_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual, result5.monomial_to_coefficient_map().at(m_x_sq),
2 * pow(a_, 2) * b_);
EXPECT_PRED2(ExprEqual, result5.monomial_to_coefficient_map().at(m_x),
3 * a_ * b_);
EXPECT_PRED2(ExprEqual, result5.monomial_to_coefficient_map().at(m_one),
7 * b_);
}
}
TEST_F(SymbolicPolynomialTest, Pow) {
for (int n = 2; n <= 5; ++n) {
for (const Expression& e : exprs_) {
Polynomial p{pow(Polynomial{e}, n)}; // p = pow(e, n)
EXPECT_PRED2(ExprEqual, p.ToExpression(), pow(e, n).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, DivideByConstant) {
for (double v = -5.5; v <= 5.5; v += 1.0) {
for (const Expression& e : exprs_) {
EXPECT_PRED2(ExprEqual, (Polynomial(e) / v).ToExpression(),
Polynomial(e / v).ToExpression());
}
}
}
TEST_F(SymbolicPolynomialTest, ConstantDividedByPolynomial) {
for (double v = -5.5; v <= 5.5; v += 1.0) {
for (const Expression& e : exprs_) {
if (e.EqualTo(0)) {
continue;
}
EXPECT_PRED2(ExprEqual, (v / Polynomial(e)).Expand(), (v / e).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, DivPolynomialExpression) {
// (Polynomial(eβ) / eβ).Expand() = (eβ / eβ).Expand().
for (const Expression& e1 : exprs_) {
for (const Expression& e2 : exprs_) {
if (e2.EqualTo(0)) {
continue;
}
EXPECT_PRED2(ExprEqual, (Polynomial(e1) / e2).Expand(),
(e1 / e2).Expand());
EXPECT_PRED2(ExprEqual, (e1 / Polynomial(e2)).Expand(),
(e1 / e2).Expand());
}
}
}
TEST_F(SymbolicPolynomialTest, DifferentiateJacobian) {
// p = 2aΒ²bxΒ² + 3bcΒ²x + 7ac.
const Polynomial p{
2 * pow(a_, 2) * b_ * pow(x_, 2) + 3 * b_ * pow(c_, 2) * x_ + 7 * a_ * c_,
{var_a_, var_b_, var_c_}};
// d/dx p = 4aΒ²bx + 3bcΒ²
const Polynomial p_x{4 * pow(a_, 2) * b_ * x_ + 3 * b_ * pow(c_, 2),
{var_a_, var_b_, var_c_}};
EXPECT_PRED2(PolyEqual, p.Differentiate(var_x_), p_x);
// d/dy p = 0
const Polynomial p_y{0, {var_a_, var_b_, var_c_}};
EXPECT_PRED2(PolyEqual, p.Differentiate(var_y_), p_y);
// d/da p = 4abxΒ² + 7c
const Polynomial p_a{4 * a_ * b_ * pow(x_, 2) + 7 * c_,
{var_a_, var_b_, var_c_}};
EXPECT_PRED2(PolyEqual, p.Differentiate(var_a_), p_a);
// d/db p = 2aΒ²xΒ² + 3cΒ²x
const Polynomial p_b{2 * pow(a_, 2) * pow(x_, 2) + 3 * pow(c_, 2) * x_,
{var_a_, var_b_, var_c_}};
EXPECT_PRED2(PolyEqual, p.Differentiate(var_b_), p_b);
// d/dc p = 6bcx + 7a
const Polynomial p_c{6 * b_ * c_ * x_ + 7 * a_, {var_a_, var_b_, var_c_}};
EXPECT_PRED2(PolyEqual, p.Differentiate(var_c_), p_c);
// Checks p.Jacobian(x, y) using static-sized matrices.
Eigen::Matrix<Variable, 2, 1> vars_xy;
vars_xy << var_x_, var_y_;
const auto J_xy = p.Jacobian(vars_xy);
static_assert(decltype(J_xy)::RowsAtCompileTime == 1 &&
decltype(J_xy)::ColsAtCompileTime == 2,
"The size of J_xy should be 1 x 2.");
EXPECT_PRED2(PolyEqual, J_xy(0, 0), p_x);
EXPECT_PRED2(PolyEqual, J_xy(0, 1), p_y);
// Checks p.Jacobian(a, b, c) using dynamic-sized matrices.
VectorX<Variable> vars_abc(3);
vars_abc << var_a_, var_b_, var_c_;
const MatrixX<Polynomial> J_abc{p.Jacobian(vars_abc)};
EXPECT_PRED2(PolyEqual, J_abc(0, 0), p_a);
EXPECT_PRED2(PolyEqual, J_abc(0, 1), p_b);
EXPECT_PRED2(PolyEqual, J_abc(0, 2), p_c);
}
TEST_F(SymbolicPolynomialTest, Integrate) {
// p = 2aΒ²xΒ²y + 3axyΒ³.
const Polynomial p{
2 * pow(a_, 2) * pow(x_, 2) * y_ + 3 * a_ * x_ * pow(y_, 3),
{var_x_, var_y_}};
// β« p dx = 2/3 aΒ²xΒ³y + 3/2 axΒ²yΒ³.
const Polynomial int_p_dx{2 * pow(a_, 2) * pow(x_, 3) * y_ / 3 +
3 * a_ * pow(x_, 2) * pow(y_, 3) / 2,
{var_x_, var_y_}};
EXPECT_PRED2(PolyEqual, p.Integrate(var_x_), int_p_dx);
// β« p dx from 1 to 3 = 52/3 aΒ²y + 12 ayΒ³.
const Polynomial def_int_p_dx{52 * pow(a_, 2) * y_ / 3 + 12 * a_ * pow(y_, 3),
{var_y_}};
EXPECT_PRED2(PolyEqual, p.Integrate(var_x_, 1, 3), def_int_p_dx);
// β« from [a,b] = -β« from [b,a]
EXPECT_PRED2(PolyEqual, p.Integrate(var_x_, 3, 1), -def_int_p_dx);
// β« p dy = aΒ²xΒ²yΒ² + 3/4 axyβ΄.
const Polynomial int_p_dy{
pow(a_, 2) * pow(x_, 2) * pow(y_, 2) + 3 * a_ * x_ * pow(y_, 4) / 4,
{var_x_, var_y_}};
EXPECT_PRED2(PolyEqual, p.Integrate(var_y_), int_p_dy);
// β« p dz = 2aΒ²xΒ²yz + 3axyΒ³z.
const Polynomial int_p_dz{
2 * pow(a_, 2) * pow(x_, 2) * y_ * z_ + 3 * a_ * x_ * pow(y_, 3) * z_,
{var_x_, var_y_, var_z_}};
EXPECT_TRUE(p.Integrate(var_z_).indeterminates().include(var_z_));
EXPECT_PRED2(PolyEqual, p.Integrate(var_z_), int_p_dz);
// β« p dz from -1 to 1 = 4aΒ²xΒ²y + 6axyΒ³.
const Polynomial def_int_p_dz{
4 * pow(a_, 2) * pow(x_, 2) * y_ + 6 * a_ * x_ * pow(y_, 3),
{var_x_, var_y_, var_z_}};
EXPECT_TRUE(p.Integrate(var_z_).indeterminates().include(var_z_));
EXPECT_PRED2(PolyEqual, p.Integrate(var_z_, -1, 1), def_int_p_dz);
EXPECT_THROW(unused(p.Integrate(var_a_)), std::exception);
EXPECT_THROW(unused(p.Integrate(var_a_, -1, 1)), std::exception);
}
TEST_F(SymbolicPolynomialTest, ConstructNonPolynomialCoefficients) {
// Given a pair of Expression and Polynomial::MapType, `(e, map)`, we check
// `Polynomial(e, indeterminates)` has the expected map, `map`.
vector<pair<Expression, Polynomial::MapType>> testcases;
// sin(a)x = sin(a) * x
testcases.emplace_back(sin(a_) * x_,
Polynomial::MapType{{{Monomial{x_}, sin(a_)}}});
// cos(a)(x + 1)Β² = cos(a) * xΒ² + 2cos(a) * x + cos(a) * 1
testcases.emplace_back(
cos(a_) * pow(x_ + 1, 2),
Polynomial::MapType{{{Monomial{{{var_x_, 2}}}, cos(a_)},
{Monomial{x_}, 2 * cos(a_)},
{Monomial{}, cos(a_)}}});
// log(a)(x + 1)Β² / sqrt(b)
// = log(a)/sqrt(b) * xΒ² + 2log(a)/sqrt(b) * x + log(a)/sqrt(b) * 1
testcases.emplace_back(
log(a_) * pow(x_ + 1, 2) / sqrt(b_),
Polynomial::MapType{{{Monomial{{{var_x_, 2}}}, log(a_) / sqrt(b_)},
{Monomial{x_}, 2 * log(a_) / sqrt(b_)},
{Monomial{}, log(a_) / sqrt(b_)}}});
// (tan(a)x + 1)Β²
// = (tan(a))Β² * xΒ² + 2tan(a) * x + 1
testcases.emplace_back(
pow(tan(a_) * x_ + 1, 2),
Polynomial::MapType{{{Monomial{{{var_x_, 2}}}, pow(tan(a_), 2)},
{Monomial{x_}, 2 * tan(a_)},
{Monomial{}, 1}}});
// abs(b + 1)x + asin(a) + acos(a) - atan(c) * x
// = (abs(b + 1) - atan(c)) * x + (asin(a) + acos(a))
testcases.emplace_back(
abs(b_ + 1) * x_ + asin(a_) + acos(a_) - atan(c_) * x_,
Polynomial::MapType{{{Monomial{x_}, abs(b_ + 1) - atan(c_)},
{Monomial{}, asin(a_) + acos(a_)}}});
// atan(b)x * atan2(a, c)y
// = (atan(b) * atan2(a, c)) * xy
testcases.emplace_back(
abs(b_) * x_ * atan2(a_, c_) * y_,
Polynomial::MapType{{{Monomial{{{var_x_, 1}, {var_y_, 1}}}, // xy
abs(b_) * atan2(a_, c_)}}});
// (sinh(a)x + cosh(b)y + tanh(c)z) / (5 * min(a, b) * max(b, c))
// = (sinh(a) / (5 * min(a, b) * max(b, c))) * x
// + (cosh(b) / (5 * min(a, b) * max(b, c))) * y
// + (tanh(c) / (5 * min(a, b) * max(b, c))) * z
testcases.emplace_back(
(sinh(a_) * x_ + cosh(b_) * y_ + tanh(c_) * z_) /
(5 * min(a_, b_) * max(b_, c_)),
Polynomial::MapType{{{
Monomial{x_},
sinh(a_) / (5 * min(a_, b_) * max(b_, c_)),
},
{
Monomial{y_},
cosh(b_) / (5 * min(a_, b_) * max(b_, c_)),
},
{
Monomial{z_},
tanh(c_) / (5 * min(a_, b_) * max(b_, c_)),
}}});
// (ceil(a) * x + floor(b) * y)Β²
// = pow(ceil(a), 2) * xΒ²
// = + 2 * ceil(a) * floor(b) * xy
// = + pow(floor(a), 2) * yΒ²
testcases.emplace_back(
pow(ceil(a_) * x_ + floor(b_) * y_, 2),
Polynomial::MapType{
{{Monomial{{{var_x_, 2}}}, ceil(a_) * ceil(a_)},
{Monomial{{{var_x_, 1}, {var_y_, 1}}}, 2 * ceil(a_) * floor(b_)},
{Monomial{{{var_y_, 2}}}, floor(b_) * floor(b_)}}});
// (ceil(a) * x + floor(b) * y)Β²
// = pow(ceil(a), 2) * xΒ²
// = + 2 * ceil(a) * floor(b) * xy
// = + pow(floor(a), 2) * yΒ²
testcases.emplace_back(
pow(ceil(a_) * x_ + floor(b_) * y_, 2),
Polynomial::MapType{
{{Monomial{{{var_x_, 2}}}, ceil(a_) * ceil(a_)},
{Monomial{{{var_x_, 1}, {var_y_, 1}}}, 2 * ceil(a_) * floor(b_)},
{Monomial{{{var_y_, 2}}}, floor(b_) * floor(b_)}}});
// UF("unnamed1", {a})) * x * UF("unnamed2", {b}) * x
// = UF("unnamed1", {a})) * UF("unnamed2", {b}) * xΒ².
const Expression uf1{uninterpreted_function("unnamed1", {var_a_})};
const Expression uf2{uninterpreted_function("unnamed2", {var_b_})};
testcases.emplace_back(
uf1 * x_ * uf2 * x_,
Polynomial::MapType{{{Monomial{{{var_x_, 2}}}, uf1 * uf2}}});
// (x + y)Β² = xΒ² + 2xy + yΒ²
testcases.emplace_back(pow(x_ + y_, 2),
Polynomial::MapType{{
{Monomial{{{var_x_, 2}}}, 1},
{Monomial{{{var_x_, 1}, {var_y_, 1}}}, 2},
{Monomial{{{var_y_, 2}}}, 1},
}});
// pow(pow(x, 2.5), 2) = xβ΅
testcases.emplace_back(pow(pow(x_, 2.5), 2),
Polynomial::MapType{{{Monomial{{{var_x_, 5}}}, 1}}});
// pow(pow(x * y, 2.5), 2) = (xy)β΅
testcases.emplace_back(
pow(pow(x_ * y_, 2.5), 2),
Polynomial::MapType{{{Monomial{{{var_x_, 5}, {var_y_, 5}}}, 1}}});
for (const pair<Expression, Polynomial::MapType>& item : testcases) {
const Expression& e{item.first};
const Polynomial p{e, indeterminates_};
const Polynomial::MapType& expected_map{item.second};
EXPECT_EQ(p.monomial_to_coefficient_map(), expected_map);
}
}
TEST_F(SymbolicPolynomialTest, NegativeTestConstruction1) {
// sin(a) * x is a polynomial.
const Expression e1{sin(a_) * x_};
DRAKE_EXPECT_NO_THROW(Polynomial(e1, indeterminates_));
// sin(x) * x is a not polynomial.
const Expression e2{sin(x_) * x_};
EXPECT_THROW(Polynomial(e2, indeterminates_), runtime_error);
}
TEST_F(SymbolicPolynomialTest, NegativeTestConstruction2) {
// aΛ£ x is not a polynomial.
const Expression e{pow(a_, x_)};
EXPECT_THROW(Polynomial(e, indeterminates_), runtime_error);
}
TEST_F(SymbolicPolynomialTest, NegativeTestConstruction3) {
// xβ»ΒΉ is not a polynomial.
const Expression e{pow(x_, -1)};
EXPECT_THROW(Polynomial(e, indeterminates_), runtime_error);
}
TEST_F(SymbolicPolynomialTest, NegativeTestConstruction4) {
// x^(2.5) is not a polynomial.
const Expression e{pow(x_, 2.5)};
EXPECT_THROW(Polynomial(e, indeterminates_), runtime_error);
}
TEST_F(SymbolicPolynomialTest, NegativeTestConstruction5) {
// xΛ£ is not a polynomial.
const Expression e{pow(x_, x_)};
EXPECT_THROW(Polynomial(e, indeterminates_), runtime_error);
}
TEST_F(SymbolicPolynomialTest, NegativeTestConstruction6) {
// 1 / a is polynomial.
const Expression e1{1 / a_};
DRAKE_EXPECT_NO_THROW(Polynomial(e1, indeterminates_));
// However, 1 / x is not a polynomial.
const Expression e2{1 / x_};
EXPECT_THROW(Polynomial(e2, indeterminates_), runtime_error);
}
TEST_F(SymbolicPolynomialTest, NegativeTestConstruction7) {
// sin(x + a) is not a polynomial.
const Expression e{sin(x_ + a_)};
EXPECT_THROW(Polynomial(e, indeterminates_), runtime_error);
}
TEST_F(SymbolicPolynomialTest, Evaluate) {
// p = axΒ²y + bxy + cz
const Polynomial p{a_ * x_ * x_ * y_ + b_ * x_ * y_ + c_ * z_, var_xyz_};
const Environment env1{{
{var_a_, 1.0},
{var_b_, 2.0},
{var_c_, 3.0},
{var_x_, -1.0},
{var_y_, -2.0},
{var_z_, -3.0},
}};
const double expected1{1.0 * -1.0 * -1.0 * -2.0 + 2.0 * -1.0 * -2.0 +
3.0 * -3.0};
EXPECT_EQ(p.Evaluate(env1), expected1);
const Environment env2{{
{var_a_, 4.0},
{var_b_, 1.0},
{var_c_, 2.0},
{var_x_, -7.0},
{var_y_, -5.0},
{var_z_, -2.0},
}};
const double expected2{4.0 * -7.0 * -7.0 * -5.0 + 1.0 * -7.0 * -5.0 +
2.0 * -2.0};
EXPECT_EQ(p.Evaluate(env2), expected2);
const Environment partial_env{{
{var_a_, 4.0},
{var_c_, 2.0},
{var_x_, -7.0},
{var_z_, -2.0},
}};
EXPECT_THROW(unused(p.Evaluate(partial_env)), runtime_error);
}
TEST_F(SymbolicPolynomialTest, PartialEvaluate1) {
// p1 = a*xΒ² + b*x + c
// p2 = p1[x β¦ 3.0] = 3Β²a + 3b + c.
const Polynomial p1{a_ * x_ * x_ + b_ * x_ + c_, var_xyz_};
const Polynomial p2{a_ * 3.0 * 3.0 + b_ * 3.0 + c_, var_xyz_};
const Environment env{{{var_x_, 3.0}}};
EXPECT_PRED2(PolyEqual, p1.EvaluatePartial(env), p2);
EXPECT_PRED2(PolyEqual, p1.EvaluatePartial(var_x_, 3.0), p2);
}
TEST_F(SymbolicPolynomialTest, PartialEvaluate2) {
// p1 = a*xyΒ² - a*xy + c
// p2 = p1[y β¦ 2.0] = (4a - 2a)*x + c = 2ax + c
const Polynomial p1{a_ * x_ * y_ * y_ - a_ * x_ * y_ + c_, var_xyz_};
const Polynomial p2{2 * a_ * x_ + c_, var_xyz_};
const Environment env{{{var_y_, 2.0}}};
EXPECT_PRED2(PolyEqual, p1.EvaluatePartial(env), p2);
EXPECT_PRED2(PolyEqual, p1.EvaluatePartial(var_y_, 2.0), p2);
}
TEST_F(SymbolicPolynomialTest, PartialEvaluate3) {
// p1 = a*xΒ² + b*x + c
// p2 = p1[a β¦ 2.0, x β¦ 3.0] = 2*3Β² + 3b + c
// = 18 + 3b + c
const Polynomial p1{a_ * x_ * x_ + b_ * x_ + c_, var_xyz_};
const Polynomial p2{18 + 3 * b_ + c_, var_xyz_};
const Environment env{{{var_a_, 2.0}, {var_x_, 3.0}}};
EXPECT_PRED2(PolyEqual, p1.EvaluatePartial(env), p2);
}
TEST_F(SymbolicPolynomialTest, PartialEvaluate4) {
// p = (a + c / b + c)*xΒ² + b*x + c
//
// Partially evaluating p with [a β¦ 0, b β¦ 0, c β¦ 0] throws `runtime_error`
// because of the divide-by-zero
const Polynomial p{((a_ + c_) / (b_ + c_)) * x_ * x_ + b_ * x_ + c_,
var_xyz_};
const Environment env{{{var_a_, 0.0}, {var_b_, 0.0}, {var_c_, 0.0}}};
EXPECT_THROW(unused(p.EvaluatePartial(env)), runtime_error);
}
TEST_F(SymbolicPolynomialTest, EvaluateIndeterminates) {
// Test EvaluateIndeterminates where polynomial.decision_variables() is empty.
const Polynomial p(var_x_ * var_x_ + 5 * var_x_ * var_y_);
// We intentionally test the case that `indeterminates` being a strict
// superset of p.indeterminates().
Vector3<symbolic::Variable> indeterminates(var_x_, var_z_, var_y_);
Eigen::Matrix<double, 3, 4> indeterminates_values;
// clang-format off
indeterminates_values << 1, 2, 3, 4,
-1, -2, -3, -4,
2, 3, 4, 5;
// clang-format on
Eigen::VectorXd polynomial_values =
p.EvaluateIndeterminates(indeterminates, indeterminates_values);
ASSERT_EQ(polynomial_values.rows(), indeterminates_values.cols());
for (int i = 0; i < indeterminates_values.cols(); ++i) {
symbolic::Environment env;
env.insert(indeterminates, indeterminates_values.col(i));
EXPECT_EQ(polynomial_values(i), p.Evaluate(env));
}
// The exception case, when the polynomial coefficients are not all constant;
const Polynomial p_exception(var_x_ * var_x_ * var_a_, var_xyz_);
DRAKE_EXPECT_THROWS_MESSAGE(
p_exception.EvaluateIndeterminates(indeterminates, indeterminates_values),
".* the coefficient .* is not a constant");
}
TEST_F(SymbolicPolynomialTest, EvaluateWithAffineCoefficients) {
const Vector2<symbolic::Variable> indeterminates(var_x_, var_y_);
Eigen::Matrix<double, 2, 3> indeterminates_values;
// clang-format off
indeterminates_values << 1, 2, 3,
4, 5, 6;
// clang-format on
Eigen::MatrixXd A;
VectorX<symbolic::Variable> decision_variables;
Eigen::VectorXd b;
{
const Polynomial p((a_ + 1) * var_x_ * var_x_ + b_ * var_x_ * var_y_ + c_,
var_xy_);
p.EvaluateWithAffineCoefficients(indeterminates, indeterminates_values, &A,
&decision_variables, &b);
EXPECT_EQ(A.rows(), indeterminates_values.cols());
EXPECT_EQ(b.rows(), indeterminates_values.cols());
EXPECT_EQ(decision_variables.rows(), 3);
for (int i = 0; i < indeterminates.cols(); ++i) {
symbolic::Environment env;
env.insert(indeterminates, indeterminates_values.col(i));
EXPECT_PRED2(ExprEqual, (p.ToExpression().EvaluatePartial(env)).Expand(),
(A.row(i).dot(decision_variables) + b(i)).Expand());
}
}
// Test special case. When the coefficients of p(x) are all constants.
{
const symbolic::Polynomial p(var_x_ * var_x_ + 2 * var_y_);
p.EvaluateWithAffineCoefficients(indeterminates, indeterminates_values, &A,
&decision_variables, &b);
EXPECT_EQ(A.cols(), 0);
EXPECT_EQ(decision_variables.rows(), 0);
for (int i = 0; i < indeterminates_values.cols(); ++i) {
symbolic::Environment env;
env.insert(indeterminates, indeterminates_values.col(i));
EXPECT_EQ(b(i), p.Evaluate(env));
}
}
// Test exception, when p(x)'s coefficient is not a polynomial expression of
// decision variables.
{
const symbolic::Polynomial p(1 + sin(var_a_) * var_x_ + var_y_, var_xy_);
DRAKE_EXPECT_THROWS_MESSAGE(
p.EvaluateWithAffineCoefficients(indeterminates, indeterminates_values,
&A, &decision_variables, &b),
".*is not a polynomial.\n");
}
// Test exception, when p(x)'s coefficient is not an affine expression of
// decision variables.
{
const symbolic::Polynomial p(1 + (a_ * a_) * var_x_ + var_y_, var_xy_);
DRAKE_EXPECT_THROWS_MESSAGE(
p.EvaluateWithAffineCoefficients(indeterminates, indeterminates_values,
&A, &decision_variables, &b),
".* is non-linear.*");
}
}
TEST_F(SymbolicPolynomialTest, SubstituteAndExpandTest) {
Polynomial::SubstituteAndExpandCacheData substitutions_cached_data;
std::unordered_map<Variable, Polynomial> indeterminate_substitution;
// A simple substitution.
indeterminate_substitution.emplace(var_x_, Polynomial(2 * var_a_));
// A substitution from one variable to a 2 indeterminate polynomial.
indeterminate_substitution.emplace(var_y_,
Polynomial(var_a_ * var_b_ + var_a_));
// A substitution with powers of a variable
indeterminate_substitution.emplace(
var_z_, Polynomial(pow(var_a_, 3) + 2 * var_a_ + 1));
// A polynomial with only linear monomials.
const Polynomial poly0{x_ + y_};
const Polynomial sub0 = poly0.SubstituteAndExpand(indeterminate_substitution,
&substitutions_cached_data);
const Polynomial sub0_expected{3 * a_ + a_ * b_};
EXPECT_TRUE(sub0.EqualTo(sub0_expected));
// We expect {1: 1, x: 2a, y: ab+a }
EXPECT_EQ(substitutions_cached_data.get_data()->size(), 3);
EXPECT_TRUE(substitutions_cached_data.get_data()
->at(Monomial())
.EqualTo(Polynomial(1)));
const Polynomial poly1{2 * x_ * x_};
const Polynomial sub1 = poly1.SubstituteAndExpand(indeterminate_substitution,
&substitutions_cached_data);
const Polynomial sub1_expected{8 * a_ * a_};
EXPECT_TRUE(sub1.EqualTo(sub1_expected));
// Expect {1: 1, x: 2a, y: ab+a, xΒ²: 4aΒ²}.
EXPECT_EQ(substitutions_cached_data.get_data()->size(), 4);
EXPECT_TRUE(substitutions_cached_data.get_data()
->at(Monomial(x_ * x_))
.EqualTo(Polynomial(4 * a_ * a_)));
const Polynomial poly2{x_ * x_ * y_};
const Polynomial sub2 = poly2.SubstituteAndExpand(indeterminate_substitution,
&substitutions_cached_data);
const Polynomial sub2_expected{4 * pow(a_, 3) * (b_ + 1)};
EXPECT_TRUE(sub2.EqualTo(sub2_expected));
// Expect {1: 1, x: 2a, y: ab+a, xΒ²: 4aΒ², xΒ²y: 8aΒ³(b+1)}.
EXPECT_EQ(substitutions_cached_data.get_data()->size(), 5);
// Make sure this hasn't changed
EXPECT_TRUE(substitutions_cached_data.get_data()
->at(Monomial(x_ * x_))
.EqualTo(Polynomial(4 * a_ * a_)));
EXPECT_TRUE(substitutions_cached_data.get_data()
->at(Monomial(x_ * x_ * y_))
.EqualTo(Polynomial(4 * pow(a_, 3) * (b_ + 1))));
const Polynomial poly3{pow(x_, 3) * z_};
const Polynomial sub3 = poly3.SubstituteAndExpand(indeterminate_substitution,
&substitutions_cached_data);
const Polynomial sub3_expected{pow(2 * a_, 3) *
(pow(var_a_, 3) + 2 * var_a_ + 1)};
EXPECT_TRUE(sub3.EqualTo(sub3_expected));
// Expect {1: 1, x: 2a, y: ab+a, xΒ²: 4aΒ², xΒ²y: 4aΒ², xz: 2a + 4aΒ² + 2aβ΄, xΒ³z:
// 2aβΉ+4aβ·+2aβΆ}
EXPECT_EQ(substitutions_cached_data.get_data()->size(), 8);
EXPECT_TRUE(substitutions_cached_data.get_data()
->at(Monomial(pow(x_, 3) * z_))
.EqualTo(sub3_expected));
indeterminate_substitution.clear();
const Polynomial::MapType a_poly_map{{Monomial(a_), pow(cos(z_) + 1, 2)}};
const Polynomial a_poly{a_poly_map};
indeterminate_substitution.emplace(var_x_, a_poly);
const Polynomial poly4{x_};
const Polynomial sub4 = poly4.SubstituteAndExpand(indeterminate_substitution);
const Polynomial::MapType sub4_expected_map{
{Monomial(a_), pow(cos(z_), 2) + 2 * cos(z_) + 1}};
const Polynomial sub4_expected{sub4_expected_map};
EXPECT_TRUE(sub4.EqualTo(sub4_expected));
}
TEST_F(SymbolicPolynomialTest, Hash) {
const auto h = std::hash<Polynomial>{};
Polynomial p1{x_ * x_};
const Polynomial p2{x_ * x_};
EXPECT_EQ(p1, p2);
EXPECT_EQ(h(p1), h(p2));
p1 += Polynomial{y_};
EXPECT_NE(p1, p2);
EXPECT_NE(h(p1), h(p2));
}
TEST_F(SymbolicPolynomialTest, CoefficientsAlmostEqual) {
Polynomial p1{x_ * x_};
// Two polynomials with the same number of terms.
EXPECT_TRUE(p1.CoefficientsAlmostEqual(Polynomial{x_ * x_}, 1e-6));
EXPECT_TRUE(
p1.CoefficientsAlmostEqual(Polynomial{(1 + 1e-7) * x_ * x_}, 1e-6));
EXPECT_FALSE(p1.CoefficientsAlmostEqual(Polynomial{2 * x_ * x_}, 1e-6));
// Another polynomial with an additional small constant term.
EXPECT_TRUE(p1.CoefficientsAlmostEqual(Polynomial{x_ * x_ + 1e-7}, 1e-6));
EXPECT_FALSE(p1.CoefficientsAlmostEqual(Polynomial{x_ * x_ + 2e-6}, 1e-6));
// Another polynomial with small difference on coefficients.
EXPECT_TRUE(p1.CoefficientsAlmostEqual(
Polynomial{(1. - 1e-7) * x_ * x_ + 1e-7}, 1e-6));
EXPECT_FALSE(p1.CoefficientsAlmostEqual(
Polynomial{(1. + 2e-6) * x_ * x_ + 1e-7}, 1e-6));
// Another polynomial with decision variables in the coefficient.
const symbolic::Polynomial p2(a_ * x_ * x_, {indeterminates_});
EXPECT_TRUE(p2.CoefficientsAlmostEqual(
Polynomial{(a_ + 1e-7) * x_ * x_, {indeterminates_}}, 1e-6));
EXPECT_FALSE(p2.CoefficientsAlmostEqual(
Polynomial{(a_ + 1e-7) * x_ * x_, {indeterminates_}}, 1e-8));
}
TEST_F(SymbolicPolynomialTest, RemoveTermsWithSmallCoefficients) {
// Single term.
Polynomial p1{1e-5 * x_ * x_};
EXPECT_PRED2(PolyEqual, p1.RemoveTermsWithSmallCoefficients(1E-4),
Polynomial(0));
EXPECT_PRED2(PolyEqual, p1.RemoveTermsWithSmallCoefficients(1E-5),
Polynomial(0));
EXPECT_PRED2(PolyEqual, p1.RemoveTermsWithSmallCoefficients(1E-6), p1);
// Multiple terms.
Polynomial p2(2 * x_ * x_ + 3 * x_ * y_ + 1E-4 * x_ - 1E-4);
EXPECT_PRED2(PolyEqual, p2.RemoveTermsWithSmallCoefficients(1E-4),
Polynomial(2 * x_ * x_ + 3 * x_ * y_));
// Coefficients are expressions.
Polynomial::MapType p3_map{};
p3_map.emplace(Monomial(var_x_, 2), 2 * sin(y_));
p3_map.emplace(Monomial(var_x_, 1), 1E-4 * cos(y_));
p3_map.emplace(Monomial(var_x_, 3), 1E-4 * y_);
p3_map.emplace(Monomial(), 1E-6);
Polynomial::MapType p3_expected_map{};
p3_expected_map.emplace(Monomial(var_x_, 2), 2 * sin(y_));
p3_expected_map.emplace(Monomial(var_x_, 1), 1E-4 * cos(y_));
p3_expected_map.emplace(Monomial(var_x_, 3), 1E-4 * y_);
EXPECT_PRED2(PolyEqual,
Polynomial(p3_map).RemoveTermsWithSmallCoefficients(1E-3),
Polynomial(p3_expected_map));
}
TEST_F(SymbolicPolynomialTest, EqualTo) {
const Polynomial p1{var_x_};
EXPECT_PRED2(PolyEqual, p1, Polynomial(var_x_));
EXPECT_PRED2(PolyEqual, Polynomial(var_a_ * var_x_, var_xy_),
Polynomial(var_x_ * var_a_, var_xy_));
EXPECT_PRED2(test::PolyNotEqual, Polynomial(var_a_ * var_x_, var_xy_),
Polynomial(var_b_ * var_x_, var_xy_));
}
TEST_F(SymbolicPolynomialTest, EqualToAfterExpansion) {
const Polynomial p1(2 * var_a_ * var_x_ * var_x_ + var_y_, var_xy_);
const Polynomial p2(var_x_ * var_x_ + 2 * var_y_, var_xy_);
const Polynomial p3(2 * var_a_ * var_x_ + var_b_ * var_x_ * var_y_, var_xy_);
// p2 * p3 * p1 and p1 * p2 * p3 are not structurally equal.
EXPECT_PRED2(test::PolyNotEqual, p2 * p3 * p1, p1 * p2 * p3);
// But they are equal after expansion.
EXPECT_PRED2(test::PolyEqualAfterExpansion, p2 * p3 * p1, p1 * p2 * p3);
// p1 * p2 is not equal to p2 * p3 after expansion.
EXPECT_PRED2(test::PolyNotEqualAfterExpansion, p1 * p2, p2 * p3);
}
// Checks if internal::CompareMonomial implements the lexicographical order.
TEST_F(SymbolicPolynomialTest, InternalCompareMonomial) {
// clang-format off
const Monomial m1{{{var_x_, 1}, }};
const Monomial m2{{{var_x_, 1}, {var_z_, 2}}};
const Monomial m3{{{var_x_, 1}, {var_y_, 1} }};
const Monomial m4{{{var_x_, 1}, {var_y_, 1}, {var_z_, 1}}};
const Monomial m5{{{var_x_, 1}, {var_y_, 1}, {var_z_, 2}}};
const Monomial m6{{{var_x_, 1}, {var_y_, 2}, {var_z_, 2}}};
const Monomial m7{{{var_x_, 1}, {var_y_, 3}, {var_z_, 1}}};
const Monomial m8{{{var_x_, 2}, }};
const Monomial m9{{{var_x_, 2}, {var_z_, 1}}};
// clang-format on
EXPECT_TRUE(internal::CompareMonomial()(m1, m2));
EXPECT_TRUE(internal::CompareMonomial()(m2, m3));
EXPECT_TRUE(internal::CompareMonomial()(m3, m4));
EXPECT_TRUE(internal::CompareMonomial()(m4, m5));
EXPECT_TRUE(internal::CompareMonomial()(m5, m6));
EXPECT_TRUE(internal::CompareMonomial()(m6, m7));
EXPECT_TRUE(internal::CompareMonomial()(m7, m8));
EXPECT_TRUE(internal::CompareMonomial()(m8, m9));
EXPECT_FALSE(internal::CompareMonomial()(m2, m1));
EXPECT_FALSE(internal::CompareMonomial()(m3, m2));
EXPECT_FALSE(internal::CompareMonomial()(m4, m3));
EXPECT_FALSE(internal::CompareMonomial()(m5, m4));
EXPECT_FALSE(internal::CompareMonomial()(m6, m5));
EXPECT_FALSE(internal::CompareMonomial()(m7, m6));
EXPECT_FALSE(internal::CompareMonomial()(m8, m7));
EXPECT_FALSE(internal::CompareMonomial()(m9, m8));
}
TEST_F(SymbolicPolynomialTest, DeterministicTraversal) {
// Using the following monomials, we construct two polynomials; one by summing
// up from top to bottom and another by summing up from bottom to top. The two
// polynomials should be the same mathematically. We check that the traversal
// operations over the two polynomials give the same sequences as well. See
// https://github.com/RobotLocomotion/drake/issues/11023#issuecomment-499948333
// for details.
const Monomial m1{{{var_x_, 1}}};
const Monomial m2{{{var_x_, 1}, {var_y_, 1}}};
const Monomial m3{{{var_x_, 1}, {var_y_, 1}, {var_z_, 1}}};
const Monomial m4{{{var_x_, 1}, {var_y_, 1}, {var_z_, 2}}};
const Polynomial p1{m1 + (m2 + (m3 + m4))};
const Polynomial p2{m4 + (m3 + (m2 + m1))};
const Polynomial::MapType& map1{p1.monomial_to_coefficient_map()};
const Polynomial::MapType& map2{p2.monomial_to_coefficient_map()};
EXPECT_EQ(map1.size(), map2.size());
auto it1 = map1.begin();
auto it2 = map2.begin();
for (; it1 != map1.end(); ++it1, ++it2) {
const Monomial& m_1{it1->first};
const Monomial& m_2{it2->first};
const Expression& e_1{it1->second};
const Expression& e_2{it2->second};
EXPECT_TRUE(m_1 == m_2);
EXPECT_TRUE(e_1.EqualTo(e_2));
}
}
TEST_F(SymbolicPolynomialTest, SetIndeterminates) {
// axΒ² + bx + c
const Expression e{a_ * x_ * x_ + b_ * x_ + c_};
{
// {x} -> {x, a}
Polynomial p{e, {var_x_}};
const Variables new_indeterminates{var_x_, var_a_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(PolyEqual, p, Polynomial(e, new_indeterminates));
}
{
// {x} -> {x, y}, note that y β variables(e).
Polynomial p{e, {var_x_}};
const Variables new_indeterminates{var_x_, var_y_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(PolyEqual, p, Polynomial(e, new_indeterminates));
}
{
// {x, a} -> {x}
Polynomial p{e, {var_x_, var_a_}};
const Variables new_indeterminates{var_x_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(PolyEqual, p, Polynomial(e, new_indeterminates));
}
{
// {x, a} -> {a}
Polynomial p{e, {var_x_, var_a_}};
const Variables new_indeterminates{var_a_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(PolyEqual, p, Polynomial(e, new_indeterminates));
}
{
// {x, a, b, c} -> {x}
Polynomial p{e, {var_x_, var_a_, var_b_, var_c_}};
const Variables new_indeterminates{var_x_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(PolyEqual, p, Polynomial(e, new_indeterminates));
}
}
TEST_F(SymbolicPolynomialTest, IsEvenOdd) {
symbolic::Polynomial p{0};
EXPECT_TRUE(p.IsEven());
EXPECT_TRUE(p.IsOdd());
p = symbolic::Polynomial{1};
EXPECT_TRUE(p.IsEven());
EXPECT_FALSE(p.IsOdd());
// p = (a+1)xβ°
p = symbolic::Polynomial{{{Monomial(), a_ + 1}}};
EXPECT_TRUE(p.IsEven());
EXPECT_FALSE(p.IsOdd());
// p = x
p = symbolic::Polynomial{{{Monomial(var_x_), 1}}};
EXPECT_FALSE(p.IsEven());
EXPECT_TRUE(p.IsOdd());
// p = x + 1
p = symbolic::Polynomial{{{Monomial(), 1}, {Monomial(var_x_), 1}}};
EXPECT_FALSE(p.IsEven());
EXPECT_FALSE(p.IsOdd());
// p = (a+2)*x
p = symbolic::Polynomial{{{Monomial(), 0}, {Monomial(var_x_), a_ + 2}}};
EXPECT_FALSE(p.IsEven());
EXPECT_TRUE(p.IsOdd());
// p = 1 + (a+1)*x*y
p = symbolic::Polynomial{
{{Monomial(), 1},
{Monomial(var_x_), pow(a_, 2) - 1 - (a_ + 1) * (a_ - 1)},
{Monomial({{var_x_, 1}, {var_y_, 1}}), a_ + 1}}};
EXPECT_TRUE(p.IsEven());
EXPECT_FALSE(p.IsOdd());
// p = a * x + 2 * xΒ²y
p = symbolic::Polynomial{
{{Monomial(), pow(a_, 2) - 1 - (a_ + 1) * (a_ - 1)},
{Monomial(var_x_), a_},
{Monomial{{{var_x_, 2}, {var_y_, 1}}}, 2},
{Monomial{{{var_x_, 2}}}, pow(a_ + 1, 2) - a_ * a_ - 2 * a_ - 1}}};
EXPECT_FALSE(p.IsEven());
EXPECT_TRUE(p.IsOdd());
}
TEST_F(SymbolicPolynomialTest, Roots) {
symbolic::Polynomial p{0};
DRAKE_EXPECT_THROWS_MESSAGE(p.Roots(), ".* is not a univariate polynomial.*");
p = symbolic::Polynomial{xy_};
DRAKE_EXPECT_THROWS_MESSAGE(p.Roots(), ".* is not a univariate polynomial.*");
p = symbolic::Polynomial{xy_, {var_x_}};
DRAKE_EXPECT_THROWS_MESSAGE(
p.Roots(), ".* only supports polynomials with constant coefficients.*");
p = symbolic::Polynomial{x_ - 1.23};
Eigen::VectorXcd roots = p.Roots();
EXPECT_TRUE(CompareMatrices(roots.real(), Vector1d{1.23}, 1e-14));
EXPECT_TRUE(CompareMatrices(roots.imag(), Vector1d::Zero(), 1e-14));
// Note: the order of the roots is not guaranteed. Sort them here by real,
// then imaginary.
auto sorted = [](const Eigen::VectorXcd& v) {
Eigen::VectorXcd v_sorted = v;
std::sort(v_sorted.data(), v_sorted.data() + v_sorted.size(),
[](const std::complex<double>& a, const std::complex<double>& b) {
if (a.real() == b.real()) {
return a.imag() < b.imag();
}
return a.real() < b.real();
});
return v_sorted;
};
// Include a repeated root.
p = symbolic::Polynomial{(x_ - 1.23) * (x_ - 4.56) * (x_ - 4.56)};
roots = sorted(p.Roots());
EXPECT_TRUE(
CompareMatrices(roots.real(), Eigen::Vector3d{1.23, 4.56, 4.56}, 1e-7));
EXPECT_TRUE(CompareMatrices(roots.imag(), Eigen::Vector3d::Zero(), 1e-7));
// Complex roots. x^4 - 1 has roots {-1, -i, i, 1}.
p = symbolic::Polynomial{pow(x_, 4) - 1};
roots = sorted(p.Roots());
EXPECT_TRUE(
CompareMatrices(roots.real(), Eigen::Vector4d{-1, 0, 0, 1}, 1e-7));
EXPECT_TRUE(
CompareMatrices(roots.imag(), Eigen::Vector4d{0, -1, 1, 0}, 1e-7));
// Leading coefficient is not 1.
p = symbolic::Polynomial{(2.1 * x_ - 1.23) * (x_ - 4.56)};
roots = sorted(p.Roots());
EXPECT_TRUE(
CompareMatrices(roots.real(), Eigen::Vector2d{1.23 / 2.1, 4.56}, 1e-7));
EXPECT_TRUE(CompareMatrices(roots.imag(), Eigen::Vector2d::Zero(), 1e-7));
}
TEST_F(SymbolicPolynomialTest, Expand) {
// p1 is already expanded.
const symbolic::Polynomial p1{
{{symbolic::Monomial(), a_}, {symbolic::Monomial(var_x_, 2), a_ + 1}}};
const auto p1_expanded = p1.Expand();
EXPECT_EQ(p1, p1_expanded);
// p2 needs expansion.
using std::pow;
const symbolic::Polynomial p2{
{{symbolic::Monomial(), (a_ + 2) * (b_ + 3)},
{symbolic::Monomial(var_x_, 2), pow(a_ + 1, 2)}}};
const symbolic::Polynomial p2_expanded = p2.Expand();
EXPECT_EQ(p2_expanded, symbolic::Polynomial(p2.ToExpression().Expand(),
symbolic::Variables({var_x_})));
// p3 is 0 after expansion.
const symbolic::Polynomial p3{
{{symbolic::Monomial(), (a_ + 1) * (a_ - 1) - pow(a_, 2) + 1}}};
EXPECT_TRUE(p3.Expand().monomial_to_coefficient_map().empty());
}
TEST_F(SymbolicPolynomialTest, CalcPolynomialWLowerTriangularPart) {
// Q is a matrix of double.
const Vector2<symbolic::Monomial> monomial_basis1(
symbolic::Monomial({{var_x_, 2}, {var_y_, 1}}),
symbolic::Monomial({{var_x_, 1}}));
Eigen::Vector3d Q1_lower(1, 2, 3);
const auto poly1 =
CalcPolynomialWLowerTriangularPart(monomial_basis1, Q1_lower);
EXPECT_PRED2(
test::PolyEqual, poly1,
symbolic::Polynomial(pow(var_x_, 4) * pow(var_y_, 2) +
4 * pow(var_x_, 3) * var_y_ + 3 * var_x_ * var_x_));
// Q is a matrix of symbolic variable.
const Vector3<symbolic::Monomial> monomial_basis2(
symbolic::Monomial({{var_x_, 2}}),
symbolic::Monomial({{var_x_, 1}, {var_y_, 1}}),
symbolic::Monomial({{var_y_, 2}}));
Vector6<symbolic::Variable> Q2_lower;
for (int i = 0; i < 6; ++i) {
Q2_lower(i) = symbolic::Variable("Q2_lower" + std::to_string(i));
}
const auto poly2 =
CalcPolynomialWLowerTriangularPart(monomial_basis2, Q2_lower);
const symbolic::Polynomial poly2_expected = symbolic::Polynomial(
Q2_lower(0) * pow(var_x_, 4) + 2 * Q2_lower(1) * pow(var_x_, 3) * var_y_ +
(2 * Q2_lower(2) + Q2_lower(3)) * pow(var_x_, 2) * pow(var_y_, 2) +
2 * Q2_lower(4) * var_x_ * pow(var_y_, 3) +
Q2_lower(5) * pow(var_y_, 4),
var_xy_);
EXPECT_PRED2(test::PolyEqualAfterExpansion, poly2, poly2_expected);
// Q is a matrix of expression.
Vector6<symbolic::Expression> Q3_lower;
Q3_lower << var_a_, 1, var_a_ + var_b_, 2, 0, var_a_ * var_b_;
const auto poly3 =
CalcPolynomialWLowerTriangularPart(monomial_basis2, Q3_lower);
const symbolic::Polynomial poly3_expected = symbolic::Polynomial(
var_a_ * pow(var_x_, 4) + 2 * pow(var_x_, 3) * var_y_ +
(2 * var_a_ + 2 * var_b_ + 2) * pow(var_x_, 2) * pow(var_y_, 2) +
var_a_ * var_b_ * pow(var_y_, 4),
var_xy_);
EXPECT_PRED2(test::PolyEqualAfterExpansion, poly3, poly3_expected);
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/polynomial_matrix_test.cc | #include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/fmt_eigen.h"
#include "drake/common/symbolic/expression.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
namespace {
using test::ExprEqual;
class SymbolicPolynomialMatrixTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
const Monomial m_x_{var_x_};
const Monomial m_y_{var_y_};
const Monomial m_z_{var_z_};
MatrixX<Polynomial> M_poly_dynamic_{2, 2};
Eigen::Matrix<Polynomial, 2, 2> M_poly_static_;
MatrixX<Monomial> M_monomial_dynamic_{2, 2};
Eigen::Matrix<Monomial, 2, 2> M_monomial_static_;
MatrixX<double> M_double_dynamic_{2, 2};
Eigen::Matrix<double, 2, 2> M_double_static_;
MatrixX<Expression> M_expression_dynamic_{2, 2};
Eigen::Matrix<Expression, 2, 2> M_expression_static_;
MatrixX<Variable> M_variable_dynamic_{2, 2};
Eigen::Matrix<Variable, 2, 2> M_variable_static_;
VectorX<Polynomial> v_poly_dynamic_{2};
Eigen::Matrix<Polynomial, 2, 1> v_poly_static_;
VectorX<Monomial> v_monomial_dynamic_{2};
Eigen::Matrix<Monomial, 2, 1> v_monomial_static_;
VectorX<double> v_double_dynamic_{2};
Eigen::Matrix<double, 2, 1> v_double_static_;
VectorX<Expression> v_expression_dynamic_{2};
Eigen::Matrix<Expression, 2, 1> v_expression_static_;
VectorX<Variable> v_variable_dynamic_{2};
Eigen::Matrix<Variable, 2, 1> v_variable_static_;
void SetUp() override {
// clang-format off
M_poly_dynamic_ << Polynomial{}, (m_x_ + m_y_), // [0 x + y]
(2 + m_x_ * m_y_), Polynomial{m_z_}; // [2 + xy z ]
M_poly_static_ << Polynomial{}, (m_x_ + m_y_), // [0 x + y]
(2 + m_x_ * m_y_), Polynomial{m_z_}; // [2 + xy z ]
M_monomial_dynamic_ << Monomial{}, m_x_, // [1 x ]
(m_x_ * m_y_), (m_x_ * m_x_ * m_z_); // [xy xΒ²z]
M_monomial_static_ << Monomial{}, m_x_, // [1 x ]
(m_x_ * m_y_), (m_x_ * m_x_ * m_z_); // [xy xΒ²z]
M_double_dynamic_ << -2.0, 4.0, // [-2.0 4.0]
5.0, -9.0; // [ 5.0 -9.0]
M_double_static_ << -2.0, 4.0, // [-2.0 4.0]
5.0, -9.0; // [ 5.0 -9.0]
// [x cos(x + y)]
// [sin(2 + xy) z ]
M_expression_dynamic_ << Expression{var_x_},
symbolic::cos(var_x_ + var_y_),
symbolic::sin(2 + var_x_ * var_y_),
Expression{var_z_};
// [x cos(x + y)]
// [sin(2 + xy) z ]
M_expression_static_ << Expression{var_x_},
symbolic::cos(var_x_ + var_y_),
symbolic::sin(2 + var_x_ * var_y_),
Expression{var_z_};
M_variable_dynamic_ << var_x_, var_y_, // [x, y]
var_z_, var_y_; // [z, y]
M_variable_static_ << var_x_, var_y_, // [x, y]
var_z_, var_y_; // [z, y]
v_poly_dynamic_ << (m_x_ + m_y_), // [x+y ]
(3 + m_x_ * m_y_ * m_z_); // [3 + xyz]
v_poly_static_ << (m_x_ + m_y_), // [x+y ]
(3 + m_x_ * m_y_ * m_z_); // [3 + xyz]
v_monomial_dynamic_ << (m_x_ * m_y_), // [xy ]
(m_x_ * m_y_ * m_z_); // [xyz]
v_monomial_static_ << (m_x_ * m_y_), // [xy ]
(m_x_ * m_y_ * m_z_); // [xyz]
v_double_dynamic_ << -1.1, // [-1.1]
5.2; // [ 5.2]
v_double_static_ << -1.1, // [-1.1]
5.2; // [ 5.2]
v_expression_dynamic_ << Expression{var_x_}, // [x]
symbolic::cos(var_x_ + var_y_); // [cos(x + y)]
v_expression_static_ << Expression{var_x_}, // [x]
symbolic::cos(var_x_ + var_y_); // [cos(x + y)]
v_variable_dynamic_ << var_x_, // [x]
var_y_; // [y]
v_variable_static_ << var_x_, // [x]
var_y_; // [y]
// clang-format on
}
};
// Compares m1 and m2 after expanding both of them.
::testing::AssertionResult CompareMatricesWithExpansion(
const Eigen::Ref<const MatrixX<Expression>>& m1,
const Eigen::Ref<const MatrixX<Expression>>& m2) {
const MatrixX<Expression> m1_expanded{m1.unaryExpr([](const Expression& e) {
return e.Expand();
})};
const MatrixX<Expression> m2_expanded{m2.unaryExpr([](const Expression& e) {
return e.Expand();
})};
if (m1_expanded == m2_expanded) {
return ::testing::AssertionSuccess() << fmt::format(
"m1 and m2 are equal after expansion where m1 = \n{}\n"
"and m2 = {}",
fmt_eigen(m1), fmt_eigen(m2));
} else {
return ::testing::AssertionFailure() << fmt::format(
"m1 and m2 are not equal after expansion where m1 = \n{}\n"
"m2 = \n{}\n"
"m1_expanded = \n{}\n"
"m2_expanded = \n{}\n",
fmt_eigen(m1), fmt_eigen(m2), fmt_eigen(m1_expanded),
fmt_eigen(m2_expanded));
}
}
template <typename Matrix1, typename Matrix2>
::testing::AssertionResult CheckAddition(const Matrix1& M1, const Matrix2& M2) {
return CompareMatricesWithExpansion(
(M1 + M2).template cast<Expression>(),
M1.template cast<Expression>() + M2.template cast<Expression>());
}
template <typename Matrix1, typename Matrix2>
::testing::AssertionResult CheckSubtraction(const Matrix1& M1,
const Matrix2& M2) {
return CompareMatricesWithExpansion(
(M1 - M2).template cast<Expression>(),
M1.template cast<Expression>() - M2.template cast<Expression>());
}
template <typename Matrix1, typename Matrix2>
::testing::AssertionResult CheckMultiplication(const Matrix1& M1,
const Matrix2& M2) {
return CompareMatricesWithExpansion(
(M1 * M2).template cast<Expression>(),
M1.template cast<Expression>() * M2.template cast<Expression>());
}
// Given two vectors with arbitrary types, computes their dot product as a
// Polynomial and then checks that the result is identical to the dot product
// after casting v1 and v2 to Expressions (i.e., using Expression's `operator+`
// and `operator*` as an oracle).
template <typename Vector1, typename Vector2>
bool CheckDotProductResPoly(const Vector1& v1, const Vector2& v2) {
const Polynomial dot = v1.dot(v2);
const Expression e1{dot.ToExpression().Expand()};
const Expression e2{v1.template cast<Expression>()
.dot(v2.template cast<Expression>())
.Expand()};
return e1.EqualTo(e2);
}
// Given two vectors with arbitrary types, computes their dot product as an
// Expression and then checks that the result is identical to the dot product
// after casting v1 and v2 to Expressions (i.e., using Expression's `operator+`
// and `operator*` as an oracle).
template <typename Vector1, typename Vector2>
bool CheckDotProductResExpr(const Vector1& v1, const Vector2& v2) {
const Expression dot = v1.dot(v2);
const Expression e1{dot.Expand()};
const Expression e2{v1.template cast<Expression>()
.dot(v2.template cast<Expression>())
.Expand()};
return e1.EqualTo(e2);
}
TEST_F(SymbolicPolynomialMatrixTest, ExpressionPolynomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_expression_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_expression_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_expression_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResExpr(v_expression_dynamic_, v_poly_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_expression_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_expression_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_expression_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResExpr(v_expression_static_, v_poly_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_expression_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_expression_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_expression_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResExpr(v_expression_dynamic_, v_poly_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_expression_static_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_expression_static_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_expression_static_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResExpr(v_expression_static_, v_poly_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, ExpressionMonomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_expression_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_expression_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_expression_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(
CheckDotProductResExpr(v_expression_dynamic_, v_monomial_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_expression_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_expression_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_expression_static_, M_monomial_dynamic_));
EXPECT_TRUE(
CheckDotProductResExpr(v_expression_static_, v_monomial_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_expression_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_expression_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_expression_dynamic_, M_monomial_static_));
EXPECT_TRUE(
CheckDotProductResExpr(v_expression_dynamic_, v_monomial_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_expression_static_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_expression_static_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_expression_static_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResExpr(v_expression_static_, v_monomial_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, PolynomialPolynomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_dynamic_, v_poly_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_static_, v_poly_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_dynamic_, v_poly_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_static_, v_poly_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, PolynomialMonomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_dynamic_, v_monomial_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_static_, v_monomial_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_dynamic_, v_monomial_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_static_, v_monomial_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, PolynomialDouble) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_double_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_double_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_double_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_dynamic_, v_double_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_double_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_double_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_double_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_static_, v_double_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_double_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_double_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_double_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_dynamic_, v_double_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_double_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_double_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_double_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_static_, v_double_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, PolynomialVariable) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_variable_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_variable_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_variable_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_dynamic_, v_variable_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_variable_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_variable_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_variable_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_static_, v_variable_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_variable_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_variable_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_variable_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_dynamic_, v_variable_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_variable_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_variable_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_variable_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_poly_static_, v_variable_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, PolynomialExpression) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_expression_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_expression_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_expression_dynamic_));
EXPECT_TRUE(CheckDotProductResExpr(v_poly_dynamic_, v_expression_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_expression_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_expression_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_expression_dynamic_));
EXPECT_TRUE(CheckDotProductResExpr(v_poly_static_, v_expression_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_dynamic_, M_expression_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_dynamic_, M_expression_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_dynamic_, M_expression_static_));
EXPECT_TRUE(CheckDotProductResExpr(v_poly_dynamic_, v_expression_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_poly_static_, M_expression_static_));
EXPECT_TRUE(CheckSubtraction(M_poly_static_, M_expression_static_));
EXPECT_TRUE(CheckMultiplication(M_poly_static_, M_expression_static_));
EXPECT_TRUE(CheckDotProductResExpr(v_poly_static_, v_expression_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, MonomialPolynomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_dynamic_, v_poly_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_static_, v_poly_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_dynamic_, v_poly_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_static_, v_poly_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, MonomialMonomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_dynamic_, v_monomial_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_static_, v_monomial_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_dynamic_, v_monomial_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_static_, v_monomial_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, MonomialVariable) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_variable_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_variable_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_variable_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_dynamic_, v_variable_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_variable_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_variable_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_variable_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_static_, v_variable_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_variable_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_variable_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_variable_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_dynamic_, v_variable_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_variable_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_variable_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_variable_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_static_, v_variable_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, MonomialExpression) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_expression_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_expression_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_expression_dynamic_));
EXPECT_TRUE(
CheckDotProductResExpr(v_monomial_dynamic_, v_expression_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_expression_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_expression_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_expression_dynamic_));
EXPECT_TRUE(
CheckDotProductResExpr(v_monomial_static_, v_expression_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_expression_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_expression_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_expression_static_));
EXPECT_TRUE(
CheckDotProductResExpr(v_monomial_dynamic_, v_expression_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_expression_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_expression_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_expression_static_));
EXPECT_TRUE(CheckDotProductResExpr(v_monomial_static_, v_expression_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, MonomialDouble) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_double_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_double_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_double_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_dynamic_, v_double_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_double_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_double_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_double_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_static_, v_double_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_dynamic_, M_double_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_dynamic_, M_double_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_dynamic_, M_double_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_dynamic_, v_double_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_monomial_static_, M_double_static_));
EXPECT_TRUE(CheckSubtraction(M_monomial_static_, M_double_static_));
EXPECT_TRUE(CheckMultiplication(M_monomial_static_, M_double_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_monomial_static_, v_double_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, VariablePolynomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_variable_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_variable_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_variable_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_variable_dynamic_, v_poly_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_variable_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_variable_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_variable_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_variable_static_, v_poly_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_variable_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_variable_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_variable_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_variable_dynamic_, v_poly_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_variable_static_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_variable_static_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_variable_static_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_variable_static_, v_poly_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, VariableMonomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_variable_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_variable_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_variable_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_variable_dynamic_, v_monomial_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_variable_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_variable_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_variable_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_variable_static_, v_monomial_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_variable_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_variable_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_variable_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_variable_dynamic_, v_monomial_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_variable_static_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_variable_static_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_variable_static_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_variable_static_, v_monomial_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, DoublePolynomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_double_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_double_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_double_dynamic_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_double_dynamic_, v_poly_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_double_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_double_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_double_static_, M_poly_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_double_static_, v_poly_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_double_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_double_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_double_dynamic_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_double_dynamic_, v_poly_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_double_static_, M_poly_static_));
EXPECT_TRUE(CheckSubtraction(M_double_static_, M_poly_static_));
EXPECT_TRUE(CheckMultiplication(M_double_static_, M_poly_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_double_static_, v_poly_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, DoubleMonomial) {
// Checks Dynamic op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_double_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_double_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_double_dynamic_, M_monomial_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_double_dynamic_, v_monomial_dynamic_));
// Checks Static op Dynamic where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_double_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckSubtraction(M_double_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckMultiplication(M_double_static_, M_monomial_dynamic_));
EXPECT_TRUE(CheckDotProductResPoly(v_double_static_, v_monomial_dynamic_));
// Checks Dynamic op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_double_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_double_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_double_dynamic_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_double_dynamic_, v_monomial_static_));
// Checks Static op Static where op = {+, -, *, Β·}.
EXPECT_TRUE(CheckAddition(M_double_static_, M_monomial_static_));
EXPECT_TRUE(CheckSubtraction(M_double_static_, M_monomial_static_));
EXPECT_TRUE(CheckMultiplication(M_double_static_, M_monomial_static_));
EXPECT_TRUE(CheckDotProductResPoly(v_double_static_, v_monomial_static_));
}
TEST_F(SymbolicPolynomialMatrixTest, EvaluateMatrix) {
const Environment env{{{var_x_, 1.0}, {var_y_, 2.0}, {var_z_, 3.0}}};
EXPECT_EQ(Evaluate(M_poly_dynamic_, env),
Evaluate(M_poly_dynamic_.cast<Expression>(), env));
EXPECT_EQ(Evaluate(M_poly_static_, env),
Evaluate(M_poly_static_.cast<Expression>(), env));
EXPECT_EQ(Evaluate(v_poly_dynamic_, env),
Evaluate(v_poly_dynamic_.cast<Expression>(), env));
EXPECT_EQ(Evaluate(v_poly_static_, env),
Evaluate(v_poly_static_.cast<Expression>(), env));
}
TEST_F(SymbolicPolynomialMatrixTest, Jacobian) {
const Vector3<Variable> vars{var_x_, var_y_, var_z_};
{
const MatrixX<Polynomial> result{Jacobian(v_poly_dynamic_, vars)};
for (int i = 0; i < v_poly_dynamic_.size(); ++i) {
for (int j = 0; j < vars.size(); ++j) {
const Polynomial p1{v_poly_dynamic_(i).Differentiate(vars(j))};
const Polynomial& p2{result(i, j)};
EXPECT_TRUE(p1.EqualTo(p2));
}
}
}
{
const MatrixX<Polynomial> result{Jacobian(v_poly_static_, vars)};
for (int i = 0; i < v_poly_static_.size(); ++i) {
for (int j = 0; j < vars.size(); ++j) {
const Polynomial p1{v_poly_static_(i).Differentiate(vars(j))};
const Polynomial& p2{result(i, j)};
EXPECT_TRUE(p1.EqualTo(p2));
}
}
}
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/polynomial_basis_test.cc | #include "drake/common/symbolic/polynomial_basis.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
class ComputePolynomialBasisUpToDegreeTest : public ::testing::Test {
protected:
const Variable x_{"x"};
const Variable y_{"y"};
const Variable z_{"z"};
const Variable w_{"w"};
void SetUp() override {
EXPECT_PRED2(test::VarLess, x_, y_);
EXPECT_PRED2(test::VarLess, y_, z_);
EXPECT_PRED2(test::VarLess, z_, w_);
}
};
TEST_F(ComputePolynomialBasisUpToDegreeTest, ChebyshevAnyParity) {
// Test ComputePolynomialBasisUpToDegree with degree_type=DegreeType::kAny.
// The chebyshev basis of x_ up to degree 0 is [1].
const Vector1<ChebyshevBasisElement> result0 =
ComputePolynomialBasisUpToDegree<1, ChebyshevBasisElement>(
Variables({x_}), 0, internal::DegreeType::kAny);
EXPECT_EQ(result0(0), ChebyshevBasisElement());
// The chebyshev basis of x_ up to degree 1 is [1, T1(x)].
const Vector2<ChebyshevBasisElement> result1 =
ComputePolynomialBasisUpToDegree<2, ChebyshevBasisElement>(
Variables({x_}), 1, internal::DegreeType::kAny);
EXPECT_EQ(result1(0), ChebyshevBasisElement());
EXPECT_EQ(result1(1), ChebyshevBasisElement(x_));
// The chebyshev basis of x_ up to degree 2 is [1, T1(x), T2(x)].
const Vector3<ChebyshevBasisElement> result2 =
ComputePolynomialBasisUpToDegree<3, ChebyshevBasisElement>(
Variables({x_}), 2, internal::DegreeType::kAny);
EXPECT_EQ(result2(0), ChebyshevBasisElement());
EXPECT_EQ(result2(1), ChebyshevBasisElement(x_, 1));
EXPECT_EQ(result2(2), ChebyshevBasisElement(x_, 2));
// The chebyshev basis of (x, y) up to degree 0 is [1]. Also instantitate the
// function with Eigen::Dynamic.
const VectorX<ChebyshevBasisElement> result3 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_, y_}), 0, internal::DegreeType::kAny);
EXPECT_EQ(result3.rows(), 1);
EXPECT_EQ(result3(0), ChebyshevBasisElement());
// The chebyshev basis of (x, y) up to degree 1 is [1, T1(x), T1(y)].
const VectorX<ChebyshevBasisElement> result4 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_, y_}), 1, internal::DegreeType::kAny);
EXPECT_EQ(result4.rows(), 3);
EXPECT_EQ(result4(0), ChebyshevBasisElement());
EXPECT_EQ(result4(1), ChebyshevBasisElement(x_));
EXPECT_EQ(result4(2), ChebyshevBasisElement(y_));
// The chebyshev basis of (x, y) up to degree 2 is [1, T1(x), T1(y), T2(x),
// T1(x)T1(y) T2(y)].
const VectorX<ChebyshevBasisElement> result5 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_, y_}), 2, internal::DegreeType::kAny);
EXPECT_EQ(result5.rows(), 6);
EXPECT_EQ(result5(0), ChebyshevBasisElement());
EXPECT_EQ(result5(1), ChebyshevBasisElement(x_));
EXPECT_EQ(result5(2), ChebyshevBasisElement(y_));
EXPECT_EQ(result5(3), ChebyshevBasisElement(x_, 2));
EXPECT_EQ(result5(4), ChebyshevBasisElement({{x_, 1}, {y_, 1}}));
EXPECT_EQ(result5(5), ChebyshevBasisElement(y_, 2));
// The chebyshev basis of (x, y) up to degree 3 is [1, T1(x), T1(y), T2(x),
// T1(x)T1(y), T2(y), T3(x), T2(x)T1(y), T1(x)T2(y), T3(y)].
const VectorX<ChebyshevBasisElement> result6 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_, y_}), 3, internal::DegreeType::kAny);
EXPECT_EQ(result6.rows(), 10);
EXPECT_EQ(result6(0), ChebyshevBasisElement());
EXPECT_EQ(result6(1), ChebyshevBasisElement(x_));
EXPECT_EQ(result6(2), ChebyshevBasisElement(y_));
EXPECT_EQ(result6(3), ChebyshevBasisElement(x_, 2));
EXPECT_EQ(result6(4), ChebyshevBasisElement({{x_, 1}, {y_, 1}}));
EXPECT_EQ(result6(5), ChebyshevBasisElement(y_, 2));
EXPECT_EQ(result6(6), ChebyshevBasisElement(x_, 3));
EXPECT_EQ(result6(7), ChebyshevBasisElement({{x_, 2}, {y_, 1}}));
EXPECT_EQ(result6(8), ChebyshevBasisElement({{x_, 1}, {y_, 2}}));
EXPECT_EQ(result6(9), ChebyshevBasisElement(y_, 3));
// The chebyshev basis of (x, y, z) up to degree 2 is [1, T1(x), T1(y),
// T1(z), T2(x), T1(x)T1(y), T1(x)T1(z), T2(y), T1(y)T1(z), T2(z)].
const VectorX<ChebyshevBasisElement> result7 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_, y_, z_}), 2, internal::DegreeType::kAny);
EXPECT_EQ(result7.rows(), 10);
EXPECT_EQ(result7(0), ChebyshevBasisElement());
EXPECT_EQ(result7(1), ChebyshevBasisElement(x_));
EXPECT_EQ(result7(2), ChebyshevBasisElement(y_));
EXPECT_EQ(result7(3), ChebyshevBasisElement(z_));
EXPECT_EQ(result7(4), ChebyshevBasisElement(x_, 2));
EXPECT_EQ(result7(5), ChebyshevBasisElement({{x_, 1}, {y_, 1}}));
EXPECT_EQ(result7(6), ChebyshevBasisElement({{x_, 1}, {z_, 1}}));
EXPECT_EQ(result7(7), ChebyshevBasisElement(y_, 2));
EXPECT_EQ(result7(8), ChebyshevBasisElement({{y_, 1}, {z_, 1}}));
EXPECT_EQ(result7(9), ChebyshevBasisElement(z_, 2));
// The chebyshev basis of (x, y, z) up to degree 3 is [1, T1(x), T1(y),
// T1(z), T2(x) T1(x)T1(y), T1(x)T1(z), T2(y), T1(y)T1(z), T2(z), T3(x),
// T2(x)T1(y), T2(x)T1(z), T1(x)T2(y), T1(x)T1(y)T1(z), T1(x)T2(z), T3(y),
// T2(y)T1(z), T1(y)T2(z), T3(z)].
const VectorX<ChebyshevBasisElement> result8 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_, y_, z_}), 3, internal::DegreeType::kAny);
EXPECT_EQ(result8.rows(), 20);
EXPECT_EQ(result8(0), ChebyshevBasisElement());
EXPECT_EQ(result8(1), ChebyshevBasisElement(x_));
EXPECT_EQ(result8(2), ChebyshevBasisElement(y_));
EXPECT_EQ(result8(3), ChebyshevBasisElement(z_));
EXPECT_EQ(result8(4), ChebyshevBasisElement(x_, 2));
EXPECT_EQ(result8(5), ChebyshevBasisElement({{x_, 1}, {y_, 1}}));
EXPECT_EQ(result8(6), ChebyshevBasisElement({{x_, 1}, {z_, 1}}));
EXPECT_EQ(result8(7), ChebyshevBasisElement(y_, 2));
EXPECT_EQ(result8(8), ChebyshevBasisElement({{y_, 1}, {z_, 1}}));
EXPECT_EQ(result8(9), ChebyshevBasisElement(z_, 2));
EXPECT_EQ(result8(10), ChebyshevBasisElement(x_, 3));
EXPECT_EQ(result8(11), ChebyshevBasisElement({{x_, 2}, {y_, 1}}));
EXPECT_EQ(result8(12), ChebyshevBasisElement({{x_, 2}, {z_, 1}}));
EXPECT_EQ(result8(13), ChebyshevBasisElement({{x_, 1}, {y_, 2}}));
EXPECT_EQ(result8(14), ChebyshevBasisElement({{x_, 1}, {y_, 1}, {z_, 1}}));
EXPECT_EQ(result8(15), ChebyshevBasisElement({{x_, 1}, {z_, 2}}));
EXPECT_EQ(result8(16), ChebyshevBasisElement(y_, 3));
EXPECT_EQ(result8(17), ChebyshevBasisElement({{y_, 2}, {z_, 1}}));
EXPECT_EQ(result8(18), ChebyshevBasisElement({{y_, 1}, {z_, 2}}));
EXPECT_EQ(result8(19), ChebyshevBasisElement(z_, 3));
}
TEST_F(ComputePolynomialBasisUpToDegreeTest, ChebyshevEvenParity) {
// Test ComputePolynomialBasisUpToDegree with degree_type=DegreeType::kEven.
// The chebyshev basis of x up to requested degree 0 or 1 (with even degrees)
// is [1].
for (int degree : {0, 1}) {
const auto result =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_}), degree, internal::DegreeType::kEven);
EXPECT_EQ(result.rows(), 1);
EXPECT_EQ(result(0), ChebyshevBasisElement());
}
// The chebyshev basis of x up to requested degree 2 or 3 (with even degrees)
// is [1, T2(x)].
for (int degree : {2, 3}) {
const auto result =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_}), degree, internal::DegreeType::kEven);
EXPECT_EQ(result.rows(), 2);
EXPECT_EQ(result(0), ChebyshevBasisElement());
EXPECT_EQ(result(1), ChebyshevBasisElement(x_, 2));
}
// The chebyshev basis of (x, y) up to requested degree 2 or 3 (with even
// degrees) is [1, T2(x), T1(x)T1(y) T2(y)].
for (int degree : {2, 3}) {
const auto result =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_, y_}), degree, internal::DegreeType::kEven);
EXPECT_EQ(result.rows(), 4);
EXPECT_EQ(result(0), ChebyshevBasisElement());
EXPECT_EQ(result(1), ChebyshevBasisElement(x_, 2));
EXPECT_EQ(result(2), ChebyshevBasisElement({{x_, 1}, {y_, 1}}));
EXPECT_EQ(result(3), ChebyshevBasisElement(y_, 2));
}
}
TEST_F(ComputePolynomialBasisUpToDegreeTest, ChebyshevOddParity) {
// Test ComputePolynomialBasisUpToDegree with degree_type=DegreeType::kOdd.
// The chebyshev basis of x up to degree 0 (with odd degrees) is [].
const auto result1 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_}), 0, internal::DegreeType::kOdd);
EXPECT_EQ(result1.rows(), 0);
// The chebyshev basis of x up to requested degree 1 or 2 (with odd degrees)
// is [T1(x)].
for (int degree : {1, 2}) {
const auto result2 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_}), degree, internal::DegreeType::kOdd);
EXPECT_EQ(result2.rows(), 1);
EXPECT_EQ(result2(0), ChebyshevBasisElement(x_));
}
// The chebyshev basis of x up to requested degree 3 or 4 (with odd degrees)
// is [T1(x), T3(x)].
for (int degree : {3, 4}) {
const auto result4 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_}), degree, internal::DegreeType::kOdd);
EXPECT_EQ(result4.rows(), 2);
EXPECT_EQ(result4(0), ChebyshevBasisElement(x_));
EXPECT_EQ(result4(1), ChebyshevBasisElement(x_, 3));
}
// The chebyshev basis of (x, y) up to requested degree 3 or 4 (with odd
// degrees) is [T1(x), T1(y), T3(x), T2(x)T1(y), T1(x)T2(y), T3(y)].
for (int degree : {3, 4}) {
const auto result5 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
Variables({x_, y_}), degree, internal::DegreeType::kOdd);
EXPECT_EQ(result5.rows(), 6);
EXPECT_EQ(result5(0), ChebyshevBasisElement(x_));
EXPECT_EQ(result5(1), ChebyshevBasisElement(y_));
EXPECT_EQ(result5(2), ChebyshevBasisElement(x_, 3));
EXPECT_EQ(result5(3), ChebyshevBasisElement({{x_, 2}, {y_, 1}}));
EXPECT_EQ(result5(4), ChebyshevBasisElement({{x_, 1}, {y_, 2}}));
EXPECT_EQ(result5(5), ChebyshevBasisElement(y_, 3));
}
}
TEST_F(ComputePolynomialBasisUpToDegreeTest, MonomialAnyParity) {
// Test ComputePolynomialBasisUpToDegree with BasisElement = Monomial
// The monomial basis of (x, y) up to requested degree 2 is [1, x, y, x^2, xy,
// y^2]
const auto result1 =
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, Monomial>(
Variables({x_, y_}), 2, internal::DegreeType::kAny);
EXPECT_EQ(result1.rows(), 6);
EXPECT_EQ(result1(0), Monomial());
EXPECT_EQ(result1(1), Monomial(x_));
EXPECT_EQ(result1(2), Monomial(y_));
EXPECT_EQ(result1(3), Monomial(x_, 2));
EXPECT_EQ(result1(4), Monomial({{x_, 1}, {y_, 1}}));
EXPECT_EQ(result1(5), Monomial(y_, 2));
}
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/generic_polynomial_test.cc | #include "drake/common/symbolic/generic_polynomial.h"
#include <gtest/gtest.h>
#include "drake/common/symbolic/polynomial_basis.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
#include "drake/common/unused.h"
namespace drake {
namespace symbolic {
namespace {
using std::pair;
using std::runtime_error;
using std::vector;
using test::ExprEqual;
using test::GenericPolyEqual;
class SymbolicGenericPolynomialTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
const Variables indeterminates_{var_x_, var_y_, var_z_};
const Variable var_a_{"a"};
const Variable var_b_{"b"};
const Variable var_c_{"c"};
const Variables var_xy_{var_x_, var_y_};
const Variables var_xyz_{var_x_, var_y_, var_z_};
const Variables var_abc_{var_a_, var_b_, var_c_};
const VectorX<MonomialBasisElement> monomials_{
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, MonomialBasisElement>(
var_xyz_, 3, internal::DegreeType::kAny)};
const VectorX<ChebyshevBasisElement> chebyshev_basis_{
ComputePolynomialBasisUpToDegree<Eigen::Dynamic, ChebyshevBasisElement>(
var_xyz_, 3, internal::DegreeType::kAny)};
const vector<double> doubles_{-9999.0, -5.0, -1.0, 0.0, 1.0, 5.0, 9999.0};
const Expression x_{var_x_};
const Expression y_{var_y_};
const Expression z_{var_z_};
const Expression a_{var_a_};
const Expression b_{var_b_};
const Expression c_{var_c_};
const vector<Expression> exprs_{
0,
-1,
3,
x_,
5 * x_,
-3 * x_,
y_,
x_* y_,
2 * x_* x_,
2 * x_* x_,
6 * x_* y_,
3 * x_* x_* y_ + 4 * pow(y_, 3) * z_ + 2,
y_ * (3 * x_ * x_ + 4 * y_ * y_ * z_) + 2,
6 * pow(x_, 3) * pow(y_, 2),
2 * pow(x_, 3) * 3 * pow(y_, 2),
pow(x_, 3) - 4 * x_* y_* y_ + 2 * x_* x_* y_ - 8 * pow(y_, 3),
pow(x_ + 2 * y_, 2) * (x_ - 2 * y_),
(x_ + 2 * y_) * (x_ * x_ - 4 * y_ * y_),
(x_ * x_ + 4 * x_ * y_ + 4 * y_ * y_) * (x_ - 2 * y_),
pow(x_ + y_ + 1, 4),
pow(x_ + y_ + 1, 3),
1 + x_* x_ + 2 * (y_ - 0.5 * x_ * x_ - 0.5),
Expression(5.0) / 2.0, // constant / constant
x_ / 3.0, // var / constant
pow(x_, 2) / 2, // pow / constant
pow(x_* y_ / 3.0, 2) / 2, // pow / constant
(x_ + y_) / 2.0, // sum / constant
(x_* y_* z_ * 3) / 2.0, // product / constant
(x_* y_ / -5.0) / 2.0, // div / constant
};
};
// Tests that default constructor and EIGEN_INITIALIZE_MATRICES_BY_ZERO
// constructor both create the same value.
TEST_F(SymbolicGenericPolynomialTest, DefaultConstructors) {
const GenericPolynomial<MonomialBasisElement> p1;
EXPECT_TRUE(p1.basis_element_to_coefficient_map().empty());
const GenericPolynomial<ChebyshevBasisElement> p2;
EXPECT_TRUE(p2.basis_element_to_coefficient_map().empty());
const GenericPolynomial<MonomialBasisElement> p3(nullptr);
EXPECT_TRUE(p3.basis_element_to_coefficient_map().empty());
const GenericPolynomial<ChebyshevBasisElement> p4(nullptr);
EXPECT_TRUE(p4.basis_element_to_coefficient_map().empty());
}
TEST_F(SymbolicGenericPolynomialTest, ConstructFromMapType1) {
GenericPolynomial<ChebyshevBasisElement>::MapType map1;
map1.emplace(ChebyshevBasisElement{var_x_}, -2.0 * a_); // Tβ(x) β β2a
map1.emplace(ChebyshevBasisElement{var_y_, 3}, 4.0 * b_); // Tβ(y) β 4b
// p=β2aTβ(x)+4bTβ(y)
const GenericPolynomial<ChebyshevBasisElement> p1(map1);
EXPECT_EQ(p1.basis_element_to_coefficient_map(), map1);
EXPECT_EQ(p1.decision_variables(), Variables({var_a_, var_b_}));
EXPECT_EQ(p1.indeterminates(), Variables({var_x_, var_y_}));
}
TEST_F(SymbolicGenericPolynomialTest, ConstructFromMapTypeError) {
GenericPolynomial<ChebyshevBasisElement>::MapType map;
map.emplace(ChebyshevBasisElement{var_x_}, -2. * a_);
map.emplace(ChebyshevBasisElement(var_a_, 2), 4 * b_);
// We cannot construct a polynomial from `map` because variable a is used as
// both a decision variable in -2a, and an indeterminate in Tβ(a).
if (kDrakeAssertIsArmed) {
DRAKE_EXPECT_THROWS_MESSAGE(GenericPolynomial<ChebyshevBasisElement>{map},
".* does not satisfy the invariant .*\n.*");
}
}
TEST_F(SymbolicGenericPolynomialTest, ConstructFromSingleElement) {
const GenericPolynomial<ChebyshevBasisElement> p1(
ChebyshevBasisElement({{var_x_, 1}, {var_y_, 2}}));
EXPECT_EQ(p1.basis_element_to_coefficient_map().size(), 1);
EXPECT_PRED2(ExprEqual,
p1.basis_element_to_coefficient_map().at(
ChebyshevBasisElement({{var_x_, 1}, {var_y_, 2}})),
Expression(1));
}
TEST_F(SymbolicGenericPolynomialTest, ConstructFromExpressionMonomialBasis) {
// p1 = 2xΒ²+3x
const GenericPolynomial<MonomialBasisElement> p1(var_x_ * var_x_ * 2 +
3 * var_x_);
EXPECT_EQ(p1.basis_element_to_coefficient_map().size(), 2);
EXPECT_PRED2(
ExprEqual,
p1.basis_element_to_coefficient_map().at(MonomialBasisElement(var_x_, 2)),
Expression(2));
EXPECT_PRED2(
ExprEqual,
p1.basis_element_to_coefficient_map().at(MonomialBasisElement(var_x_)),
Expression(3));
// p2 = 4xy+5yΒ²+3xzΒ³+2
const GenericPolynomial<MonomialBasisElement> p2(
4 * var_x_ * var_y_ + 5 * pow(var_y_, 2) + 3 * var_x_ * pow(var_z_, 3) +
2);
EXPECT_EQ(p2.basis_element_to_coefficient_map().size(), 4);
EXPECT_PRED2(ExprEqual,
p2.basis_element_to_coefficient_map().at(
MonomialBasisElement({{var_x_, 1}, {var_y_, 1}})),
Expression(4));
EXPECT_PRED2(
ExprEqual,
p2.basis_element_to_coefficient_map().at(MonomialBasisElement(var_y_, 2)),
Expression(5));
EXPECT_PRED2(ExprEqual,
p2.basis_element_to_coefficient_map().at(
MonomialBasisElement({{var_x_, 1}, {var_z_, 3}})),
Expression(3));
EXPECT_PRED2(ExprEqual,
p2.basis_element_to_coefficient_map().at(MonomialBasisElement()),
Expression(2));
}
TEST_F(SymbolicGenericPolynomialTest, ConstructFromExpressionChebyshevBasis) {
// 1 = T0().
const GenericPolynomial<ChebyshevBasisElement> p1(Expression(1.));
EXPECT_EQ(p1.basis_element_to_coefficient_map().size(), 1);
EXPECT_PRED2(
ExprEqual,
p1.basis_element_to_coefficient_map().at(ChebyshevBasisElement()),
Expression(1.));
// Tβ(x)=2xΒ²β1
const GenericPolynomial<ChebyshevBasisElement> p2(2 * pow(var_x_, 2) - 1);
EXPECT_EQ(p2.basis_element_to_coefficient_map().size(), 1);
EXPECT_PRED2(ExprEqual,
p2.basis_element_to_coefficient_map().at(
ChebyshevBasisElement(var_x_, 2)),
Expression(1.));
// Tβ(x)Tβ(y)=(2xΒ²β1)(4yΒ³β3y)
const GenericPolynomial<ChebyshevBasisElement> p3(
(2 * pow(var_x_, 2) - 1) * (4 * pow(var_y_, 3) - 3 * var_y_));
EXPECT_EQ(p3.basis_element_to_coefficient_map().size(), 1);
EXPECT_PRED2(ExprEqual,
p3.basis_element_to_coefficient_map().at(
ChebyshevBasisElement({{var_x_, 2}, {var_y_, 3}})),
Expression(1.));
// 2Tβ(x)Tβ(y)+Tβ(x)Tβ(y)=2(2xΒ²β1)(4yΒ³β3y)+x(2yΒ²β1)
// = 16xΒ²yΒ³β8yΒ³β12xΒ²y+6y+2xyΒ²βx
const GenericPolynomial<ChebyshevBasisElement> p4(
16 * pow(var_x_, 2) * pow(var_y_, 3) - 8 * pow(var_y_, 3) -
12 * pow(var_x_, 2) * var_y_ + 6 * var_y_ + 2 * var_x_ * pow(var_y_, 2) -
var_x_);
EXPECT_EQ(p4.basis_element_to_coefficient_map().size(), 2);
EXPECT_PRED2(ExprEqual,
p4.basis_element_to_coefficient_map().at(
ChebyshevBasisElement({{var_x_, 2}, {var_y_, 3}})),
Expression(2.));
EXPECT_PRED2(ExprEqual,
p4.basis_element_to_coefficient_map().at(
ChebyshevBasisElement({{var_x_, 1}, {var_y_, 2}})),
Expression(1.));
// 3Tβ()+2Tβ(x)+4Tβ(x)+3Tβ(x) = 3+2x+8xΒ²β4+12xΒ³β9x
// = 12xΒ³+8xΒ²β7xβ1
const GenericPolynomial<ChebyshevBasisElement> p5(
12 * pow(var_x_, 3) + 8 * pow(var_x_, 2) - 7 * var_x_ - 1);
EXPECT_EQ(p5.basis_element_to_coefficient_map().size(), 4);
EXPECT_PRED2(
ExprEqual,
p5.basis_element_to_coefficient_map().at(ChebyshevBasisElement()),
Expression(3));
EXPECT_PRED2(
ExprEqual,
p5.basis_element_to_coefficient_map().at(ChebyshevBasisElement(var_x_)),
Expression(2));
EXPECT_PRED2(ExprEqual,
p5.basis_element_to_coefficient_map().at(
ChebyshevBasisElement(var_x_, 2)),
Expression(4));
EXPECT_PRED2(ExprEqual,
p5.basis_element_to_coefficient_map().at(
ChebyshevBasisElement(var_x_, 3)),
Expression(3));
// 2Tβ(x)+1=8xΒ³β6x+1
// Note that although the polynomial contains a term 6x, when represented by
// Chebyshev basis, it doesn't contain Tβ(x) (The coefficient for Tβ(x) is 0).
const GenericPolynomial<ChebyshevBasisElement> p6(8 * pow(var_x_, 3) -
6 * x_ + 1);
EXPECT_EQ(p6.basis_element_to_coefficient_map().size(), 2);
EXPECT_PRED2(ExprEqual,
p6.basis_element_to_coefficient_map().at(
ChebyshevBasisElement(var_x_, 3)),
Expression(2));
EXPECT_PRED2(
ExprEqual,
p6.basis_element_to_coefficient_map().at(ChebyshevBasisElement()),
Expression(1));
}
TEST_F(SymbolicGenericPolynomialTest,
ConstructFromExpressionIndeterminatesMonomialBasis) {
// Test constructing GenericPolynomial<MonomialBasisElement> from expression
// and indeterminates
// e=aΒ²xΒ²+(a+b)xyΒ²+c, indeterminates = {x, y, z}.
const GenericPolynomial<MonomialBasisElement> p1(
pow(var_a_, 2) * pow(var_x_, 2) + (a_ + b_) * var_x_ * pow(var_y_, 2) +
c_,
indeterminates_);
EXPECT_EQ(p1.basis_element_to_coefficient_map().size(), 3);
EXPECT_EQ(p1.indeterminates(), indeterminates_);
EXPECT_EQ(p1.decision_variables(), Variables({var_a_, var_b_, var_c_}));
EXPECT_PRED2(
ExprEqual,
p1.basis_element_to_coefficient_map().at(MonomialBasisElement(var_x_, 2)),
pow(var_a_, 2));
EXPECT_PRED2(ExprEqual,
p1.basis_element_to_coefficient_map().at(
MonomialBasisElement({{var_x_, 1}, {var_y_, 2}})),
a_ + b_);
EXPECT_PRED2(ExprEqual,
p1.basis_element_to_coefficient_map().at(MonomialBasisElement()),
c_);
}
TEST_F(SymbolicGenericPolynomialTest,
ConstructFromExpressionIndeterminatesChebyshevBasis) {
// Test constructing GenericPolynomial<ChebyshevBasisElement> from expression
// and indeterminates.
// e=aTβ(x)+(a+b)Tβ(x)Tβ(y)+cTβ(), indeterminates={x, y, z}.
const GenericPolynomial<ChebyshevBasisElement> p1(
a_ * (2 * pow(var_x_, 2) - 1) +
(a_ + b_) * x_ * (2 * pow(var_y_, 2) - 1) + c_,
indeterminates_);
EXPECT_EQ(p1.basis_element_to_coefficient_map().size(), 3);
EXPECT_EQ(p1.indeterminates(), indeterminates_);
EXPECT_EQ(p1.decision_variables(), Variables({var_a_, var_b_, var_c_}));
EXPECT_PRED2(ExprEqual,
p1.basis_element_to_coefficient_map().at(
ChebyshevBasisElement(var_x_, 2)),
a_);
EXPECT_PRED2(ExprEqual,
p1.basis_element_to_coefficient_map()
.at(ChebyshevBasisElement({{var_x_, 1}, {var_y_, 2}}))
.Expand(),
a_ + b_);
EXPECT_PRED2(
ExprEqual,
p1.basis_element_to_coefficient_map().at(ChebyshevBasisElement()), c_);
}
TEST_F(SymbolicGenericPolynomialTest,
ConstructFromExpressionExpandMonomialBasis) {
// Expression -------------------> Polynomial
// | .Expand() | .ToExpression()
// \/ \/
// Expanded Expression == Expression
for (const Expression& e : exprs_) {
const Expression expanded_expr{e.Expand()};
const Expression expr_from_polynomial{
GenericPolynomial<MonomialBasisElement>{e}.ToExpression()};
EXPECT_PRED2(ExprEqual, expanded_expr, expr_from_polynomial);
}
}
TEST_F(SymbolicGenericPolynomialTest,
ConstructFromExpressionExpandChebyshevBasis) {
// Expression -------------------> Polynomial
// | .Expand() | .ToExpression()
// \/ \/
// Expanded Expression == Expression
for (const Expression& e : exprs_) {
const Expression expanded_expr{e.Expand()};
const Expression expr_from_polynomial{
GenericPolynomial<ChebyshevBasisElement>{e}.ToExpression()};
EXPECT_PRED2(ExprEqual, expanded_expr, expr_from_polynomial);
}
}
TEST_F(SymbolicGenericPolynomialTest,
ConstructorFromExpressionAndIndeterminates1) {
const GenericPolynomial<MonomialBasisElement> p1{1.0, var_xyz_}; // pβ = 1.0,
EXPECT_EQ(p1.basis_element_to_coefficient_map(),
GenericPolynomial<MonomialBasisElement>::MapType(
{{MonomialBasisElement{}, Expression(1.0)}}));
// pβ = ax + by + cz + 10
const GenericPolynomial<MonomialBasisElement> p2{
a_ * x_ + b_ * y_ + c_ * z_ + 10, var_xyz_};
EXPECT_EQ(p2.basis_element_to_coefficient_map(),
GenericPolynomial<MonomialBasisElement>::MapType(
{{MonomialBasisElement{var_x_}, a_},
{MonomialBasisElement{var_y_}, b_},
{MonomialBasisElement{var_z_}, c_},
{MonomialBasisElement{}, 10}}));
// pβ = 3abΒ²*xΒ²y -bc*zΒ³ + bΒ²
const GenericPolynomial<MonomialBasisElement> p3{
3 * a_ * pow(b_, 2) * pow(x_, 2) * y_ - b_ * c_ * pow(z_, 3) + pow(b_, 2),
var_xyz_};
EXPECT_EQ(p3.basis_element_to_coefficient_map(),
GenericPolynomial<MonomialBasisElement>::MapType(
// xΒ²y β¦ 3abΒ²
{{MonomialBasisElement{{{var_x_, 2}, {var_y_, 1}}},
3 * a_ * pow(b_, 2)},
// zΒ³ β¦ -bc
{MonomialBasisElement{{{var_z_, 3}}}, -b_ * c_},
// 1 β¦ bΒ²
{MonomialBasisElement(), pow(b_, 2)}}));
// pβ = 3abΒ²*xΒ²y - bc*xΒ³
const GenericPolynomial<MonomialBasisElement> p4{
3 * a_ * pow(b_, 2) * pow(x_, 2) * y_ - b_ * c_ * pow(x_, 3), var_xyz_};
EXPECT_EQ(p4.basis_element_to_coefficient_map(),
GenericPolynomial<MonomialBasisElement>::MapType(
{{MonomialBasisElement{{{var_x_, 2}, {var_y_, 1}}},
3 * a_ * pow(b_, 2)},
{MonomialBasisElement{{{var_x_, 3}}}, -b_ * c_}}));
// pβ
= (ax)Β³
const GenericPolynomial<MonomialBasisElement> p5{pow(a_ * x_, 3), var_xyz_};
EXPECT_EQ(p5.indeterminates(), var_xyz_);
EXPECT_EQ(p5.basis_element_to_coefficient_map().size(), 1);
EXPECT_EQ(
p5.basis_element_to_coefficient_map().at(MonomialBasisElement(var_x_, 3)),
pow(a_, 3));
}
TEST_F(SymbolicGenericPolynomialTest,
ConstructorFromExpressionAndIndeterminates2) {
const Expression e{x_ * x_ + y_ * y_}; // e = xΒ² + yΒ².
// Show that providing a set of indeterminates {x, y, z} which is a super-set
// of what appeared in `e`, {x, y}, doesn't change the constructed polynomial.
const GenericPolynomial<MonomialBasisElement> p1{e, {var_x_, var_y_}};
const GenericPolynomial<MonomialBasisElement> p2{e, {var_x_, var_y_, var_z_}};
EXPECT_EQ(p1.basis_element_to_coefficient_map(),
p2.basis_element_to_coefficient_map());
}
TEST_F(SymbolicGenericPolynomialTest, DegreeAndTotalDegree) {
const GenericPolynomial<ChebyshevBasisElement> p1(
{{ChebyshevBasisElement({{var_x_, 1}, {var_y_, 2}}), 3 * var_a_ + var_b_},
{ChebyshevBasisElement({{var_x_, 4}}), var_a_ * var_b_}});
EXPECT_EQ(p1.TotalDegree(), 4);
EXPECT_EQ(p1.Degree(var_x_), 4);
EXPECT_EQ(p1.Degree(var_y_), 2);
EXPECT_EQ(p1.Degree(var_z_), 0);
EXPECT_EQ(p1.Degree(var_a_), 0);
}
// Could use the type_visit trick mentioned in the comment
// https://github.com/RobotLocomotion/drake/pull/14053#pullrequestreview-490104889
// to construct these templated tests.
template <typename BasisElement>
void CheckAdditionPolynomialPolynomial(const std::vector<Expression>& exprs,
double tol) {
// (Polynomial(eβ) + Polynomial(eβ)) = Polynomial(eβ + eβ)
for (const Expression& e1 : exprs) {
for (const Expression& e2 : exprs) {
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>,
(GenericPolynomial<BasisElement>{e1} +
GenericPolynomial<BasisElement>{e2}),
GenericPolynomial<BasisElement>(e1 + e2), tol);
}
}
// Test Polynomial& operator+=(Polynomial& c);
for (const Expression& e1 : exprs) {
for (const Expression& e2 : exprs) {
GenericPolynomial<BasisElement> p{e1};
p += GenericPolynomial<BasisElement>{e2};
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>, p,
GenericPolynomial<BasisElement>(e1 + e2, p.indeterminates()),
tol);
}
}
}
TEST_F(SymbolicGenericPolynomialTest,
AdditionPolynomialPolynomialMonomialBasis) {
CheckAdditionPolynomialPolynomial<MonomialBasisElement>(exprs_, 0.);
}
TEST_F(SymbolicGenericPolynomialTest,
AdditionPolynomialPolynomialChebyshevBasis) {
CheckAdditionPolynomialPolynomial<ChebyshevBasisElement>(exprs_, 1E-10);
}
template <typename BasisElement>
void CheckAdditionPolynomialBasisElement(
const std::vector<Expression>& exprs,
const VectorX<BasisElement>& basis_elements) {
// (Polynomial(e) + m).ToExpression() = (e + m.ToExpression()).Expand()
// (m + Polynomial(e)).ToExpression() = (m.ToExpression() + e).Expand()
for (const Expression& e : exprs) {
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m{basis_elements[i]};
EXPECT_PRED2(ExprEqual,
(GenericPolynomial<BasisElement>(e) + m).ToExpression(),
(e + m.ToExpression()).Expand());
EXPECT_PRED2(ExprEqual,
(m + GenericPolynomial<BasisElement>(e)).ToExpression(),
(m.ToExpression() + e).Expand());
}
}
// Test Polynomial& operator+=(const Monomial& m);
for (const Expression& e : exprs) {
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m{basis_elements[i]};
GenericPolynomial<BasisElement> p{e};
p += m;
EXPECT_PRED2(ExprEqual, p.ToExpression(),
(e + m.ToExpression()).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest, AdditionPolynomialMonomial) {
CheckAdditionPolynomialBasisElement<MonomialBasisElement>(exprs_, monomials_);
}
TEST_F(SymbolicGenericPolynomialTest, AdditionPolynomialChebyshevBasisElement) {
CheckAdditionPolynomialBasisElement<ChebyshevBasisElement>(exprs_,
chebyshev_basis_);
}
template <typename BasisElement>
void CheckAdditionPolynomialDouble(const std::vector<Expression>& exprs,
const std::vector<double>& doubles) {
// (Polynomial(e) + c).ToExpression() = (e + c).Expand()
// (c + Polynomial(e)).ToExpression() = (c + e).Expand()
for (const Expression& e : exprs) {
for (const double c : doubles) {
EXPECT_PRED2(ExprEqual,
(GenericPolynomial<BasisElement>(e) + c).ToExpression(),
(e + c).Expand());
EXPECT_PRED2(ExprEqual,
(c + GenericPolynomial<BasisElement>(e)).ToExpression(),
(c + e).Expand());
}
}
// Test Polynomial& operator+=(double c).
for (const Expression& e : exprs) {
for (const double c : doubles) {
GenericPolynomial<BasisElement> p{e};
p += c;
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e + c).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest, AdditionPolynomialDoubleMonomialBasis) {
CheckAdditionPolynomialDouble<MonomialBasisElement>(exprs_, doubles_);
}
TEST_F(SymbolicGenericPolynomialTest, AdditionPolynomialDoubleChebyshevBasis) {
CheckAdditionPolynomialDouble<ChebyshevBasisElement>(exprs_, doubles_);
}
template <typename BasisElement>
void CheckAdditionPolynomialVariable(const std::vector<Expression>& exprs,
const Variables& vars) {
// (Polynomial(e) + v).ToExpression() = (e + v).Expand()
// (v + Polynomial(e)).ToExpression() = (v + e).Expand()
for (const Expression& e : exprs) {
for (const Variable& v : vars) {
EXPECT_PRED2(ExprEqual,
(GenericPolynomial<BasisElement>(e) + v).ToExpression(),
(e + v).Expand());
EXPECT_PRED2(ExprEqual,
(v + GenericPolynomial<BasisElement>(e)).ToExpression(),
(v + e).Expand());
}
}
// Test Polynomial& operator+=(Variable v).
for (const Expression& e : exprs) {
for (const Variable& v : vars) {
GenericPolynomial<BasisElement> p{e};
p += v;
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e + v).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest, AdditionPolynomialVariableMonomialBasis) {
CheckAdditionPolynomialVariable<MonomialBasisElement>(exprs_, var_xyz_);
}
TEST_F(SymbolicGenericPolynomialTest,
AdditionPolynomialVariableChebyshevBasis) {
CheckAdditionPolynomialVariable<ChebyshevBasisElement>(exprs_, var_xyz_);
}
template <typename BasisElement>
void CheckSubtractionPolynomialPolynomial(const std::vector<Expression>& exprs,
double tol) {
// (Polynomial(eβ) - Polynomial(eβ)) = Polynomial(eβ - eβ)
for (const Expression& e1 : exprs) {
for (const Expression& e2 : exprs) {
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>,
GenericPolynomial<BasisElement>{e1} -
GenericPolynomial<BasisElement>{e2},
GenericPolynomial<BasisElement>(e1 - e2), tol);
}
}
// Test Polynomial& operator-=(Polynomial& c);
for (const Expression& e1 : exprs) {
for (const Expression& e2 : exprs) {
GenericPolynomial<BasisElement> p{e1};
p -= GenericPolynomial<BasisElement>{e2};
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>, p,
GenericPolynomial<BasisElement>(e1 - e2), tol);
}
}
}
TEST_F(SymbolicGenericPolynomialTest,
SubtractionPolynomialPolynomialMonomialBasis) {
CheckSubtractionPolynomialPolynomial<MonomialBasisElement>(exprs_, 0.);
}
TEST_F(SymbolicGenericPolynomialTest,
SubtractionPolynomialPolynomialChebyshevBasis) {
CheckSubtractionPolynomialPolynomial<ChebyshevBasisElement>(exprs_, 1E-15);
}
template <typename BasisElement>
void CheckSubtractionPolynomialBasisElement(
const std::vector<Expression>& exprs,
const VectorX<BasisElement>& basis_elements) {
// (Polynomial(e) - m).ToExpression() = (e - m.ToExpression()).Expand()
// (m - Polynomial(e)).ToExpression() = (m.ToExpression() - e).Expand()
for (const Expression& e : exprs) {
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m{basis_elements[i]};
EXPECT_PRED2(ExprEqual,
(GenericPolynomial<BasisElement>(e) - m).ToExpression(),
(e - m.ToExpression()).Expand());
EXPECT_PRED2(ExprEqual,
(m - GenericPolynomial<BasisElement>(e)).ToExpression(),
(m.ToExpression() - e).Expand());
}
}
// Test Polynomial& operator-=(const Monomial& m);
for (const Expression& e : exprs) {
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m{basis_elements[i]};
GenericPolynomial<BasisElement> p{e};
p -= m;
EXPECT_PRED2(ExprEqual, p.ToExpression(),
(e - m.ToExpression()).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest, SubtractionPolynomialMonomial) {
CheckSubtractionPolynomialBasisElement(exprs_, monomials_);
}
TEST_F(SymbolicGenericPolynomialTest, SubtractionPolynomialChebyshev) {
CheckSubtractionPolynomialBasisElement(exprs_, chebyshev_basis_);
}
template <typename BasisElement>
void CheckSubtractionPolynomialDouble(const std::vector<Expression>& exprs,
const std::vector<double>& doubles) {
// (Polynomial(e) - c).ToExpression() = (e - c).Expand()
// (c - Polynomial(e)).ToExpression() = (c - e).Expand()
for (const Expression& e : exprs) {
for (const double c : doubles) {
EXPECT_PRED2(ExprEqual,
(GenericPolynomial<BasisElement>(e) - c).ToExpression(),
(e - c).Expand());
EXPECT_PRED2(ExprEqual,
(c - GenericPolynomial<BasisElement>(e)).ToExpression(),
(c - e).Expand());
}
}
// Test Polynomial& operator-=(double c).
for (const Expression& e : exprs) {
for (const double c : doubles) {
GenericPolynomial<BasisElement> p{e};
p -= c;
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e - c).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest,
SubtractionPolynomialDoubleMonomialBasis) {
CheckSubtractionPolynomialDouble<MonomialBasisElement>(exprs_, doubles_);
}
TEST_F(SymbolicGenericPolynomialTest,
SubtractionPolynomialDoubleChebyshevBasis) {
CheckSubtractionPolynomialDouble<ChebyshevBasisElement>(exprs_, doubles_);
}
template <typename BasisElement>
void CheckSubtractionBasisElementBasisElement(
const VectorX<BasisElement>& basis_elements) {
// (m1 - m2).ToExpression().Expand() = (m1.ToExpression() -
// m2.ToExpression()).Expand()
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m_i{basis_elements[i]};
for (int j = 0; j < basis_elements.size(); ++j) {
const BasisElement& m_j{basis_elements[j]};
EXPECT_PRED2(ExprEqual, (m_i - m_j).ToExpression().Expand(),
(m_i.ToExpression() - m_j.ToExpression()).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest, SubtractionMonomialMonomial) {
CheckSubtractionBasisElementBasisElement(monomials_);
}
TEST_F(SymbolicGenericPolynomialTest, SubtractionChebyshevChebyshev) {
CheckSubtractionBasisElementBasisElement(chebyshev_basis_);
}
template <typename BasisElement>
void CheckSubtractionBasisElementDouble(
const VectorX<BasisElement>& basis_elements,
const std::vector<double>& doubles) {
// (m - c).ToExpression() = m.ToExpression() - c
// (c - m).ToExpression() = c - m.ToExpression()
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m{basis_elements[i]};
for (const double c : doubles) {
EXPECT_PRED2(ExprEqual, (m - c).ToExpression().Expand(),
(m.ToExpression() - c).Expand());
EXPECT_PRED2(ExprEqual, (c - m).ToExpression().Expand(),
(c - m.ToExpression()).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest, SubtractionMonomialDouble) {
CheckSubtractionBasisElementDouble(monomials_, doubles_);
}
TEST_F(SymbolicGenericPolynomialTest, SubtractionChebyshevDouble) {
CheckSubtractionBasisElementDouble(chebyshev_basis_, doubles_);
}
template <typename BasisElement>
void CheckUnaryMinus(const std::vector<Expression>& exprs) {
// (-Polynomial(e)).ToExpression() = -(e.Expand())
for (const Expression& e : exprs) {
EXPECT_PRED2(ExprEqual,
(-GenericPolynomial<BasisElement>(e)).ToExpression(),
-(e.Expand()));
}
}
TEST_F(SymbolicGenericPolynomialTest, UnaryMinusMonomialBasis) {
CheckUnaryMinus<MonomialBasisElement>(exprs_);
}
TEST_F(SymbolicGenericPolynomialTest, UnaryMinusChebyshevBasis) {
CheckUnaryMinus<ChebyshevBasisElement>(exprs_);
}
template <typename BasisElement>
void CheckMultiplicationPolynomialPolynomial(
const std::vector<Expression>& exprs, double tol) {
// (Polynomial(eβ) * Polynomial(eβ)) = Polynomial(eβ * eβ)
for (const Expression& e1 : exprs) {
for (const Expression& e2 : exprs) {
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>,
(GenericPolynomial<BasisElement>{e1} *
GenericPolynomial<BasisElement>{e2}),
GenericPolynomial<BasisElement>(e1 * e2), tol);
}
}
// Test Polynomial& operator*=(Polynomial& c);
for (const Expression& e1 : exprs) {
for (const Expression& e2 : exprs) {
GenericPolynomial<BasisElement> p{e1};
p *= GenericPolynomial<BasisElement>{e2};
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>, p,
GenericPolynomial<BasisElement>(e1 * e2), tol);
}
}
}
TEST_F(SymbolicGenericPolynomialTest,
MultiplicationPolynomialPolynomialMonoialBasis1) {
CheckMultiplicationPolynomialPolynomial<MonomialBasisElement>(exprs_, 1E-12);
}
TEST_F(SymbolicGenericPolynomialTest,
MultiplicationPolynomialPolynomialChebyshev1) {
CheckMultiplicationPolynomialPolynomial<ChebyshevBasisElement>(exprs_, 1E-12);
}
template <typename BasisElement>
void CheckMultiplicationPolynomialBasisElement(
const std::vector<Expression>& exprs,
const VectorX<BasisElement>& basis_elements, double tol) {
// (Polynomial(e) * m) = Polynomial(e * m)
// (m * Polynomial(e)) = Polynomial(m * e)
for (const Expression& e : exprs) {
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m{basis_elements[i]};
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>,
GenericPolynomial<BasisElement>(e) * m,
GenericPolynomial<BasisElement>(e * m.ToExpression()), tol);
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>,
GenericPolynomial<BasisElement>(m.ToExpression() * e),
m * GenericPolynomial<BasisElement>(e), tol);
}
}
// Test Polynomial& operator*=(const BasisElement& m);
for (const Expression& e : exprs) {
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m{basis_elements[i]};
GenericPolynomial<BasisElement> p{e};
p *= m;
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>, p,
GenericPolynomial<BasisElement>(e * m.ToExpression()), tol);
}
}
}
TEST_F(SymbolicGenericPolynomialTest, MultiplicationPolynomialMonomial) {
CheckMultiplicationPolynomialBasisElement<MonomialBasisElement>(
exprs_, monomials_, 0.);
}
TEST_F(SymbolicGenericPolynomialTest, MultiplicationPolynomialChebyshev) {
CheckMultiplicationPolynomialBasisElement<ChebyshevBasisElement>(
exprs_, chebyshev_basis_, 1E-15);
}
template <typename BasisElement>
void CheckMultiplicationPolynomialDouble(const std::vector<Expression>& exprs,
const std::vector<double>& doubles) {
// (Polynomial(e) * c).ToExpression() = (e * c).Expand()
// (c * Polynomial(e)).ToExpression() = (c * e).Expand()
for (const Expression& e : exprs) {
for (const double c : doubles) {
EXPECT_PRED2(ExprEqual,
(GenericPolynomial<BasisElement>(e) * c).ToExpression(),
(e * c).Expand());
EXPECT_PRED2(ExprEqual,
(c * GenericPolynomial<BasisElement>(e)).ToExpression(),
(c * e).Expand());
}
}
// Test Polynomial& operator*=(double c).
for (const Expression& e : exprs) {
for (const double c : doubles) {
GenericPolynomial<BasisElement> p{e};
p *= c;
EXPECT_PRED2(ExprEqual, p.ToExpression(), (e * c).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest,
MultiplicationPolynomialDoubleMonomialBasis) {
CheckMultiplicationPolynomialDouble<MonomialBasisElement>(exprs_, doubles_);
}
TEST_F(SymbolicGenericPolynomialTest,
MultiplicationPolynomialDoubleChebyshevBasis) {
CheckMultiplicationPolynomialDouble<ChebyshevBasisElement>(exprs_, doubles_);
}
template <typename BasisElement>
void CheckMultiplicationBasisElementDouble(
const VectorX<BasisElement>& basis_elements,
const std::vector<double>& doubles) {
// (m * c).ToExpression() = (m.ToExpression() * c).Expand()
// (c * m).ToExpression() = (c * m.ToExpression()).Expand()
for (int i = 0; i < basis_elements.size(); ++i) {
const BasisElement& m{basis_elements[i]};
for (const double c : doubles) {
EXPECT_PRED2(ExprEqual, (m * c).ToExpression(),
(m.ToExpression() * c).Expand());
EXPECT_PRED2(ExprEqual, (c * m).ToExpression(),
(c * m.ToExpression()).Expand());
}
}
}
TEST_F(SymbolicGenericPolynomialTest, MultiplicationMonomialDouble) {
CheckMultiplicationBasisElementDouble(monomials_, doubles_);
}
TEST_F(SymbolicGenericPolynomialTest, MultiplicationChebyshevDouble) {
CheckMultiplicationBasisElementDouble(chebyshev_basis_, doubles_);
}
TEST_F(SymbolicGenericPolynomialTest,
MultiplicationPolynomialPolynomialMonomialBasis2) {
// Evaluates (1 + x) * (1 - x) to confirm that the cross term 0 * x is
// erased from the product.
const GenericPolynomial<MonomialBasisElement> p1(1 + x_);
const GenericPolynomial<MonomialBasisElement> p2(1 - x_);
GenericPolynomial<MonomialBasisElement>::MapType product_map_expected{};
product_map_expected.emplace(MonomialBasisElement(), 1);
product_map_expected.emplace(MonomialBasisElement(var_x_, 2), -1);
EXPECT_EQ(product_map_expected, (p1 * p2).basis_element_to_coefficient_map());
}
TEST_F(SymbolicGenericPolynomialTest,
MultiplicationPolynomialPolynomialChebyshevBasis2) {
// Evaluates (1 + x) * (1 - x) to confirm that the cross term 0 * x is
// erased from the product.
const GenericPolynomial<ChebyshevBasisElement> p1(1 + x_);
const GenericPolynomial<ChebyshevBasisElement> p2(1 - x_);
GenericPolynomial<ChebyshevBasisElement>::MapType product_map_expected{};
product_map_expected.emplace(ChebyshevBasisElement(), 0.5);
product_map_expected.emplace(ChebyshevBasisElement(var_x_, 2), -0.5);
EXPECT_EQ(product_map_expected, (p1 * p2).basis_element_to_coefficient_map());
}
TEST_F(SymbolicGenericPolynomialTest,
BinaryOperationBetweenPolynomialAndVariableMonomialBasis) {
// p = 2aΒ²xΒ² + 3ax + 7.
const GenericPolynomial<MonomialBasisElement> p{
2 * pow(a_, 2) * pow(x_, 2) + 3 * a_ * x_ + 7, {var_x_}};
const MonomialBasisElement m_x_cube{var_x_, 3};
const MonomialBasisElement m_x_sq{var_x_, 2};
const MonomialBasisElement m_x{var_x_, 1};
const MonomialBasisElement m_one;
// Checks addition.
{
const GenericPolynomial<MonomialBasisElement> result1{p + var_a_};
const GenericPolynomial<MonomialBasisElement> result2{var_a_ + p};
// result1 = 2aΒ²xΒ² + 3ax + (7 + a).
EXPECT_TRUE(result1.EqualTo(result2));
EXPECT_EQ(result1.basis_element_to_coefficient_map().size(), 3);
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_PRED2(ExprEqual,
result1.basis_element_to_coefficient_map().at(m_one), 7 + a_);
const GenericPolynomial<MonomialBasisElement> result3{p + var_x_};
const GenericPolynomial<MonomialBasisElement> result4{var_x_ + p};
// result3 = 2aΒ²xΒ² + (3a + 1)x + 7.
EXPECT_TRUE(result3.EqualTo(result4));
EXPECT_EQ(result3.basis_element_to_coefficient_map().size(), 3);
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_PRED2(ExprEqual, result3.basis_element_to_coefficient_map().at(m_x),
3 * a_ + 1);
}
// Checks subtraction.
{
const GenericPolynomial<MonomialBasisElement> result1{p - var_a_};
// result1 = 2aΒ²xΒ² + 3ax + (7 - a).
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_EQ(result1.basis_element_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual,
result1.basis_element_to_coefficient_map().at(m_one), 7 - a_);
const GenericPolynomial<MonomialBasisElement> result2{var_a_ - p};
EXPECT_TRUE((-result2).EqualTo(result1));
const GenericPolynomial<MonomialBasisElement> result3{p - var_x_};
// result3 = 2aΒ²xΒ² + (3a - 1)x + 7.
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_EQ(result3.basis_element_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual, result3.basis_element_to_coefficient_map().at(m_x),
3 * a_ - 1);
const GenericPolynomial<MonomialBasisElement> result4{var_x_ - p};
EXPECT_TRUE((-result4).EqualTo(result3));
}
// Checks multiplication.
{
const GenericPolynomial<MonomialBasisElement> result1{p * var_a_};
// result1 = 2aΒ³xΒ² + 3aΒ²x + 7a.
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_EQ(result1.basis_element_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual,
result1.basis_element_to_coefficient_map().at(m_x_sq),
2 * pow(a_, 3));
EXPECT_PRED2(ExprEqual, result1.basis_element_to_coefficient_map().at(m_x),
3 * pow(a_, 2));
EXPECT_PRED2(ExprEqual,
result1.basis_element_to_coefficient_map().at(m_one), 7 * a_);
const GenericPolynomial<MonomialBasisElement> result2{var_a_ * p};
EXPECT_TRUE(result2.EqualTo(result1));
const GenericPolynomial<MonomialBasisElement> result3{p * var_x_};
// result3 = 2aΒ²xΒ³ + 3axΒ² + 7x.
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_EQ(result3.basis_element_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual,
result3.basis_element_to_coefficient_map().at(m_x_cube),
2 * pow(a_, 2));
EXPECT_PRED2(ExprEqual,
result3.basis_element_to_coefficient_map().at(m_x_sq), 3 * a_);
EXPECT_PRED2(ExprEqual, result3.basis_element_to_coefficient_map().at(m_x),
7);
const GenericPolynomial<MonomialBasisElement> result4{var_x_ * p};
EXPECT_TRUE(result4.EqualTo(result3));
}
}
TEST_F(SymbolicGenericPolynomialTest,
BinaryOperationBetweenPolynomialAndVariableChebyshevBasis) {
// p = 2aΒ²Tβ(x)+3aTβ(x)+7Tβ()
const GenericPolynomial<ChebyshevBasisElement> p{
{{ChebyshevBasisElement(var_x_, 2), 2 * pow(a_, 2)},
{ChebyshevBasisElement(var_x_), 3 * a_},
{ChebyshevBasisElement(), 7}}};
const ChebyshevBasisElement t_x_cube{var_x_, 3};
const ChebyshevBasisElement t_x_sq{var_x_, 2};
const ChebyshevBasisElement t_x{var_x_, 1};
const ChebyshevBasisElement t_zero;
// Checks addition.
{
const GenericPolynomial<ChebyshevBasisElement> result1{p + var_a_};
const GenericPolynomial<ChebyshevBasisElement> result2{var_a_ + p};
// result1 = 2aΒ²Tβ(x)+3aTβ(x)+(7+a)Tβ()
EXPECT_TRUE(result1.EqualTo(result2));
EXPECT_EQ(result1.basis_element_to_coefficient_map().size(), 3);
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_PRED2(ExprEqual,
result1.basis_element_to_coefficient_map().at(t_zero), 7 + a_);
const GenericPolynomial<ChebyshevBasisElement> result3{p + var_x_};
const GenericPolynomial<ChebyshevBasisElement> result4{var_x_ + p};
// result3 = 2aΒ²Tβ(x)+(3a + 1) Tβ(x)+7Tβ()
EXPECT_TRUE(result3.EqualTo(result4));
EXPECT_EQ(result3.basis_element_to_coefficient_map().size(), 3);
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_PRED2(ExprEqual, result3.basis_element_to_coefficient_map().at(t_x),
3 * a_ + 1);
}
// Checks subtraction.
{
const GenericPolynomial<ChebyshevBasisElement> result1{p - var_a_};
// result1 = 2aΒ²Tβ(x)+3aTβ(x)+(7-a)Tβ()
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_EQ(result1.basis_element_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual,
result1.basis_element_to_coefficient_map().at(t_zero), 7 - a_);
const GenericPolynomial<ChebyshevBasisElement> result2{var_a_ - p};
EXPECT_TRUE((-result2).EqualTo(result1));
const GenericPolynomial<ChebyshevBasisElement> result3{p - var_x_};
// result3 = 2aΒ²Tβ(x)+(3a-1)Tβ(x)+7Tβ()
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_EQ(result3.basis_element_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual, result3.basis_element_to_coefficient_map().at(t_x),
3 * a_ - 1);
const GenericPolynomial<ChebyshevBasisElement> result4{var_x_ - p};
EXPECT_TRUE((-result4).EqualTo(result3));
}
// Checks multiplication.
{
const GenericPolynomial<ChebyshevBasisElement> result1{p * var_a_};
// result1 = 2aΒ³Tβ(x)+3aΒ²Tβ(x)+7aTβ()
EXPECT_EQ(result1.indeterminates(), p.indeterminates());
EXPECT_EQ(result1.basis_element_to_coefficient_map().size(), 3);
EXPECT_PRED2(ExprEqual,
result1.basis_element_to_coefficient_map().at(t_x_sq),
2 * pow(a_, 3));
EXPECT_PRED2(ExprEqual, result1.basis_element_to_coefficient_map().at(t_x),
3 * pow(a_, 2));
EXPECT_PRED2(ExprEqual,
result1.basis_element_to_coefficient_map().at(t_zero), 7 * a_);
const GenericPolynomial<ChebyshevBasisElement> result2{var_a_ * p};
EXPECT_TRUE(result2.EqualTo(result1));
const GenericPolynomial<ChebyshevBasisElement> result3{p * var_x_};
// result3 = aΒ²Tβ(x)+1.5aTβ(x)+(7+aΒ²)Tβ(x)+1.5aTβ()
EXPECT_EQ(result3.indeterminates(), p.indeterminates());
EXPECT_EQ(result3.basis_element_to_coefficient_map().size(), 4);
EXPECT_PRED2(ExprEqual,
result3.basis_element_to_coefficient_map().at(t_x_cube),
pow(a_, 2));
EXPECT_PRED2(ExprEqual,
result3.basis_element_to_coefficient_map().at(t_x_sq),
1.5 * a_);
EXPECT_PRED2(ExprEqual, result3.basis_element_to_coefficient_map().at(t_x),
7 + pow(a_, 2));
EXPECT_PRED2(ExprEqual,
result3.basis_element_to_coefficient_map().at(t_zero),
1.5 * a_);
const GenericPolynomial<ChebyshevBasisElement> result4{var_x_ * p};
EXPECT_TRUE(result4.EqualTo(result3));
}
}
template <typename BasisElement>
void TestPow(const std::vector<symbolic::Expression>& exprs, double tol) {
for (int n = 2; n <= 5; ++n) {
for (const Expression& e : exprs) {
const GenericPolynomial<BasisElement> p(e);
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>, pow(p, n),
GenericPolynomial<BasisElement>(pow(e, n)), tol);
}
}
}
TEST_F(SymbolicGenericPolynomialTest, Pow) {
// Test negative power
DRAKE_EXPECT_THROWS_MESSAGE(
pow(GenericPolynomial<MonomialBasisElement>(2 * x_), -1),
".*the degree should be non-negative.*");
// Test power of 0 degree.
auto result = pow(GenericPolynomial<ChebyshevBasisElement>(2 * x_), 0);
EXPECT_EQ(result.basis_element_to_coefficient_map().size(), 1);
EXPECT_EQ(
result.basis_element_to_coefficient_map().at(ChebyshevBasisElement()), 1);
// Test power of 1 degree.
result = pow(GenericPolynomial<ChebyshevBasisElement>(2 * x_), 1);
EXPECT_PRED2(test::GenericPolyEqual<ChebyshevBasisElement>, result,
GenericPolynomial<ChebyshevBasisElement>(2 * x_));
// Test higher degrees.
TestPow<MonomialBasisElement>(exprs_, 1E-14);
TestPow<ChebyshevBasisElement>(exprs_, 1E-14);
}
template <typename BasisElement>
void CheckDivideByConstant(const std::vector<Expression>& exprs, double tol) {
for (double v = -5.5; v <= 5.5; v += 1.0) {
for (const Expression& e : exprs) {
EXPECT_PRED3(test::GenericPolyAlmostEqual<BasisElement>,
GenericPolynomial<BasisElement>(e) / v,
GenericPolynomial<BasisElement>(e / v), tol);
}
}
}
TEST_F(SymbolicGenericPolynomialTest, DivideByConstant) {
CheckDivideByConstant<MonomialBasisElement>(exprs_, 0.);
CheckDivideByConstant<ChebyshevBasisElement>(exprs_, 1E-15);
}
TEST_F(SymbolicGenericPolynomialTest, DifferentiateForMonomialBasis) {
// p = 2aΒ²bxΒ² + 3bcΒ²x + 7ac.
const GenericPolynomial<MonomialBasisElement> p{
{{MonomialBasisElement(var_x_, 2), 2 * pow(a_, 2) * b_},
{MonomialBasisElement(var_x_), 3 * b_ * pow(c_, 2)},
{MonomialBasisElement(), 7 * a_ * c_}}};
// d/dx p = 4aΒ²bx + 3bcΒ²
const GenericPolynomial<MonomialBasisElement> p_x{
{{MonomialBasisElement(var_x_), 4 * pow(a_, 2) * b_},
{MonomialBasisElement(), 3 * b_ * pow(c_, 2)}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, p.Differentiate(var_x_),
p_x);
// d/dy p = 0
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, p.Differentiate(var_y_),
GenericPolynomial<MonomialBasisElement>());
// d/da p = 4abxΒ² + 7c
const GenericPolynomial<MonomialBasisElement> p_a{
{{MonomialBasisElement(var_x_, 2), 4 * a_ * b_},
{MonomialBasisElement(), 7 * c_}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, p.Differentiate(var_a_),
p_a);
// d/db p = 2aΒ²xΒ² + 3cΒ²x
const GenericPolynomial<MonomialBasisElement> p_b{
{{MonomialBasisElement(var_x_, 2), 2 * pow(a_, 2)},
{MonomialBasisElement(var_x_), 3 * pow(c_, 2)}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, p.Differentiate(var_b_),
p_b);
// d/dc p = 6bcx + 7a
const GenericPolynomial<MonomialBasisElement> p_c{
{{MonomialBasisElement(var_x_), 6 * b_ * c_},
{MonomialBasisElement(), 7 * a_}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, p.Differentiate(var_c_),
p_c);
}
TEST_F(SymbolicGenericPolynomialTest, DifferentiateForChebyshevBasis1) {
// p = 2aΒ²bTβ(x)Tβ(y) + 3acTβ(y)
const GenericPolynomial<ChebyshevBasisElement> p{
{{ChebyshevBasisElement({{var_x_, 1}, {var_y_, 3}}), 2 * pow(a_, 2) * b_},
{ChebyshevBasisElement(var_y_, 2), 3 * a_ * c_}}};
// dp/dx = 2aΒ²bTβ(y)
const GenericPolynomial<ChebyshevBasisElement> p_x{
{{ChebyshevBasisElement(var_y_, 3), 2 * pow(a_, 2) * b_}}};
EXPECT_PRED2(GenericPolyEqual<ChebyshevBasisElement>, p.Differentiate(var_x_),
p_x);
// dp/dy = 6aΒ²bTβ(x) + 12aΒ²bTβ(x)Tβ(y) + 12acTβ(y)
const GenericPolynomial<ChebyshevBasisElement> p_y(
{{ChebyshevBasisElement(var_x_), 6 * pow(a_, 2) * b_},
{ChebyshevBasisElement({{var_x_, 1}, {var_y_, 2}}),
12 * pow(a_, 2) * b_},
{ChebyshevBasisElement(var_y_), 12 * a_ * c_}});
EXPECT_PRED2(GenericPolyEqual<ChebyshevBasisElement>, p.Differentiate(var_y_),
p_y);
// dp/dz = 0
EXPECT_PRED2(GenericPolyEqual<ChebyshevBasisElement>, p.Differentiate(var_z_),
GenericPolynomial<ChebyshevBasisElement>(nullptr));
// dp/da = 4abTβ(x)Tβ(y)+3cTβ(y)
const GenericPolynomial<ChebyshevBasisElement> p_a(
{{ChebyshevBasisElement({{var_x_, 1}, {var_y_, 3}}), 4 * a_ * b_},
{ChebyshevBasisElement(var_y_, 2), 3 * c_}});
EXPECT_PRED2(GenericPolyEqual<ChebyshevBasisElement>, p.Differentiate(var_a_),
p_a);
}
TEST_F(SymbolicGenericPolynomialTest, DifferentiateForChebyshevBasis2) {
// p = aTβ(x)+aTβ(x)+aΒ²Tβ(x)
// Notice that dTβ(x)/dx, dTβ(x)/dx and dTβ(x)/dx would all produce results
// containing Tβ(x) (or Tβ(x) and Tβ(x)).
const GenericPolynomial<ChebyshevBasisElement> p(
{{ChebyshevBasisElement(var_x_), a_},
{ChebyshevBasisElement(var_x_, 2), a_},
{ChebyshevBasisElement(var_x_, 3), pow(a_, 2)}});
// dp/dx = (a+3aΒ²)Tβ(x) + 4aTβ(x) + 6aΒ²Tβ(x)
const GenericPolynomial<ChebyshevBasisElement> p_x(
{{ChebyshevBasisElement(nullptr), a_ + 3 * pow(a_, 2)},
{ChebyshevBasisElement(var_x_), 4 * a_},
{ChebyshevBasisElement(var_x_, 2), 6 * pow(a_, 2)}});
EXPECT_PRED2(GenericPolyEqual<ChebyshevBasisElement>, p.Differentiate(var_x_),
p_x);
// dp/da =Tβ(x)+Tβ(x)+2aTβ(x)
const GenericPolynomial<ChebyshevBasisElement> p_a(
{{ChebyshevBasisElement(var_x_), 1},
{ChebyshevBasisElement(var_x_, 2), 1},
{ChebyshevBasisElement(var_x_, 3), 2 * a_}});
EXPECT_PRED2(GenericPolyEqual<ChebyshevBasisElement>, p.Differentiate(var_a_),
p_a);
}
TEST_F(SymbolicGenericPolynomialTest, Jacobian) {
// p = axΒ²y + (3a+b)xzΒ²
const GenericPolynomial<MonomialBasisElement> p{
{{MonomialBasisElement({{var_x_, 2}, {var_y_, 1}}), a_},
{MonomialBasisElement({{var_x_, 1}, {var_z_, 2}}), 3 * a_ + b_}}};
const Vector2<Variable> vars_xy(var_x_, var_y_);
const auto J_xy = p.Jacobian(vars_xy);
static_assert(decltype(J_xy)::RowsAtCompileTime == 1 &&
decltype(J_xy)::ColsAtCompileTime == 2,
"The size of J_xy should be 1 x 2.");
// dp/dx = 2axy + (3a+b)zΒ²
const GenericPolynomial<MonomialBasisElement> p_x(
{{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), 2 * a_},
{MonomialBasisElement(var_z_, 2), 3 * a_ + b_}});
// dp/dy = axΒ²
const GenericPolynomial<MonomialBasisElement> p_y(
{{MonomialBasisElement(var_x_, 2), a_}});
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, J_xy(0), p_x);
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, J_xy(1), p_y);
// dp/da = xΒ²y + 3xzΒ²
const GenericPolynomial<MonomialBasisElement> p_a(
{{MonomialBasisElement({{var_x_, 2}, {var_y_, 1}}), 1},
{MonomialBasisElement({{var_x_, 1}, {var_z_, 2}}), 3}});
// dp/db = xzΒ²
const GenericPolynomial<MonomialBasisElement> p_b(
MonomialBasisElement({{var_x_, 1}, {var_z_, 2}}));
const Vector2<Variable> var_ab(var_a_, var_b_);
const auto J_ab = p.Jacobian(var_ab);
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, J_ab(0), p_a);
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, J_ab(1), p_b);
}
TEST_F(SymbolicGenericPolynomialTest, ConstructNonPolynomialCoefficients) {
// Given a pair of Expression and Polynomial::MapType, `(e, map)`, we check
// `Polynomial(e, indeterminates)` has the expected map, `map`.
vector<pair<Expression, GenericPolynomial<MonomialBasisElement>::MapType>>
testcases;
// sin(a)x = sin(a) * x
testcases.emplace_back(sin(a_) * x_,
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{x_}, sin(a_)}}});
// cos(a)(x + 1)Β² = cos(a) * xΒ² + 2cos(a) * x + cos(a) * 1
testcases.emplace_back(cos(a_) * pow(x_ + 1, 2),
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 2}}}, cos(a_)},
{MonomialBasisElement{x_}, 2 * cos(a_)},
{MonomialBasisElement{}, cos(a_)}}});
// log(a)(x + 1)Β² / sqrt(b)
// = log(a)/sqrt(b) * xΒ² + 2log(a)/sqrt(b) * x + log(a)/sqrt(b) * 1
testcases.emplace_back(
log(a_) * pow(x_ + 1, 2) / sqrt(b_),
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 2}}}, log(a_) / sqrt(b_)},
{MonomialBasisElement{x_}, 2 * log(a_) / sqrt(b_)},
{MonomialBasisElement{}, log(a_) / sqrt(b_)}}});
// (tan(a)x + 1)Β²
// = (tan(a))Β² * xΒ² + 2tan(a) * x + 1
testcases.emplace_back(
pow(tan(a_) * x_ + 1, 2),
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 2}}}, pow(tan(a_), 2)},
{MonomialBasisElement{x_}, 2 * tan(a_)},
{MonomialBasisElement{}, 1}}});
// abs(b + 1)x + asin(a) + acos(a) - atan(c) * x
// = (abs(b + 1) - atan(c)) * x + (asin(a) + acos(a))
testcases.emplace_back(
abs(b_ + 1) * x_ + asin(a_) + acos(a_) - atan(c_) * x_,
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{x_}, abs(b_ + 1) - atan(c_)},
{MonomialBasisElement{}, asin(a_) + acos(a_)}}});
// atan(b)x * atan2(a, c)y
// = (atan(b) * atan2(a, c)) * xy
testcases.emplace_back(
abs(b_) * x_ * atan2(a_, c_) * y_,
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 1}, {var_y_, 1}}}, // xy
abs(b_) * atan2(a_, c_)}}});
// (sinh(a)x + cosh(b)y + tanh(c)z) / (5 * min(a, b) * max(b, c))
// = (sinh(a) / (5 * min(a, b) * max(b, c))) * x
// + (cosh(b) / (5 * min(a, b) * max(b, c))) * y
// + (tanh(c) / (5 * min(a, b) * max(b, c))) * z
testcases.emplace_back((sinh(a_) * x_ + cosh(b_) * y_ + tanh(c_) * z_) /
(5 * min(a_, b_) * max(b_, c_)),
GenericPolynomial<MonomialBasisElement>::MapType{
{{
MonomialBasisElement{x_},
sinh(a_) / (5 * min(a_, b_) * max(b_, c_)),
},
{
MonomialBasisElement{y_},
cosh(b_) / (5 * min(a_, b_) * max(b_, c_)),
},
{
MonomialBasisElement{z_},
tanh(c_) / (5 * min(a_, b_) * max(b_, c_)),
}}});
// (ceil(a) * x + floor(b) * y)Β²
// = pow(ceil(a), 2) * xΒ²
// = + 2 * ceil(a) * floor(b) * xy
// = + pow(floor(a), 2) * yΒ²
testcases.emplace_back(
pow(ceil(a_) * x_ + floor(b_) * y_, 2),
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 2}}}, ceil(a_) * ceil(a_)},
{MonomialBasisElement{{{var_x_, 1}, {var_y_, 1}}},
2 * ceil(a_) * floor(b_)},
{MonomialBasisElement{{{var_y_, 2}}}, floor(b_) * floor(b_)}}});
// (ceil(a) * x + floor(b) * y)Β²
// = pow(ceil(a), 2) * xΒ²
// = + 2 * ceil(a) * floor(b) * xy
// = + pow(floor(a), 2) * yΒ²
testcases.emplace_back(
pow(ceil(a_) * x_ + floor(b_) * y_, 2),
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 2}}}, ceil(a_) * ceil(a_)},
{MonomialBasisElement{{{var_x_, 1}, {var_y_, 1}}},
2 * ceil(a_) * floor(b_)},
{MonomialBasisElement{{{var_y_, 2}}}, floor(b_) * floor(b_)}}});
// UF("unnamed1", {a})) * x * UF("unnamed2", {b}) * x
// = UF("unnamed1", {a})) * UF("unnamed2", {b}) * xΒ².
const Expression uf1{uninterpreted_function("unnamed1", {var_a_})};
const Expression uf2{uninterpreted_function("unnamed2", {var_b_})};
testcases.emplace_back(
uf1 * x_ * uf2 * x_,
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 2}}}, uf1 * uf2}}});
// (x + y)Β² = xΒ² + 2xy + yΒ²
testcases.emplace_back(
pow(x_ + y_, 2),
GenericPolynomial<MonomialBasisElement>::MapType{{
{MonomialBasisElement{{{var_x_, 2}}}, 1},
{MonomialBasisElement{{{var_x_, 1}, {var_y_, 1}}}, 2},
{MonomialBasisElement{{{var_y_, 2}}}, 1},
}});
// pow(pow(x, 2.5), 2) = xβ΅
testcases.emplace_back(pow(pow(x_, 2.5), 2),
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 5}}}, 1}}});
// pow(pow(x * y, 2.5), 2) = (xy)β΅
testcases.emplace_back(
pow(pow(x_ * y_, 2.5), 2),
GenericPolynomial<MonomialBasisElement>::MapType{
{{MonomialBasisElement{{{var_x_, 5}, {var_y_, 5}}}, 1}}});
for (const auto& [e, expected_map] : testcases) {
const GenericPolynomial<MonomialBasisElement> p{e, indeterminates_};
EXPECT_EQ(p.basis_element_to_coefficient_map(), expected_map);
}
}
TEST_F(SymbolicGenericPolynomialTest, NegativeTestConstruction1) {
// sin(a) * x is a polynomial.
const Expression e1{sin(a_) * x_};
DRAKE_EXPECT_NO_THROW(
GenericPolynomial<MonomialBasisElement>(e1, indeterminates_));
// sin(x) * x is a not polynomial.
const Expression e2{sin(x_) * x_};
EXPECT_THROW(GenericPolynomial<MonomialBasisElement>(e2, indeterminates_),
runtime_error);
}
TEST_F(SymbolicGenericPolynomialTest, NegativeTestConstruction2) {
// aΛ£ x is not a polynomial.
const Expression e{pow(a_, x_)};
EXPECT_THROW(GenericPolynomial<MonomialBasisElement>(e, indeterminates_),
runtime_error);
}
TEST_F(SymbolicGenericPolynomialTest, NegativeTestConstruction3) {
// xβ»ΒΉ is not a polynomial.
const Expression e{pow(x_, -1)};
EXPECT_THROW(GenericPolynomial<MonomialBasisElement>(e, indeterminates_),
runtime_error);
}
TEST_F(SymbolicGenericPolynomialTest, NegativeTestConstruction4) {
// x^(2.5) is not a polynomial.
const Expression e{pow(x_, 2.5)};
EXPECT_THROW(GenericPolynomial<MonomialBasisElement>(e, indeterminates_),
runtime_error);
}
TEST_F(SymbolicGenericPolynomialTest, NegativeTestConstruction5) {
// xΛ£ is not a polynomial.
const Expression e{pow(x_, x_)};
EXPECT_THROW(GenericPolynomial<MonomialBasisElement>(e, indeterminates_),
runtime_error);
}
TEST_F(SymbolicGenericPolynomialTest, NegativeTestConstruction6) {
// 1 / a is polynomial.
const Expression e1{1 / a_};
DRAKE_EXPECT_NO_THROW(
GenericPolynomial<MonomialBasisElement>(e1, indeterminates_));
// However, 1 / x is not a polynomial.
const Expression e2{1 / x_};
EXPECT_THROW(GenericPolynomial<MonomialBasisElement>(e2, indeterminates_),
runtime_error);
}
TEST_F(SymbolicGenericPolynomialTest, NegativeTestConstruction7) {
// sin(x + a) is not a polynomial.
const Expression e{sin(x_ + a_)};
EXPECT_THROW(GenericPolynomial<MonomialBasisElement>(e, indeterminates_),
runtime_error);
}
TEST_F(SymbolicGenericPolynomialTest, NegativeTestConstruction) {
std::vector<Expression> bad_expressions;
// tan(x) is not a polynomial.
bad_expressions.push_back(tan(x_));
// abs(x + a) is not a polynomial.
bad_expressions.push_back(abs(x_ + a_));
// exp(x + a) is not a polynomial.
bad_expressions.push_back(exp(x_ + a_));
// sqrt(x * x_ + 1) is not a polynomial.
bad_expressions.push_back(sqrt(x_ * x_ + 1));
// atan(x * x_ + 1) is not a polynomial.
bad_expressions.push_back(atan(x_ * x_ + 1));
// atan2(2, x * x_ + 1) is not a polynomial.
bad_expressions.push_back(atan2(2, x_ * x_ + 1));
// sinh(x * x_ + 1) is not a polynomial.
bad_expressions.push_back(sinh(x_ * x_ + 1));
// cosh(x * x_ + 1) is not a polynomial.
bad_expressions.push_back(cosh(x_ * x_ + 1));
// tanh(x * x_ + 1) is not a polynomial.
bad_expressions.push_back(tanh(x_ * x_ + 1));
// min(x * x_ + 1, x_* x_) is not a polynomial.
bad_expressions.push_back(min(x_ * x_ + 1, x_ * x_));
// max(x * x_ + 1, x_* x_) is not a polynomial.
bad_expressions.push_back(max(x_ * x_ + 1, x_ * x_));
// ceil(x * x_ + 1) is not a polynomial.
bad_expressions.push_back(ceil(x_ * x_ + 1));
// floor(x * x_ + 1) is not a polynomial.
bad_expressions.push_back(floor(x_ * x_ + 1));
// IfThenElse(x_, x_, x * x_ + 1) is not a polynomial.
bad_expressions.push_back(if_then_else(x_ > 0, x_, x_ * x_ + 1));
// (sin(x+a))Β³ is not a polynomial.
bad_expressions.push_back(pow(sin(x_ + a_), 3));
// (sin(x))Β³ is not a polynomial.
bad_expressions.push_back(pow(sin(x_), 3));
for (const auto& e : bad_expressions) {
EXPECT_THROW(GenericPolynomial<MonomialBasisElement>(e, indeterminates_),
runtime_error);
}
}
TEST_F(SymbolicGenericPolynomialTest, Evaluate) {
// p = axΒ²y + bxy + cz
const GenericPolynomial<MonomialBasisElement> p{
{{MonomialBasisElement({{var_x_, 2}, {var_y_, 1}}), a_},
{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), b_},
{MonomialBasisElement(var_z_), c_}}};
const Environment env1{{
{var_a_, 1.0},
{var_b_, 2.0},
{var_c_, 3.0},
{var_x_, -1.0},
{var_y_, -2.0},
{var_z_, -3.0},
}};
const double expected1{1.0 * -1.0 * -1.0 * -2.0 + 2.0 * -1.0 * -2.0 +
3.0 * -3.0};
EXPECT_EQ(p.Evaluate(env1), expected1);
const Environment env2{{
{var_a_, 4.0},
{var_b_, 1.0},
{var_c_, 2.0},
{var_x_, -7.0},
{var_y_, -5.0},
{var_z_, -2.0},
}};
const double expected2{4.0 * -7.0 * -7.0 * -5.0 + 1.0 * -7.0 * -5.0 +
2.0 * -2.0};
EXPECT_EQ(p.Evaluate(env2), expected2);
const Environment partial_env{{
{var_a_, 4.0},
{var_c_, 2.0},
{var_x_, -7.0},
{var_z_, -2.0},
}};
double dummy{};
EXPECT_THROW(dummy = p.Evaluate(partial_env), std::invalid_argument);
unused(dummy);
}
TEST_F(SymbolicGenericPolynomialTest, PartialEvaluate1) {
// p1 = a*xΒ² + b*x + c
// p2 = p1[x β¦ 3.0] = 3Β²a + 3b + c.
const GenericPolynomial<MonomialBasisElement> p1{
{{MonomialBasisElement(var_x_, 2), a_},
{MonomialBasisElement(var_x_), b_},
{MonomialBasisElement(), c_}}};
const GenericPolynomial<MonomialBasisElement> p2{
{{MonomialBasisElement(), a_ * 3.0 * 3.0 + b_ * 3.0 + c_}}};
const Environment env{{{var_x_, 3.0}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, p1.EvaluatePartial(env),
p2);
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>,
p1.EvaluatePartial(var_x_, 3.0), p2);
}
TEST_F(SymbolicGenericPolynomialTest, PartialEvaluate2) {
// p1 = a*xyΒ² - a*xy + c
// p2 = p1[y β¦ 2.0] = (4a - 2a)*x + c = 2ax + c
const GenericPolynomial<MonomialBasisElement> p1{
{{MonomialBasisElement({{var_x_, 1}, {var_y_, 2}}), a_},
{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), -a_},
{MonomialBasisElement(), c_}}};
const GenericPolynomial<MonomialBasisElement> p2{
{{MonomialBasisElement(var_x_), 2 * a_}, {MonomialBasisElement(), c_}}};
const Environment env{{{var_y_, 2.0}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, p1.EvaluatePartial(env),
p2);
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>,
p1.EvaluatePartial(var_y_, 2.0), p2);
}
TEST_F(SymbolicGenericPolynomialTest, PartialEvaluate3) {
// p1 = a*xΒ² + b*x + c
// p2 = p1[a β¦ 2.0, x β¦ 3.0] = 2*3Β² + 3b + c
// = 18 + 3b + c
const GenericPolynomial<MonomialBasisElement> p1{
{{MonomialBasisElement(var_x_, 2), a_},
{MonomialBasisElement(var_x_), b_},
{MonomialBasisElement(), c_}}};
const GenericPolynomial<MonomialBasisElement> p2{
{{MonomialBasisElement(), 18 + 3 * b_ + c_}}};
const Environment env{{{var_a_, 2.0}, {var_x_, 3.0}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, p1.EvaluatePartial(env),
p2);
}
TEST_F(SymbolicGenericPolynomialTest, PartialEvaluate4) {
// p = (a + c / b + c)*xΒ² + b*x + c
//
// Partially evaluating p with [a β¦ 0, b β¦ 0, c β¦ 0] throws `runtime_error`
// because of the divide-by-zero
const GenericPolynomial<MonomialBasisElement> p{
{{MonomialBasisElement(var_x_, 2), (a_ + c_) / (b_ + c_)},
{MonomialBasisElement(var_x_), b_},
{MonomialBasisElement(), c_}}};
const Environment env{{{var_a_, 0.0}, {var_b_, 0.0}, {var_c_, 0.0}}};
GenericPolynomial<MonomialBasisElement> dummy;
EXPECT_THROW(dummy = p.EvaluatePartial(env), runtime_error);
}
TEST_F(SymbolicGenericPolynomialTest, EqualTo) {
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>,
GenericPolynomial<MonomialBasisElement>(),
GenericPolynomial<MonomialBasisElement>(nullptr));
EXPECT_PRED2(
GenericPolyEqual<MonomialBasisElement>,
GenericPolynomial<MonomialBasisElement>(MonomialBasisElement(var_x_)),
GenericPolynomial<MonomialBasisElement>(
{{MonomialBasisElement(var_x_), 1}}));
EXPECT_FALSE(
GenericPolynomial<MonomialBasisElement>(MonomialBasisElement(var_x_))
.EqualTo(GenericPolynomial<MonomialBasisElement>(
MonomialBasisElement(var_y_))));
EXPECT_FALSE(
GenericPolynomial<MonomialBasisElement>(MonomialBasisElement(var_x_))
.EqualTo(GenericPolynomial<MonomialBasisElement>(
{{MonomialBasisElement(var_y_), a_}})));
EXPECT_FALSE(GenericPolynomial<MonomialBasisElement>(
{{MonomialBasisElement(var_x_), 1},
{MonomialBasisElement(var_x_, 2), 2}})
.EqualTo(GenericPolynomial<MonomialBasisElement>(
{{MonomialBasisElement(var_x_), 1}})));
EXPECT_FALSE(GenericPolynomial<MonomialBasisElement>(
{{MonomialBasisElement(var_x_), 2},
{MonomialBasisElement(var_x_, 2), 2}})
.EqualTo(GenericPolynomial<MonomialBasisElement>(
{{MonomialBasisElement(var_x_), 1},
{MonomialBasisElement(var_x_, 2), 2}})));
}
TEST_F(SymbolicGenericPolynomialTest, AddProduct1) {
// p = axΒ² + bxy
// p + czΒ² = axΒ² + czΒ² + bxy
// The added term and p doesn't share basis element.
GenericPolynomial<MonomialBasisElement> p(
{{MonomialBasisElement(var_x_, 2), a_},
{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), b_}});
const GenericPolynomial<MonomialBasisElement> sum =
p.AddProduct(c_, MonomialBasisElement(var_z_, 2));
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, sum, p);
const GenericPolynomial<MonomialBasisElement> sum_expected(
{{MonomialBasisElement(var_x_, 2), a_},
{MonomialBasisElement(var_z_, 2), c_},
{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), b_}});
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, sum, sum_expected);
EXPECT_EQ(p.decision_variables(), Variables({var_a_, var_b_, var_c_}));
EXPECT_EQ(p.indeterminates(), Variables({var_x_, var_y_, var_z_}));
}
TEST_F(SymbolicGenericPolynomialTest, AddProduct2) {
// p = ayΒ² + bxy
// p + cxΒ² = (a+c)xΒ² + bxy
// The added term and p shares basis element.
GenericPolynomial<MonomialBasisElement> p(
{{MonomialBasisElement(var_x_, 2), a_},
{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), b_}});
const GenericPolynomial<MonomialBasisElement> sum =
p.AddProduct(c_, MonomialBasisElement(var_x_, 2));
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, sum, p);
const GenericPolynomial<MonomialBasisElement> sum_expected(
{{MonomialBasisElement(var_x_, 2), a_ + c_},
{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), b_}});
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>, sum, sum_expected);
EXPECT_EQ(p.decision_variables(), Variables({var_a_, var_b_, var_c_}));
EXPECT_EQ(p.indeterminates(), Variables({var_x_, var_y_}));
}
template <typename BasisElement>
void CheckHash(const Expression& x, const Expression& y) {
const auto h = std::hash<Polynomial>{};
GenericPolynomial<BasisElement> p1{x * x};
const GenericPolynomial<BasisElement> p2{x * x};
EXPECT_EQ(p1, p2);
EXPECT_EQ(h(p1), h(p2));
p1 += GenericPolynomial<BasisElement>{y};
EXPECT_NE(p1, p2);
EXPECT_NE(h(p1), h(p2));
}
TEST_F(SymbolicGenericPolynomialTest, Hash) {
CheckHash<MonomialBasisElement>(x_, y_);
CheckHash<ChebyshevBasisElement>(x_, y_);
}
TEST_F(SymbolicGenericPolynomialTest, CoefficientsAlmostEqual) {
GenericPolynomial<MonomialBasisElement> p1{x_ * x_};
// Two polynomials with the same number of terms.
EXPECT_TRUE(p1.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{x_ * x_}, 1e-6));
EXPECT_TRUE(p1.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{(1 + 1e-7) * x_ * x_}, 1e-6));
EXPECT_FALSE(p1.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{2 * x_ * x_}, 1e-6));
// Another polynomial with an additional small constant term.
EXPECT_TRUE(p1.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{x_ * x_ + 1e-7}, 1e-6));
EXPECT_FALSE(p1.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{x_ * x_ + 2e-6}, 1e-6));
EXPECT_TRUE(GenericPolynomial<MonomialBasisElement>{x_ * x_ + 1e-7}
.CoefficientsAlmostEqual(p1, 1e-6));
EXPECT_FALSE(GenericPolynomial<MonomialBasisElement>{x_ * x_ + 2e-6}
.CoefficientsAlmostEqual(p1, 1e-6));
// Another polynomial with small difference on coefficients.
EXPECT_TRUE(p1.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{(1. - 1e-7) * x_ * x_ + 1e-7},
1e-6));
EXPECT_FALSE(p1.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{(1. + 2e-6) * x_ * x_ + 1e-7},
1e-6));
// Another polynomial with decision variables in the coefficient.
const symbolic::GenericPolynomial<MonomialBasisElement> p2(a_ * x_ * x_,
{indeterminates_});
EXPECT_TRUE(p2.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{(a_ + 1e-7) * x_ * x_,
{indeterminates_}},
1e-6));
EXPECT_FALSE(p2.CoefficientsAlmostEqual(
GenericPolynomial<MonomialBasisElement>{(a_ + 1e-7) * x_ * x_,
{indeterminates_}},
1e-8));
}
TEST_F(SymbolicGenericPolynomialTest, RemoveTermsWithSmallCoefficients) {
// Single term.
GenericPolynomial<MonomialBasisElement> p1{
{{MonomialBasisElement(var_x_, 2), 1e-5}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>,
p1.RemoveTermsWithSmallCoefficients(1E-4),
GenericPolynomial<MonomialBasisElement>(0));
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>,
p1.RemoveTermsWithSmallCoefficients(1E-5),
GenericPolynomial<MonomialBasisElement>(0));
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>,
p1.RemoveTermsWithSmallCoefficients(1E-6), p1);
// Multiple terms.
const GenericPolynomial<MonomialBasisElement> p2{
{{MonomialBasisElement(var_x_, 2), 2},
{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), 3},
{MonomialBasisElement(var_x_), 1E-4},
{MonomialBasisElement(), -1E-4}}};
const GenericPolynomial<MonomialBasisElement> p2_cleaned{
{{MonomialBasisElement(var_x_, 2), 2},
{MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}), 3}}};
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>,
p2.RemoveTermsWithSmallCoefficients(1E-4), p2_cleaned);
// Coefficients are expressions.
GenericPolynomial<MonomialBasisElement>::MapType p3_map{};
p3_map.emplace(MonomialBasisElement(var_x_, 2), 2 * sin(y_));
p3_map.emplace(MonomialBasisElement(var_x_, 1), 1E-4 * cos(y_));
p3_map.emplace(MonomialBasisElement(var_x_, 3), 1E-4 * y_);
p3_map.emplace(MonomialBasisElement(), 1E-6);
GenericPolynomial<MonomialBasisElement>::MapType p3_expected_map{};
p3_expected_map.emplace(MonomialBasisElement(var_x_, 2), 2 * sin(y_));
p3_expected_map.emplace(MonomialBasisElement(var_x_, 1), 1E-4 * cos(y_));
p3_expected_map.emplace(MonomialBasisElement(var_x_, 3), 1E-4 * y_);
EXPECT_PRED2(GenericPolyEqual<MonomialBasisElement>,
GenericPolynomial<MonomialBasisElement>(p3_map)
.RemoveTermsWithSmallCoefficients(1E-3),
GenericPolynomial<MonomialBasisElement>(p3_expected_map));
}
TEST_F(SymbolicGenericPolynomialTest, EqualToAfterExpansion) {
// Test equal with / without expansion.
const GenericPolynomial<MonomialBasisElement> p1(
{{MonomialBasisElement(var_x_, 2), (a_ + b_) * (a_ + c_)}});
const GenericPolynomial<MonomialBasisElement> p2(
{{MonomialBasisElement(var_x_, 2),
pow(var_a_, 2) + a_ * b_ + a_ * c_ + b_ * c_}});
// No expansion
EXPECT_FALSE(p1.EqualTo(p2));
EXPECT_TRUE(p1.EqualToAfterExpansion(p2));
}
TEST_F(SymbolicGenericPolynomialTest, SetIndeterminates) {
// axΒ² + bx + c
const Expression e{a_ * x_ * x_ + b_ * x_ + c_};
{
// {x} -> {x, a}
// Grow the indeterminates with a variable moves from decision variables
// to indeterminates.
GenericPolynomial<MonomialBasisElement> p{e, {var_x_}};
const Variables new_indeterminates{var_x_, var_a_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(
GenericPolyEqual<MonomialBasisElement>, p,
GenericPolynomial<MonomialBasisElement>(e, new_indeterminates));
}
{
// {x} -> {x, y}, note that y β variables(e).
GenericPolynomial<MonomialBasisElement> p{e, {var_x_}};
const Variables new_indeterminates{var_x_, var_y_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(
GenericPolyEqual<MonomialBasisElement>, p,
GenericPolynomial<MonomialBasisElement>(e, new_indeterminates));
}
{
// {x} -> {x, a, b, c}
GenericPolynomial<MonomialBasisElement> p{e, {var_x_}};
const Variables new_indeterminates{var_x_, var_a_, var_b_, var_c_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(
GenericPolyEqual<MonomialBasisElement>, p,
GenericPolynomial<MonomialBasisElement>(e, new_indeterminates));
}
{
// {x, a} -> {x}
GenericPolynomial<MonomialBasisElement> p{e, {var_x_, var_a_}};
const Variables new_indeterminates{var_x_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(
GenericPolyEqual<MonomialBasisElement>, p,
GenericPolynomial<MonomialBasisElement>(e, new_indeterminates));
}
{
// {x, a} -> {a}
GenericPolynomial<MonomialBasisElement> p{e, {var_x_, var_a_}};
const Variables new_indeterminates{var_a_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(
GenericPolyEqual<MonomialBasisElement>, p,
GenericPolynomial<MonomialBasisElement>(e, new_indeterminates));
}
{
// {x, a, b, c} -> {x}
GenericPolynomial<MonomialBasisElement> p{e,
{var_x_, var_a_, var_b_, var_c_}};
const Variables new_indeterminates{var_x_};
p.SetIndeterminates(new_indeterminates);
EXPECT_PRED2(
GenericPolyEqual<MonomialBasisElement>, p,
GenericPolynomial<MonomialBasisElement>(e, new_indeterminates));
}
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/simplification_test.cc | #include "drake/common/symbolic/simplification.h"
#include <functional>
#include <stdexcept>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
namespace {
using std::function;
using std::runtime_error;
using test::ExprEqual;
class SymbolicUnificationTest : public ::testing::Test {
protected:
// Provides common variables that are used by the following tests.
const Variable x_{"x"};
const Variable y_{"y"};
const Variable z_{"z"};
const Variable a_{"a"};
const Variable b_{"b"};
const Variable c_{"c"};
};
TEST_F(SymbolicUnificationTest, VariableSuccess) {
// Rule: x => x + 1
const RewritingRule rule{x_, x_ + 1};
const Rewriter rewriter = MakeRuleRewriter(rule);
const Expression e1{a_ + b_};
// The `rewriter` matches the whole `a + b` with the LHS of the rule, `x`, and
// generates a substitution, {x β¦ a + b}. Then, it applies the substitution to
// the RHS of the rule, `x + 1`, resulting in `a + b + 1`.
//
// Note that this is *not* a congruence-rewriter which would traverse the
// expression `a + b`, rewrite `a` to `a + 1` and `b` to `b + 1`, and return
// `(a + 1) + (b + 1)`, which is `a + b + 2`.
EXPECT_PRED2(ExprEqual, rewriter(e1), a_ + b_ + 1);
const Expression e2{sin(a_)};
EXPECT_PRED2(ExprEqual, rewriter(e2), sin(a_) + 1);
}
TEST_F(SymbolicUnificationTest, VariableFailure) {
// Rule: pow(x, x) => pow(x + 1, x + 2).
const RewritingRule rule{pow(x_, x_), pow(x_ + 1, x_ + 2)};
const Rewriter rewriter = MakeRuleRewriter(rule);
// Fails to match pow(a, b) with the above rule
// since we can't have x β¦ a and x β¦ b at the same time.
const Expression e{pow(a_, b_)};
EXPECT_PRED2(ExprEqual, rewriter(e), e /* no change */);
}
TEST_F(SymbolicUnificationTest, ConstantSuccess) {
// Rule: 3 => 5.
const RewritingRule rule{3, 5};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites 3 to 5.
const Expression e{3};
EXPECT_PRED2(ExprEqual, rewriter(e), 5);
}
TEST_F(SymbolicUnificationTest, ConstantFailure) {
// Rule: 3 => 5.
const RewritingRule rule{3, 5};
const Rewriter rewriter = MakeRuleRewriter(rule);
// Fails to match 4 with the above rule.
const Expression e{4};
EXPECT_PRED2(ExprEqual, rewriter(e), e /* no change */);
}
TEST_F(SymbolicUnificationTest, AdditionSuccessNonZeroCoeff) {
// Rule: 2 + x + y => 3 + 4x + 5y.
const RewritingRule rule{2 + x_ + y_, 3 + 4 * x_ + 5 * y_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites 2 + 2a + 3b to 3 + 4(2a) + 5(3b).
// Example of Case 4 in UnificationVisitor::VisitAddition.
const Expression e1{2 + 2 * a_ + 3 * b_};
EXPECT_PRED2(ExprEqual, rewriter(e1), 3 + 8 * a_ + 15 * b_);
// It rewrites 2 + 2a + 3b + 5c to 3 + 4(2a) + 5(3b + 5c).
// Example of Case 4 in UnificationVisitor::VisitAddition.
const Expression e2{2 + 2 * a_ + 3 * b_ + 5 * c_};
EXPECT_PRED2(ExprEqual, rewriter(e2), 3 + 4 * 2 * a_ + 5 * (3 * b_ + 5 * c_));
}
// This is an example of the Case 1 in the description of
// UnificationVisitor::VisitAddition method.
TEST_F(SymbolicUnificationTest, AdditionSuccessZeroCoeff) {
// Rule: x + y => 2x + 3y
const RewritingRule rule{x_ + y_, 2 * x_ + 3 * y_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites a + b => 2a + 3b
// Example of Case 1 in UnificationVisitor::VisitAddition.
const Expression e1{a_ + b_};
EXPECT_PRED2(ExprEqual, rewriter(e1), 2 * a_ + 3 * b_);
// It rewrites 1 + 2a => 2 + 6a
// Example of Case 2 in UnificationVisitor::VisitAddition.
const Expression e2{1 + 2 * a_};
EXPECT_PRED2(ExprEqual, rewriter(e2), 2 + 6 * a_);
}
TEST_F(SymbolicUnificationTest, AdditionFailureNonZeroCoeff) {
// Rule: 2 + sin(x) + cos(y) => 3 + 4x + 5y.
const RewritingRule rule{2 + sin(x_) + cos(y_), 3 + 4 * x_ + 5 * y_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// Fails to match the following with the above rule (constant
// mismatched).
// Example of Case 4 in UnificationVisitor::VisitAddition.
const Expression e1{5 + sin(a_) + cos(b_)};
EXPECT_PRED2(ExprEqual, rewriter(e1), e1 /* no change */);
// Fails to match the following with the above rule (length).
// Example of Case 4 in UnificationVisitor::VisitAddition.
const Expression e2{2 + sin(a_)};
EXPECT_PRED2(ExprEqual, rewriter(e2), e2 /* no change */);
// Fails to match the following with the above rule (sin != cos).
// Example of Case 4 in UnificationVisitor::VisitAddition.
const Expression e3{2 + cos(a_) + cos(b_)};
EXPECT_PRED2(ExprEqual, rewriter(e3), e3 /* no change */);
// Fails to match the following with the above rule (cos != tan).
// Example of Case 4 in UnificationVisitor::VisitAddition.
const Expression e4{2 + sin(a_) + tan(b_)};
EXPECT_PRED2(ExprEqual, rewriter(e4), e4 /* no change */);
// Fails to match the following with the above rule (coefficient
// mismatched).
// Example of Case 3 in UnificationVisitor::VisitAddition.
const Expression e5{sin(a_) + cos(b_)};
EXPECT_PRED2(ExprEqual, rewriter(e5), e5 /* no change */);
}
TEST_F(SymbolicUnificationTest, AdditionFailureZeroCoeff) {
// Rule: sin(x) + cos(y) + sin(z) => x + y + z.
const RewritingRule rule{sin(x_) + cos(y_) + sin(z_), x_ + y_ + z_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// Fails to match the following with the above rule (not addition).
const Expression e1{cos(a_)};
EXPECT_PRED2(ExprEqual, rewriter(e1), e1 /* no change */);
// Fails to match the following with the above rule (length).
// Example of Case 2 in UnificationVisitor::VisitAddition.
const Expression e2{3 + cos(a_)};
EXPECT_PRED2(ExprEqual, rewriter(e2), e2 /* no change */);
// Fails to match the following with the above rule (sin(x) vs 1).
// Example of Case 2 in UnificationVisitor::VisitAddition.
const Expression e3{1 + log(a_) + abs(b_)};
EXPECT_PRED2(ExprEqual, rewriter(e3), e3 /* no change */);
// Fails to match the following with the above rule (sin != tan).
// Example of Case 1 in UnificationVisitor::VisitAddition.
const Expression e4{sin(b_) + cos(a_) + tan(c_)};
EXPECT_PRED2(ExprEqual, rewriter(e4), e4 /* no change */);
}
TEST_F(SymbolicUnificationTest, UnaryMinus) {
// -x => x.
const RewritingRule rule{-x_, x_};
const Rewriter rewriter = MakeRuleRewriter(rule);
const Expression e1{-a_};
const Expression expected1{a_};
EXPECT_PRED2(ExprEqual, rewriter(e1), expected1);
const Expression e2{-2 * a_};
const Expression expected2{2 * a_};
EXPECT_PRED2(ExprEqual, rewriter(e2), expected2);
}
TEST_F(SymbolicUnificationTest, MultiplicationSuccess1) {
// Rule: x * y => x + y
const RewritingRule rule{x_ * y_, x_ + y_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites a * b to a + b.
// Example of Case 1 in UnificationVisitor::VisitMultiplication.
const Expression e1{a_ * b_};
EXPECT_PRED2(ExprEqual, rewriter(e1), a_ + b_);
// It rewrites 3 * a to 3 + a.
// Example of Case 2 in UnificationVisitor::VisitMultiplication.
const Expression e2{3 * a_};
EXPECT_PRED2(ExprEqual, rewriter(e2), 3 + a_);
}
TEST_F(SymbolicUnificationTest, MultiplicationSuccess2) {
// Rule: x * pow(sin(y), 2) * cos(z)
// => x * pow(sin(y), 3) * tan(z).
const RewritingRule rule{x_ * pow(sin(y_), 2) * cos(z_),
x_ * pow(sin(y_), 3) * tan(z_)};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites a*sinΒ²(y)cos(z) to a sinΒ³(y)tan(z).
// Example of Case 1 in UnificationVisitor::VisitMultiplication.
const Expression e{a_ * pow(sin(b_), 2) * cos(c_)};
EXPECT_PRED2(ExprEqual, rewriter(e), a_ * pow(sin(b_), 3) * tan(c_));
}
TEST_F(SymbolicUnificationTest, MultiplicationSuccess3) {
// Rule: 2 * x * y => x + y.
const RewritingRule rule{2 * x_ * y_, x_ + y_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites 2 * a * b to a + b.
// Example of Case 4 in UnificationVisitor::VisitMultiplication.
const Expression e{2 * a_ * b_};
EXPECT_PRED2(ExprEqual, rewriter(e), a_ + b_);
}
TEST_F(SymbolicUnificationTest, MultiplicationFailure1) {
// Rule: 3pow(sin(x), cos(y))tan(z)
// => 4pow(x, y)pow(2, z)
const RewritingRule rule{3 * pow(sin(x_), cos(y_)) * tan(z_),
4 * pow(x_, y_) * pow(2, z_)};
const Rewriter rewriter = MakeRuleRewriter(rule);
// Fails to match the following with the above rule.
// Example of Case 3 in UnificationVisitor::VisitMultiplication.
const Expression e{pow(cos(a_), c_) * cos(b_)};
EXPECT_PRED2(ExprEqual, rewriter(e), e /* no change */);
}
TEST_F(SymbolicUnificationTest, MultiplicationFailure2) {
// Rule: sin(x) * cos(y) * tan(z)
// => x + y + z
const RewritingRule rule{sin(x_) * cos(y_) * tan(z_), x_ + y_ + z_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// Fails to match the following with the above rule.
// Example of Case 1 in UnificationVisitor::VisitMultiplication.
const Expression e1{sin(a_) * acos(b_) * tan(c_)};
EXPECT_PRED2(ExprEqual, rewriter(e1), e1 /* no change */);
// Fails to match the following with the above rule.
// Example of Case 1 in UnificationVisitor::VisitMultiplication.
const Expression e2{a_ * sin(b_)};
EXPECT_PRED2(ExprEqual, rewriter(e2), e2 /* no change */);
// Fails to match the following with the above rule.
// Example of Case 2 in UnificationVisitor::VisitMultiplication.
const Expression e3{5 * cos(b_) * tan(z_)};
EXPECT_PRED2(ExprEqual, rewriter(e3), e3 /* no change */);
// Fails to match the following with the above rule.
const Expression e4{5};
EXPECT_PRED2(ExprEqual, rewriter(e4), e4 /* no change */);
}
TEST_F(SymbolicUnificationTest, MultiplicationFailure3) {
// Rule: 2 * x * y * z => x + y + z.
const RewritingRule rule{2 * x_ * y_ * z_, x_ + y_ + z_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// Fails to match the following with the above rule (coefficients).
// Example of Case 4 in UnificationVisitor::VisitMultiplication.
const Expression e1{3 * a_ * b_ * c_};
EXPECT_PRED2(ExprEqual, rewriter(e1), e1 /* no change */);
// Fails to match the following with the above rule (length).
// Example of Case 4 in UnificationVisitor::VisitMultiplication.
const Expression e2{3 * a_ * b_};
EXPECT_PRED2(ExprEqual, rewriter(e2), e2 /* no change */);
}
TEST_F(SymbolicUnificationTest, MultiplicationFailure4) {
// Rule: x * y * z => x + y + z.
const RewritingRule rule{x_ * y_ * z_, x_ + y_ + z_};
const Rewriter rewriter = MakeRuleRewriter(rule);
// Fails to match the following with the above rule.
// Example of Case 2 in UnificationVisitor::VisitMultiplication.
const Expression e{3 * a_};
EXPECT_PRED2(ExprEqual, rewriter(e), e /* no change */);
}
// https://github.com/google/googletest/issues/1610
enum UnaryTestOp {
Abs,
Log,
Exp,
Sqrt,
Sin,
Cos,
Tan,
Asin,
Acos,
Atan,
Sinh,
Cosh,
Tanh,
Ceil,
Floor
};
// clang-format off
std::function<Expression(const Variable& x)>UnaryOpToFunction(UnaryTestOp op) {
switch (op) {
case Abs: return [](const Variable& x) { return abs(x); };
case Log: return [](const Variable& x) { return log(x); };
case Exp: return [](const Variable& x) { return exp(x); };
case Sqrt: return [](const Variable& x) { return sqrt(x); };
case Sin: return [](const Variable& x) { return sin(x); };
case Cos: return [](const Variable& x) { return cos(x); };
case Tan: return [](const Variable& x) { return tan(x); };
case Asin: return [](const Variable& x) { return asin(x); };
case Acos: return [](const Variable& x) { return acos(x); };
case Atan: return [](const Variable& x) { return atan(x); };
case Sinh: return [](const Variable& x) { return sinh(x); };
case Cosh: return [](const Variable& x) { return cosh(x); };
case Tanh: return [](const Variable& x) { return tanh(x); };
case Ceil: return [](const Variable& x) { return ceil(x); };
case Floor: return [](const Variable& x) { return floor(x); };
}
DRAKE_UNREACHABLE();
}
// clang-format on
class SymbolicUnificationTestUnary
: public ::testing::TestWithParam<UnaryTestOp> {
protected:
const Variable x_{"x"};
const Variable a_{"a"};
};
TEST_P(SymbolicUnificationTestUnary, Check) {
const Expression& lhs = UnaryOpToFunction(GetParam())(x_);
const RewritingRule rule{lhs, x_};
const Rewriter rewriter = MakeRuleRewriter(rule);
const Expression& e1 = UnaryOpToFunction(GetParam())(a_);
EXPECT_PRED2(ExprEqual, rewriter(e1), a_);
const Expression e2{a_ * a_};
EXPECT_PRED2(ExprEqual, rewriter(e2), e2 /* no change */);
}
INSTANTIATE_TEST_SUITE_P(UnaryCases, SymbolicUnificationTestUnary,
::testing::Values(Abs, Log, Exp, Sqrt, Sin, Cos, Tan,
Asin, Acos, Atan, Sinh, Cosh, Tanh,
Ceil, Floor));
// https://github.com/google/googletest/issues/1610
enum BinaryTestOp { Pow, Div, Min, Max, Atan2 };
// clang-format off
std::function<Expression(const Variable&, const Variable&)>
BinaryOpToFunction(BinaryTestOp op) {
switch (op) {
case Pow:
return [](const Variable& x, const Variable& y) { return pow(x, y); };
case Div:
return [](const Variable& x, const Variable& y) { return x / y; };
case Min:
return [](const Variable& x, const Variable& y) { return min(x, y); };
case Max:
return [](const Variable& x, const Variable& y) { return max(x, y); };
case Atan2:
return [](const Variable& x, const Variable& y) { return atan2(x, y); };
}
// Should not be reachable.
DRAKE_UNREACHABLE();
}
// clang-format on
class SymbolicUnificationTestBinary
: public ::testing::TestWithParam<BinaryTestOp> {
protected:
const Variable x_{"x"};
const Variable y_{"y"};
const Variable a_{"a"};
const Variable b_{"b"};
};
TEST_P(SymbolicUnificationTestBinary, Check) {
const Expression& lhs = BinaryOpToFunction(GetParam())(x_, y_);
const RewritingRule rule{lhs, x_ + y_};
const Rewriter rewriter = MakeRuleRewriter(rule);
const Expression& e1 = BinaryOpToFunction(GetParam())(a_, b_);
EXPECT_PRED2(ExprEqual, rewriter(e1), a_ + b_);
const Expression e2{a_ + b_};
EXPECT_PRED2(ExprEqual, rewriter(e2), e2 /* no change */);
}
INSTANTIATE_TEST_SUITE_P(BinaryCases, SymbolicUnificationTestBinary,
::testing::Values(Pow, Div, Min, Max, Atan2));
TEST_F(SymbolicUnificationTest, IfThenElse) {
// Not supported.
const RewritingRule rule{if_then_else(x_ > y_, x_, y_), x_ + 2 * y_};
const Rewriter rewriter = MakeRuleRewriter(rule);
const Expression e{if_then_else(a_ > b_, a_, b_)};
EXPECT_THROW(rewriter(e), runtime_error);
}
TEST_F(SymbolicUnificationTest, UninterpretedFunction) {
// Not supported.
const RewritingRule rule{uninterpreted_function("uf", {x_}), x_};
const Rewriter rewriter = MakeRuleRewriter(rule);
const Expression e{uninterpreted_function("uf", {a_})};
EXPECT_THROW(rewriter(e), runtime_error);
}
TEST_F(SymbolicUnificationTest, CheckCommonTrigIdentities1) {
// Rule: sinΒ²(x) + cosΒ²(y) => 1.
const RewritingRule rule{pow(sin(x_), 2) + pow(cos(y_), 2), 1};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites cosΒ²(a + b) + sinΒ²(a + b) to 1.0.
const Expression e{pow(cos(a_ + b_), 2) + pow(sin(a_ + b_), 2)};
EXPECT_PRED2(ExprEqual, rewriter(e), 1.0);
}
TEST_F(SymbolicUnificationTest, CheckCommonTrigIdentities2) {
// Rule: sin(x + y) => sin(x)cos(y) + cos(x)sin(y).
const RewritingRule rule{sin(x_ + y_), sin(x_) * cos(y_) + cos(x_) * sin(y_)};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites sin(2a + 3b) = sin(2a)cos(3b) + cos(3b)sin(2a).
const Expression e{sin(2 * a_ + 3 * b_)};
EXPECT_PRED2(ExprEqual, rewriter(e),
sin(2 * a_) * cos(3 * b_) + cos(2 * a_) * sin(3 * b_));
}
TEST_F(SymbolicUnificationTest, CheckCommonTrigIdentities3) {
// Rule: tan(x - y) => (tan(x) - tan(y)) / (1 + tan(x)*tan(y)).
const RewritingRule rule{tan(x_ - y_),
(tan(x_) - tan(y_)) / (1 + tan(x_) * tan(y_))};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites tan(2a - 3b) = (tan(2a) - tan(3b)) / (1 + tan(2a)*tan(3b)).
const Expression e{tan(2 * a_ - 3 * b_)};
EXPECT_PRED2(ExprEqual, rewriter(e),
(tan(2 * a_) - tan(3 * b_)) / (1 + tan(2 * a_) * tan(3 * b_)));
}
TEST_F(SymbolicUnificationTest, CheckCommonTrigIdentities4) {
// Rule: cos(x) - cos(y) => -2sin((x + y)/2)sin((x - y)/2).
const RewritingRule rule{cos(x_) - cos(y_),
-2 * sin((x_ + y_) / 2) * sin((x_ - y_) / 2)};
const Rewriter rewriter = MakeRuleRewriter(rule);
// It rewrites cos(2a) - cos(4a) => -2sin((2a + 4a)/2)sin((2a - 4a) /2).
const Expression e{cos(2 * a_) - cos(4 * a_)};
EXPECT_PRED2(ExprEqual, rewriter(e), -2 * sin(6 * a_ / 2) * sin(-2 * a_ / 2));
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/rational_function_test.cc | #include "drake/common/symbolic/rational_function.h"
#include <gtest/gtest.h>
#include "drake/common/symbolic/expression.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
namespace {
using test::PolyEqual;
using test::RationalFunctionEqual;
class SymbolicRationalFunctionTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
const Variable var_a_{"a"};
const Variable var_b_{"b"};
const Variable var_c_{"c"};
const Variables var_xy_{var_x_, var_y_};
const Variables var_xyz_{var_x_, var_y_, var_z_};
const Expression x_{var_x_};
const Expression y_{var_y_};
const Expression z_{var_z_};
const Expression a_{var_a_};
const Expression b_{var_b_};
const Expression c_{var_c_};
const Polynomial polynomial_zero_{0};
const Polynomial polynomial_one_{1};
const Polynomial p1_{var_x_ * var_x_ * 2 + var_y_, var_xy_};
const Polynomial p2_{var_x_ * var_x_ + 2 * var_y_};
const Polynomial p3_{var_a_ * var_x_ + var_b_ + var_y_, var_xy_};
const Polynomial p4_{2 * var_a_ * var_x_ + var_b_ + var_x_ * var_y_, var_xy_};
const Monomial monom_x_{var_x_};
};
TEST_F(SymbolicRationalFunctionTest, DefaultConstructor) {
const RationalFunction p;
EXPECT_PRED2(PolyEqual, p.numerator(), polynomial_zero_);
EXPECT_PRED2(PolyEqual, p.denominator(), polynomial_one_);
}
TEST_F(SymbolicRationalFunctionTest, Constructor) {
RationalFunction f(polynomial_zero_, polynomial_one_);
EXPECT_PRED2(PolyEqual, f.numerator(), polynomial_zero_);
EXPECT_PRED2(PolyEqual, f.denominator(), polynomial_one_);
const symbolic::Polynomial p1(var_x_ * var_a_, {var_x_});
const symbolic::Polynomial p2(var_a_ * var_x_ * var_x_ + var_y_, var_xy_);
RationalFunction f_p1_p2(p1, p2);
EXPECT_PRED2(PolyEqual, f_p1_p2.numerator(), p1);
EXPECT_PRED2(PolyEqual, f_p1_p2.denominator(), p2);
}
TEST_F(SymbolicRationalFunctionTest, ConstructorWithPolynomial) {
// Constructor with numerator only.
RationalFunction f1(p1_);
EXPECT_PRED2(PolyEqual, f1.numerator(), p1_);
EXPECT_PRED2(PolyEqual, f1.denominator(), polynomial_one_);
}
TEST_F(SymbolicRationalFunctionTest, ConstructorWithMonomial) {
// Constructor with numerator only.
RationalFunction f1(monom_x_);
EXPECT_PRED2(PolyEqual, f1.numerator(), Polynomial(monom_x_));
EXPECT_PRED2(PolyEqual, f1.denominator(), polynomial_one_);
}
TEST_F(SymbolicRationalFunctionTest, ConstructorWithDouble) {
// Constructor with a double scalar.
const double c = 5;
RationalFunction f1(c);
EXPECT_PRED2(PolyEqual, f1.numerator(), c * polynomial_one_);
EXPECT_PRED2(PolyEqual, f1.denominator(), polynomial_one_);
}
TEST_F(SymbolicRationalFunctionTest, EqualTo) {
const Polynomial p1(var_x_ * var_x_ + var_y_);
const Polynomial p2(var_x_ + var_y_);
const RationalFunction f(p1, p2);
EXPECT_TRUE(f.EqualTo(RationalFunction(p1, p2)));
EXPECT_FALSE(f.EqualTo(RationalFunction(2 * p1, 2 * p2)));
EXPECT_FALSE(f.EqualTo(RationalFunction(p1, 2 * p2)));
EXPECT_FALSE(f.EqualTo(RationalFunction(2 * p1, p2)));
}
TEST_F(SymbolicRationalFunctionTest, OperatorEqual) {
EXPECT_EQ(RationalFunction(p1_, p2_), RationalFunction(p1_, p2_));
EXPECT_EQ(RationalFunction(p1_, p2_), RationalFunction(2 * p1_, 2 * p2_));
}
TEST_F(SymbolicRationalFunctionTest, OperatorNotEqual) {
EXPECT_NE(RationalFunction(p1_, p2_), RationalFunction(p1_ + 1, p2_));
EXPECT_NE(RationalFunction(p1_, p2_), RationalFunction(p1_, p2_ + 1));
}
TEST_F(SymbolicRationalFunctionTest, UnaryMinus) {
const Polynomial p1(var_x_ * var_x_ * 2 + var_y_);
const Polynomial p2(var_x_ * var_x_ + 2 * var_y_);
const RationalFunction f(p1, p2);
const RationalFunction f_minus = -f;
EXPECT_PRED2(PolyEqual, -f_minus.numerator(), p1);
EXPECT_PRED2(PolyEqual, f_minus.denominator(), p2);
}
TEST_F(SymbolicRationalFunctionTest, Addition) {
// Test RationalFunction + RationalFunction
const RationalFunction f1(p1_, p2_);
const RationalFunction f2(p3_, p4_);
const RationalFunction f1_f2_sum_expected(p1_ * p4_ + p2_ * p3_, p2_ * p4_);
EXPECT_PRED2(RationalFunctionEqual, f1 + f2, f1_f2_sum_expected);
EXPECT_PRED2(RationalFunctionEqual, f2 + f1, f1_f2_sum_expected);
RationalFunction f1_f2_sum(p1_, p2_);
f1_f2_sum += f2;
EXPECT_PRED2(RationalFunctionEqual, f1_f2_sum, f1_f2_sum_expected);
// Test RationalFunction + RationalFunction same denominator
const RationalFunction f4(p3_, p2_);
const RationalFunction f1_f4_sum_expected(p1_ + p3_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 + f4, f1_f4_sum_expected);
EXPECT_PRED2(RationalFunctionEqual, f4 + f1, f1_f4_sum_expected);
RationalFunction f1_f4_sum(p1_, p2_);
f1_f4_sum += f4;
EXPECT_PRED2(RationalFunctionEqual, f1_f4_sum, f1_f4_sum_expected);
// Test Polynomial + RationalFunction
const RationalFunction f1_p3_sum_expected(p1_ + p2_ * p3_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 + p3_, f1_p3_sum_expected);
EXPECT_PRED2(RationalFunctionEqual, p3_ + f1, f1_p3_sum_expected);
RationalFunction f1_p3_sum(p1_, p2_);
f1_p3_sum += p3_;
EXPECT_PRED2(RationalFunctionEqual, f1_p3_sum, f1_p3_sum_expected);
// Test Monomial + RationalFunction
const RationalFunction f1_monom_x_sum_expected(p1_ + p2_ * monom_x_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 + monom_x_, f1_monom_x_sum_expected);
EXPECT_PRED2(RationalFunctionEqual, monom_x_ + f1, f1_monom_x_sum_expected);
RationalFunction f1_monom_x_sum(p1_, p2_);
f1_monom_x_sum += monom_x_;
EXPECT_PRED2(RationalFunctionEqual, f1_monom_x_sum, f1_monom_x_sum_expected);
// Test double + RationalFunction
const double c = 2;
const RationalFunction f1_c_sum_expected(p1_ + c * p2_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 + c, f1_c_sum_expected);
EXPECT_PRED2(RationalFunctionEqual, c + f1, f1_c_sum_expected);
RationalFunction f1_c_sum(p1_, p2_);
f1_c_sum += c;
EXPECT_PRED2(RationalFunctionEqual, f1_c_sum, f1_c_sum_expected);
}
TEST_F(SymbolicRationalFunctionTest, Subtraction) {
// Test RationalFunction - RationalFunction
const RationalFunction f1(p1_, p2_);
const RationalFunction f2(p3_, p4_);
const RationalFunction f1_minus_f2_expected(p1_ * p4_ - p2_ * p3_, p2_ * p4_);
EXPECT_PRED2(RationalFunctionEqual, f1 - f2, f1_minus_f2_expected);
EXPECT_PRED2(RationalFunctionEqual, f2 - f1, -f1_minus_f2_expected);
RationalFunction f1_minus_f2 = f1;
f1_minus_f2 -= f2;
EXPECT_PRED2(RationalFunctionEqual, f1_minus_f2, f1_minus_f2_expected);
// Test RationalFunction - RationalFunction same denominator
const RationalFunction f4(p3_, p2_);
const RationalFunction f1_minus_f4_expected(p1_ - p3_, p2_);
const RationalFunction f4_minus_f1_expected(p3_ - p1_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 - f4, f1_minus_f4_expected);
EXPECT_PRED2(RationalFunctionEqual, f4 - f1, f4_minus_f1_expected);
RationalFunction f1_f4_minus(p1_, p2_);
f1_f4_minus -= f4;
EXPECT_PRED2(RationalFunctionEqual, f1_f4_minus, f1_minus_f4_expected);
// Test Polynomial - RationalFunction
const RationalFunction f1_minus_p3_expected(p1_ - p2_ * p3_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 - p3_, f1_minus_p3_expected);
EXPECT_PRED2(RationalFunctionEqual, p3_ - f1, -f1_minus_p3_expected);
RationalFunction f1_minus_p3 = f1;
f1_minus_p3 -= p3_;
EXPECT_PRED2(RationalFunctionEqual, f1_minus_p3, f1_minus_p3_expected);
// Test Monomial - RationalFunction
const RationalFunction f1_minus_monom_x_expected(p1_ - p2_ * monom_x_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 - monom_x_, f1_minus_monom_x_expected);
EXPECT_PRED2(RationalFunctionEqual, monom_x_ - f1,
-f1_minus_monom_x_expected);
RationalFunction f1_monom_x_minus(p1_, p2_);
f1_monom_x_minus -= monom_x_;
EXPECT_PRED2(RationalFunctionEqual, f1_monom_x_minus,
f1_minus_monom_x_expected);
// Test double - RationalFunction and RationalFunction - double
const double c = 2;
const RationalFunction f1_minus_c_expected(p1_ - p2_ * c, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 - c, f1_minus_c_expected);
EXPECT_PRED2(RationalFunctionEqual, c - f1, -f1_minus_c_expected);
RationalFunction f1_minus_c = f1;
f1_minus_c -= c;
EXPECT_PRED2(RationalFunctionEqual, f1_minus_c, f1_minus_c_expected);
}
TEST_F(SymbolicRationalFunctionTest, Product) {
// Test RationalFunction * RationalFunction
const RationalFunction f1(p1_, p2_);
const RationalFunction f2(p3_, p4_);
const RationalFunction f1_times_f2_expected(p1_ * p3_, p2_ * p4_);
EXPECT_PRED2(RationalFunctionEqual, f1 * f2, f1_times_f2_expected);
EXPECT_PRED2(RationalFunctionEqual, f2 * f1, f1_times_f2_expected);
RationalFunction f1_times_f2 = f1;
f1_times_f2 *= f2;
EXPECT_PRED2(RationalFunctionEqual, f1_times_f2, f1_times_f2_expected);
// Test Polynomial * RationalFunction
const RationalFunction f1_times_p3_expected(p1_ * p3_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 * p3_, f1_times_p3_expected);
EXPECT_PRED2(RationalFunctionEqual, p3_ * f1, f1_times_p3_expected);
RationalFunction f1_times_p3 = f1;
f1_times_p3 *= p3_;
EXPECT_PRED2(RationalFunctionEqual, f1_times_p3, f1_times_p3_expected);
// Test Monomial * RationalFunction
const RationalFunction f1_times_monom_x_expected(p1_ * monom_x_, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 * monom_x_, f1_times_monom_x_expected);
EXPECT_PRED2(RationalFunctionEqual, monom_x_ * f1, f1_times_monom_x_expected);
RationalFunction f1_times_monom_x(p1_, p2_);
f1_times_monom_x *= monom_x_;
EXPECT_PRED2(RationalFunctionEqual, f1_times_monom_x,
f1_times_monom_x_expected);
// Test double * RationalFunction
const double c = 2;
const RationalFunction f1_times_c_expected(p1_ * c, p2_);
EXPECT_PRED2(RationalFunctionEqual, f1 * c, f1_times_c_expected);
EXPECT_PRED2(RationalFunctionEqual, c * f1, f1_times_c_expected);
RationalFunction f1_times_c = f1;
f1_times_c *= c;
EXPECT_PRED2(RationalFunctionEqual, f1_times_c, f1_times_c_expected);
}
TEST_F(SymbolicRationalFunctionTest, Division) {
// Test RationalFunction / RationalFunction.
const RationalFunction f1(p1_, p2_);
const RationalFunction f2(p3_, p4_);
const RationalFunction f1_divides_f2_expected(p3_ * p2_, p1_ * p4_);
EXPECT_PRED2(RationalFunctionEqual, f2 / f1, f1_divides_f2_expected);
EXPECT_PRED2(RationalFunctionEqual, f1 / f2, 1 / f1_divides_f2_expected);
RationalFunction f1_divides_f2 = f2;
f1_divides_f2 /= f1;
EXPECT_PRED2(RationalFunctionEqual, f1_divides_f2, f1_divides_f2_expected);
// Test RationalFunction / Polynomial and Polynomial / RationalFunction.
const RationalFunction p3_divides_f1_expected(p1_, p2_ * p3_);
EXPECT_PRED2(RationalFunctionEqual, f1 / p3_, p3_divides_f1_expected);
EXPECT_PRED2(RationalFunctionEqual, p3_ / f1, 1 / p3_divides_f1_expected);
RationalFunction p3_divides_f1 = f1;
p3_divides_f1 /= p3_;
EXPECT_PRED2(RationalFunctionEqual, p3_divides_f1, p3_divides_f1_expected);
// Test RationalFunction / Monomial and Monomial / RationalFunction.
const RationalFunction monom_x_divides_f1_expected(p1_, p2_ * monom_x_);
EXPECT_PRED2(RationalFunctionEqual, f1 / monom_x_,
monom_x_divides_f1_expected);
EXPECT_PRED2(RationalFunctionEqual, monom_x_ / f1,
1 / monom_x_divides_f1_expected);
RationalFunction monom_x_divides_f1 = f1;
monom_x_divides_f1 /= monom_x_;
EXPECT_PRED2(RationalFunctionEqual, monom_x_divides_f1,
monom_x_divides_f1_expected);
// Test RationalFunction / double and double / RationalFunction.
const double c = 2;
const RationalFunction c_divides_f1_expected(p1_, p2_ * c);
EXPECT_PRED2(RationalFunctionEqual, f1 / c, c_divides_f1_expected);
EXPECT_PRED2(RationalFunctionEqual, c / f1, 1 / c_divides_f1_expected);
RationalFunction c_divides_f1 = f1;
c_divides_f1 /= c;
EXPECT_PRED2(RationalFunctionEqual, c_divides_f1, c_divides_f1_expected);
// Test divide by zero error
const std::string zero_divider_error{
"RationalFunction: operator/=: The divider is 0."};
DRAKE_EXPECT_THROWS_MESSAGE(f1 / 0, zero_divider_error);
// Note that it is too expensive to catch in general whether we are performing
// division by a zero polynomial. These only test whether our cheap test to
// catch division by zero are working.
DRAKE_EXPECT_THROWS_MESSAGE(f1 / polynomial_zero_, zero_divider_error);
const RationalFunction polynomial_fraction_zero;
DRAKE_EXPECT_THROWS_MESSAGE(f1 / polynomial_fraction_zero,
zero_divider_error);
DRAKE_EXPECT_THROWS_MESSAGE(p1_ / polynomial_fraction_zero,
zero_divider_error);
DRAKE_EXPECT_THROWS_MESSAGE(monom_x_ / polynomial_fraction_zero,
zero_divider_error);
DRAKE_EXPECT_THROWS_MESSAGE(2 / polynomial_fraction_zero, zero_divider_error);
}
TEST_F(SymbolicRationalFunctionTest, Exponentiation) {
const RationalFunction f(p1_, p2_);
EXPECT_PRED2(RationalFunctionEqual, pow(f, 0),
RationalFunction(polynomial_one_, polynomial_one_));
EXPECT_PRED2(RationalFunctionEqual, pow(f, 1), f);
EXPECT_PRED2(RationalFunctionEqual, pow(f, 2),
RationalFunction(pow(p1_, 2), pow(p2_, 2)));
EXPECT_PRED2(RationalFunctionEqual, pow(f, -1), RationalFunction(p2_, p1_));
EXPECT_PRED2(RationalFunctionEqual, pow(f, -2),
RationalFunction(pow(p2_, 2), pow(p1_, 2)));
}
TEST_F(SymbolicRationalFunctionTest, ProductAndAddition) {
// Test f1 * f2 + f3 * f4 where f's are all rational functions. This
// prouduct-and-addition operation is used in matrix product.
const RationalFunction f1(p1_, p2_);
const RationalFunction f2(p3_, p4_);
const RationalFunction f3(p2_, p4_);
const RationalFunction f4(p3_, p1_);
// (p1 / p2) * (p3 / p4) + (p2 / p4) + (p3 / p1) = (p1*p1*p3*p4 +
// p2*p2*p3*p4)/(p1*p2*p4*p4)
const RationalFunction result = f1 * f2 + f3 * f4;
const RationalFunction result_expected(
p1_ * p1_ * p3_ * p4_ + p2_ * p2_ * p3_ * p4_, p1_ * p2_ * p4_ * p4_);
EXPECT_PRED2(test::PolyEqualAfterExpansion, result.numerator(),
result_expected.numerator());
EXPECT_PRED2(test::PolyEqualAfterExpansion, result.denominator(),
result_expected.denominator());
}
TEST_F(SymbolicRationalFunctionTest, Evaluate) {
// p = axΒ²y + bxy + cz
const Polynomial p{a_ * x_ * x_ * y_ + b_ * x_ * y_ + c_ * z_, var_xyz_};
// q = axz + byz + cxy
const Polynomial q{a_ * x_ * z_ + b_ * y_ * z_ + c_ * x_ * y_, var_xyz_};
// f = p/q
const RationalFunction f{p, q};
const Environment env{{
{var_a_, 4.0},
{var_b_, 1.0},
{var_c_, 2.0},
{var_x_, -7.0},
{var_y_, -5.0},
{var_z_, -2.0},
}};
const double expected_numerator{4.0 * -7.0 * -7.0 * -5.0 + 1.0 * -7.0 * -5.0 +
2.0 * -2.0};
const double expected_denominator{4.0 * -7.0 * -2.0 + 1.0 * -5.0 * -2.0 +
2.0 * -7.0 * -5.0};
EXPECT_EQ(f.Evaluate(env), expected_numerator / expected_denominator);
}
TEST_F(SymbolicRationalFunctionTest, ToExpression) {
// p = axΒ²y + bxy + cz
const Polynomial p{a_ * x_ * x_ * y_ + b_ * x_ * y_ + c_ * z_, var_xyz_};
// q = axz + byz + cxy
const Polynomial q{a_ * x_ * z_ + b_ * y_ * z_ + c_ * x_ * y_, var_xyz_};
const RationalFunction f{p, q};
const RationalFunction p_rat{p};
EXPECT_EQ(f.ToExpression(), p.ToExpression() / q.ToExpression());
// Ensures that the elision of the implied 1 in the denominator occurs in
// ToExpression
EXPECT_EQ(p_rat.ToExpression(), p.ToExpression());
}
TEST_F(SymbolicRationalFunctionTest, SetIndetermiantes) {
// a rational function with indeterminates var_xy_
RationalFunction f{p1_, p4_};
// set indeterminates requires a type Variables not Variable
symbolic::Variables vars_a_{var_a_};
f.SetIndeterminates(vars_a_);
EXPECT_EQ(f.numerator().indeterminates(), vars_a_);
EXPECT_EQ(f.denominator().indeterminates(), vars_a_);
f.SetIndeterminates(var_xy_);
EXPECT_EQ(f.numerator().indeterminates(), var_xy_);
EXPECT_EQ(f.denominator().indeterminates(), var_xy_);
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/trigonometric_polynomial_test.cc | #include "drake/common/symbolic/trigonometric_polynomial.h"
#include <vector>
#include <fmt/format.h>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
namespace {
using test::ExprEqual;
GTEST_TEST(SymbolicLatex, BasicTest) {
Variable x{"x"}, y{"y"}, z{"z"};
Variable sx{"sx"}, sy{"sy"}, cx{"cx"}, cy{"cy"};
SinCosSubstitution subs;
subs.emplace(x, SinCos(sx, cx));
subs.emplace(y, SinCos(sy, cy));
// Expressions.
EXPECT_PRED2(ExprEqual, Substitute(x, subs), x);
EXPECT_PRED2(ExprEqual, Substitute(sin(x), subs), sx);
EXPECT_PRED2(ExprEqual, Substitute(cos(x), subs), cx);
// Addition.
EXPECT_PRED2(ExprEqual, Substitute(sin(x + y), subs), sx * cy + cx * sy);
EXPECT_PRED2(ExprEqual, Substitute(sin(x + z), subs),
sx * cos(z) + cx * sin(z));
EXPECT_PRED2(ExprEqual, Substitute(sin(z + x), subs),
sx * cos(z) + cx * sin(z));
EXPECT_PRED2(ExprEqual, Substitute(sin(x + 0.15), subs),
sx * cos(0.15) + cx * sin(0.15));
EXPECT_PRED2(ExprEqual, Substitute(cos(x + y), subs), cx * cy - sx * sy);
EXPECT_PRED2(ExprEqual, Substitute(cos(x + z), subs),
cx * cos(z) - sx * sin(z));
EXPECT_PRED2(ExprEqual, Substitute(cos(z + x), subs),
cx * cos(z) - sx * sin(z));
EXPECT_PRED2(ExprEqual, Substitute(cos(x + 0.15), subs),
cx * cos(0.15) - sx * sin(0.15));
EXPECT_PRED2(ExprEqual, Substitute(2 + 3 * x + 4 * y, subs),
2 + 3 * x + 4 * y);
// Multiplication.
EXPECT_PRED2(ExprEqual, Substitute(sin(2 * x), subs), 2 * sx * cx);
EXPECT_PRED2(ExprEqual, Substitute(sin(-2 * x), subs), -2 * sx * cx);
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(2.4 * x), subs),
".*only support sin.* where c is an integer.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(x * x), subs),
".*'status == kNotSinCos' failed.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(x * y), subs),
".*only support sin.* where c is an integer.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(x * z), subs),
".*only support sin.* where c is an integer.*");
EXPECT_PRED2(ExprEqual, Substitute(cos(2 * x), subs), cx * cx - sx * sx);
EXPECT_PRED2(ExprEqual, Substitute(cos(-2 * x), subs), cx * cx - sx * sx);
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(2.4 * x), subs),
".*only support cos.* where c is an integer.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(x * x), subs),
".*'status == kNotSinCos' failed.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(x * y), subs),
".*only support cos.* where c is an integer.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(x * z), subs),
".*only support cos.* where c is an integer.*");
EXPECT_PRED2(ExprEqual, Substitute(x * sin(x) * cos(x), subs), x * sx * cx);
EXPECT_PRED2(ExprEqual, Substitute(sin(2 * x + y), subs),
2 * sx * cx * cy + (cx * cx - sx * sx) * sy);
// Other Expressions.
const auto TestUnary =
[&x, &sx, &cx,
&subs](const std::function<Expression(const Expression&)>& pred) {
EXPECT_PRED2(ExprEqual, Substitute(pred(x), subs), pred(x));
EXPECT_PRED2(ExprEqual, Substitute(pred(sin(x)), subs), pred(sx));
EXPECT_PRED2(ExprEqual, Substitute(pred(cos(x)), subs), pred(cx));
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(pred(x)), subs),
".*'status == kNotSinCos' failed.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(pred(x)), subs),
".*'status == kNotSinCos' failed.*");
};
const auto TestBinary =
[&x, &y, &sx, &cx, &sy, &cy, &subs](
const std::function<Expression(const Expression&, const Expression&)>&
pred) {
EXPECT_PRED2(ExprEqual, Substitute(pred(x, y), subs), pred(x, y));
EXPECT_PRED2(ExprEqual, Substitute(pred(sin(x), y), subs), pred(sx, y));
EXPECT_PRED2(ExprEqual, Substitute(pred(cos(x), y), subs), pred(cx, y));
EXPECT_PRED2(ExprEqual, Substitute(pred(x, sin(y)), subs), pred(x, sy));
EXPECT_PRED2(ExprEqual, Substitute(pred(x, cos(y)), subs), pred(x, cy));
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(pred(x, y)), subs),
".*'status == kNotSinCos' failed.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(pred(x, y)), subs),
".*'status == kNotSinCos' failed.*");
};
const auto mypow = [](const Expression& e1, const Expression e2) {
return pow(e1, e2);
};
TestBinary(mypow); // TestBinary(pow) doesn't compile for some reason.
EXPECT_PRED2(ExprEqual, Substitute(x / y, subs), x / y);
EXPECT_PRED2(ExprEqual, Substitute(sin(x) / sin(y), subs), sx / sy);
EXPECT_PRED2(ExprEqual, Substitute(cos(x) / cos(y), subs), cx / cy);
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(x / y), subs),
".*'status == kNotSinCos' failed.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(x / y), subs),
".*'status == kNotSinCos' failed.*");
TestUnary(abs);
TestUnary(log);
TestUnary(exp);
TestUnary(sqrt);
EXPECT_PRED2(ExprEqual, Substitute(tan(x), subs), sx / cx);
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(tan(x)), subs),
".*'status == kNotSinCos' failed.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(tan(x)), subs),
".*'status == kNotSinCos' failed.*");
TestUnary(asin);
TestUnary(acos);
TestUnary(atan);
TestBinary(atan2);
TestUnary(sinh);
TestUnary(cosh);
TestUnary(tanh);
TestBinary(min);
TestBinary(max);
TestUnary(ceil);
TestUnary(floor);
EXPECT_PRED2(ExprEqual, Substitute(if_then_else(z > 1, z, 1), subs),
if_then_else(z > 1, z, 1));
DRAKE_EXPECT_THROWS_MESSAGE(
Substitute(if_then_else(x > y, x, y), subs),
"Substituting sin/cos into formulas is not supported yet");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(if_then_else(x > y, x, y)), subs),
".*'status == kNotSinCos' failed.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(if_then_else(x > y, x, y)), subs),
".*'status == kNotSinCos' failed.*");
// Limited half-angle support.
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(sin(0.5 * x), subs),
".*only support sin.* where c is an integer.*");
DRAKE_EXPECT_THROWS_MESSAGE(Substitute(cos(0.5 * x), subs),
".*only support cos.* where c is an integer.*");
// Matrix<Expression>
Eigen::Matrix<Expression, 2, 2> m;
m << x, sin(x), sin(y), sin(x + y);
const Eigen::Matrix<Expression, 2, 2> m2 = Substitute(m, subs);
EXPECT_PRED2(ExprEqual, m2(0, 0), x);
EXPECT_PRED2(ExprEqual, m2(0, 1), sx);
EXPECT_PRED2(ExprEqual, m2(1, 0), sy);
EXPECT_PRED2(ExprEqual, m2(1, 1), sx * cy + sy * cx);
}
GTEST_TEST(SymbolicLatex, HalfAngleTest) {
Variable x{"x"}, y{"y"}, z{"z"};
Variable sx{"sx"}, sy{"sy"}, cx{"cx"}, cy{"cy"};
SinCosSubstitution subs;
subs.emplace(x, SinCos(sx, cx, SinCosSubstitutionType::kHalfAnglePreferSin));
subs.emplace(y, SinCos(sy, cy, SinCosSubstitutionType::kHalfAnglePreferCos));
EXPECT_PRED2(ExprEqual, Substitute(sin(x), subs), 2 * sx * cx);
EXPECT_PRED2(ExprEqual, Substitute(sin(1 * x), subs), 2 * sx * cx);
EXPECT_PRED2(ExprEqual, Substitute(sin(2 * x), subs),
4 * sx * cx * (1 - 2 * sx * sx));
EXPECT_PRED2(ExprEqual, Substitute(cos(x), subs), 1 - 2 * sx * sx);
EXPECT_PRED2(ExprEqual, Substitute(sin(y), subs), 2 * sy * cy);
EXPECT_PRED2(ExprEqual, Substitute(cos(y), subs), 2 * cy * cy - 1);
EXPECT_PRED2(ExprEqual, Substitute(sin(0.5 * x), subs), sx);
EXPECT_PRED2(ExprEqual, Substitute(cos(0.5 * x), subs), cx);
EXPECT_PRED2(ExprEqual, Substitute(sin(-0.5 * x), subs), -sx);
EXPECT_PRED2(ExprEqual, Substitute(cos(-0.5 * x), subs), cx);
// Note: We don't support division yet, but calling Expand makes this work:
EXPECT_PRED2(ExprEqual, Substitute(sin(x / 2.0).Expand(), subs), sx);
// Matrix half-angle.
Eigen::Matrix<Expression, 2, 2> m;
m << x, sin(x), sin(y), sin(x + y);
const Eigen::Matrix<Expression, 2, 2> m2 = Substitute(m, subs);
EXPECT_PRED2(ExprEqual, m2(0, 0), x);
EXPECT_PRED2(ExprEqual, m2(0, 1), 2 * sx * cx);
EXPECT_PRED2(ExprEqual, m2(1, 0), 2 * sy * cy);
EXPECT_PRED2(
ExprEqual, m2(1, 1),
(2 * sx * cx) * (2 * cy * cy - 1) + (2 * sy * cy) * (1 - 2 * sx * sx));
}
void CheckSubstituteStereographicProjection(
const symbolic::Polynomial& e_poly, const std::vector<SinCos>& sin_cos,
const VectorX<symbolic::Variable>& t_angle,
const symbolic::RationalFunction& e_rational_expected) {
const symbolic::RationalFunction e_rational2 =
SubstituteStereographicProjection(e_poly, sin_cos, t_angle);
EXPECT_PRED2(symbolic::test::PolyEqualAfterExpansion, e_rational2.numerator(),
e_rational_expected.numerator());
EXPECT_PRED2(symbolic::test::PolyEqualAfterExpansion,
e_rational2.denominator(), e_rational_expected.denominator());
}
class SubstituteStereographicProjectionTest : public testing::Test {
public:
SubstituteStereographicProjectionTest()
: cos_vars_(3),
sin_vars_(3),
t_angle_(3),
theta_(3),
a_("a"),
b_("b"),
x_("x"),
y_("y") {
for (int i = 0; i < 3; ++i) {
theta_(i) = symbolic::Variable("theta" + std::to_string(i));
cos_vars_(i) =
symbolic::Variable("cos(theta(" + std::to_string(i) + "))");
sin_vars_(i) =
symbolic::Variable("sin(theta(" + std::to_string(i) + "))");
t_angle_(i) = symbolic::Variable("t_angle(" + std::to_string(i) + ")");
sin_cos_.emplace_back(sin_vars_(i), cos_vars_(i));
}
cos_sin_vars_.insert(symbolic::Variables(cos_vars_));
cos_sin_vars_.insert(symbolic::Variables(sin_vars_));
t_ = symbolic::Variables(t_angle_);
for (int i = 0; i < 3; ++i) {
subs_.emplace(theta_(i), t_angle_(i));
}
for (int i = 0; i < t_angle_.rows(); ++i) {
xy_sin_cos_.insert(sin_vars_(i));
xy_sin_cos_.insert(cos_vars_(i));
xyt_.insert(t_angle_(i));
}
xy_sin_cos_.insert(x_);
xy_sin_cos_.insert(y_);
xyt_.insert(x_);
xyt_.insert(y_);
}
protected:
VectorX<symbolic::Variable> cos_vars_;
VectorX<symbolic::Variable> sin_vars_;
VectorX<symbolic::Variable> t_angle_;
VectorX<symbolic::Variable> theta_;
std::vector<SinCos> sin_cos_;
symbolic::Variables cos_sin_vars_;
symbolic::Variables t_;
std::unordered_map<symbolic::Variable, symbolic::Variable> subs_;
symbolic::Variable a_;
symbolic::Variable b_;
symbolic::Variable x_;
symbolic::Variable y_;
symbolic::Variables xy_sin_cos_;
symbolic::Variables xyt_;
};
TEST_F(SubstituteStereographicProjectionTest, SingleTrigonometricPoly) {
// test cos(theta(0))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(cos_vars_(0)), sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(1 - t_angle_(0) * t_angle_(0)),
symbolic::Polynomial(1 + t_angle_(0) * t_angle_(0))));
// test sin(theta(0))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(sin_vars_(0)), sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(2 * t_angle_(0)),
symbolic::Polynomial(1 + t_angle_(0) * t_angle_(0))));
}
TEST_F(SubstituteStereographicProjectionTest, One) {
// test constant polynomial 1.
CheckSubstituteStereographicProjection(symbolic::Polynomial(1), sin_cos_,
t_angle_,
symbolic::RationalFunction(1));
}
TEST_F(SubstituteStereographicProjectionTest, ConstantPoly) {
// test a + b as a constant polynomial.
CheckSubstituteStereographicProjection(
symbolic::Polynomial({{symbolic::Monomial(), a_ + b_}}), sin_cos_,
t_angle_,
symbolic::RationalFunction(symbolic::Polynomial(
a_ + b_,
t_) /* A constant polynomial with a+b being the constant term */));
}
TEST_F(SubstituteStereographicProjectionTest, OnePlusCos) {
// test 1 + cos(theta(0))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(1 + cos_vars_(0)), sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(2),
symbolic::Polynomial(1 + t_angle_(0) * t_angle_(0))));
}
TEST_F(SubstituteStereographicProjectionTest, LinearTrigPoly) {
// test a + b*cos(delta_q(0)) + sin(delta_q(1))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(a_ + b_ * cos_vars_(0) + sin_vars_(1),
cos_sin_vars_),
sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(
a_ * (1 + t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)) +
b_ * (1 - t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)) +
2 * t_angle_(1) * (1 + t_angle_(0) * t_angle_(0)),
t_),
symbolic::Polynomial((1 + t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)))));
}
TEST_F(SubstituteStereographicProjectionTest, NonlinearTrigPoly1) {
// test a + b * cos(theta(0) * sin(theta(1)) + sin(theta(0))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(a_ + b_ * cos_vars_(0) * sin_vars_(1) + sin_vars_(0),
cos_sin_vars_),
sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(
a_ * (1 + t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)) +
b_ * (1 - t_angle_(0) * t_angle_(0)) * 2 * t_angle_(1) +
2 * t_angle_(0) * (1 + t_angle_(1) * t_angle_(1)),
t_),
symbolic::Polynomial((1 + t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)))));
}
TEST_F(SubstituteStereographicProjectionTest, NonlinearTrigPoly2) {
// test a + b * cos(theta(0)) * sin(theta(1)) + sin(theta(0)) * cos(theta(2))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(
a_ + b_ * cos_vars_(0) * sin_vars_(1) + sin_vars_(0) * cos_vars_(2),
cos_sin_vars_),
sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(
a_ * (1 + t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)) *
(1 + t_angle_(2) * t_angle_(2)) +
b_ * (1 - t_angle_(0) * t_angle_(0)) * 2 * t_angle_(1) *
(1 + t_angle_(2) * t_angle_(2)) +
2 * t_angle_(0) * (1 + t_angle_(1) * t_angle_(1)) *
(1 - t_angle_(2) * t_angle_(2)),
t_),
symbolic::Polynomial((1 + t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)) *
(1 + t_angle_(2) * t_angle_(2)))));
}
TEST_F(SubstituteStereographicProjectionTest, TAngle) {
// test t_angle(0)
CheckSubstituteStereographicProjection(
symbolic::Polynomial({{symbolic::Monomial(), t_angle_(0)}}), sin_cos_,
t_angle_,
symbolic::RationalFunction(symbolic::Polynomial(t_angle_(0), t_)));
}
TEST_F(SubstituteStereographicProjectionTest, TAngleTimesCos) {
// test t_angle(0) * cos(theta(0))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(t_angle_(0) * cos_vars_(0), cos_sin_vars_), sin_cos_,
t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(
t_angle_(0) - t_angle_(0) * t_angle_(0) * t_angle_(0), t_),
symbolic::Polynomial(1 + t_angle_(0) * t_angle_(0), t_)));
}
TEST_F(SubstituteStereographicProjectionTest, TAngleTimesSin) {
// test t_angle(0) * sin(theta(0))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(t_angle_(0) * sin_vars_(0), cos_sin_vars_), sin_cos_,
t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(2 * t_angle_(0) * t_angle_(0), t_),
symbolic::Polynomial(1 + t_angle_(0) * t_angle_(0), t_)));
}
TEST_F(SubstituteStereographicProjectionTest, NonlinearTrigPolyWithT) {
// test (t_angle(0) * a + t_angle(1) * b) * sin(delta_q(0)) * cos(delta_q(1))
// + 2 * t_angle(0) * b
CheckSubstituteStereographicProjection(
symbolic::Polynomial(
(t_angle_(0) * a_ + t_angle_(1) * b_) * sin_vars_(0) * cos_vars_(1) +
2 * t_angle_(0) * b_,
cos_sin_vars_),
sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(
(a_ * t_angle_(0) + b_ * t_angle_(1)) * 2 * t_angle_(0) *
(1 - t_angle_(1) * t_angle_(1)) +
2 * t_angle_(0) * b_ * (1 + t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)),
t_),
symbolic::Polynomial(
(1 + t_angle_(0) * t_angle_(0)) * (1 + t_angle_(1) * t_angle_(1)),
t_)));
}
TEST_F(SubstituteStereographicProjectionTest, XTimesSin) {
// Check x*sin(theta(0))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(x_ * sin_vars_(0)), sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(2 * x_ * t_angle_(0)),
symbolic::Polynomial(1 + t_angle_(0) * t_angle_(0))));
}
TEST_F(SubstituteStereographicProjectionTest, NonlinearTrigPoly3) {
// Check a * x * sin(theta(0)) + b * x*y * sin(theta(0))*cos(theta(1)) with x,
// y, sin, cos being indeterminates.
CheckSubstituteStereographicProjection(
symbolic::Polynomial(
a_ * x_ * sin_vars_(0) + b_ * x_ * y_ * sin_vars_(0) * cos_vars_(1),
xy_sin_cos_),
sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(
a_ * x_ * 2 * t_angle_(0) * (1 + t_angle_(1) * t_angle_(1)) +
b_ * x_ * y_ * 2 * t_angle_(0) *
(1 - t_angle_(1) * t_angle_(1)),
xyt_),
symbolic::Polynomial((1 + t_angle_(0) * t_angle_(0)) *
(1 + t_angle_(1) * t_angle_(1)))));
}
TEST_F(SubstituteStereographicProjectionTest, HighDegreeTrigPoly1) {
// (sin(theta(0)))Β²
CheckSubstituteStereographicProjection(
symbolic::Polynomial(sin_vars_(0) * sin_vars_(0)), sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(4 * t_angle_(0) * t_angle_(0)),
symbolic::Polynomial(pow(1 + t_angle_(0) * t_angle_(0), 2))));
// (cos(theta(0)))Β²
CheckSubstituteStereographicProjection(
symbolic::Polynomial(cos_vars_(0) * cos_vars_(0)), sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(pow(1 - t_angle_(0) * t_angle_(0), 2)),
symbolic::Polynomial(pow(1 + t_angle_(0) * t_angle_(0), 2))));
// sin(theta(0))*cos(theta(0))
CheckSubstituteStereographicProjection(
symbolic::Polynomial(sin_vars_(0) * cos_vars_(0)), sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(2 * t_angle_(0) *
(1 - t_angle_(0) * t_angle_(0))),
symbolic::Polynomial(pow(1 + t_angle_(0) * t_angle_(0), 2))));
}
TEST_F(SubstituteStereographicProjectionTest, HighDegreeTrigPoly2) {
// (sin(theta0))Β²cos(theta1) + 3*cos(theta0)sin(theta1)cos(theta1)cos(theta2)
const symbolic::Polynomial numerator(
4 * t_angle_(0) * t_angle_(0) * (1 - t_angle_(1) * t_angle_(1)) *
(1 + t_angle_(1) * t_angle_(1)) * (1 + t_angle_(2) * t_angle_(2)) +
3 * (1 - t_angle_(0) * t_angle_(0)) * (1 + t_angle_(0) * t_angle_(0)) *
2 * t_angle_(1) * (1 - t_angle_(1) * t_angle_(1)) *
(1 - t_angle_(2) * t_angle_(2)));
const symbolic::Polynomial denominator(pow(1 + t_angle_(0) * t_angle_(0), 2) *
pow(1 + t_angle_(1) * t_angle_(1), 2) *
(1 + t_angle_(2) * t_angle_(2)));
CheckSubstituteStereographicProjection(
symbolic::Polynomial(sin_vars_(0) * sin_vars_(0) * cos_vars_(1) +
3 * cos_vars_(0) * sin_vars_(1) * cos_vars_(1) *
cos_vars_(2)),
sin_cos_, t_angle_, symbolic::RationalFunction(numerator, denominator));
}
TEST_F(SubstituteStereographicProjectionTest, NonlinearTrigPoly4) {
// a * x * t0 * cos(theta1)
CheckSubstituteStereographicProjection(
symbolic::Polynomial(a_ * x_ * t_angle_(0) * cos_vars_(1), xy_sin_cos_),
sin_cos_, t_angle_,
symbolic::RationalFunction(
symbolic::Polynomial(
a_ * x_ * t_angle_(0) * (1 - t_angle_(1) * t_angle_(1)), xyt_),
symbolic::Polynomial(1 + t_angle_(1) * t_angle_(1))));
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/chebyshev_basis_element_test.cc | #include "drake/common/symbolic/chebyshev_basis_element.h"
#include <fmt/format.h>
#include <gtest/gtest.h>
#include "drake/common/symbolic/chebyshev_polynomial.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
class SymbolicChebyshevBasisElementTest : public ::testing::Test {
protected:
const Variable x_{"x"};
const Variable y_{"y"};
const Variable z_{"z"};
};
TEST_F(SymbolicChebyshevBasisElementTest, LessThan) {
const ChebyshevBasisElement p1({{x_, 1}, {y_, 2}});
const ChebyshevBasisElement p2({{y_, 3}});
const ChebyshevBasisElement p3({{x_, 3}});
const ChebyshevBasisElement p4({{z_, 1}});
EXPECT_LT(p2, p1);
EXPECT_LT(p1, p3);
EXPECT_LT(p4, p1);
EXPECT_LT(p2, p3);
EXPECT_LT(p4, p3);
}
TEST_F(SymbolicChebyshevBasisElementTest, Constructor) {
const ChebyshevBasisElement b1{};
EXPECT_TRUE(b1.var_to_degree_map().empty());
EXPECT_EQ(b1.total_degree(), 0);
const ChebyshevBasisElement b2{x_};
EXPECT_EQ(b2.var_to_degree_map().size(), 1);
EXPECT_EQ(b2.var_to_degree_map().at(x_), 1);
EXPECT_EQ(b2.total_degree(), 1);
const ChebyshevBasisElement b3{x_, 2};
EXPECT_EQ(b3.var_to_degree_map().size(), 1);
EXPECT_EQ(b3.var_to_degree_map().at(x_), 2);
EXPECT_EQ(b3.total_degree(), 2);
const ChebyshevBasisElement b4{{{x_, 2}, {y_, 1}}};
EXPECT_EQ(b4.var_to_degree_map().size(), 2);
EXPECT_EQ(b4.var_to_degree_map().at(x_), 2);
EXPECT_EQ(b4.var_to_degree_map().at(y_), 1);
EXPECT_EQ(b4.total_degree(), 3);
const ChebyshevBasisElement b5{Vector2<Variable>(x_, y_),
Eigen::Vector2i(2, 1)};
EXPECT_EQ(b5.var_to_degree_map().size(), 2);
EXPECT_EQ(b5.var_to_degree_map().at(x_), 2);
EXPECT_EQ(b5.var_to_degree_map().at(y_), 1);
EXPECT_EQ(b5.total_degree(), 3);
const ChebyshevBasisElement b6{Vector2<Variable>(x_, y_),
Eigen::Vector2i(2, 0)};
EXPECT_EQ(b6.var_to_degree_map().size(), 1);
EXPECT_EQ(b6.var_to_degree_map().at(x_), 2);
EXPECT_EQ(b6.total_degree(), 2);
DRAKE_EXPECT_THROWS_MESSAGE(
ChebyshevBasisElement(Vector2<Variable>(x_, x_), Eigen::Vector2i(2, 1)),
".*x is repeated");
DRAKE_EXPECT_THROWS_MESSAGE(
ChebyshevBasisElement(Vector2<Variable>(x_, y_), Eigen::Vector2i(2, -1)),
"The exponent is negative.");
}
TEST_F(SymbolicChebyshevBasisElementTest, Evaluate) {
Environment env;
env.insert(x_, 2);
env.insert(y_, 3);
env.insert(z_, 4);
EXPECT_EQ(ChebyshevBasisElement({{x_, 1}}).Evaluate(env), 2);
EXPECT_EQ(ChebyshevBasisElement({{x_, 1}, {y_, 2}}).Evaluate(env), 34);
EXPECT_EQ(ChebyshevBasisElement({{x_, 1}, {y_, 2}, {z_, 3}}).Evaluate(env),
2 * 17 * 244);
}
TEST_F(SymbolicChebyshevBasisElementTest, multiply) {
const auto result1 =
ChebyshevBasisElement({{x_, 1}}) * ChebyshevBasisElement({{y_, 2}});
EXPECT_EQ(result1.size(), 1);
EXPECT_EQ(result1.at(ChebyshevBasisElement({{x_, 1}, {y_, 2}})), 1.);
const auto result2 =
ChebyshevBasisElement({{x_, 1}}) * ChebyshevBasisElement({{x_, 2}});
EXPECT_EQ(result2.size(), 2);
EXPECT_EQ(result2.at(ChebyshevBasisElement({{x_, 3}})), 0.5);
EXPECT_EQ(result2.at(ChebyshevBasisElement({{x_, 1}})), 0.5);
const auto result3 = ChebyshevBasisElement({{x_, 1}, {y_, 2}}) *
ChebyshevBasisElement({{x_, 2}});
EXPECT_EQ(result3.size(), 2);
EXPECT_EQ(result3.at(ChebyshevBasisElement({{x_, 3}, {y_, 2}})), 0.5);
EXPECT_EQ(result3.at(ChebyshevBasisElement({{x_, 1}, {y_, 2}})), 0.5);
const auto result4 =
ChebyshevBasisElement({{y_, 2}}) * ChebyshevBasisElement({{x_, 1}});
EXPECT_EQ(result4.size(), 1);
EXPECT_EQ(result4.at(ChebyshevBasisElement({{x_, 1}, {y_, 2}})), 1.);
const auto result5 = ChebyshevBasisElement({{x_, 1}, {y_, 3}}) *
ChebyshevBasisElement({{x_, 2}, {y_, 1}});
EXPECT_EQ(result5.size(), 4);
EXPECT_EQ(result5.at(ChebyshevBasisElement({{x_, 3}, {y_, 4}})), 0.25);
EXPECT_EQ(result5.at(ChebyshevBasisElement({{x_, 3}, {y_, 2}})), 0.25);
EXPECT_EQ(result5.at(ChebyshevBasisElement({{x_, 1}, {y_, 4}})), 0.25);
EXPECT_EQ(result5.at(ChebyshevBasisElement({{x_, 1}, {y_, 2}})), 0.25);
const auto result6 = ChebyshevBasisElement({{y_, 2}, {z_, 3}}) *
ChebyshevBasisElement({{x_, 3}, {y_, 1}});
EXPECT_EQ(result6.size(), 2);
EXPECT_EQ(result6.at(ChebyshevBasisElement({{x_, 3}, {y_, 3}, {z_, 3}})),
0.5);
EXPECT_EQ(result6.at(ChebyshevBasisElement({{x_, 3}, {y_, 1}, {z_, 3}})),
0.5);
const auto result7 = ChebyshevBasisElement({{x_, 1}, {y_, 2}, {z_, 3}}) *
ChebyshevBasisElement({{x_, 2}, {y_, 3}, {z_, 1}});
EXPECT_EQ(result7.size(), 8);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 3}, {y_, 5}, {z_, 4}})),
0.125);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 3}, {y_, 5}, {z_, 2}})),
0.125);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 3}, {y_, 1}, {z_, 4}})),
0.125);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 3}, {y_, 1}, {z_, 2}})),
0.125);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 1}, {y_, 5}, {z_, 4}})),
0.125);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 1}, {y_, 5}, {z_, 2}})),
0.125);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 1}, {y_, 1}, {z_, 4}})),
0.125);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 1}, {y_, 1}, {z_, 2}})),
0.125);
}
TEST_F(SymbolicChebyshevBasisElementTest, Differentiate) {
// d1/dx = 0
const auto result1 = ChebyshevBasisElement().Differentiate(x_);
EXPECT_TRUE(result1.empty());
// dT2(x) / dy = 0
const auto result2 = ChebyshevBasisElement({{x_, 2}}).Differentiate(y_);
EXPECT_TRUE(result2.empty());
// dT2(x) / dx = 4 * T1(x)
const auto result3 = ChebyshevBasisElement({{x_, 2}}).Differentiate(x_);
EXPECT_EQ(result3.size(), 1);
EXPECT_EQ(result3.at(ChebyshevBasisElement({{x_, 1}})), 4);
// d(T2(x) * T3(y)) / dx = 4 * T1(x)*T3(y)
const auto result4 =
ChebyshevBasisElement({{x_, 2}, {y_, 3}}).Differentiate(x_);
EXPECT_EQ(result4.size(), 1);
EXPECT_EQ(result4.at(ChebyshevBasisElement({{x_, 1}, {y_, 3}})), 4);
// dT3(x) / dx = 6*T2(x) + 3
const auto result5 = ChebyshevBasisElement({{x_, 3}}).Differentiate(x_);
EXPECT_EQ(result5.size(), 2);
EXPECT_EQ(result5.at(ChebyshevBasisElement({{x_, 2}})), 6);
EXPECT_EQ(result5.at(ChebyshevBasisElement()), 3);
// d(T3(x) * T4(y)) / dx = 6*T2(x)*T4(y) + 3*T4(y)
const auto result6 =
ChebyshevBasisElement({{x_, 3}, {y_, 4}}).Differentiate(x_);
EXPECT_EQ(result6.size(), 2);
EXPECT_EQ(result6.at(ChebyshevBasisElement({{x_, 2}, {y_, 4}})), 6);
EXPECT_EQ(result6.at(ChebyshevBasisElement({{y_, 4}})), 3);
// dT4(x) / dx = 8*T3(x) + 8*T1(x)
const auto result7 = ChebyshevBasisElement({{x_, 4}}).Differentiate(x_);
EXPECT_EQ(result7.size(), 2);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 3}})), 8);
EXPECT_EQ(result7.at(ChebyshevBasisElement({{x_, 1}})), 8);
// d(T4(x)*T3(y)) / dx = 8*T3(x)T3(y) + 8*T1(x)T3(y)
const auto result8 =
ChebyshevBasisElement({{x_, 4}, {y_, 3}}).Differentiate(x_);
EXPECT_EQ(result8.size(), 2);
EXPECT_EQ(result8.at(ChebyshevBasisElement({{x_, 3}, {y_, 3}})), 8);
EXPECT_EQ(result8.at(ChebyshevBasisElement({{x_, 1}, {y_, 3}})), 8);
}
TEST_F(SymbolicChebyshevBasisElementTest, Integrate) {
// β«1dx = T1(x)
const auto result1 = ChebyshevBasisElement().Integrate(x_);
EXPECT_EQ(result1.size(), 1);
EXPECT_EQ(result1.at(ChebyshevBasisElement({{x_, 1}})), 1);
// β«T2(x)dy = T2(x)T1(y)
const auto result2 = ChebyshevBasisElement({{x_, 2}}).Integrate(y_);
EXPECT_EQ(result2.size(), 1);
EXPECT_EQ(result2.at(ChebyshevBasisElement({{x_, 2}, {y_, 1}})), 1);
// β«T2(x)dx = 1/6*T3(x) - 1/2*T1(x)
const auto result3 = ChebyshevBasisElement({{x_, 2}}).Integrate(x_);
EXPECT_EQ(result3.size(), 2);
EXPECT_EQ(result3.at(ChebyshevBasisElement({{x_, 3}})), 1. / 6);
EXPECT_EQ(result3.at(ChebyshevBasisElement({{x_, 1}})), -1. / 2);
// β«T3(x)T2(y)dx = 1/8*T4(x)T2(y) - 1/4*T2(x)T2(y)
const auto result4 = ChebyshevBasisElement({{x_, 3}, {y_, 2}}).Integrate(x_);
EXPECT_EQ(result4.size(), 2);
EXPECT_EQ(result4.at(ChebyshevBasisElement({{x_, 4}, {y_, 2}})), 1. / 8);
EXPECT_EQ(result4.at(ChebyshevBasisElement({{x_, 2}, {y_, 2}})), -1. / 4);
}
TEST_F(SymbolicChebyshevBasisElementTest, StringOutput) {
std::ostringstream os1;
os1 << ChebyshevBasisElement();
EXPECT_EQ(fmt::format("{}", os1.str()), "T0()");
std::ostringstream os2;
os2 << ChebyshevBasisElement({{x_, 1}});
EXPECT_EQ(fmt::format("{}", os2.str()), "T1(x)");
std::ostringstream os3;
os3 << ChebyshevBasisElement({{x_, 0}});
EXPECT_EQ(fmt::format("{}", os3.str()), "T0()");
std::ostringstream os4;
os4 << ChebyshevBasisElement({{x_, 1}, {y_, 2}});
EXPECT_EQ(fmt::format("{}", os4.str()), "T1(x)T2(y)");
}
TEST_F(SymbolicChebyshevBasisElementTest, ToExpression) {
EXPECT_PRED2(test::ExprEqual, ChebyshevBasisElement().ToExpression(),
Expression(1.));
EXPECT_PRED2(test::ExprEqual, ChebyshevBasisElement({{x_, 0}}).ToExpression(),
Expression(1.));
EXPECT_PRED2(test::ExprEqual, ChebyshevBasisElement({{x_, 2}}).ToExpression(),
ChebyshevPolynomial(x_, 2).ToPolynomial().ToExpression());
EXPECT_PRED2(test::ExprEqual,
ChebyshevBasisElement({{x_, 2}, {y_, 3}}).ToExpression(),
ChebyshevPolynomial(x_, 2).ToPolynomial().ToExpression() *
ChebyshevPolynomial(y_, 3).ToPolynomial().ToExpression());
}
TEST_F(SymbolicChebyshevBasisElementTest, EigenMatrix) {
// Checks we can have an Eigen matrix of ChebyshevBasisElements without
// compilation errors. No assertions in the test.
Eigen::Matrix<ChebyshevBasisElement, 2, 2> M;
M << ChebyshevBasisElement(), ChebyshevBasisElement({{x_, 1}}),
ChebyshevBasisElement({{x_, 1}, {y_, 2}}),
ChebyshevBasisElement({{y_, 2}});
}
TEST_F(SymbolicChebyshevBasisElementTest, Hash) {
// Check that ChebyshevBasisElement can be used as a key in
// std::unordered_map.
std::unordered_map<ChebyshevBasisElement, int> map;
map.emplace(ChebyshevBasisElement({{x_, 1}}), 1);
EXPECT_EQ(map.size(), 1);
EXPECT_EQ(map.at(ChebyshevBasisElement({{x_, 1}})), 1);
map.emplace(ChebyshevBasisElement({{x_, 1}, {y_, 2}}), 2);
EXPECT_EQ(map.size(), 2);
EXPECT_EQ(map.at(ChebyshevBasisElement({{x_, 1}, {y_, 2}})), 2);
// Test the special case to map T0() to 3.
map.emplace(ChebyshevBasisElement({{x_, 0}}), 3);
EXPECT_EQ(map.size(), 3);
// T0(y) = T0(x) = 1.
EXPECT_EQ(map.at(ChebyshevBasisElement({{y_, 0}})), 3);
}
TEST_F(SymbolicChebyshevBasisElementTest, EvaluatePartial) {
Environment env;
env.insert(x_, 3);
const ChebyshevBasisElement m1{{{x_, 2}, {y_, 4}, {z_, 3}}};
double coeff;
ChebyshevBasisElement new_basis_element;
std::tie(coeff, new_basis_element) = m1.EvaluatePartial(env);
EXPECT_EQ(coeff, 17);
EXPECT_EQ(new_basis_element, ChebyshevBasisElement({{y_, 4}, {z_, 3}}));
env.insert(z_, 2);
std::tie(coeff, new_basis_element) = m1.EvaluatePartial(env);
EXPECT_EQ(coeff, 17 * 26);
EXPECT_EQ(new_basis_element, ChebyshevBasisElement(y_, 4));
}
TEST_F(SymbolicChebyshevBasisElementTest, MergeBasisElementInPlace) {
// Merge Tβ(x)Tβ(y) and Tβ(x)Tβ(z) gets Tβ(x)Tβ(y)Tβ(z)
ChebyshevBasisElement basis_element1({{x_, 1}, {y_, 3}});
basis_element1.MergeBasisElementInPlace(
ChebyshevBasisElement({{x_, 1}, {z_, 2}}));
EXPECT_EQ(basis_element1.var_to_degree_map().size(), 3);
EXPECT_EQ(basis_element1.var_to_degree_map().at(x_), 2);
EXPECT_EQ(basis_element1.var_to_degree_map().at(y_), 3);
EXPECT_EQ(basis_element1.var_to_degree_map().at(z_), 2);
EXPECT_EQ(basis_element1.total_degree(), 7);
}
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/codegen_test.cc | #include "drake/common/symbolic/codegen.h"
#include <sstream>
#include <vector>
#include <fmt/format.h>
#include <gtest/gtest.h>
namespace drake {
namespace symbolic {
namespace {
using std::ostringstream;
using std::string;
using std::vector;
// Helper function to combine the function name @p function_name and an
// expression @p e with the proper function header and footer.
string MakeScalarFunctionCode(const string& function_name, const int n,
const string& e) {
// Note that fmtlib requires to escape "{'" and "}" using "{{" and "}}".
return fmt::format(
R"""(double {0}(const double* p) {{
return {1};
}}
typedef struct {{
/* p: input, vector */
struct {{ int size; }} p;
}} {0}_meta_t;
{0}_meta_t {0}_meta() {{ return {{{{{2}}}}}; }}
)""",
function_name, e, n);
}
// Helper function to generate expected codegen outcome for a dense matrix @p
// M. It combines the function name @p function_name, the number of input
// parameters @p in, the number of rows in M, @p rows, the number of columns in
// M, @p cols, and the expected code for the entries in M, @p expressions.
string MakeDenseMatrixFunctionCode(const string& function_name, const int in,
const int rows, const int cols,
const vector<string>& expressions) {
ostringstream oss;
// Main function f.
oss << fmt::format("void {0}(const double* p, double* m) {{\n",
function_name);
for (size_t i{0}; i < expressions.size(); ++i) {
oss << fmt::format(" m[{0}] = {1};\n", i, expressions[i]);
}
oss << "}\n";
// f_meta_t.
oss << fmt::format(
R"""(typedef struct {{
/* p: input, vector */
struct {{ int size; }} p;
/* m: output, matrix */
struct {{ int rows; int cols; }} m;
}} {0}_meta_t;
{0}_meta_t {0}_meta() {{ return {{{{{1}}}, {{{2}, {3}}}}}; }}
)""",
function_name, in, rows, cols);
return oss.str();
}
class SymbolicCodeGenTest : public ::testing::Test {
protected:
const Variable x_{"x"};
const Variable y_{"y"};
const Variable z_{"z"};
const Variable w_{"w"};
};
TEST_F(SymbolicCodeGenTest, Variable) {
EXPECT_EQ(CodeGen("f", {x_, y_}, x_), MakeScalarFunctionCode("f", 2, "p[0]"));
EXPECT_EQ(CodeGen("f", {x_, y_, z_}, z_),
MakeScalarFunctionCode("f", 3, "p[2]"));
}
TEST_F(SymbolicCodeGenTest, Constant) {
EXPECT_EQ(CodeGen("f", {}, 3.141592),
MakeScalarFunctionCode("f", 0, "3.141592"));
}
TEST_F(SymbolicCodeGenTest, Addition) {
EXPECT_EQ(CodeGen("f", {x_, y_}, 2.0 + 3.0 * x_ - 7.0 * y_),
MakeScalarFunctionCode("f", 2, "(2 + (3 * p[0]) + (-7 * p[1]))"));
}
TEST_F(SymbolicCodeGenTest, Multiplication) {
EXPECT_EQ(CodeGen("f", {x_, y_}, 2.0 * 3.0 * x_ * x_ * -7.0 * y_ * y_ * y_),
MakeScalarFunctionCode(
"f", 2, "(-42 * pow(p[0], 2.000000) * pow(p[1], 3.000000))"));
}
TEST_F(SymbolicCodeGenTest, Pow) {
EXPECT_EQ(CodeGen("f", {x_, y_}, pow(2 + x_, 3 * y_)),
MakeScalarFunctionCode("f", 2, "pow((2 + p[0]), (3 * p[1]))"));
}
TEST_F(SymbolicCodeGenTest, Division) {
EXPECT_EQ(CodeGen("f", {x_, y_}, (2 + x_) / (3 * y_)),
MakeScalarFunctionCode("f", 2, "((2 + p[0]) / (3 * p[1]))"));
}
TEST_F(SymbolicCodeGenTest, Abs) {
EXPECT_EQ(CodeGen("f", {x_, y_}, abs(2 + x_)),
MakeScalarFunctionCode("f", 2, "fabs((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Log) {
EXPECT_EQ(CodeGen("f", {x_, y_}, log(2 + x_)),
MakeScalarFunctionCode("f", 2, "log((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Exp) {
EXPECT_EQ(CodeGen("f", {x_, y_}, exp(2 + x_)),
MakeScalarFunctionCode("f", 2, "exp((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Sqrt) {
EXPECT_EQ(CodeGen("f", {x_, y_}, sqrt(2 + x_)),
MakeScalarFunctionCode("f", 2, "sqrt((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Sin) {
EXPECT_EQ(CodeGen("f", {x_, y_}, sin(2 + x_)),
MakeScalarFunctionCode("f", 2, "sin((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Cos) {
EXPECT_EQ(CodeGen("f", {x_, y_}, cos(2 + x_)),
MakeScalarFunctionCode("f", 2, "cos((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Tan) {
EXPECT_EQ(CodeGen("f", {x_, y_}, tan(2 + x_)),
MakeScalarFunctionCode("f", 2, "tan((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Asin) {
EXPECT_EQ(CodeGen("f", {x_, y_}, asin(2 + x_)),
MakeScalarFunctionCode("f", 2, "asin((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Acos) {
EXPECT_EQ(CodeGen("f", {x_, y_}, acos(2 + x_)),
MakeScalarFunctionCode("f", 2, "acos((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Atan) {
EXPECT_EQ(CodeGen("f", {x_, y_}, atan(2 + x_)),
MakeScalarFunctionCode("f", 2, "atan((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Atan2) {
EXPECT_EQ(CodeGen("f", {x_, y_}, atan2(2 + x_, 3 + y_)),
MakeScalarFunctionCode("f", 2, "atan2((2 + p[0]), (3 + p[1]))"));
}
TEST_F(SymbolicCodeGenTest, Sinh) {
EXPECT_EQ(CodeGen("f", {x_, y_}, sinh(2 + x_)),
MakeScalarFunctionCode("f", 2, "sinh((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Cosh) {
EXPECT_EQ(CodeGen("f", {x_, y_}, cosh(2 + x_)),
MakeScalarFunctionCode("f", 2, "cosh((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Tanh) {
EXPECT_EQ(CodeGen("f", {x_, y_}, tanh(2 + x_)),
MakeScalarFunctionCode("f", 2, "tanh((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Min) {
EXPECT_EQ(CodeGen("f", {x_, y_}, min(2 + x_, 3 + y_)),
MakeScalarFunctionCode("f", 2, "fmin((2 + p[0]), (3 + p[1]))"));
}
TEST_F(SymbolicCodeGenTest, Max) {
EXPECT_EQ(CodeGen("f", {x_, y_}, max(2 + x_, 3 + y_)),
MakeScalarFunctionCode("f", 2, "fmax((2 + p[0]), (3 + p[1]))"));
}
TEST_F(SymbolicCodeGenTest, Ceil) {
EXPECT_EQ(CodeGen("f", {x_, y_}, ceil(2 + x_)),
MakeScalarFunctionCode("f", 2, "ceil((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, Floor) {
EXPECT_EQ(CodeGen("f", {x_, y_}, floor(2 + x_)),
MakeScalarFunctionCode("f", 2, "floor((2 + p[0]))"));
}
TEST_F(SymbolicCodeGenTest, IfThenElse) {
const Expression e{if_then_else(x_ > y_, x_, y_)};
EXPECT_THROW(CodeGen("f", {x_, y_}, e), std::runtime_error);
}
TEST_F(SymbolicCodeGenTest, UninterpretedFunction) {
const Expression e{uninterpreted_function("uf", {x_, y_})};
EXPECT_THROW(CodeGen("f", {x_, y_}, e), std::runtime_error);
}
TEST_F(SymbolicCodeGenTest, ScalarExampleInDocumentation) {
EXPECT_EQ(CodeGen("f", {x_, y_}, 1 + sin(x_) + cos(y_)),
MakeScalarFunctionCode("f", 2, "(1 + sin(p[0]) + cos(p[1]))"));
}
TEST_F(SymbolicCodeGenTest, DenseMatrixRowMajor) {
Eigen::Matrix<symbolic::Expression, 3, 2, Eigen::RowMajor> M;
vector<string> expected;
M(0, 0) = 3 + 2 * x_ + y_;
expected.push_back("(3 + (2 * p[0]) + p[1])");
M(0, 1) = 2 * pow(x_, 2) * pow(y_, 3);
expected.push_back("(2 * pow(p[0], 2.000000) * pow(p[1], 3.000000))");
M(1, 0) = 5 + sin(x_) + cos(z_);
expected.push_back("(5 + sin(p[0]) + cos(p[2]))");
M(1, 1) = 3 * min(x_, w_);
expected.push_back("(3 * fmin(p[0], p[3]))");
M(2, 0) = (x_ + 2) / (y_ - 2);
expected.push_back("((2 + p[0]) / (-2 + p[1]))");
M(2, 1) = atan2(w_ + 3, y_ + 4);
expected.push_back("atan2((3 + p[3]), (4 + p[1]))");
EXPECT_EQ(CodeGen("f", {x_, y_, z_, w_}, M),
MakeDenseMatrixFunctionCode("f", 4 /* number of input parameters */,
3 /* number of rows */,
2 /* number of columns */, expected));
}
TEST_F(SymbolicCodeGenTest, DenseMatrixColMajor) {
Eigen::Matrix<symbolic::Expression, 3, 2, Eigen::ColMajor> M;
vector<string> expected;
M(0, 0) = 3 + 2 * x_ + y_;
expected.push_back("(3 + (2 * p[0]) + p[1])");
M(1, 0) = 5 + sin(x_) + cos(z_);
expected.push_back("(5 + sin(p[0]) + cos(p[2]))");
M(2, 0) = (x_ + 2) / (y_ - 2);
expected.push_back("((2 + p[0]) / (-2 + p[1]))");
M(0, 1) = 2 * pow(x_, 2) * pow(y_, 3);
expected.push_back("(2 * pow(p[0], 2.000000) * pow(p[1], 3.000000))");
M(1, 1) = 3 * min(x_, w_);
expected.push_back("(3 * fmin(p[0], p[3]))");
M(2, 1) = atan2(w_ + 3, y_ + 4);
expected.push_back("atan2((3 + p[3]), (4 + p[1]))");
EXPECT_EQ(CodeGen("f", {x_, y_, z_, w_}, M),
MakeDenseMatrixFunctionCode("f", 4 /* number of input parameters */,
3 /* number of rows */,
2 /* number of columns */, expected));
}
TEST_F(SymbolicCodeGenTest, DenseMatrixExampleInDocumentation) {
Eigen::Matrix<symbolic::Expression, 2, 2, Eigen::ColMajor> M;
vector<string> expected;
M(0, 0) = 1.0;
expected.push_back("1.000000");
M(1, 0) = 3 + x_ + y_;
expected.push_back("(3 + p[0] + p[1])");
M(0, 1) = 4 * y_;
expected.push_back("(4 * p[1])");
M(1, 1) = sin(x_);
expected.push_back("sin(p[0])");
EXPECT_EQ(CodeGen("f", {x_, y_}, M),
MakeDenseMatrixFunctionCode("f", 2 /* number of input parameters */,
2 /* number of rows */,
2 /* number of columns */, expected));
}
TEST_F(SymbolicCodeGenTest, SparseMatrixColMajor) {
const Variable x{"x"};
const Variable y{"y"};
const Variable z{"z"};
// | x 0 0 0 z 0|
// | 0 0 y 0 0 0|
// | 0 0 0 y 0 y|
Eigen::SparseMatrix<Expression, Eigen::ColMajor> m(3, 6);
m.insert(0, 0) = x;
m.insert(0, 4) = z;
m.insert(1, 2) = y;
m.insert(2, 3) = y;
m.insert(2, 5) = y;
m.makeCompressed();
const string generated{CodeGen("f", {x, y, z}, m)};
const string expected{
R"""(void f(const double* p, int* outer_indices, int* inner_indices, double* values) {
outer_indices[0] = 0;
outer_indices[1] = 1;
outer_indices[2] = 1;
outer_indices[3] = 2;
outer_indices[4] = 3;
outer_indices[5] = 4;
outer_indices[6] = 5;
inner_indices[0] = 0;
inner_indices[1] = 1;
inner_indices[2] = 2;
inner_indices[3] = 0;
inner_indices[4] = 2;
values[0] = p[0];
values[1] = p[1];
values[2] = p[1];
values[3] = p[2];
values[4] = p[1];
}
typedef struct {
/* p: input, vector */
struct { int size; } p;
/* m: output, matrix */
struct {
int rows;
int cols;
int non_zeros;
int outer_indices;
int inner_indices;
} m;
} f_meta_t;
f_meta_t f_meta() { return {{3}, {3, 6, 5, 7, 5}}; }
)"""};
EXPECT_EQ(generated, expected);
}
// This is the generated code (string expected) from the above
// SparseMatrixColMajor testcase. We use it in the following
// SparseMatrixColMajorExampleUsingEigenMap testcase.
void f(const double* p, int* outer_indices, int* inner_indices,
double* values) {
outer_indices[0] = 0;
outer_indices[1] = 1;
outer_indices[2] = 1;
outer_indices[3] = 2;
outer_indices[4] = 3;
outer_indices[5] = 4;
outer_indices[6] = 5;
inner_indices[0] = 0;
inner_indices[1] = 1;
inner_indices[2] = 2;
inner_indices[3] = 0;
inner_indices[4] = 2;
values[0] = p[0];
values[1] = p[1];
values[2] = p[1];
values[3] = p[2];
values[4] = p[1];
}
typedef struct {
/* p: input, vector */
struct {
int size;
} p;
/* m: output, matrix */
struct {
int rows;
int cols;
int non_zeros;
int outer_indices;
int inner_indices;
} m;
} f_meta_t;
f_meta_t f_meta() {
return {{3}, {3, 6, 5, 7, 5}};
}
TEST_F(SymbolicCodeGenTest, SparseMatrixColMajorExampleUsingEigenMap) {
f_meta_t meta = f_meta();
// Checks that the meta information is correct.
EXPECT_EQ(meta.p.size, 3);
EXPECT_EQ(meta.m.rows, 3);
EXPECT_EQ(meta.m.cols, 6);
EXPECT_EQ(meta.m.non_zeros, 5);
// Prepares param, outer_indices, inner_indices, and values to call the
// generated function f.
const Eigen::Vector3d param{1 /* x */, 2 /* y */, 3 /* z */};
vector<int> outer_indices(meta.m.outer_indices);
vector<int> inner_indices(meta.m.inner_indices);
vector<double> values(meta.m.non_zeros);
// Calls f to fill the output parameters, `outer_indices`, `inner_indices`,
// and `values`.
f(param.data(), outer_indices.data(), inner_indices.data(), values.data());
// Uses `Eigen::Map` to construct a sparse matrix of double from
// `outer_indices`, `inner_indices`, and `values`.
Eigen::Map<Eigen::SparseMatrix<double, Eigen::ColMajor>> map_sp(
meta.m.rows, meta.m.cols, meta.m.non_zeros, outer_indices.data(),
inner_indices.data(), values.data());
const Eigen::SparseMatrix<double> m_double{map_sp.eval()};
// Checks that the constructed m_double is the expected one.
EXPECT_EQ(m_double.rows(), 3);
EXPECT_EQ(m_double.cols(), 6);
EXPECT_EQ(m_double.nonZeros(), 5);
EXPECT_EQ(m_double.coeff(0, 0), 1.0 /* x */);
EXPECT_EQ(m_double.coeff(0, 4), 3.0 /* z */);
EXPECT_EQ(m_double.coeff(1, 2), 2.0 /* y */);
EXPECT_EQ(m_double.coeff(2, 3), 2.0 /* y */);
EXPECT_EQ(m_double.coeff(2, 5), 2.0 /* y */);
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/monomial_basis_element_test.cc | #include "drake/common/symbolic/monomial_basis_element.h"
#include <fmt/format.h>
#include <gtest/gtest.h>
#include "drake/common/symbolic/expression.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
#include "drake/common/unused.h"
using std::pair;
using std::runtime_error;
namespace drake {
namespace symbolic {
using test::ExprEqual;
using test::VarLess;
class MonomialBasisElementTest : public ::testing::Test {
protected:
const symbolic::Variable var_w_{"w"};
const symbolic::Variable var_z_{"z"};
const symbolic::Variable var_y_{"y"};
const symbolic::Variable var_x_{"x"};
const Expression w_{var_w_};
const Expression z_{var_z_};
const Expression y_{var_y_};
const Expression x_{var_x_};
std::vector<MonomialBasisElement> monomials_;
void SetUp() override {
monomials_ = {
MonomialBasisElement{}, // 1.0
MonomialBasisElement{var_x_, 1}, // x^1
MonomialBasisElement{var_y_, 1}, // y^1
MonomialBasisElement{var_z_, 1}, // z^1
MonomialBasisElement{var_x_, 2}, // x^2
MonomialBasisElement{var_y_, 3}, // y^3
MonomialBasisElement{var_z_, 4}, // z^4
MonomialBasisElement{{{var_x_, 1}, {var_y_, 2}}}, // xy^2
MonomialBasisElement{{{var_y_, 2}, {var_z_, 5}}}, // y^2z^5
MonomialBasisElement{
{{var_x_, 1}, {var_y_, 2}, {var_z_, 3}}}, // xy^2z^3
MonomialBasisElement{
{{var_x_, 2}, {var_y_, 4}, {var_z_, 3}}}, // x^2y^4z^3
};
EXPECT_PRED2(VarLess, var_y_, var_x_);
EXPECT_PRED2(VarLess, var_z_, var_y_);
EXPECT_PRED2(VarLess, var_w_, var_z_);
}
// Helper function to extract Substitution (Variable -> Expression) from a
// symbolic environment.
Substitution ExtractSubst(const Environment& env) {
Substitution subst;
subst.reserve(env.size());
for (const pair<const Variable, double>& p : env) {
subst.emplace(p.first, p.second);
}
return subst;
}
// Checks if MonomialBasisElement::Evaluate corresponds to
// Expression::Evaluate.
//
// ToExpression
// MonomialBasisElement ----> Expression
// || ||
// MonomialBasisElement::Evaluate || || Expression::Evaluate
// || ||
// \/ \/
// double (result2) == double (result1)
//
// In one direction (left-to-right), we convert a Monomial to an Expression
// and evaluate it to a double value (result1). In another direction
// (top-to-bottom), we directly evaluate a Monomial to double (result2). The
// two result1 and result2 should be the same.
bool CheckEvaluate(const MonomialBasisElement& m, const Environment& env) {
const double result1{m.ToExpression().Evaluate(env)};
const double result2{m.Evaluate(env)};
return result1 == result2;
}
// Checks if MonomialBasisElement::EvaluatePartial corresponds to Expression's
// EvaluatePartial.
//
// ToExpression
// MonomialBasisElement ---------> Expression
// || ||
// EvaluatePartial || || EvaluatePartial
// || ||
// \/ \/
// double * MonomialBasisElement (e2) == Expression (e1)
//
// In one direction (left-to-right), first we convert a MonomialBasisElement
// to an Expression using MonomialBasisElement::ToExpression and call
// Expression::EvaluatePartial to have an Expression (e1). In another
// direction (top-to-bottom), we call MonomialBasisElement::EvaluatePartial
// which returns a pair of double (coefficient part) and Monomial. We obtain
// e2 by multiplying the two. Then, we check if e1 and e2 are structurally
// equal.
bool CheckEvaluatePartial(const MonomialBasisElement& m,
const Environment& env) {
const Expression e1{m.ToExpression().EvaluatePartial(env)};
const pair<double, MonomialBasisElement> subst_result{
m.EvaluatePartial(env)};
const Expression e2{subst_result.first *
subst_result.second.ToExpression()};
return e1.EqualTo(e2);
}
};
TEST_F(MonomialBasisElementTest, Constructor) {
const MonomialBasisElement m1{};
EXPECT_TRUE(m1.var_to_degree_map().empty());
EXPECT_EQ(m1.total_degree(), 0);
const MonomialBasisElement m2{var_x_};
EXPECT_EQ(m2.var_to_degree_map().size(), 1);
EXPECT_EQ(m2.var_to_degree_map().at(var_x_), 1);
EXPECT_EQ(m2.total_degree(), 1);
const MonomialBasisElement m3{pow(var_x_, 2) * pow(var_y_, 3)};
EXPECT_EQ(m3.var_to_degree_map().size(), 2);
EXPECT_EQ(m3.var_to_degree_map().at(var_x_), 2);
EXPECT_EQ(m3.var_to_degree_map().at(var_y_), 3);
EXPECT_EQ(m3.total_degree(), 5);
const MonomialBasisElement m4{{{var_x_, 3}, {var_y_, 2}}};
EXPECT_EQ(m4.var_to_degree_map().size(), 2);
EXPECT_EQ(m4.var_to_degree_map().at(var_x_), 3);
EXPECT_EQ(m4.var_to_degree_map().at(var_y_), 2);
EXPECT_EQ(m4.total_degree(), 5);
const MonomialBasisElement m5{{{var_x_, 3}, {var_y_, 0}}};
EXPECT_EQ(m5.var_to_degree_map().size(), 1);
EXPECT_EQ(m5.var_to_degree_map().at(var_x_), 3);
EXPECT_EQ(m5.total_degree(), 3);
const MonomialBasisElement m6{Vector2<Variable>(var_x_, var_y_),
Eigen::Vector2i(1, 3)};
EXPECT_EQ(m6.var_to_degree_map().size(), 2);
EXPECT_EQ(m6.var_to_degree_map().at(var_x_), 1);
EXPECT_EQ(m6.var_to_degree_map().at(var_y_), 3);
EXPECT_EQ(m6.total_degree(), 4);
const MonomialBasisElement m7{var_x_, 3};
EXPECT_EQ(m7.var_to_degree_map().size(), 1);
EXPECT_EQ(m7.var_to_degree_map().at(var_x_), 3);
EXPECT_EQ(m7.total_degree(), 3);
}
// Tests that default constructor and EIGEN_INITIALIZE_MATRICES_BY_ZERO
// constructor both create the same value.
TEST_F(MonomialBasisElementTest, DefaultConstructors) {
const MonomialBasisElement m_default;
const MonomialBasisElement m_zero(0);
EXPECT_EQ(m_default.total_degree(), 0);
EXPECT_EQ(m_zero.total_degree(), 0);
}
TEST_F(MonomialBasisElementTest, ConstructFromVariable) {
const MonomialBasisElement m1{var_x_};
const std::map<Variable, int> powers{m1.var_to_degree_map()};
// Checks that powers = {x β¦ 1}.
ASSERT_EQ(powers.size(), 1u);
EXPECT_EQ(powers.begin()->first, var_x_);
EXPECT_EQ(powers.begin()->second, 1);
}
TEST_F(MonomialBasisElementTest, ConstructFromVariablesAndExponents) {
// [] * [] => 1.
const VectorX<Variable> vars(0);
const VectorX<int> exponents(0);
const MonomialBasisElement one{MonomialBasisElement{Expression::One()}};
EXPECT_EQ(MonomialBasisElement(vars, exponents), one);
const Vector3<Variable> vars_xyz{var_x_, var_y_, var_z_};
// [x, y, z] * [0, 0, 0] => 1.
const MonomialBasisElement m1{vars_xyz, Eigen::Vector3i{0, 0, 0}};
EXPECT_EQ(m1, one);
// [x, y, z] * [1, 1, 1] => xyz.
const MonomialBasisElement m2{vars_xyz, Eigen::Vector3i{1, 1, 1}};
const MonomialBasisElement m2_expected{x_ * y_ * z_};
EXPECT_EQ(m2, m2_expected);
// [x, y, z] * [2, 0, 3] => xΒ²zΒ³.
const MonomialBasisElement m3{vars_xyz, Eigen::Vector3i{2, 0, 3}};
const MonomialBasisElement m3_expected{pow(x_, 2) * pow(z_, 3)};
EXPECT_EQ(m3, m3_expected);
// [x, y, z] * [2, 0, -1] => Exception!
DRAKE_EXPECT_THROWS_MESSAGE(
MonomialBasisElement(vars_xyz, Eigen::Vector3i(2, 0, -1)),
"The exponent is negative.");
}
TEST_F(MonomialBasisElementTest, GetVariables) {
const MonomialBasisElement m0{};
EXPECT_EQ(m0.GetVariables(), Variables{});
const MonomialBasisElement m1{var_z_, 4};
EXPECT_EQ(m1.GetVariables(), Variables({var_z_}));
const MonomialBasisElement m2{{{var_x_, 1}, {var_y_, 2}}};
EXPECT_EQ(m2.GetVariables(), Variables({var_x_, var_y_}));
const MonomialBasisElement m3{{{var_x_, 1}, {var_y_, 2}, {var_z_, 3}}};
EXPECT_EQ(m3.GetVariables(), Variables({var_x_, var_y_, var_z_}));
}
// Checks we can have an Eigen matrix of Monomials without compilation
// errors. No assertions in the test.
TEST_F(MonomialBasisElementTest, EigenMatrixOfMonomials) {
Eigen::Matrix<MonomialBasisElement, 2, 2> M;
// M = | 1 x |
// | yΒ² xΒ²zΒ³ |
M << MonomialBasisElement{}, MonomialBasisElement{var_x_},
MonomialBasisElement{{{var_y_, 2}}},
MonomialBasisElement{{{var_x_, 2}, {var_z_, 3}}};
}
TEST_F(MonomialBasisElementTest, MonomialOne) {
// Compares monomials all equal to 1, but with different variables.
MonomialBasisElement m1{};
MonomialBasisElement m2({{var_x_, 0}});
MonomialBasisElement m3({{var_x_, 0}, {var_y_, 0}});
EXPECT_EQ(m1, m2);
EXPECT_EQ(m1, m3);
EXPECT_EQ(m2, m3);
}
TEST_F(MonomialBasisElementTest, MonomialWithZeroExponent) {
// Compares monomials containing zero exponent, such as x^0 * y^2
MonomialBasisElement m1({{var_y_, 2}});
MonomialBasisElement m2({{var_x_, 0}, {var_y_, 2}});
EXPECT_EQ(m1, m2);
EXPECT_EQ(m2.var_to_degree_map().size(), 1);
std::map<Variable, int> power_expected;
power_expected.emplace(var_y_, 2);
EXPECT_EQ(m2.var_to_degree_map(), power_expected);
}
// This test shows that we can have a std::unordered_map whose key is of
// MonomialBasisElement.
TEST_F(MonomialBasisElementTest, UnorderedMapOfMonomial) {
std::unordered_map<MonomialBasisElement, double> monomial_to_coeff_map;
MonomialBasisElement x_3{var_x_, 3};
MonomialBasisElement y_5{var_y_, 5};
// Add 2 * x^3
monomial_to_coeff_map.emplace(x_3, 2);
// Add -7 * y^5
monomial_to_coeff_map.emplace(y_5, -7);
const auto it1 = monomial_to_coeff_map.find(x_3);
ASSERT_TRUE(it1 != monomial_to_coeff_map.end());
EXPECT_EQ(it1->second, 2);
const auto it2 = monomial_to_coeff_map.find(y_5);
ASSERT_TRUE(it2 != monomial_to_coeff_map.end());
EXPECT_EQ(it2->second, -7);
}
// Converts a constant to monomial.
TEST_F(MonomialBasisElementTest, ToMonomial0) {
MonomialBasisElement expected;
EXPECT_EQ(MonomialBasisElement(1), expected);
EXPECT_EQ(MonomialBasisElement(pow(x_, 0)), expected);
EXPECT_THROW(MonomialBasisElement(2), std::exception);
}
// Converts expression x to monomial.
TEST_F(MonomialBasisElementTest, ToMonomial1) {
MonomialBasisElement expected(var_x_, 1);
EXPECT_EQ(MonomialBasisElement(x_), expected);
}
// Converts expression x * y to monomial.
TEST_F(MonomialBasisElementTest, ToMonomial2) {
std::map<Variable, int> powers;
powers.emplace(var_x_, 1);
powers.emplace(var_y_, 1);
MonomialBasisElement expected(powers);
EXPECT_EQ(MonomialBasisElement(x_ * y_), expected);
}
// Converts expression x^3 to monomial.
TEST_F(MonomialBasisElementTest, ToMonomial3) {
MonomialBasisElement expected(var_x_, 3);
EXPECT_EQ(MonomialBasisElement(pow(x_, 3)), expected);
EXPECT_EQ(MonomialBasisElement(pow(x_, 2) * x_), expected);
}
// Converts expression x^3 * y to monomial.
TEST_F(MonomialBasisElementTest, ToMonomial4) {
std::map<Variable, int> powers;
powers.emplace(var_x_, 3);
powers.emplace(var_y_, 1);
MonomialBasisElement expected(powers);
EXPECT_EQ(MonomialBasisElement(pow(x_, 3) * y_), expected);
EXPECT_EQ(MonomialBasisElement(pow(x_, 2) * y_ * x_), expected);
}
// Converts expression x*(y+z) - x*y to monomial
TEST_F(MonomialBasisElementTest, ToMonomial5) {
std::map<Variable, int> powers({{var_x_, 1}, {var_z_, 1}});
MonomialBasisElement expected(powers);
EXPECT_EQ(MonomialBasisElement(x_ * z_), expected);
EXPECT_EQ(MonomialBasisElement(x_ * (y_ + z_) - x_ * y_), expected);
}
// `pow(x * y, 2) * pow(x^2 * y^2, 3)` is a monomial (x^8 * y^8).
TEST_F(MonomialBasisElementTest, ToMonomial6) {
const MonomialBasisElement m1{pow(x_ * y_, 2) * pow(x_ * x_ * y_ * y_, 3)};
const MonomialBasisElement m2{{{var_x_, 8}, {var_y_, 8}}};
EXPECT_EQ(m1, m2);
}
// x^0 is a monomial (1).
TEST_F(MonomialBasisElementTest, ToMonomial7) {
const MonomialBasisElement m1(var_x_, 0);
const MonomialBasisElement m2{Expression{1.0}};
const MonomialBasisElement m3{pow(x_, 0.0)};
EXPECT_EQ(m1, m2);
EXPECT_EQ(m1, m3);
EXPECT_EQ(m2, m3);
}
// `2 * x` is not a monomial because of its coefficient `2`.
TEST_F(MonomialBasisElementTest, ToMonomialException1) {
EXPECT_THROW(MonomialBasisElement{2 * x_}, runtime_error);
}
// `x + y` is not a monomial.
TEST_F(MonomialBasisElementTest, ToMonomialException2) {
EXPECT_THROW(MonomialBasisElement{x_ + y_}, runtime_error);
}
// `x / 2.0` is not a monomial.
TEST_F(MonomialBasisElementTest, ToMonomialException3) {
EXPECT_THROW(MonomialBasisElement{x_ / 2.0}, runtime_error);
}
// `x ^ -1` is not a monomial.
TEST_F(MonomialBasisElementTest, ToMonomialException4) {
// Note: Parentheses are required around macro argument containing braced
// initializer list.
DRAKE_EXPECT_THROWS_MESSAGE((MonomialBasisElement{{{var_x_, -1}}}),
"The degree for x is negative.");
}
TEST_F(MonomialBasisElementTest, Multiplication) {
// mβ = xyΒ²
const MonomialBasisElement m1{{{var_x_, 1}, {var_y_, 2}}};
// mβ = yΒ²zβ΅
const MonomialBasisElement m2{{{var_y_, 2}, {var_z_, 5}}};
// mβ = mβ * mβ = xyβ΄zβ΅
const MonomialBasisElement m3{{{var_x_, 1}, {var_y_, 4}, {var_z_, 5}}};
const std::map<MonomialBasisElement, double> result1 = m1 * m2;
EXPECT_EQ(result1.size(), 1);
EXPECT_EQ(result1.at(m3), 1);
// mβ=zΒ³
const MonomialBasisElement m4(var_z_, 3);
const auto result2 = m1 * m4;
EXPECT_EQ(result2.size(), 1);
EXPECT_EQ(
result2.at(MonomialBasisElement({{var_x_, 1}, {var_y_, 2}, {var_z_, 3}})),
1);
const auto result3 = m2 * m4;
EXPECT_EQ(result3.size(), 1);
EXPECT_EQ(result3.at(MonomialBasisElement({{var_y_, 2}, {var_z_, 8}})), 1);
}
TEST_F(MonomialBasisElementTest, Pow) {
// mβ = xyΒ²
const MonomialBasisElement m1{{{var_x_, 1}, {var_y_, 2}}};
// mβ = yΒ²zβ΅
const MonomialBasisElement m2{{{var_y_, 2}, {var_z_, 5}}};
// pow(mβ, 0) = 1.0
const std::map<MonomialBasisElement, double> result1 = pow(m1, 0);
EXPECT_EQ(result1.size(), 1);
EXPECT_EQ(result1.at(MonomialBasisElement()), 1);
// pow(mβ, 0) = 1.0
const std::map<MonomialBasisElement, double> result2 = pow(m2, 0);
EXPECT_EQ(result2.size(), 1);
EXPECT_EQ(result2.at(MonomialBasisElement()), 1);
// pow(mβ, 1) = mβ
const auto result3 = pow(m1, 1);
EXPECT_EQ(result3.size(), 1);
EXPECT_EQ(result3.at(m1), 1);
// pow(mβ, 1) = mβ
const auto result4 = pow(m2, 1);
EXPECT_EQ(result4.size(), 1);
EXPECT_EQ(result4.at(m2), 1);
// pow(mβ, 3) = xΒ³yβΆ
const auto result5 = pow(m1, 3);
EXPECT_EQ(result5.size(), 1);
EXPECT_EQ(result5.at(MonomialBasisElement({{var_x_, 3}, {var_y_, 6}})), 1);
EXPECT_EQ(result5.begin()->first.total_degree(), 9);
// pow(mβ, 4) = yβΈzΒ²β°
const auto result6 = pow(m2, 4);
EXPECT_EQ(result6.size(), 1);
EXPECT_EQ(result6.at(MonomialBasisElement({{var_y_, 8}, {var_z_, 20}})), 1);
EXPECT_EQ(result6.begin()->first.total_degree(), 28);
// pow(mβ, -1) throws an exception.
EXPECT_THROW(pow(m1, -1), runtime_error);
// pow(mβ, -5) throws an exception.
EXPECT_THROW(pow(m2, -5), runtime_error);
}
TEST_F(MonomialBasisElementTest, PowInPlace) {
// mβ = xyΒ²
MonomialBasisElement m1{{{var_x_, 1}, {var_y_, 2}}};
const MonomialBasisElement m1_copy{m1};
EXPECT_EQ(m1, m1_copy);
// mβ.pow_in_place modifies mβ.
m1.pow_in_place(2);
EXPECT_NE(m1, m1_copy);
EXPECT_EQ(m1, MonomialBasisElement({{var_x_, 2}, {var_y_, 4}}));
EXPECT_EQ(m1.total_degree(), 6);
// mβ gets mββ°, which is 1.
m1.pow_in_place(0);
EXPECT_EQ(m1, MonomialBasisElement());
EXPECT_EQ(m1.total_degree(), 0);
}
TEST_F(MonomialBasisElementTest, Evaluate) {
const std::vector<Environment> environments{
{{var_x_, 1.0}, {var_y_, 2.0}, {var_z_, 3.0}}, // + + +
{{var_x_, -1.0}, {var_y_, 2.0}, {var_z_, 3.0}}, // - + +
{{var_x_, 1.0}, {var_y_, -2.0}, {var_z_, 3.0}}, // + - +
{{var_x_, 1.0}, {var_y_, 2.0}, {var_z_, -3.0}}, // + + -
{{var_x_, -1.0}, {var_y_, -2.0}, {var_z_, 3.0}}, // - - +
{{var_x_, 1.0}, {var_y_, -2.0}, {var_z_, -3.0}}, // + - -
{{var_x_, -1.0}, {var_y_, 2.0}, {var_z_, -3.0}}, // - + -
{{var_x_, -1.0}, {var_y_, -2.0}, {var_z_, -3.0}}, // - - -
};
for (const MonomialBasisElement& m : monomials_) {
for (const Environment& env : environments) {
EXPECT_TRUE(CheckEvaluate(m, env));
}
}
}
TEST_F(MonomialBasisElementTest, EvaluateException) {
const MonomialBasisElement m{{{var_x_, 1}, {var_y_, 2}}}; // xy^2
const Environment env{{{var_x_, 1.0}}};
double dummy{};
EXPECT_THROW(dummy = m.Evaluate(env), std::invalid_argument);
unused(dummy);
}
TEST_F(MonomialBasisElementTest, EvaluatePartial) {
const std::vector<Environment> environments{
{{var_x_, 2.0}},
{{var_y_, 3.0}},
{{var_z_, 4.0}},
{{var_x_, 2.0}, {var_y_, -2.0}},
{{var_y_, -4.0}, {var_z_, 2.5}},
{{var_x_, -2.3}, {var_z_, 2.6}},
{{var_x_, -1.0}, {var_y_, 2.0}, {var_z_, 3.0}},
};
for (const MonomialBasisElement& m : monomials_) {
for (const Environment& env : environments) {
EXPECT_TRUE(CheckEvaluatePartial(m, env));
}
}
}
TEST_F(MonomialBasisElementTest, DegreeVariable) {
EXPECT_EQ(MonomialBasisElement().degree(var_x_), 0);
EXPECT_EQ(MonomialBasisElement().degree(var_y_), 0);
EXPECT_EQ(MonomialBasisElement(var_x_).degree(var_x_), 1);
EXPECT_EQ(MonomialBasisElement(var_x_).degree(var_y_), 0);
EXPECT_EQ(MonomialBasisElement(var_x_, 4).degree(var_x_), 4);
EXPECT_EQ(MonomialBasisElement(var_x_, 4).degree(var_y_), 0);
EXPECT_EQ(MonomialBasisElement({{var_x_, 1}, {var_y_, 2}}).degree(var_x_), 1);
EXPECT_EQ(MonomialBasisElement({{var_x_, 1}, {var_y_, 2}}).degree(var_y_), 2);
}
TEST_F(MonomialBasisElementTest, TotalDegree) {
EXPECT_EQ(MonomialBasisElement().total_degree(), 0);
EXPECT_EQ(MonomialBasisElement(var_x_).total_degree(), 1);
EXPECT_EQ(MonomialBasisElement(var_x_, 1).total_degree(), 1);
EXPECT_EQ(MonomialBasisElement(var_x_, 4).total_degree(), 4);
EXPECT_EQ(MonomialBasisElement({{var_x_, 1}, {var_y_, 2}}).total_degree(), 3);
}
TEST_F(MonomialBasisElementTest, Differentiate) {
// d1/dx = 0
const std::map<MonomialBasisElement, double> result1 =
MonomialBasisElement().Differentiate(var_x_);
EXPECT_TRUE(result1.empty());
// dxy / dz = 0
const std::map<MonomialBasisElement, double> result2 =
MonomialBasisElement{{{var_x_, 1}, {var_y_, 1}}}.Differentiate(var_z_);
EXPECT_TRUE(result2.empty());
// dx / dx = 1
const auto result3 = MonomialBasisElement(var_x_).Differentiate(var_x_);
EXPECT_EQ(result3.size(), 1);
EXPECT_EQ(result3.at(MonomialBasisElement()), 1);
// dxy / dy = x
const auto result4 =
MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}).Differentiate(var_y_);
EXPECT_EQ(result4.size(), 1);
EXPECT_EQ(result4.at(MonomialBasisElement(var_x_)), 1);
// dxΒ²yΒ²z / dx = 2xyΒ²z
const auto result5 =
MonomialBasisElement({{var_x_, 2}, {var_y_, 2}, {var_z_, 1}})
.Differentiate(var_x_);
EXPECT_EQ(result5.size(), 1);
EXPECT_EQ(
result5.at(MonomialBasisElement({{var_x_, 1}, {var_y_, 2}, {var_z_, 1}})),
2);
// xΒ³yβ΄zΒ² / dy = 4xΒ³yΒ³zΒ²
const auto result6 =
MonomialBasisElement({{var_x_, 3}, {var_y_, 4}, {var_z_, 2}})
.Differentiate(var_y_);
EXPECT_EQ(result6.size(), 1);
EXPECT_EQ(
result6.at(MonomialBasisElement({{var_x_, 3}, {var_y_, 3}, {var_z_, 2}})),
4);
}
TEST_F(MonomialBasisElementTest, Integrate) {
// β«1 dx = x
const std::map<MonomialBasisElement, double> result1 =
MonomialBasisElement().Integrate(var_x_);
EXPECT_EQ(result1.size(), 1);
EXPECT_EQ(result1.at(MonomialBasisElement(var_x_)), 1);
// β« x dy = xy
const std::map<MonomialBasisElement, double> result2 =
MonomialBasisElement(var_x_).Integrate(var_y_);
EXPECT_EQ(result2.size(), 1);
EXPECT_EQ(result2.at(MonomialBasisElement({{var_x_, 1}, {var_y_, 1}})), 1);
// β«x dx = xΒ²/2
const auto result3 = MonomialBasisElement(var_x_).Integrate(var_x_);
EXPECT_EQ(result3.size(), 1);
EXPECT_EQ(result3.at(MonomialBasisElement(var_x_, 2)), 0.5);
// β« xyΒ² dy = 1/3 xyΒ³
const auto result4 =
MonomialBasisElement({{var_x_, 1}, {var_y_, 2}}).Integrate(var_y_);
EXPECT_EQ(result4.size(), 1);
EXPECT_EQ(result4.at(MonomialBasisElement({{var_x_, 1}, {var_y_, 3}})),
1. / 3);
// β« xΒ²yΒ³z dy = 1/4 xΒ²yβ΄z
const auto result5 =
MonomialBasisElement({{var_x_, 2}, {var_y_, 3}, {var_z_, 1}})
.Integrate(var_y_);
EXPECT_EQ(result5.size(), 1);
EXPECT_EQ(
result5.at(MonomialBasisElement({{var_x_, 2}, {var_y_, 4}, {var_z_, 1}})),
1. / 4);
}
TEST_F(MonomialBasisElementTest, ToChebyshevBasisUnivariate) {
// Test ToChebyshevBasis for univariate monomials.
// 1 = T0()
const std::map<ChebyshevBasisElement, double> result1 =
MonomialBasisElement().ToChebyshevBasis();
EXPECT_EQ(result1.size(), 1);
EXPECT_EQ(result1.at(ChebyshevBasisElement()), 1.);
// x = T1(x)
const std::map<ChebyshevBasisElement, double> result2 =
MonomialBasisElement(var_x_).ToChebyshevBasis();
EXPECT_EQ(result2.size(), 1);
EXPECT_EQ(result2.at(ChebyshevBasisElement(var_x_)), 1.);
// xΒ² = 0.5Tβ(x)+0.5Tβ(x)
const std::map<ChebyshevBasisElement, double> result3 =
MonomialBasisElement(var_x_, 2).ToChebyshevBasis();
EXPECT_EQ(result3.size(), 2);
EXPECT_EQ(result3.at(ChebyshevBasisElement(var_x_, 2)), 0.5);
EXPECT_EQ(result3.at(ChebyshevBasisElement()), 0.5);
// xΒ³ = 0.25Tβ(x)+0.75Tβ(x)
const std::map<ChebyshevBasisElement, double> result4 =
MonomialBasisElement(var_x_, 3).ToChebyshevBasis();
EXPECT_EQ(result4.size(), 2);
EXPECT_EQ(result4.at(ChebyshevBasisElement(var_x_, 3)), 0.25);
EXPECT_EQ(result4.at(ChebyshevBasisElement(var_x_, 1)), 0.75);
// xβ΄ = 1/8Tβ(x)+1/2Tβ(x)+3/8Tβ(x)
const std::map<ChebyshevBasisElement, double> result5 =
MonomialBasisElement(var_x_, 4).ToChebyshevBasis();
EXPECT_EQ(result5.size(), 3);
EXPECT_EQ(result5.at(ChebyshevBasisElement(var_x_, 4)), 1.0 / 8);
EXPECT_EQ(result5.at(ChebyshevBasisElement(var_x_, 2)), 1.0 / 2);
EXPECT_EQ(result5.at(ChebyshevBasisElement(var_x_, 0)), 3.0 / 8);
// The coefficient of the Chebyshev polynomial of T20(x) for x^20 is 1/(2^19).
const std::map<ChebyshevBasisElement, double> result6 =
MonomialBasisElement(var_x_, 20).ToChebyshevBasis();
EXPECT_EQ(result6.at(ChebyshevBasisElement(var_x_, 20)), std::pow(0.5, 19));
}
TEST_F(MonomialBasisElementTest, ToChebyshevBasisMultivariate) {
// xy = T1(x)T1(y)
const std::map<ChebyshevBasisElement, double> result1 =
MonomialBasisElement({{var_x_, 1}, {var_y_, 1}}).ToChebyshevBasis();
EXPECT_EQ(result1.size(), 1);
EXPECT_EQ(result1.at(ChebyshevBasisElement({{var_x_, 1}, {var_y_, 1}})), 1.);
// xyz = T1(x)T1(y)T1(z)
const std::map<ChebyshevBasisElement, double> result2 =
MonomialBasisElement({{var_x_, 1}, {var_y_, 1}, {var_z_, 1}})
.ToChebyshevBasis();
EXPECT_EQ(result2.size(), 1);
EXPECT_EQ(result2.at(
ChebyshevBasisElement({{var_x_, 1}, {var_y_, 1}, {var_z_, 1}})),
1.);
// xΒ²y = 0.5Tβ(x)Tβ(y)+0.5Tβ(y)
const std::map<ChebyshevBasisElement, double> result3 =
MonomialBasisElement({{var_x_, 2}, {var_y_, 1}}).ToChebyshevBasis();
EXPECT_EQ(result3.size(), 2);
EXPECT_EQ(result3.at(ChebyshevBasisElement({{var_x_, 2}, {var_y_, 1}})), 0.5);
EXPECT_EQ(result3.at(ChebyshevBasisElement(var_y_)), 0.5);
// xΒ³yΒ²z=1/8Tβ(x)Tβ(y)Tβ(z)+3/8Tβ(x)Tβ(y)Tβ(z)+1/8Tβ(x)Tβ(z)+3/8Tβ(x)Tβ(z)
const std::map<ChebyshevBasisElement, double> result4 =
MonomialBasisElement({{var_x_, 3}, {var_y_, 2}, {var_z_, 1}})
.ToChebyshevBasis();
EXPECT_EQ(result4.size(), 4);
EXPECT_EQ(result4.at(
ChebyshevBasisElement({{var_x_, 3}, {var_y_, 2}, {var_z_, 1}})),
1.0 / 8);
EXPECT_EQ(result4.at(
ChebyshevBasisElement({{var_x_, 1}, {var_y_, 2}, {var_z_, 1}})),
3.0 / 8);
EXPECT_EQ(result4.at(ChebyshevBasisElement({{var_x_, 3}, {var_z_, 1}})),
1.0 / 8);
EXPECT_EQ(result4.at(ChebyshevBasisElement({{var_x_, 1}, {var_z_, 1}})),
3.0 / 8);
}
TEST_F(MonomialBasisElementTest, MergeBasisElementInPlace) {
// xΒ²yΒ³ * xyzΒ² = xΒ³yβ΄zΒ²
MonomialBasisElement basis_element1({{var_x_, 2}, {var_y_, 3}});
basis_element1.MergeBasisElementInPlace(
MonomialBasisElement({{var_x_, 1}, {var_y_, 1}, {var_z_, 2}}));
EXPECT_EQ(basis_element1.var_to_degree_map().size(), 3);
EXPECT_EQ(basis_element1.var_to_degree_map().at(var_x_), 3);
EXPECT_EQ(basis_element1.var_to_degree_map().at(var_y_), 4);
EXPECT_EQ(basis_element1.var_to_degree_map().at(var_z_), 2);
EXPECT_EQ(basis_element1.total_degree(), 9);
}
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/ostream_test.cc | // Drake never uses operator<< for Eigen::Matix data, but we'd like users to be
// able to do so at their discretion. Therefore, we test it here to ensure that
// our NumTraits specialization is sufficient for this purpose.
#undef EIGEN_NO_IO
#include <sstream>
#include <gtest/gtest.h>
#include "drake/common/symbolic/chebyshev_basis_element.h"
#include "drake/common/symbolic/monomial_basis_element.h"
#include "drake/common/symbolic/polynomial.h"
namespace drake {
namespace symbolic {
class OstreamTest : public ::testing::Test {
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
};
TEST_F(OstreamTest, ChebyshevBasisElementEigenMatrix) {
Eigen::Matrix<ChebyshevBasisElement, 2, 2> M;
M << ChebyshevBasisElement(), ChebyshevBasisElement({{var_x_, 1}}),
ChebyshevBasisElement({{var_x_, 1}, {var_y_, 2}}),
ChebyshevBasisElement({{var_y_, 2}});
// The following fails if we do not provide
// `Eigen::NumTraits<drake::symbolic::DerivedA>`
std::ostringstream oss;
oss << M;
}
TEST_F(OstreamTest, MonomialEigenMatrix) {
Eigen::Matrix<Monomial, 2, 2> M;
// M = | 1 x |
// | yΒ² xΒ²zΒ³ |
// clang-format off
M << Monomial{}, Monomial{var_x_},
Monomial{{{var_y_, 2}}}, Monomial{{{var_x_, 2}, {var_z_, 3}}};
// clang-format on
// The following fails if we do not provide
// `Eigen::NumTraits<drake::symbolic::Monomial>`.
std::ostringstream oss;
oss << M;
}
TEST_F(OstreamTest, MonomialBasisElementEigenMatrix) {
Eigen::Matrix<MonomialBasisElement, 2, 2> M;
// M = | 1 x |
// | yΒ² xΒ²zΒ³ |
M << MonomialBasisElement{}, MonomialBasisElement{var_x_},
MonomialBasisElement{{{var_y_, 2}}},
MonomialBasisElement{{{var_x_, 2}, {var_z_, 3}}};
// The following fails if we do not provide
// `Eigen::NumTraits<drake::symbolic::MonomialBasisElement>`.
std::ostringstream oss;
oss << M;
}
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/chebyshev_polynomial_test.cc | #include "drake/common/symbolic/chebyshev_polynomial.h"
#include <limits>
#include <ostream>
#include <fmt/format.h>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
const double kEps = std::numeric_limits<double>::epsilon();
GTEST_TEST(ChebyshevPolynomialTest, TestConstructor) {
const Variable x("x");
const ChebyshevPolynomial p1(x, 0);
EXPECT_EQ(p1.var(), x);
EXPECT_EQ(p1.degree(), 0);
const ChebyshevPolynomial p2(x, 1);
EXPECT_EQ(p2.var(), x);
EXPECT_EQ(p2.degree(), 1);
}
GTEST_TEST(ChebyshevPolynomialTest, ToPolynomial) {
const Variable x("x");
const ChebyshevPolynomial p0(x, 0);
EXPECT_PRED2(test::PolyEqual, p0.ToPolynomial(), Polynomial(1));
const ChebyshevPolynomial p1(x, 1);
EXPECT_PRED2(test::PolyEqual, p1.ToPolynomial(), Polynomial(x));
const ChebyshevPolynomial p2(x, 2);
EXPECT_PRED2(test::PolyEqual, p2.ToPolynomial(), Polynomial(2 * x * x - 1));
const ChebyshevPolynomial p3(x, 3);
EXPECT_PRED2(test::PolyEqual, p3.ToPolynomial(),
Polynomial(4 * x * x * x - 3 * x));
const ChebyshevPolynomial p4(x, 4);
EXPECT_PRED2(test::PolyEqual, p4.ToPolynomial(),
Polynomial(8 * pow(x, 4) - 8 * x * x + 1));
for (int n = 5; n < 20; ++n) {
const ChebyshevPolynomial T_n_minus_2(x, n - 2);
const ChebyshevPolynomial T_n_minus_1(x, n - 1);
const ChebyshevPolynomial T_n(x, n);
EXPECT_PRED2(test::PolyEqual, T_n.ToPolynomial(),
Polynomial(2 * x * T_n_minus_1.ToPolynomial().ToExpression() -
T_n_minus_2.ToPolynomial().ToExpression()));
}
}
GTEST_TEST(ChebyshevPolynomialTest, Eval) {
const Variable x("x");
const double tol = 10 * kEps;
EXPECT_EQ(ChebyshevPolynomial(x, 0).Evaluate(2), 1);
EXPECT_NEAR(ChebyshevPolynomial(x, 1).Evaluate(2), 2, tol);
EXPECT_NEAR(ChebyshevPolynomial(x, 2).Evaluate(2), 7, tol);
EXPECT_NEAR(ChebyshevPolynomial(x, 3).Evaluate(2), 26, tol);
// Use the alternative definition for Chebyshev polynomial that
// Tβ(cos(ΞΈ)) = cos(nΞΈ)
const double theta = 0.2 * M_PI;
const double cos_theta = std::cos(theta);
for (int degree = 0; degree < 20; ++degree) {
EXPECT_NEAR(ChebyshevPolynomial(x, degree).Evaluate(cos_theta),
std::cos(degree * theta), tol);
}
}
GTEST_TEST(ChebyshevPolynomialTest, EqualAndNotEqual) {
const Variable x("x");
EXPECT_TRUE(ChebyshevPolynomial(x, 1) == ChebyshevPolynomial(x, 1));
EXPECT_EQ(ChebyshevPolynomial(x, 1), ChebyshevPolynomial(x, 1));
EXPECT_TRUE(ChebyshevPolynomial(x, 2) == ChebyshevPolynomial(x, 2));
EXPECT_EQ(ChebyshevPolynomial(x, 2), ChebyshevPolynomial(x, 2));
EXPECT_TRUE(ChebyshevPolynomial(x, 3) == ChebyshevPolynomial(x, 3));
EXPECT_EQ(ChebyshevPolynomial(x, 3), ChebyshevPolynomial(x, 3));
const Variable y("y");
EXPECT_TRUE(ChebyshevPolynomial(x, 0) == ChebyshevPolynomial(y, 0));
EXPECT_EQ(ChebyshevPolynomial(x, 0), ChebyshevPolynomial(y, 0));
EXPECT_FALSE(ChebyshevPolynomial(x, 1) == ChebyshevPolynomial(x, 2));
EXPECT_TRUE(ChebyshevPolynomial(x, 1) != ChebyshevPolynomial(x, 2));
EXPECT_NE(ChebyshevPolynomial(x, 1), ChebyshevPolynomial(x, 2));
EXPECT_FALSE(ChebyshevPolynomial(x, 1) == ChebyshevPolynomial(y, 1));
EXPECT_TRUE(ChebyshevPolynomial(x, 1) != ChebyshevPolynomial(y, 1));
EXPECT_NE(ChebyshevPolynomial(x, 1), ChebyshevPolynomial(y, 1));
}
GTEST_TEST(ChebyshevPolynomialTest, Differentiate) {
const Variable x("x");
EXPECT_TRUE(ChebyshevPolynomial(x, 0).Differentiate().empty());
const ChebyshevPolynomial p1(x, 1);
// The gradient of T1(x) is 1 = T0(x)
const std::vector<std::pair<ChebyshevPolynomial, double>> p1_derivative =
p1.Differentiate();
EXPECT_EQ(p1_derivative.size(), 1);
EXPECT_EQ(p1_derivative[0].first, ChebyshevPolynomial(x, 0));
EXPECT_EQ(p1_derivative[0].second, 1);
const ChebyshevPolynomial p2(x, 2);
// The gradient of T2(x) is 4*x = 4*T1(x)
const std::vector<std::pair<ChebyshevPolynomial, double>> p2_derivative =
p2.Differentiate();
EXPECT_EQ(p2_derivative.size(), 1);
EXPECT_EQ(p2_derivative[0].first, ChebyshevPolynomial(x, 1));
EXPECT_EQ(p2_derivative[0].second, 4);
const ChebyshevPolynomial p3(x, 3);
// The gradient of T3(x) is 12*x^2 - 3 = 6*T2(x) + 3 * T0(x)
const std::vector<std::pair<ChebyshevPolynomial, double>> p3_derivative =
p3.Differentiate();
EXPECT_EQ(p3_derivative.size(), 2);
EXPECT_EQ(p3_derivative[0].first, ChebyshevPolynomial(x, 0));
EXPECT_EQ(p3_derivative[0].second, 3);
EXPECT_EQ(p3_derivative[1].first, ChebyshevPolynomial(x, 2));
EXPECT_EQ(p3_derivative[1].second, 6);
const ChebyshevPolynomial p4(x, 4);
// The gradient of T4(x) is 32 * x^3 - 16 * x = 8*T3(x) + 8*T1(x)
std::vector<std::pair<ChebyshevPolynomial, double>> p4_derivative =
p4.Differentiate();
EXPECT_EQ(p4_derivative.size(), 2);
EXPECT_EQ(p4_derivative[0].first, ChebyshevPolynomial(x, 1));
EXPECT_EQ(p4_derivative[0].second, 8);
EXPECT_EQ(p4_derivative[1].first, ChebyshevPolynomial(x, 3));
EXPECT_EQ(p4_derivative[1].second, 8);
// Chebyshev polynomial has the property (1βxΒ²)*dTβ(x)/dx=n*(xTβ(x)βTβββ(x)) =
// n*(Tβββ(x) β xTβ(x)) for n >= 2. We check this property.
for (int degree = 2; degree < 20; ++degree) {
const ChebyshevPolynomial T_n(x, degree);
const ChebyshevPolynomial T_n_minus_1(x, degree - 1);
const ChebyshevPolynomial T_n_plus_1(x, degree + 1);
const std::vector<std::pair<ChebyshevPolynomial, double>> T_derivative =
T_n.Differentiate();
if (degree % 2 == 0) {
// Even degree Chebyshev polynomial
// dTβ(x)/dx = 2n ββ±Ό Tβ±Ό(x), j is odd and j <= n-1
EXPECT_EQ(T_derivative.size(), degree / 2);
for (int i = 0; i < degree / 2; ++i) {
EXPECT_EQ(T_derivative[i].first.degree(), 2 * i + 1);
}
} else {
// Odd degree Chebyshev polynomial
// dTβ(x)/dx = 2n ββ±Ό Tβ±Ό(x) - n, j is even and j <= n-1
EXPECT_EQ(T_derivative.size(), (degree + 1) / 2);
for (int i = 0; i < (degree + 1) / 2; ++i) {
EXPECT_EQ(T_derivative[i].first.degree(), 2 * i);
}
}
Polynomial T_derivative_poly(0);
for (const auto& pair : T_derivative) {
T_derivative_poly += pair.first.ToPolynomial() * pair.second;
}
// lhs is (1βxΒ²)*dTβ(x)/dx
const Polynomial lhs = Polynomial(1 - x * x, {x}) * T_derivative_poly;
EXPECT_PRED2(test::PolyEqual, lhs,
degree * (x * T_n.ToPolynomial() - T_n_plus_1.ToPolynomial()));
EXPECT_PRED2(
test::PolyEqual, lhs,
degree * (T_n_minus_1.ToPolynomial() - x * T_n.ToPolynomial()));
}
}
GTEST_TEST(ChebyshevPolynomialTest, UnorderedMapOfChebyshevPolynomial) {
// This test shows that we can use a std::unordered_map whose key is of
// ChebyshevPolynomial, namely we can hash ChebyshevPolynomial.
const Variable x("x");
std::unordered_map<ChebyshevPolynomial, int> chebyshev_to_coeff_map;
chebyshev_to_coeff_map.emplace(ChebyshevPolynomial(x, 0), 1);
chebyshev_to_coeff_map.emplace(ChebyshevPolynomial(x, 1), 2);
chebyshev_to_coeff_map.emplace(ChebyshevPolynomial(x, 2), 3);
const auto it1 = chebyshev_to_coeff_map.find(ChebyshevPolynomial(x, 1));
ASSERT_TRUE(it1 != chebyshev_to_coeff_map.end());
EXPECT_EQ(it1->second, 2);
EXPECT_EQ(chebyshev_to_coeff_map.find(ChebyshevPolynomial(x, 3)),
chebyshev_to_coeff_map.end());
// T0(y) should also be found in the map, since T0(x) is a key of the map, and
// T0(x) = T0(y) = 1.
const Variable y("y");
const auto it0 = chebyshev_to_coeff_map.find(ChebyshevPolynomial(y, 0));
ASSERT_NE(it0, chebyshev_to_coeff_map.end());
EXPECT_EQ(it0->second, 1);
}
GTEST_TEST(ChebyshevPolynomial, OperatorOut) {
const Variable x("x");
std::ostringstream os1;
os1 << ChebyshevPolynomial(x, 0);
EXPECT_EQ(fmt::format("{}", os1.str()), "T0()");
std::ostringstream os2;
os2 << ChebyshevPolynomial(x, 2);
EXPECT_EQ(fmt::format("{}", os2.str()), "T2(x)");
}
GTEST_TEST(ChebyshevPolynomialTest, ChebyshevPolynomialLess) {
// Test operator<
const Variable x("x");
const Variable y("y");
ASSERT_TRUE(x.get_id() < y.get_id());
EXPECT_FALSE(ChebyshevPolynomial(x, 0) < ChebyshevPolynomial(x, 0));
EXPECT_FALSE(ChebyshevPolynomial(x, 0) < ChebyshevPolynomial(y, 0));
EXPECT_LT(ChebyshevPolynomial(x, 0), ChebyshevPolynomial(y, 1));
EXPECT_LT(ChebyshevPolynomial(x, 0), ChebyshevPolynomial(x, 1));
EXPECT_FALSE(ChebyshevPolynomial(x, 1) < ChebyshevPolynomial(y, 0));
EXPECT_LT(ChebyshevPolynomial(x, 1), ChebyshevPolynomial(y, 1));
EXPECT_LT(ChebyshevPolynomial(x, 2), ChebyshevPolynomial(y, 1));
EXPECT_LT(ChebyshevPolynomial(x, 2), ChebyshevPolynomial(y, 3));
EXPECT_FALSE(ChebyshevPolynomial(y, 2) < ChebyshevPolynomial(y, 1));
// Test using ChebyshevPolynomial as a key of std::set
std::set<ChebyshevPolynomial> poly_set;
poly_set.emplace(x, 0);
poly_set.emplace(x, 1);
EXPECT_NE(poly_set.find(ChebyshevPolynomial(x, 0)), poly_set.end());
// T0(y) = T0(x) = 1, they are the same polynomial, so the set should also
// contain T0(y).
EXPECT_NE(poly_set.find(ChebyshevPolynomial(y, 0)), poly_set.end());
EXPECT_NE(poly_set.find(ChebyshevPolynomial(x, 1)), poly_set.end());
EXPECT_EQ(poly_set.find(ChebyshevPolynomial(y, 1)), poly_set.end());
}
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/rational_function_matrix_test.cc | #include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/symbolic/expression.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
namespace drake {
namespace symbolic {
using test::RationalFunctionEqual;
class SymbolicRationalFunctionMatrixTest : public ::testing::Test {
public:
void SetUp() override {
M_rational_function_dynamic_ << RationalFunction(p1_, p2_),
RationalFunction(p1_, p3_), RationalFunction(p2_, p3_),
RationalFunction(p1_, p2_ + p3_);
M_rational_function_static_ = M_rational_function_dynamic_;
v_rational_function_dynamic_ << RationalFunction(p2_, p4_),
RationalFunction(p3_, p2_ + p4_);
v_rational_function_static_ = v_rational_function_dynamic_;
M_poly_dynamic_ << p1_, p2_, p5_, p6_;
M_poly_static_ = M_poly_dynamic_;
v_poly_dynamic_ << p1_, p3_;
v_poly_static_ = v_poly_dynamic_;
M_double_dynamic_ << 1, 2, 3, 4;
M_double_static_ = M_double_dynamic_;
v_double_dynamic_ << 1, 2;
v_double_static_ = v_double_dynamic_;
}
protected:
const Variable var_x_{"x"};
const Variable var_y_{"y"};
const Variable var_z_{"z"};
const Variables var_xyz_{{var_x_, var_y_, var_z_}};
const Variable var_a_{"a"};
const Variable var_b_{"b"};
const Variable var_c_{"c"};
const Variables var_abc_{{var_a_, var_b_, var_c_}};
const Polynomial p1_{var_x_ * var_x_};
const Polynomial p2_{var_x_ * var_y_ + 2 * var_y_ + 1};
const Polynomial p3_{var_x_ * var_z_ + var_a_ * var_x_ * var_x_, var_xyz_};
const Polynomial p4_{var_a_ * var_x_ * var_y_ + var_b_ * var_x_ * var_z_,
var_xyz_};
const Polynomial p5_{var_a_ * var_x_ + var_b_ * 2 * var_z_ * var_y_,
var_xyz_};
const Polynomial p6_{
3 * var_a_ * var_x_ * var_x_ + var_b_ * 2 * var_z_ * var_y_, var_xyz_};
MatrixX<RationalFunction> M_rational_function_dynamic_{2, 2};
Matrix2<RationalFunction> M_rational_function_static_;
VectorX<RationalFunction> v_rational_function_dynamic_{2};
Vector2<RationalFunction> v_rational_function_static_;
MatrixX<Polynomial> M_poly_dynamic_{2, 2};
Matrix2<Polynomial> M_poly_static_;
VectorX<Polynomial> v_poly_dynamic_{2};
Vector2<Polynomial> v_poly_static_;
Eigen::MatrixXd M_double_dynamic_{2, 2};
Eigen::Matrix2d M_double_static_;
Eigen::VectorXd v_double_dynamic_{2};
Eigen::Vector2d v_double_static_;
};
template <typename Derived1, typename Derived2>
typename std::enable_if_t<
std::is_same_v<typename Derived1::Scalar, RationalFunction> &&
std::is_same_v<typename Derived2::Scalar, RationalFunction>>
CompareMatrixWithRationalFunction(const Derived1& m1, const Derived2& m2) {
EXPECT_EQ(m1.rows(), m2.rows());
EXPECT_EQ(m1.cols(), m2.cols());
for (int i = 0; i < m1.rows(); ++i) {
for (int j = 0; j < m1.cols(); ++j) {
EXPECT_PRED2(test::PolyEqualAfterExpansion, m1(i, j).numerator(),
m2(i, j).numerator());
EXPECT_PRED2(test::PolyEqualAfterExpansion, m1(i, j).denominator(),
m2(i, j).denominator());
}
}
}
template <typename Derived1, typename Derived2>
void CheckAddition(const Derived1& m1, const Derived2& m2) {
DRAKE_DEMAND(m1.rows() == m2.rows());
DRAKE_DEMAND(m1.cols() == m2.cols());
MatrixX<RationalFunction> m1_add_m2_expected(m1.rows(), m1.cols());
for (int i = 0; i < m1.rows(); ++i) {
for (int j = 0; j < m1.cols(); ++j) {
m1_add_m2_expected(i, j) = m1(i, j) + m2(i, j);
}
}
static_assert(
std::is_same_v<typename decltype(m1 + m2)::Scalar, RationalFunction>,
"m1 + m2 should have scalar type RationalFunction.");
const MatrixX<RationalFunction> m1_add_m2 = m1 + m2;
CompareMatrixWithRationalFunction(m1_add_m2, m1_add_m2_expected);
CompareMatrixWithRationalFunction(m2 + m1, m1_add_m2_expected);
}
template <typename Derived1, typename Derived2>
void CheckSubtraction(const Derived1& m1, const Derived2& m2) {
DRAKE_DEMAND(m1.rows() == m2.rows());
DRAKE_DEMAND(m1.cols() == m2.cols());
MatrixX<RationalFunction> m1_minus_m2_expected(m1.rows(), m1.cols());
for (int i = 0; i < m1.rows(); ++i) {
for (int j = 0; j < m1.cols(); ++j) {
m1_minus_m2_expected(i, j) = m1(i, j) - m2(i, j);
}
}
static_assert(
std::is_same_v<typename decltype(m1 - m2)::Scalar, RationalFunction>,
"m1 - m2 should have scalar type RationalFunction.");
const MatrixX<RationalFunction> m1_minus_m2 = m1 - m2;
CompareMatrixWithRationalFunction(m1_minus_m2, m1_minus_m2_expected);
CompareMatrixWithRationalFunction(m2 - m1, -m1_minus_m2_expected);
}
template <typename Derived1, typename Derived2>
void CheckProduct(const Derived1& m1, const Derived2& m2) {
// If we change the type from Derived1 to Eigen::MatrixBase<Derived1>, the
// compiler would fail, as the SFINAE fails for the overloaded operator* in
// symbolic_ration_function.h.
DRAKE_DEMAND(m1.cols() == m2.rows());
MatrixX<RationalFunction> m1_times_m2_expected(m1.rows(), m2.cols());
for (int i = 0; i < m1.rows(); ++i) {
for (int j = 0; j < m2.cols(); ++j) {
for (int k = 0; k < m1.cols(); ++k) {
m1_times_m2_expected(i, j) += m1(i, k) * m2(k, j);
}
}
}
static_assert(
std::is_same_v<typename decltype(m1 * m2)::Scalar, RationalFunction>,
"m1 * m2 should have scalar type RationalFunction.");
const MatrixX<RationalFunction> m1_times_m2 = m1 * m2;
CompareMatrixWithRationalFunction(m1_times_m2, m1_times_m2_expected);
}
template <typename Derived1, typename Derived2>
typename std::enable_if_t<is_eigen_vector<Derived1>::value &&
is_eigen_vector<Derived2>::value>
CheckConjugateProdocut(const Derived1& v1, const Derived2& v2) {
DRAKE_DEMAND(v1.rows() == v2.rows());
RationalFunction v1_dot_v2_expected;
for (int i = 0; i < v1.rows(); ++i) {
v1_dot_v2_expected += v1(i) * v2(i);
}
static_assert(std::is_same_v<decltype(v1.dot(v2)), RationalFunction>,
"v1.dot(v2) should be RationalFunction.");
const RationalFunction v1_dot_v2 = v1.dot(v2);
EXPECT_PRED2(test::PolyEqualAfterExpansion, v1_dot_v2.denominator(),
v1_dot_v2_expected.denominator());
EXPECT_PRED2(test::PolyEqualAfterExpansion, v1_dot_v2.numerator(),
v1_dot_v2_expected.numerator());
}
template <typename Derived1, typename Derived2>
void CheckMatrixMatrixBinaryOperations(const Derived1& m1, const Derived2& m2) {
CheckAddition(m1, m2);
CheckSubtraction(m1, m2);
CheckProduct(m1, m2);
CheckProduct(m2, m1);
}
template <typename Derived1, typename Derived2>
typename std::enable_if_t<is_eigen_vector<Derived2>::value>
CheckMatrixVectorBinaryOperations(const Derived1& m1, const Derived2& m2) {
CheckProduct(m1, m2);
}
template <typename Derived1, typename Derived2>
typename std::enable_if_t<is_eigen_vector<Derived1>::value &&
is_eigen_vector<Derived2>::value>
CheckVectorVectorBinaryOperations(const Derived1& m1, const Derived2& m2) {
CheckAddition(m1, m2);
CheckSubtraction(m1, m2);
CheckConjugateProdocut(m1, m2);
}
TEST_F(SymbolicRationalFunctionMatrixTest, RationalFunctionOpRationalFunction) {
Matrix2<RationalFunction> M2;
M2 << RationalFunction(p2_, p3_ + 2 * p4_),
RationalFunction(p1_ + p2_, 2 * p3_), RationalFunction(p1_, p4_ - p5_),
RationalFunction(p2_, p3_ * p6_);
CheckMatrixMatrixBinaryOperations(M_rational_function_static_, M2);
CheckMatrixMatrixBinaryOperations(M_rational_function_dynamic_, M2);
Vector2<RationalFunction> v2(RationalFunction(p1_, p4_ + 2 * p5_),
RationalFunction(p3_, p2_ - p1_));
CheckVectorVectorBinaryOperations(v_rational_function_static_, v2);
CheckVectorVectorBinaryOperations(v_rational_function_dynamic_, v2);
CheckMatrixVectorBinaryOperations(M_rational_function_static_,
v_rational_function_static_);
CheckMatrixVectorBinaryOperations(M_rational_function_dynamic_,
v_rational_function_static_);
CheckMatrixVectorBinaryOperations(M_rational_function_static_,
v_rational_function_dynamic_);
CheckMatrixVectorBinaryOperations(M_rational_function_dynamic_,
v_rational_function_dynamic_);
}
TEST_F(SymbolicRationalFunctionMatrixTest, RationalFunctionOpPolynomial) {
CheckMatrixMatrixBinaryOperations(M_rational_function_static_,
M_poly_static_);
CheckMatrixMatrixBinaryOperations(M_rational_function_static_,
M_poly_dynamic_);
CheckMatrixMatrixBinaryOperations(M_rational_function_dynamic_,
M_poly_static_);
CheckMatrixMatrixBinaryOperations(M_rational_function_dynamic_,
M_poly_dynamic_);
CheckVectorVectorBinaryOperations(v_rational_function_static_,
v_poly_static_);
CheckVectorVectorBinaryOperations(v_rational_function_static_,
v_poly_dynamic_);
CheckVectorVectorBinaryOperations(v_rational_function_dynamic_,
v_poly_static_);
CheckVectorVectorBinaryOperations(v_rational_function_dynamic_,
v_poly_dynamic_);
CheckMatrixVectorBinaryOperations(M_rational_function_static_,
v_poly_static_);
CheckMatrixVectorBinaryOperations(M_rational_function_static_,
v_poly_dynamic_);
CheckMatrixVectorBinaryOperations(M_rational_function_dynamic_,
v_poly_static_);
CheckMatrixVectorBinaryOperations(M_rational_function_dynamic_,
v_poly_dynamic_);
}
TEST_F(SymbolicRationalFunctionMatrixTest, RationalFunctionOpDouble) {
CheckMatrixMatrixBinaryOperations(M_rational_function_static_,
M_double_static_);
CheckMatrixMatrixBinaryOperations(M_rational_function_static_,
M_double_dynamic_);
CheckMatrixMatrixBinaryOperations(M_rational_function_dynamic_,
M_double_static_);
CheckMatrixMatrixBinaryOperations(M_rational_function_dynamic_,
M_double_dynamic_);
CheckVectorVectorBinaryOperations(v_rational_function_static_,
v_double_static_);
CheckVectorVectorBinaryOperations(v_rational_function_static_,
v_double_dynamic_);
CheckVectorVectorBinaryOperations(v_rational_function_dynamic_,
v_double_static_);
CheckVectorVectorBinaryOperations(v_rational_function_dynamic_,
v_double_dynamic_);
CheckMatrixVectorBinaryOperations(M_rational_function_static_,
v_double_static_);
CheckMatrixVectorBinaryOperations(M_rational_function_static_,
v_double_dynamic_);
CheckMatrixVectorBinaryOperations(M_rational_function_dynamic_,
v_double_static_);
CheckMatrixVectorBinaryOperations(M_rational_function_dynamic_,
v_double_dynamic_);
}
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/polynomial_basis_element_test.cc | #include "drake/common/symbolic/polynomial_basis_element.h"
#include <fmt/format.h>
#include <gtest/gtest.h>
#include "drake/common/symbolic/expression.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/test_utilities/symbolic_test_util.h"
#include "drake/common/unused.h"
#define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER
#include "drake/common/symbolic/expression/expression_cell.h"
#undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER
namespace drake {
namespace symbolic {
// Create a concrete derived polynomial basis class.
class DerivedBasisA : public PolynomialBasisElement {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(DerivedBasisA);
DerivedBasisA() : PolynomialBasisElement() {}
explicit DerivedBasisA(const std::map<Variable, int>& var_to_degree_map)
: PolynomialBasisElement(var_to_degree_map) {}
bool operator<(const DerivedBasisA& other) const {
return this->lexicographical_compare(other);
}
std::pair<double, DerivedBasisA> EvaluatePartial(
const Environment& env) const {
double coeff;
std::map<Variable, int> new_var_to_degree_map;
this->DoEvaluatePartial(env, &coeff, &new_var_to_degree_map);
return std::make_pair(coeff, DerivedBasisA(new_var_to_degree_map));
}
void MergeBasisElementInPlace(const DerivedBasisA& other) {
this->DoMergeBasisElementInPlace(other);
}
private:
double DoEvaluate(double variable_val, int degree) const override {
return std::pow(variable_val, degree);
}
Expression DoToExpression() const override {
std::map<Expression, Expression> base_to_exponent_map;
for (const auto& [var, degree] : var_to_degree_map()) {
base_to_exponent_map.emplace(Expression{var}, degree);
}
return ExpressionMulFactory{1.0, base_to_exponent_map}.GetExpression();
}
};
class DerivedBasisB : public PolynomialBasisElement {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(DerivedBasisB);
DerivedBasisB() : PolynomialBasisElement() {}
explicit DerivedBasisB(const std::map<Variable, int>& var_to_degree_map)
: PolynomialBasisElement(var_to_degree_map) {}
bool operator<(const DerivedBasisB& other) const {
return this->lexicographical_compare(other);
}
void MergeBasisElementInPlace(const DerivedBasisB& other) {
this->DoMergeBasisElementInPlace(other);
}
private:
double DoEvaluate(double variable_val, int degree) const override {
return 1.;
}
Expression DoToExpression() const override { return Expression(1.); }
};
class SymbolicPolynomialBasisElementTest : public ::testing::Test {
protected:
const Variable x_{"x"};
const Variable y_{"y"};
const Variable z_{"z"};
};
TEST_F(SymbolicPolynomialBasisElementTest, Constructor) {
const DerivedBasisA p1({{x_, 1}, {y_, 2}});
EXPECT_EQ(p1.total_degree(), 3);
EXPECT_EQ(p1.var_to_degree_map().size(), 2);
EXPECT_EQ(p1.var_to_degree_map().at(x_), 1);
EXPECT_EQ(p1.var_to_degree_map().at(y_), 2);
const DerivedBasisA p2({{x_, 0}, {y_, 2}});
EXPECT_EQ(p2.total_degree(), 2);
EXPECT_EQ(p2.var_to_degree_map().size(), 1);
EXPECT_EQ(p2.var_to_degree_map().at(y_), 2);
const DerivedBasisA p3({{x_, 0}, {y_, 0}});
EXPECT_EQ(p3.total_degree(), 0);
EXPECT_EQ(p3.var_to_degree_map().size(), 0);
const DerivedBasisA p4(std::map<Variable, int>({}));
EXPECT_EQ(p4.total_degree(), 0);
EXPECT_EQ(p4.var_to_degree_map().size(), 0);
DRAKE_EXPECT_THROWS_MESSAGE(DerivedBasisA({{x_, -1}}),
"The degree for x is negative.");
}
TEST_F(SymbolicPolynomialBasisElementTest, degree) {
EXPECT_EQ(DerivedBasisA({{x_, 1}, {y_, 2}}).degree(x_), 1);
EXPECT_EQ(DerivedBasisA({{x_, 1}, {y_, 2}}).degree(y_), 2);
EXPECT_EQ(DerivedBasisA({{x_, 1}, {y_, 2}}).degree(z_), 0);
EXPECT_EQ(DerivedBasisA(std::map<Variable, int>()).degree(x_), 0);
}
TEST_F(SymbolicPolynomialBasisElementTest, GetVariables) {
const symbolic::DerivedBasisA p1({{x_, 1}, {y_, 2}});
EXPECT_EQ(p1.GetVariables(), Variables({x_, y_}));
const symbolic::DerivedBasisA p2({{x_, 0}, {y_, 2}});
EXPECT_EQ(p2.GetVariables(), Variables({y_}));
const symbolic::DerivedBasisA p3({{x_, 0}, {y_, 0}});
EXPECT_EQ(p3.GetVariables(), Variables({}));
const symbolic::DerivedBasisA p4(std::map<Variable, int>({}));
EXPECT_EQ(p4.GetVariables(), Variables({}));
}
TEST_F(SymbolicPolynomialBasisElementTest, OperatorEqualNotEqual) {
const DerivedBasisA p1({{x_, 1}, {y_, 2}});
const DerivedBasisA p2({{x_, 1}, {y_, 2}});
const DerivedBasisA p3({{x_, 0}, {y_, 2}});
const DerivedBasisA p4({{y_, 2}});
const DerivedBasisB p5({{y_, 2}});
const DerivedBasisB p6({{x_, 2}});
EXPECT_EQ(p1, p2);
// xβ°yΒ² == yΒ²
EXPECT_EQ(p3, p4);
// The degree for x is different
EXPECT_NE(p1, p3);
// The derived basis types are different.
EXPECT_NE(p4, p5);
// The variable is different.
EXPECT_NE(p5, p6);
}
TEST_F(SymbolicPolynomialBasisElementTest, Evaluate) {
Environment env1;
env1.insert(x_, 2);
env1.insert(y_, 3);
const DerivedBasisA p1({{x_, 0}, {y_, 2}});
EXPECT_EQ(p1.Evaluate(env1), 9);
const DerivedBasisA p2({{x_, 1}, {y_, 2}});
EXPECT_EQ(p2.Evaluate(env1), 18);
Environment env2;
env2.insert(y_, 3);
// p1=yΒ²
EXPECT_EQ(p1.Evaluate(env2), 9);
// p2=xyΒ², but env2 does not contain value for x.
double dummy{};
DRAKE_EXPECT_THROWS_MESSAGE(dummy = p2.Evaluate(env2), ".* x is not in env");
unused(dummy);
}
TEST_F(SymbolicPolynomialBasisElementTest, LessThan) {
const DerivedBasisA p1({{x_, 1}, {y_, 2}});
const DerivedBasisA p2({{y_, 3}});
const DerivedBasisA p3({{x_, 2}});
EXPECT_LT(p2, p1);
EXPECT_LT(p1, p3);
EXPECT_LT(p2, p3);
}
TEST_F(SymbolicPolynomialBasisElementTest, EigenMatrix) {
// Checks we can have an Eigen matrix of PolynomialBasisElements without
// compilation errors. No assertions in the test.
Eigen::Matrix<DerivedBasisA, 2, 2> M;
M << DerivedBasisA(std::map<Variable, int>({})), DerivedBasisA({{x_, 1}}),
DerivedBasisA({{x_, 1}, {y_, 2}}), DerivedBasisA({{y_, 2}});
}
TEST_F(SymbolicPolynomialBasisElementTest, EvaluatePartial) {
Environment env;
env.insert(x_, 2);
const DerivedBasisA m1{{{x_, 3}, {y_, 4}}};
double coeff;
DerivedBasisA new_basis;
std::tie(coeff, new_basis) = m1.EvaluatePartial(env);
EXPECT_EQ(coeff, 8);
EXPECT_EQ(new_basis, DerivedBasisA({{y_, 4}}));
const DerivedBasisA m2{{{y_, 3}, {z_, 2}}};
std::tie(coeff, new_basis) = m2.EvaluatePartial(env);
EXPECT_EQ(coeff, 1);
EXPECT_EQ(new_basis, m2);
}
TEST_F(SymbolicPolynomialBasisElementTest, BasisElementGradedReverseLexOrder) {
EXPECT_PRED2(test::VarLess, x_, y_);
EXPECT_PRED2(test::VarLess, y_, z_);
BasisElementGradedReverseLexOrder<std::less<Variable>, DerivedBasisA> compare;
// y^0 = x^0 = 1.
EXPECT_FALSE(compare(DerivedBasisA({{y_, 0}}), DerivedBasisA({{x_, 0}})));
EXPECT_FALSE(compare(DerivedBasisA({{x_, 0}}), DerivedBasisA({{y_, 0}})));
// x < y < z
EXPECT_TRUE(compare(DerivedBasisA({{x_, 1}}), DerivedBasisA({{y_, 1}})));
EXPECT_TRUE(compare(DerivedBasisA({{x_, 1}}), DerivedBasisA({{z_, 1}})));
EXPECT_TRUE(compare(DerivedBasisA({{y_, 1}}), DerivedBasisA({{z_, 1}})));
// x < y < z < xΒ² < xy < xz < yΒ² < yz < zΒ²
std::vector<DerivedBasisA> derived_basis_all;
derived_basis_all.emplace_back(std::map<Variable, int>{{x_, 0}});
derived_basis_all.emplace_back(std::map<Variable, int>{{x_, 1}});
derived_basis_all.emplace_back(std::map<Variable, int>{{y_, 1}});
derived_basis_all.emplace_back(std::map<Variable, int>{{z_, 1}});
derived_basis_all.emplace_back(std::map<Variable, int>{{x_, 2}});
derived_basis_all.emplace_back(std::map<Variable, int>{{x_, 1}, {y_, 1}});
derived_basis_all.emplace_back(std::map<Variable, int>{{x_, 1}, {z_, 1}});
derived_basis_all.emplace_back(std::map<Variable, int>{{y_, 2}});
derived_basis_all.emplace_back(std::map<Variable, int>{{y_, 1}, {z_, 1}});
derived_basis_all.emplace_back(std::map<Variable, int>{{z_, 2}});
for (int i = 0; i < static_cast<int>(derived_basis_all.size()); ++i) {
for (int j = 0; j < static_cast<int>(derived_basis_all.size()); ++j) {
if (i < j) {
EXPECT_TRUE(compare(derived_basis_all[i], derived_basis_all[j]));
} else {
EXPECT_FALSE(compare(derived_basis_all[i], derived_basis_all[j]));
}
}
}
}
TEST_F(SymbolicPolynomialBasisElementTest, MergeBasisElementInPlace) {
// Merge [(x->1), (y->2)] and [(x->2), (y->1)] gets [(x->3), (y->3)]
DerivedBasisA basis_element1({{x_, 1}, {y_, 2}});
basis_element1.MergeBasisElementInPlace(DerivedBasisA({{x_, 2}, {y_, 1}}));
EXPECT_EQ(basis_element1.var_to_degree_map().size(), 2);
EXPECT_EQ(basis_element1.var_to_degree_map().at(x_), 3);
EXPECT_EQ(basis_element1.var_to_degree_map().at(y_), 3);
EXPECT_EQ(basis_element1.total_degree(), 6);
// Merge [(x->2), (z->1)] and [(x->3), (y->4)] gets [(x->5), (y->4), (z->1)]
DerivedBasisA basis_element2({{x_, 2}, {z_, 1}});
basis_element2.MergeBasisElementInPlace(DerivedBasisA({{x_, 3}, {y_, 4}}));
EXPECT_EQ(basis_element2.var_to_degree_map().size(), 3);
EXPECT_EQ(basis_element2.var_to_degree_map().at(x_), 5);
EXPECT_EQ(basis_element2.var_to_degree_map().at(y_), 4);
EXPECT_EQ(basis_element2.var_to_degree_map().at(z_), 1);
EXPECT_EQ(basis_element2.total_degree(), 10);
// Merge [(z->3)] and [(x->1), (y->2)] gets [(x->1), (y->2), (z->3)]
DerivedBasisA basis_element3({{z_, 3}});
basis_element3.MergeBasisElementInPlace(DerivedBasisA({{x_, 1}, {y_, 2}}));
EXPECT_EQ(basis_element3.var_to_degree_map().size(), 3);
EXPECT_EQ(basis_element3.var_to_degree_map().at(x_), 1);
EXPECT_EQ(basis_element3.var_to_degree_map().at(y_), 2);
EXPECT_EQ(basis_element3.var_to_degree_map().at(z_), 3);
EXPECT_EQ(basis_element3.total_degree(), 6);
// Merge [(x->2)] and [(x->1), (y->3), (z->2)] gets [(x->3), (y->3), (z->2)]
DerivedBasisA basis_element4({{x_, 2}});
basis_element4.MergeBasisElementInPlace(
DerivedBasisA({{x_, 1}, {y_, 3}, {z_, 2}}));
EXPECT_EQ(basis_element4.var_to_degree_map().size(), 3);
EXPECT_EQ(basis_element4.var_to_degree_map().at(x_), 3);
EXPECT_EQ(basis_element4.var_to_degree_map().at(y_), 3);
EXPECT_EQ(basis_element4.var_to_degree_map().at(z_), 2);
EXPECT_EQ(basis_element4.total_degree(), 8);
// Merge [] with [(x->1)] gets [(x->1)]
DerivedBasisA basis_element5{};
basis_element5.MergeBasisElementInPlace(DerivedBasisA({{x_, 1}}));
EXPECT_EQ(basis_element5.var_to_degree_map().size(), 1);
EXPECT_EQ(basis_element5.var_to_degree_map().at(x_), 1);
EXPECT_EQ(basis_element5.total_degree(), 1);
// Merge [(x->1)] with [] gets [(x->1)]
DerivedBasisA basis_element6{{{x_, 1}}};
basis_element6.MergeBasisElementInPlace(DerivedBasisA());
EXPECT_EQ(basis_element6.var_to_degree_map().size(), 1);
EXPECT_EQ(basis_element6.var_to_degree_map().at(x_), 1);
EXPECT_EQ(basis_element6.total_degree(), 1);
}
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/symbolic | /home/johnshepherd/drake/common/symbolic/test/replace_bilinear_terms_test.cc | #include "drake/common/symbolic/replace_bilinear_terms.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/symbolic_test_util.h"
using drake::symbolic::test::ExprEqual;
namespace drake {
namespace symbolic {
namespace {
class BilinearProductTest : public ::testing::Test {
public:
BilinearProductTest()
: x_{Variable{"x0"}, Variable{"x1"}, Variable{"x2"}},
y_{Variable{"y0"}, Variable{"y1"}, Variable{"y2"}, Variable{"y3"}},
z_{Variable{"z0"}, Variable{"z1"}} {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j) {
xy_(i, j) = Expression(Variable("xy(" + std::to_string(i) + "," +
std::to_string(j) + ")"));
}
}
for (int i = 0; i < 3; ++i) {
for (int j = i; j < 3; ++j) {
xx_(i, j) = Expression(Variable("xx(" + std::to_string(i) + "," +
std::to_string(j) + ")"));
}
}
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < i; ++j) {
xx_(i, j) = xx_(j, i);
}
}
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
Z1_(i, j) = Expression(Variable("Z1(" + std::to_string(i) + "," +
std::to_string(j) + ")"));
Z2_(i, j) = Expression(Variable("Z2(" + std::to_string(i) + "," +
std::to_string(j) + ")"));
}
}
}
protected:
Vector3<Variable> x_;
Vector4<Variable> y_;
Vector2<Variable> z_;
Eigen::Matrix<Expression, 3, 4> xy_;
Eigen::Matrix<Expression, 3, 3> xx_;
Eigen::Matrix<Expression, 3, 3> Z1_;
Eigen::Matrix<Expression, 3, 3> Z2_;
};
TEST_F(BilinearProductTest, ConstantTerm) {
const std::vector<Expression> expressions{0, 1, z_(0) + z_(1),
pow(z_(0), 3) + z_(0) * z_(1)};
for (const auto& ei : expressions) {
EXPECT_PRED2(ExprEqual, ei, ReplaceBilinearTerms(ei, x_, y_, xy_));
EXPECT_PRED2(ExprEqual, ei, ReplaceBilinearTerms(ei, x_, x_, xx_));
}
}
TEST_F(BilinearProductTest, LinearTerm) {
const std::vector<Expression> expressions{
x_(0), y_(0), x_(0) + y_(1) + z_(0) + 2,
2 * x_(0) + 3 * y_(1) * z_(1) + 3,
2 * x_(0) + 3 * y_(1) * z_(0) + pow(z_(1), 3)};
for (const auto& ei : expressions) {
EXPECT_PRED2(ExprEqual, ei, ReplaceBilinearTerms(ei, x_, y_, xy_));
EXPECT_PRED2(ExprEqual, ei, ReplaceBilinearTerms(ei, x_, x_, xx_));
}
}
TEST_F(BilinearProductTest, QuadraticTerm0) {
Expression e{x_(0) * x_(0)};
Expression e_expected{xx_(0, 0)};
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = x_(0) * x_(0) + 2 * x_(1) * x_(1);
e_expected = xx_(0, 0) + 2 * xx_(1, 1);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = 2 * x_(0) * x_(0) * y_(0) * y_(1);
e_expected = 2 * xx_(0, 0) * y_(0) * y_(1);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = 2 * x_(2) * x_(2) * y_(0) * y_(1) + 3 * y_(1) * x_(2) + 2;
e_expected = 2 * xx_(2, 2) * y_(0) * y_(1) + 3 * y_(1) * x_(2) + 2;
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = (2 + y_(0) + y_(0) * y_(1)) * x_(0) * x_(0);
e_expected = (2 + y_(0) + y_(0) * y_(1)) * xx_(0, 0);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
}
TEST_F(BilinearProductTest, QuadraticTerm1) {
Expression e{x_(0) * x_(1)};
Expression e_expected{xx_(0, 1)};
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = 2 * x_(0) * x_(1);
e_expected = 2 * xx_(0, 1);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = 2 * y_(0) * y_(1) * x_(1) * x_(2);
e_expected = 2 * y_(0) * y_(1) * xx_(1, 2);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = 2 * pow(y_(0), 3) * x_(1) * x_(2) + y_(1) * x_(1) * x_(1) + 2 * x_(0) +
3 + 3 * x_(1);
e_expected = 2 * pow(y_(0), 3) * xx_(1, 2) + y_(1) * xx_(1, 1) + 2 * x_(0) +
3 + 3 * x_(1);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = (2 + y_(0) + y_(0) * y_(1)) * x_(0) * x_(1);
e_expected = (2 + y_(0) + y_(0) * y_(1)) * xx_(0, 1);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = 2 * x_(0) * x_(0) + xx_(0, 0);
e_expected = 3 * xx_(0, 0);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
e = xx_(0, 0) * x_(0) * x_(0);
e_expected = xx_(0, 0) * xx_(0, 0);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, x_, xx_));
}
TEST_F(BilinearProductTest, QuadraticTerm2) {
Expression e{x_(0) * y_(0)};
Expression e_expected{xy_(0, 0)};
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, y_, xy_));
e = 4 * x_(0) * y_(1);
e_expected = 4 * xy_(0, 1);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, y_, xy_));
e = 2 * z_(0) * z_(1) * z_(1) * x_(0) * y_(2);
e_expected = 2 * z_(0) * z_(1) * z_(1) * xy_(0, 2);
EXPECT_PRED2(ExprEqual, e_expected, ReplaceBilinearTerms(e, x_, y_, xy_));
e = 2 * pow(z_(1), 3) * x_(0) * y_(2) + z_(0) * x_(1) * y_(1) +
(4 * z_(0) + z_(1)) * x_(2) * y_(3) + 3 * x_(2) + 4;
e_expected = 2 * pow(z_(1), 3) * xy_(0, 2) + z_(0) * xy_(1, 1) +
(4 * z_(0) + z_(1)) * xy_(2, 3) + 3 * x_(2) + 4;
EXPECT_PRED2(ExprEqual, e_expected.Expand(),
ReplaceBilinearTerms(e, x_, y_, xy_).Expand());
}
TEST_F(BilinearProductTest, HigherOrderTest) {
EXPECT_THROW(ReplaceBilinearTerms(pow(x_(0), 3), x_, x_, xx_),
std::runtime_error);
EXPECT_THROW(ReplaceBilinearTerms(x_(0) * x_(0) * x_(1), x_, x_, xx_),
std::runtime_error);
EXPECT_THROW(ReplaceBilinearTerms(x_(0) * x_(1) * x_(2), x_, x_, xx_),
std::runtime_error);
EXPECT_THROW(ReplaceBilinearTerms(x_(0) * x_(0), x_, y_, xy_),
std::runtime_error);
EXPECT_THROW(ReplaceBilinearTerms(x_(0) * x_(1), x_, y_, xy_),
std::runtime_error);
EXPECT_THROW(ReplaceBilinearTerms(x_(0) * x_(1) * x_(1), x_, y_, xy_),
std::runtime_error);
EXPECT_THROW(ReplaceBilinearTerms(x_(0) * y_(1) * y_(2), x_, y_, xy_),
std::runtime_error);
EXPECT_THROW(ReplaceBilinearTerms(x_(0) * y_(2) * y_(2), x_, y_, xy_),
std::runtime_error);
}
TEST_F(BilinearProductTest, WIncludesXY) {
// When W(i, j) is just a single variable, then that variable can be in x or
// y.
const Vector2<Variable> x{x_(0), x_(1)};
const Vector2<Variable> y{y_(0), y_(1)};
Matrix2<Expression> W;
W << x(0), x(1), y(0), y(1); // W contains entries in x or y.
const Expression e{x(0) * y(0) + W(0, 0)};
EXPECT_PRED2(ExprEqual, ReplaceBilinearTerms(e, x, y, W), 2 * x(0));
}
TEST_F(BilinearProductTest, WIsExpression0) {
EXPECT_PRED2(ExprEqual,
ReplaceBilinearTerms(x_(0) * y_(0), x_.head<3>(), y_.head<3>(),
Z1_ - Z2_),
Z1_(0, 0) - Z2_(0, 0));
}
TEST_F(BilinearProductTest, WIsExpression1) {
EXPECT_PRED2(
ExprEqual,
ReplaceBilinearTerms(x_(0) * y_(0), x_.head<3>(), y_.head<3>(),
Z1_ + 2 * Z2_ + 2 * Eigen::Matrix3d::Identity()),
Z1_(0, 0) + 2 * Z2_(0, 0) + 2);
}
TEST_F(BilinearProductTest, WIsExpression2) {
EXPECT_PRED2(
ExprEqual,
(ReplaceBilinearTerms(x_(0) * y_(1) + 2 * x_(0) * y_(0) + Z1_(0, 0),
x_.head<3>(), y_.head<3>(), Z1_ - Z2_))
.Expand(),
Z1_(0, 1) - Z2_(0, 1) + 2 * Z1_(0, 0) - 2 * Z2_(0, 0) + Z1_(0, 0));
}
TEST_F(BilinearProductTest, WIsExpression3) {
// W is an expression, that contains x or y. This is not allowed.
Eigen::Matrix<Expression, 3, 4> W = xy_;
W(0, 1) += x_(0);
Expression dummy;
EXPECT_THROW(
dummy = ReplaceBilinearTerms(x_(0) + x_(0) * y_(1), x_, y_, W).Expand(),
std::runtime_error);
}
TEST_F(BilinearProductTest, DuplicateEntry) {
// x_duplicate contains duplicate entries.
Vector2<Variable> x_duplicate(x_(0), x_(0));
EXPECT_THROW(ReplaceBilinearTerms(x_(0) * x_(0), x_duplicate, x_duplicate,
xx_.block<2, 2>(0, 0)),
std::runtime_error);
}
} // namespace
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/diagnostic_policy_test_base.h | #pragma once
#include <deque>
#include <string>
#include <gtest/gtest.h>
#include "drake/common/diagnostic_policy.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/ssize.h"
#include "drake/common/text_logging.h"
namespace drake {
namespace test {
using drake::internal::DiagnosticDetail;
using drake::internal::DiagnosticPolicy;
/// A base class for test fixtures that involve DiagnosticPolicy output. It
/// sets error and warning actions on construction to collect all
/// diagnostics. On destruction, it expects its internal warning and error
/// collections to be empty. Test cases meet this requirement by calling
/// TakeError() and/or TakeWarning() to consume and examine expected
/// diagnostics.
class DiagnosticPolicyTestBase : public ::testing::Test {
public:
DiagnosticPolicyTestBase() {
diagnostic_policy_.SetActionForErrors(
[this](const DiagnosticDetail& detail) {
error_records_.push_back(detail);
});
diagnostic_policy_.SetActionForWarnings(
[this](const DiagnosticDetail& detail) {
warning_records_.push_back(detail);
});
}
~DiagnosticPolicyTestBase() { FlushDiagnostics(); }
/// Remove an error from internal records and return its formatted string.
std::string TakeError() {
ScopedTrace trace;
EXPECT_FALSE(error_records_.empty());
return Take(&error_records_).FormatError();
}
/// Remove a warning from internal records and return its formatted string.
std::string TakeWarning() {
ScopedTrace trace;
EXPECT_FALSE(warning_records_.empty());
return Take(&warning_records_).FormatWarning();
}
/// Return the current number of errors.
int NumErrors() { return ssize(error_records_); }
/// Return the current number of warnings.
int NumWarnings() { return ssize(warning_records_); }
// This resets the diagnostic collections so that lingering reports to not
// pollute additional testing. All current reports are silently discarded.
void ClearDiagnostics() {
error_records_.clear();
warning_records_.clear();
}
// This will trip on unexpected errors or warnings that remain after the
// test logic has finished. It also resets the collections so lingering
// reports to not pollute additional testing.
void FlushDiagnostics() {
ScopedTrace trace;
EXPECT_TRUE(error_records_.empty()) << DumpErrors();
EXPECT_TRUE(warning_records_.empty()) << DumpWarnings();
ClearDiagnostics();
}
protected:
std::string DumpErrors() {
std::stringstream stream;
for (const DiagnosticDetail& record : error_records_) {
stream << record.FormatError() << '\n';
}
return stream.str();
}
std::string DumpWarnings() {
std::stringstream stream;
for (const DiagnosticDetail& record : warning_records_) {
stream << record.FormatWarning() << '\n';
}
return stream.str();
}
void ThrowErrors() {
diagnostic_policy_.SetActionForErrors(
&DiagnosticPolicy::ErrorDefaultAction);
}
void RecordErrors() {
diagnostic_policy_.SetActionForErrors(
[this](const DiagnosticDetail& detail) {
error_records_.push_back(detail);
});
}
// Returns the first error as a string (or else fails the test case,
// if there were no errors).
std::string FormatFirstError() {
ScopedTrace trace;
if (error_records_.empty()) {
for (const auto& warning : warning_records_) {
log()->warn(warning.FormatWarning());
}
EXPECT_GT(error_records_.size(), 0)
<< "FormatFirstError did not get any errors";
return {};
}
return error_records_[0].FormatError();
}
// Returns the first warning as a string (or else fails the test case,
// if there were no warnings). Also fails if there were any errors.
std::string FormatFirstWarning() {
ScopedTrace trace;
for (const auto& error : error_records_) {
log()->error(error.FormatError());
}
EXPECT_TRUE(error_records_.empty());
if (warning_records_.empty()) {
EXPECT_TRUE(warning_records_.size() > 0)
<< "FormatFirstWarning did not get any warnings";
return {};
}
return warning_records_[0].FormatWarning();
}
template <typename T>
T Take(std::deque<T>* c) {
T result = c->at(0);
c->pop_front();
return result;
}
// Extend the gtest scoped tracing feature to give more context to failures
// found by the DiagnosticPolicyTestBase. When a failure is found in a scope
// containing a ScopedTrace instance, an extra message will give the file
// name, line number, and test name in the derived ("end user") unit test.
//
// Note that this differs from the SCOPED_TRACE() macro, which reports the
// source code location of itself. The mechanism here reports the source code
// location of the derived test case.
//
// For details of the gtest features used, see the following documentation:
// https://google.github.io/googletest/advanced.html#getting-the-current-tests-name
// https://google.github.io/googletest/advanced.html#adding-traces-to-assertions
class ScopedTrace {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ScopedTrace)
ScopedTrace() = default;
private:
const testing::TestInfo* const test_info_{
testing::UnitTest::GetInstance()->current_test_info()};
::testing::ScopedTrace trace_{
test_info_->file(), test_info_->line(),
fmt::format("{}.{}", test_info_->test_suite_name(),
test_info_->name())};
};
std::deque<DiagnosticDetail> error_records_;
std::deque<DiagnosticDetail> warning_records_;
DiagnosticPolicy diagnostic_policy_;
};
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/symbolic_test_util.h | #pragma once
/// @file
/// This file provides a set of predicates which can be used with GTEST's
/// ASSERT/EXPECT_PRED{n} macros. The motivation is to provide better diagnostic
/// information when the assertions fail. Please consider a scenario where a
/// user wants to assert that two symbolic expressions, `e1` and `e2`, are
/// structurally identical.
///
/// @code
/// // The following does not work because `operator==(const Expression& e1,
/// // const Expression& e2)` does not return a Boolean value. We need to use
/// // Expression::EqualTo() method instead.
/// ASSERT_EQ(e1, e2);
///
/// // The following compiles, but it does not provide enough information when
/// // the assertion fails. It merely reports that `e1.EqualTo(e2)` is evaluated
/// // to `false`, not to `true`.
/// ASSERT_TRUE(e1.EqualTo(e2));
///
/// // When the following assertion fails, it reports the value of `e1` and `e2`
/// // which should help debugging.
/// ASSERT_PRED2(ExprEqual, e1, e2);
/// @endcode
#include <algorithm>
#include <tuple>
#include <vector>
#include <gtest/gtest.h>
#include "drake/common/symbolic/expression.h"
#include "drake/common/symbolic/generic_polynomial.h"
#include "drake/common/symbolic/polynomial.h"
#include "drake/common/symbolic/rational_function.h"
namespace drake {
namespace symbolic {
namespace test {
[[nodiscard]] inline bool VarEqual(const Variable& v1, const Variable& v2) {
return v1.equal_to(v2);
}
[[nodiscard]] inline bool TupleVarEqual(
const std::tuple<Variable, Variable>& vars) {
return VarEqual(std::get<0>(vars), std::get<1>(vars));
}
[[nodiscard]] inline bool VarNotEqual(const Variable& v1,
const Variable& v2) {
return !VarEqual(v1, v2);
}
[[nodiscard]] inline bool VarLess(const Variable& v1, const Variable& v2) {
return v1.less(v2);
}
[[nodiscard]] inline bool VarNotLess(const Variable& v1, const Variable& v2) {
return !VarLess(v1, v2);
}
[[nodiscard]] inline bool ExprEqual(const Expression& e1,
const Expression& e2) {
return e1.EqualTo(e2);
}
[[nodiscard]] inline bool ExprNotEqual(const Expression& e1,
const Expression& e2) {
return !ExprEqual(e1, e2);
}
[[nodiscard]] inline bool ExprLess(const Expression& e1,
const Expression& e2) {
return e1.Less(e2);
}
[[nodiscard]] inline bool ExprNotLess(const Expression& e1,
const Expression& e2) {
return !ExprLess(e1, e2);
}
template <typename BasisElement>
[[nodiscard]] bool GenericPolyEqual(const GenericPolynomial<BasisElement>& p1,
const GenericPolynomial<BasisElement>& p2) {
return p1.EqualTo(p2);
}
template <typename BasisElement>
[[nodiscard]] bool GenericPolyNotEqual(
const GenericPolynomial<BasisElement>& p1,
const GenericPolynomial<BasisElement>& p2) {
return !p1.EqualTo(p2);
}
template <typename BasisElement>
[[nodiscard]] bool GenericPolyEqualAfterExpansion(
const GenericPolynomial<BasisElement>& p1,
const GenericPolynomial<BasisElement>& p2) {
return p1.EqualToAfterExpansion(p2);
}
template <typename BasisElement>
[[nodiscard]] bool GenericPolyNotEqualAfterExpansion(
const GenericPolynomial<BasisElement>& p1,
const GenericPolynomial<BasisElement>& p2) {
return !p1.EqualToAfterExpansion(p2);
}
template <typename BasisElement>
[[nodiscard]] bool GenericPolyAlmostEqual(
const GenericPolynomial<BasisElement>& p1,
const GenericPolynomial<BasisElement>& p2, double tol) {
return p1.CoefficientsAlmostEqual(p2, tol);
}
[[nodiscard]] inline bool PolyEqual(const Polynomial& p1,
const Polynomial& p2) {
return p1.EqualTo(p2);
}
[[nodiscard]] inline bool PolyNotEqual(const Polynomial& p1,
const Polynomial& p2) {
return !PolyEqual(p1, p2);
}
[[nodiscard]] inline bool PolyEqualAfterExpansion(const Polynomial& p1,
const Polynomial& p2) {
return p1.Expand().EqualTo(p2.Expand());
}
[[nodiscard]] inline bool PolyNotEqualAfterExpansion(const Polynomial& p1,
const Polynomial& p2) {
return !p1.Expand().EqualTo(p2.Expand());
}
[[nodiscard]] inline bool RationalFunctionEqual(const RationalFunction& f1,
const RationalFunction& f2) {
return f1.EqualTo(f2);
}
[[nodiscard]] inline bool RationalFunctionNotEqual(
const RationalFunction& f1, const RationalFunction& f2) {
return !RationalFunctionEqual(f1, f2);
}
template <typename F>
[[nodiscard]] bool all_of(const std::vector<Formula>& formulas, const F& f) {
return std::all_of(formulas.begin(), formulas.end(), f);
}
template <typename F>
[[nodiscard]] bool any_of(const std::vector<Formula>& formulas, const F& f) {
return std::any_of(formulas.begin(), formulas.end(), f);
}
[[nodiscard]] inline bool FormulaEqual(const Formula& f1, const Formula& f2) {
return f1.EqualTo(f2);
}
[[nodiscard]] inline bool FormulaNotEqual(const Formula& f1,
const Formula& f2) {
return !FormulaEqual(f1, f2);
}
[[nodiscard]] inline bool FormulaLess(const Formula& f1, const Formula& f2) {
return f1.Less(f2);
}
[[nodiscard]] inline bool FormulaNotLess(const Formula& f1,
const Formula& f2) {
return !FormulaLess(f1, f2);
}
/**
* Compare if two polynomials p1 and p2 are the same, by checking if all the
* coefficients in their difference p1 - p2 is no larger than tol.
* @param p1 A polynomial.
* @param p2 A polynomial.
* @param tol The tolerance on the coefficients of p1 - p2.
*/
[[nodiscard]] inline ::testing::AssertionResult PolynomialEqual(
const symbolic::Polynomial& p1, const symbolic::Polynomial& p2,
double tol) {
const symbolic::Polynomial diff = p1 - p2;
// Check if the absolute value of the coefficient for each monomial is less
// than tol.
const symbolic::Polynomial::MapType& map = diff.monomial_to_coefficient_map();
for (const auto& p : map) {
if (std::abs(get_constant_value(p.second)) > tol) {
return ::testing::AssertionFailure()
<< "The coefficient for " << p.first << " is " << p.second
<< ", exceed tolerance " << tol << "\n";
}
}
return ::testing::AssertionSuccess();
}
} // namespace test
} // namespace symbolic
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_binary",
"drake_cc_googletest",
"drake_cc_library",
"drake_cc_package_library",
)
load(
"//tools/skylark:drake_py.bzl",
"drake_py_library",
)
package(default_visibility = ["//visibility:public"])
exports_files([
"drake_py_unittest_main.py",
])
# This should encompass every cc_library in this package, except for items that
# should only ever be linked into main() programs.
drake_cc_package_library(
name = "test_utilities",
testonly = 1,
visibility = ["//visibility:public"],
deps = [
":diagnostic_policy_test_base",
":eigen_matrix_compare",
":expect_no_throw",
":expect_throws_message",
":is_dynamic_castable",
":is_memcpy_movable",
":maybe_pause_for_user",
":measure_execution",
":random_polynomial_matrix",
":symbolic_test_util",
],
)
drake_cc_library(
name = "diagnostic_policy_test_base",
testonly = 1,
hdrs = ["diagnostic_policy_test_base.h"],
deps = [
"//common:diagnostic_policy",
"@gtest//:without_main",
],
)
drake_cc_library(
name = "eigen_matrix_compare",
testonly = 1,
hdrs = ["eigen_matrix_compare.h"],
deps = [
"//common:essential",
"@gtest//:without_main",
],
)
drake_cc_library(
name = "expect_no_throw",
testonly = 1,
hdrs = ["expect_no_throw.h"],
deps = [
"//common:nice_type_name",
],
)
drake_cc_library(
name = "expect_throws_message",
testonly = 1,
hdrs = ["expect_throws_message.h"],
deps = ["//common:essential"],
)
drake_cc_library(
name = "gtest_printers",
testonly = 1,
hdrs = [
"eigen_printer.h",
"fmt_format_printer.h",
],
tags = ["exclude_from_package"],
visibility = ["@gtest//:__pkg__"],
deps = [
"//common:fmt",
"@eigen",
"@fmt",
],
)
drake_cc_library(
name = "is_dynamic_castable",
testonly = 1,
hdrs = ["is_dynamic_castable.h"],
deps = [
"//common:nice_type_name",
],
)
drake_cc_library(
name = "is_memcpy_movable",
testonly = 1,
hdrs = ["is_memcpy_movable.h"],
)
drake_cc_library(
name = "measure_execution",
testonly = 1,
hdrs = ["measure_execution.h"],
)
drake_cc_library(
name = "random_polynomial_matrix",
testonly = 1,
hdrs = ["random_polynomial_matrix.h"],
deps = [
"//common:polynomial",
],
)
drake_cc_library(
name = "limit_malloc",
testonly = 1,
srcs = ["limit_malloc.cc"],
hdrs = ["limit_malloc.h"],
copts = [
# We shouldn't call __tsan_func_entry from allocations during dl_init.
"-fno-sanitize=thread",
],
tags = [
# The limit_malloc library be used sparingly, and not by default.
# Don't add this library into the ":test_utilities" package library.
"exclude_from_package",
],
deps = [
# Keep it simple and don't depend on any Drake code.
],
)
drake_cc_library(
name = "symbolic_test_util",
testonly = 1,
hdrs = ["symbolic_test_util.h"],
deps = [
"//common/symbolic:expression",
"//common/symbolic:generic_polynomial",
"//common/symbolic:polynomial",
"//common/symbolic:rational_function",
],
)
drake_cc_library(
name = "drake_cc_googletest_main",
testonly = 1,
srcs = ["drake_cc_googletest_main.cc"],
tags = [
# This is only intended to be used by the drake_cc_googletest() macro.
# Don't add this library into the ":test_utilities" package library.
"exclude_from_package",
],
deps = [
"//common:add_text_logging_gflags",
"@gtest//:without_main",
],
)
drake_cc_googletest(
name = "limit_malloc_test",
args = [
# By default, we will skip the death tests because they only pass on
# non-Apple, non-Sanitizer, non-Memcheck builds. We will explicitly
# run them (below) for the configurations that succeed.
"--gtest_filter=-*DeathTest*",
],
deps = [
":limit_malloc",
],
)
drake_cc_binary(
name = "limit_malloc_manual_test",
testonly = 1,
srcs = ["test/limit_malloc_manual_test.cc"],
deps = [
":limit_malloc",
],
)
# N.B. All sh_tests are excluded from sanitizer builds by default; these death
# tests are therefore skipped under those configurations.
sh_test(
name = "limit_malloc_death_test",
srcs = [":limit_malloc_test"],
args = select({
"//tools/cc_toolchain:apple": [
# The code to enforce malloc limits is not implemented on macOS.
"--gtest_filter=-*",
],
"//conditions:default": [
# Run only the death tests, not the plain tests.
"--gtest_filter=*DeathTest*",
],
}),
data = [
":limit_malloc_test",
],
# Fails to terminate when run under Valgrind tools.
tags = ["no_valgrind_tools"],
)
drake_cc_googletest(
name = "eigen_matrix_compare_test",
deps = [
":eigen_matrix_compare",
"//common:essential",
],
)
drake_cc_googletest(
name = "is_dynamic_castable_test",
deps = [
":is_dynamic_castable",
],
)
drake_cc_googletest(
name = "is_memcpy_movable_test",
deps = [
":is_memcpy_movable",
],
)
drake_py_library(
name = "disable_python_unittest",
srcs = ["disable_python_unittest/unittest/__init__.py"],
imports = ["disable_python_unittest"],
)
drake_cc_googletest(
name = "expect_no_throw_test",
deps = [
":expect_no_throw",
],
)
drake_cc_library(
name = "maybe_pause_for_user",
testonly = 1,
srcs = ["maybe_pause_for_user.cc"],
hdrs = ["maybe_pause_for_user.h"],
)
drake_cc_googletest(
name = "maybe_pause_for_user_test",
deps = [
":maybe_pause_for_user",
],
)
drake_cc_binary(
name = "maybe_pause_for_user_manual_test",
testonly = 1,
srcs = ["test/maybe_pause_for_user_manual_test.cc"],
deps = [
":maybe_pause_for_user",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/maybe_pause_for_user.h | #pragma once
namespace drake {
namespace common {
/** Pauses execution for the user to examine visualization output, for use
within bazel unit tests. This function will not pause execution when running
as a bazel test, but when running as a command-line executable, it will enable
users to see the visualization outputs.
The complete behavior is somewhat more subtle, depending on the bazel rules
used to build the program, and the way it is invoked:
- built with a bazel test rule
- invoked with "bazel test" -- does not pause
- invoked with "bazel run" -- does not pause
- invoked directly ("bazel/bin/[PROGRAM]") -- does pause
- built with a bazel binary rule
- invoked with "bazel run" -- does pause
- invoked directly ("bazel/bin/[PROGRAM]") -- does pause
*/
void MaybePauseForUser();
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/drake_cc_googletest_main.cc | /// @file
/// This is Drake's default main() function for gtest-based unit tests.
#include <gflags/gflags.h>
#include <gmock/gmock.h>
int main(int argc, char** argv) {
std::cout << "Using drake_cc_googletest_main.cc\n";
// Initialize gtest and gmock.
testing::InitGoogleMock(&argc, argv);
std::cout << "\n"; // Put a linebreak between gtest help and gflags help.
// Initialize gflags; this must happen after gtest initialization, so that the
// gtest flags have already been removed from argv and won't confuse gflags.
google::SetUsageMessage(" "); // Nerf a silly warning emitted by gflags.
google::ParseCommandLineFlags(&argc, &argv, true);
// Actually run the tests.
return RUN_ALL_TESTS();
}
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/drake_py_unittest_main.py | """This is Drake's default main() for unittest-based tests. It is intended for
use by the drake_py_unittest macro defined in //tools/skylark:drake_py.bzl and
should NOT be called directly by anything else.
"""
import argparse
from importlib.machinery import SourceFileLoader
import io
import os
from pathlib import Path
import re
import sys
import trace
import unittest
import warnings
import xmlrunner
try:
from pydrake.common.deprecation import DrakeDeprecationWarning
has_pydrake = True
except ImportError:
has_pydrake = False
def _unittest_main(*, module, argv, testRunner):
"""Just like unittest.main, but obeys TEST_TOTAL_SHARDS.
Refer to https://bazel.build/reference/test-encyclopedia#test-sharding for
an overview of the sharding protocol used by the Bazel test runner that
invokes us.
Only a subset of unittest.main's kwargs are supported.
"""
# In case sharding won't be used, delegate to the vanilla unittest.main.
has_shard_count = "TEST_TOTAL_SHARDS" in os.environ
if has_shard_count and len(argv) > 1:
print("warning: Ignoring shard_count due to test arguments")
has_shard_count = False
if not has_shard_count:
# Use `warnings=False` to tell unittest to keep its hands off of our
# warnings settings, exploiting a loophole where it checks "if warnings
# is None" to check if the user passed a kwarg, but "if warning" to
# actually apply the user's kwarg.
unittest.main(module=module, argv=argv, warnings=False,
testRunner=testRunner)
return
# Affirm to the test environment that we are cognizant of sharding.
if "TEST_SHARD_STATUS_FILE" in os.environ:
Path(os.environ["TEST_SHARD_STATUS_FILE"]).touch()
# Run only some of the tests, per the BUILD.bazel's shard_count.
total_shards = int(os.environ["TEST_TOTAL_SHARDS"])
shard_index = int(os.environ["TEST_SHARD_INDEX"])
suites = unittest.loader.defaultTestLoader.loadTestsFromModule(
sys.modules[module])
tests = []
for suite in suites:
tests += list(suite)
if total_shards > len(tests):
print(f"error: shard_count = {total_shards} exceeds the number of test"
f" cases ({len(tests)})")
sys.exit(1)
shard_tests = tests[shard_index::total_shards]
assert len(shard_tests) > 0
print(f"info: Shard {shard_index + 1} / {total_shards} has these tests:")
for shard_test in shard_tests:
print(f"info: - {str(shard_test)}")
sys.stdout.flush()
shard_suite = unittest.TestSuite(shard_tests)
result = testRunner.run(shard_suite)
sys.exit(0 if result.wasSuccessful() else 1)
def main():
# Obtain the full path for this test case; it looks a bit like this:
# .../execroot/.../foo_test.runfiles/.../drake_py_unittest_main.py
# Also work around kcov#368 by consuming DRAKE_KCOV_LINK_PATH.
# TODO(rpoyner-tri): remove DRAKE_KCOV_LINK_PATH when newer kcov is ready.
main_py = os.environ.get('DRAKE_KCOV_LINK_PATH', sys.argv[0])
os.environ.pop('DRAKE_KCOV_LINK_PATH', None)
# Parse the test case name out of the runfiles directory name.
match = re.search("^(.*bin/(.*?/)?(py/)?([^/]*_test).runfiles/)", main_py)
if not match:
print("error: no test name match in {}".format(main_py))
sys.exit(1)
runfiles, test_package, _, test_name, = match.groups()
test_basename = test_name + ".py"
# Check the test's source code for a (misleading) __main__.
runfiles_test_filename = (
runfiles + "drake/" + test_package + "test/" + test_basename)
if not os.path.exists(runfiles_test_filename):
raise RuntimeError("Could not find {} at {}".format(
test_basename, runfiles_test_filename))
realpath_test_filename = os.path.realpath(runfiles_test_filename)
with io.open(realpath_test_filename, "r", encoding="utf8") as infile:
for line in infile.readlines():
if any([line.startswith("if __name__ =="),
line.strip().startswith("unittest.main")]):
print(f"error: {test_basename} appears to have a main "
"function (checks 'if __name__ == ') or call the main "
"function of unittest ('unittest.main') but also uses "
"drake_py_unittest; when using drake_py_unittest, "
"the boilerplate main function should not be used; "
"if this test is not based on unittest, declare it "
"as drake_py_test instead of drake_py_unittest and "
"keep the main function intact")
sys.exit(1)
if os.access(realpath_test_filename, os.X_OK):
print(f"error: {test_basename} uses drake_py_unittest but is "
"marked executable in the filesystem; fix this via "
f"chmod a-x {test_basename}")
sys.exit(1)
# On import, force all drake deprecation warnings to trigger an error.
if has_pydrake:
warnings.simplefilter("error", DrakeDeprecationWarning)
module = SourceFileLoader(test_name, runfiles_test_filename).load_module(
test_name)
# Figure out which arguments are for unittest and which are for the module
# under test.
unittest_argv = sys.argv[:1]
known_unittest_args = [
"-h", "--help",
"-v", "--verbose",
"-q", "--quiet",
"-f", "--failfast",
"-c", "--catch",
"-b", "--buffer",
]
test_class_guesses = [
x for x in dir(module)
if x.startswith("Test")
]
if module.__doc__:
print(module.__doc__)
print()
index = 1
while index < len(sys.argv):
arg = sys.argv[index]
if arg in known_unittest_args or any([
arg.startswith(clazz) for clazz in test_class_guesses]):
unittest_argv.append(arg)
sys.argv.pop(index)
continue
index += 1
# Custom flags.
parser = argparse.ArgumentParser(description="Drake-specific arguments")
parser.add_argument(
"--trace", type=str, choices=["none", "user", "sys"], default="none",
help="Enable source tracing. `none` implies no tracing, `user` "
"implies tracing user code, and `sys` implies tracing all "
"code. Default is `none`.")
parser.add_argument(
"--nostdout_to_stderr", action="store_true",
help="Do not reexec to get unbuffered output. When running from the "
"Bazel client (non-batch), stdout and stderr ordering may not "
"flush at convenient times, making errors less readable. Having "
"the output be unbuffered makes it more readable.")
parser.add_argument(
"--deprecation_action", type=str, default="once",
help="Action for any deprecation warnings. See "
"`warnings.simplefilter()`.")
parser.add_argument(
"--drake_deprecation_action", type=str, default="error",
help="Action for Drake deprecation warnings. Applied after "
"--deprecation_action.")
args, remaining = parser.parse_known_args()
sys.argv = sys.argv[:1] + remaining
def run():
# Ensure we print out help.
if "-h" in unittest_argv or "--help" in unittest_argv:
parser.print_help()
print("\n`unittest` specific arguments")
# Delegate the rest to unittest.
# N.B. Do not use the runner when `--trace={user,sys}` is enabled.
if "XML_OUTPUT_FILE" in os.environ and args.trace == "none":
with open(os.environ["XML_OUTPUT_FILE"], "wb") as output:
_unittest_main(
module=test_name, argv=unittest_argv,
testRunner=xmlrunner.XMLTestRunner(output=output))
else:
_unittest_main(
module=test_name, argv=unittest_argv,
testRunner=unittest.TextTestRunner)
# Ensure deprecation warnings are always shown at least once.
warnings.simplefilter(args.deprecation_action, DeprecationWarning)
# Handle Drake-specific deprecations.
if has_pydrake:
warnings.simplefilter(
args.drake_deprecation_action, DrakeDeprecationWarning)
if args.trace != "none":
if args.trace == "user":
# Add `sys.prefix` here, just in case we're debugging with a
# virtualenv.
ignoredirs = ["/usr", sys.prefix]
else:
ignoredirs = []
run = traced(run, ignoredirs=ignoredirs)
run()
# N.B. `reexecute_if_unbuffered` and `traced` should be kept in exact sync with
# `doc/python_bindings.rst`. It should be easy to copy and paste this in other
# scripts.
def reexecute_if_unbuffered():
"""Ensures that output is immediately flushed (e.g. for segfaults).
ONLY use this at your entrypoint. Otherwise, you may have code be
re-executed that will clutter your console."""
import os
import shlex
import sys
if os.environ.get("PYTHONUNBUFFERED") in (None, ""):
os.environ["PYTHONUNBUFFERED"] = "1"
argv = list(sys.argv)
if argv[0] != sys.executable:
argv.insert(0, sys.executable)
cmd = " ".join([shlex.quote(arg) for arg in argv])
sys.stdout.flush()
os.execv(argv[0], argv)
def traced(func, ignoredirs=None):
"""Decorates func such that its execution is traced, but filters out any
Python code outside of the system prefix."""
import functools
import sys
import trace
if ignoredirs is None:
ignoredirs = ["/usr", sys.prefix]
tracer = trace.Trace(trace=1, count=0, ignoredirs=ignoredirs)
@functools.wraps(func)
def wrapped(*args, **kwargs):
return tracer.runfunc(func, *args, **kwargs)
return wrapped
if __name__ == '__main__':
# TODO(eric.cousineau): Move this into `main()` to leverage argparse if we
# can simplify the custom parsing logic (e.g. not have to import source
# modules).
# Avoid re-executing if run under kcov; it defeats kcov's instrumentation.
if "--nostdout_to_stderr" not in sys.argv \
and 'DRAKE_KCOV_COMMAND' not in os.environ:
reexecute_if_unbuffered()
# N.B. If execv is called by `reexecute_if_unbuffered`, then `main`
# will not be called by this current process image; instead, it will be
# called in the *new* process image.
main()
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/measure_execution.h | #pragma once
/// @file
/// A benchmarking helper.
#include <chrono>
#include <utility>
namespace drake {
namespace common {
namespace test {
/// Returns the elapsed time of `func(args)`, in seconds.
template <typename F, typename... Args>
[[nodiscard]] static double MeasureExecutionTime(F func, Args&&... args) {
using clock = std::chrono::steady_clock;
const clock::time_point start = clock::now();
func(std::forward<Args>(args)...);
const clock::time_point end = clock::now();
return std::chrono::duration<double>(end - start).count();
}
} // namespace test
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/fmt_format_printer.h | #pragma once
#include <type_traits>
#include <fmt/format.h>
namespace drake {
namespace internal {
/* Defines a googletest printer for values that provide fmt::format.
We hack this option into our tools/workspace/gtest/package.BUILD.bazel file. */
struct FmtFormatPrinter {
// This is true iff the type provides fmt::formatter<T> directly, without
// any conversions or fallback to operator<< streaming.
template <typename T>
static constexpr bool is_directly_formattable =
std::is_constructible_v<fmt::formatter<T, char>>;
// SFINAE on whether the type directly supports formatting.
// If not, gtest has a suite of other kinds of printers is will fall back on.
template <typename T, typename = std::enable_if_t<is_directly_formattable<T>>>
static void PrintValue(const T& value, std::ostream* os) {
*os << fmt::to_string(value);
}
};
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/eigen_printer.h | #pragma once
#include <string>
#include <type_traits>
#include "drake/common/fmt_eigen.h"
namespace drake {
namespace internal {
/* Defines a googletest printer for Eigen matrices.
We hack this option into our tools/workspace/gtest/package.BUILD.bazel file. */
struct EigenPrinter {
template <typename Derived>
static constexpr bool is_eigen_matrix =
std::is_base_of_v<Eigen::MatrixBase<Derived>, Derived>;
// SFINAE on whether the type is an Eigen::Matrix of some kind.
// If not, gtest has a suite of other kinds of printers is will fall back on.
template <typename T, typename = std::enable_if_t<is_eigen_matrix<T>>>
static void PrintValue(const T& value, std::ostream* os) {
// If the printed representation has newlines, start it on a fresh line.
std::string printed = fmt::to_string(fmt_eigen(value));
for (const char ch : printed) {
if (ch == '\n') {
*os << '\n';
break;
}
}
*os << printed;
}
};
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/random_polynomial_matrix.h | #pragma once
#include "drake/common/polynomial.h"
namespace drake {
namespace test {
/// Obtains a matrix of random unvariate Polynomials of the specified size.
template <typename T = double>
static Eigen::Matrix<Polynomial<T>, Eigen::Dynamic, Eigen::Dynamic>
RandomPolynomialMatrix(Eigen::Index num_coefficients_per_polynomial,
Eigen::Index rows, Eigen::Index cols) {
Eigen::Matrix<Polynomial<T>, Eigen::Dynamic, Eigen::Dynamic>
mat(rows, cols);
for (Eigen::Index row = 0; row < mat.rows(); ++row) {
for (Eigen::Index col = 0; col < mat.cols(); ++col) {
auto coeffs =
(Eigen::Matrix<T, Eigen::Dynamic, 1>::Random(
num_coefficients_per_polynomial)).eval();
mat(row, col) = Polynomial<T>(coeffs);
}
}
return mat;
}
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/limit_malloc.cc | #include "drake/common/test_utilities/limit_malloc.h"
#include <signal.h>
#include <atomic>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <mutex>
#include <new>
#include <stdexcept>
#include <type_traits>
#include <utility>
// Analyze the cases where heap hooks should be compiled and linked. Avoid
// Apple platforms; also avoid ASan builds (spelled various ways for different
// compilers). For ASan background, see #14901.
#define DRAKE_INSTALL_HEAP_HOOKS 1
#ifdef __APPLE__
# undef DRAKE_INSTALL_HEAP_HOOKS
# define DRAKE_INSTALL_HEAP_HOOKS 0
#elif defined(__has_feature)
// Detect ASan the clang way.
# if __has_feature(address_sanitizer)
# undef DRAKE_INSTALL_HEAP_HOOKS
# define DRAKE_INSTALL_HEAP_HOOKS 0
# endif
#elif defined(__SANITIZE_ADDRESS__)
// Detect ASan the gcc way.
# if __SANITIZE_ADDRESS__
# undef DRAKE_INSTALL_HEAP_HOOKS
# define DRAKE_INSTALL_HEAP_HOOKS 0
# endif
#endif
// Functions that are called during dl_init must not use the sanitizer runtime.
#ifdef __clang__
#define DRAKE_NO_SANITIZE __attribute__((no_sanitize("address")))
#else
#define DRAKE_NO_SANITIZE
#endif
// Declare this function here so its definition can follow the
// platform-specific enabling of observations.
static void EvaluateMinNumAllocations(int observed, int min_num_allocations);
namespace drake {
namespace test {
namespace {
// LimitMalloc does not work properly with some configurations. Check this
// predicate and disarm to avoid erroneous results.
bool IsSupportedConfiguration() {
static const bool is_supported{DRAKE_INSTALL_HEAP_HOOKS &&
!std::getenv("LSAN_OPTIONS") &&
!std::getenv("VALGRIND_OPTS")};
return is_supported;
}
// This variable is used as an early short-circuit for our malloc hooks. When
// false, we execute as minimal code footprint as possible. This keeps dl_init
// happy when its invoke malloc and we can't yet execute our C++ code.
volatile bool g_any_monitor_has_ever_been_installed = false;
// A set of limits and current tallies.
class Monitor {
public:
Monitor(const LimitMalloc* owner, LimitMallocParams args)
: owner_(owner), args_(std::move(args)) {}
// Returns true iff our owner is x.
bool has_owner(const LimitMalloc* x) const { return owner_ == x; }
// To be called by our hooks when an allocation attempt occurs,
void malloc(size_t) { ObserveAllocation(); }
void calloc(size_t, size_t) { ObserveAllocation(); }
void realloc(void*, size_t, bool is_noop) {
if (!(is_noop && args_.ignore_realloc_noops)) {
ObserveAllocation();
}
}
int num_allocations() const { return observed_num_allocations_.load(); }
const LimitMallocParams& params() const { return args_; }
private:
void ObserveAllocation();
// Do not de-reference owner_, it may be dangling; use for operator== only.
const LimitMalloc* const owner_{};
// The in-effect limits for this Monitor.
const LimitMallocParams args_{};
// The current tallies for this Monitor.
std::atomic_int observed_num_allocations_{0};
};
// A cut-down version of drake/common/never_destroyed.
template <typename T>
class never_destroyed {
public:
never_destroyed() { new (&storage_) T(); }
T& access() { return *reinterpret_cast<T*>(&storage_); }
private:
typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_;
};
class ActiveMonitor {
public:
// Returns the currently-active monitor (or nullptr if none). The result
// remains valid even if the LimitMalloc guard is destroyed in the meantime.
static std::shared_ptr<Monitor> load() {
auto& self = singleton();
std::shared_ptr<Monitor> result;
if (self.active_.get() != nullptr) {
std::lock_guard<std::mutex> guard(self.mutex_);
result = self.active_;
}
return result;
}
// Swaps the currently-active monitor, returning the prior one.
static std::shared_ptr<Monitor> exchange(std::shared_ptr<Monitor> next) {
auto& self = singleton();
g_any_monitor_has_ever_been_installed = true;
std::lock_guard<std::mutex> guard(self.mutex_);
self.active_.swap(next);
return next;
}
// Removes and returns currently-active monitor.
static std::shared_ptr<Monitor> reset() {
std::shared_ptr<Monitor> no_monitor;
return exchange(no_monitor);
}
// To be called by our hooks when an allocation attempt occurs,
DRAKE_NO_SANITIZE
static void malloc(size_t size) {
if (g_any_monitor_has_ever_been_installed) {
auto monitor = load();
if (monitor) {
monitor->malloc(size);
}
}
}
DRAKE_NO_SANITIZE
static void calloc(size_t nmemb, size_t size) {
if (g_any_monitor_has_ever_been_installed) {
auto monitor = load();
if (monitor) {
monitor->calloc(nmemb, size);
}
}
}
DRAKE_NO_SANITIZE
static void realloc(void* ptr, size_t size, bool is_noop) {
if (g_any_monitor_has_ever_been_installed) {
auto monitor = load();
if (monitor) {
monitor->realloc(ptr, size, is_noop);
}
}
}
private:
// Singleton mutex guarding active_;
std::mutex mutex_;
// Singleton shared_ptr denoting the active monitor.
std::shared_ptr<Monitor> active_;
static ActiveMonitor& singleton() {
static never_destroyed<ActiveMonitor> instance;
return instance.access();
}
};
void Monitor::ObserveAllocation() {
if (!IsSupportedConfiguration()) { return; }
bool failure = false;
// Check the allocation-call limit.
const int observed = ++observed_num_allocations_;
if ((args_.max_num_allocations >= 0) &&
(observed > args_.max_num_allocations)) {
failure = true;
}
// TODO(jwnimmer-tri) Add more limits (requested bytes?) here.
if (!failure) { return; }
// Non-fatal breakpoint action; use with helper script:
// tools/dynamic_analysis/dump_limit_malloc_stacks
const auto break_env = std::getenv("DRAKE_LIMIT_MALLOC_NONFATAL_BREAKPOINT");
// Use the action if the environment variable is defined and not empty.
if ((break_env != nullptr) && (*break_env != '\0')) {
::raise(SIGTRAP);
return;
}
// Report an error (but re-enable malloc before doing so!).
ActiveMonitor::reset();
std::cerr << "abort due to malloc #" << observed
<< " while max_num_allocations = "
<< args_.max_num_allocations << " in effect";
std::cerr << std::endl;
// TODO(jwnimmer-tri) It would be nice to print a backtrace here.
std::abort();
}
} // namespace
LimitMalloc::LimitMalloc() : LimitMalloc({ .max_num_allocations = 0 }) {}
LimitMalloc::LimitMalloc(LimitMallocParams args) {
// Make sure the configuration check is warm before trying it within a malloc
// call stack.
IsSupportedConfiguration();
// Prepare a monitor with our requested limits.
auto monitor = std::make_shared<Monitor>(this, std::move(args));
// Activate our Monitor.
auto prior = ActiveMonitor::exchange(monitor);
if (prior) {
throw std::logic_error("Cannot nest LimitMalloc guards");
}
}
int LimitMalloc::num_allocations() const {
return ActiveMonitor::load()->num_allocations();
}
const LimitMallocParams& LimitMalloc::params() const {
return ActiveMonitor::load()->params();
}
LimitMalloc::~LimitMalloc() {
// Copy out the monitor's data before we delete it.
const int observed = num_allocations();
const LimitMallocParams args = params();
// De-activate our Monitor.
auto prior = ActiveMonitor::reset();
if (!(prior && prior->has_owner(this))) {
std::cerr << "LimitMalloc dtor invariant failure\n";
}
::EvaluateMinNumAllocations(observed, args.min_num_allocations);
}
} // namespace test
} // namespace drake
// Optionally compile the code that places the heap hooks.
#if DRAKE_INSTALL_HEAP_HOOKS
// https://www.gnu.org/software/libc/manual/html_node/Replacing-malloc.html#Replacing-malloc
extern "C" void* __libc_malloc(size_t);
extern "C" void* __libc_free(void*);
extern "C" void* __libc_calloc(size_t, size_t);
extern "C" void* __libc_realloc(void*, size_t);
void* malloc(size_t size) {
drake::test::ActiveMonitor::malloc(size);
return __libc_malloc(size);
}
void free(void* ptr) {
__libc_free(ptr);
}
void* calloc(size_t nmemb, size_t size) {
drake::test::ActiveMonitor::calloc(nmemb, size);
return __libc_calloc(nmemb, size);
}
void* realloc(void* ptr, size_t size) {
void* result = __libc_realloc(ptr, size);
bool is_noop = (result == ptr);
drake::test::ActiveMonitor::realloc(ptr, size, is_noop);
return result;
}
static void EvaluateMinNumAllocations(int observed, int min_num_allocations) {
if (!drake::test::IsSupportedConfiguration()) { return; }
if ((min_num_allocations >= 0) && (observed < min_num_allocations)) {
std::cerr << "abort due to scope end with "
<< observed << " mallocs while min_num_allocations = "
<< min_num_allocations << " in effect";
std::cerr << std::endl;
std::abort();
}
}
#else
// Evaluating the minimum is a no-op when no counts are observed.
static void EvaluateMinNumAllocations(int observed, int min_num_allocations) {}
#endif
#undef DRAKE_NO_SANITIZE
#undef DRAKE_INSTALL_HEAP_HOOKS
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/limit_malloc.h | #pragma once
namespace drake {
namespace test {
/// Parameters to control malloc limits.
struct LimitMallocParams {
/// Maximum calls to malloc, calloc, or realloc (totaled as one).
/// When less than zero, there is no limit on the number of calls.
int max_num_allocations{-1};
/// Minimum calls to malloc, calloc, or realloc (totaled as one).
/// When less than zero, there is no limit on the number of calls.
int min_num_allocations{-1};
/// Whether a realloc() that leaves its `ptr` unchanged should be ignored.
bool ignore_realloc_noops{false};
};
/// Instantiate this class in a unit test scope where malloc (and realloc,
/// etc.) should be disallowed or curtailed.
///
/// @note This class is currently a no-op in some build configurations:
/// - macOS
/// - leak sanitizer
/// - valgrind tools
///
/// Example:
/// @code
/// GTEST_TEST(LimitMallocTest, BasicTest) {
/// std::vector<double> foo(100); // Heap allocation is OK.
/// {
/// LimitMalloc guard;
/// // The guarded code goes here. Heap allocations result in aborts.
/// std::array<double, 100> stack;
/// }
/// std::vector<double> bar(100); // Heap allocation is OK again.
/// }
/// @endcode
///
/// Currently, when the device under test violates its allocation limits, the
/// test terminates with an abort(). To better isolate what went wrong, re-run
/// the test in a debugger.
///
/// This class is only intended for use in test code. To temporarily use it in
/// non-test code, hack the BUILD.bazel file to mark this library `testonly = 0`
/// instead of `testonly = 1`.
class LimitMalloc final {
public:
/// Applies malloc limits until this object's destructor is run.
/// All allocations will fail.
/// For now, only *one* instance of this class may be created at a time.
/// (In the future, we may allow updating the limits by nesting these guards.)
LimitMalloc();
/// Applies malloc limits until this object's destructor is run.
/// A allocations will succeed except for any limits designated in args.
/// For now, only *one* instance of this class may be created at a time.
/// (In the future, we may allow updating the limits by nesting these guards.)
explicit LimitMalloc(LimitMallocParams args);
/// Undoes this object's malloc limits.
~LimitMalloc();
/// Returns the number of allocations observed so far.
int num_allocations() const;
/// Returns the parameters structure used to construct this object.
const LimitMallocParams& params() const;
// We write this out by hand, to avoid depending on Drake *at all*.
/// @name Does not allow copy, move, or assignment
//@{
LimitMalloc(const LimitMalloc&) = delete;
void operator=(const LimitMalloc&) = delete;
LimitMalloc(LimitMalloc&&) = delete;
void operator=(LimitMalloc&&) = delete;
//@}
};
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/expect_no_throw.h | #pragma once
#include <exception>
#include <gtest/gtest.h>
#include "drake/common/nice_type_name.h"
// Private helper macro to ensure error messages are the same for EXPECT and
// ASSERT variants of this macro.
// TODO(eric.cousineau): Add support for ostream additions, e.g.
// `DRAKE_EXPECT_NO_THROW(stuff) << "Message"`, like `GTEST_TEST_NO_THROW_`
// does with labels. (Though TBH, `SCOPED_TRACE(...)` is better.)
#define _DRAKE_TEST_NO_THROW(statement, fail_macro) \
try { \
statement; \
} catch (const std::exception& e) { \
fail_macro() \
<< "Expected: Does not throw:\n " << #statement << std::endl \
<< "Actual: Throws " << ::drake::NiceTypeName::Get(e) << std::endl \
<< " " << e.what(); \
} catch (...) { \
fail_macro() \
<< "Expected: Does not throw:\n " << #statement << std::endl \
<< "Actual: Throws type which does not inherit from std::exception"; \
}
/**
Unittest helper to explicitly indicate that a statement should not throw an
exception. This should be used in place of EXPECT_NO_THROW because it will have
useful information when a failure indeed happens.
*/
#define DRAKE_EXPECT_NO_THROW(statement) \
_DRAKE_TEST_NO_THROW(statement, ADD_FAILURE)
/**
Same as DRAKE_EXPECT_NO_THROW, but halts the execution of the given test case
on failure.
*/
#define DRAKE_ASSERT_NO_THROW(statement) \
_DRAKE_TEST_NO_THROW(statement, GTEST_FAIL)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/is_memcpy_movable.h | #pragma once
#include <cstdlib>
#include <cstring>
#include <functional>
#include <memory>
#include <type_traits>
namespace drake {
namespace test {
/// Checks if @p value of @p T type is movable via memcpy. That is, it tests
/// memcpy on @p value keeps a given invariant between @p value and a copy of
/// it. It uses a binary function object @p invariant_pred to check for
/// invariance.
///
/// @note Eigen's reallocation mechanisms have an issue. It is moving bytes
/// using `memcpy` without calling a move constructor. As a result, if a
/// `Scalar` type of Eigen matrix/array is not IsMemcpyMovable, we have
/// undefined behavior when `conservativeResize` method is called. This should
/// *always* be used to test a `Scalar` used within an `Eigen::EigenBase<...>`
/// object. Please see https://github.com/RobotLocomotion/drake/issues/5974 for
/// more information.
template <typename T, typename InvariantPred = std::equal_to<T>>
[[nodiscard]] bool IsMemcpyMovable(
const T& value, const InvariantPred& invariant_pred = InvariantPred()) {
// 1. Create ptr_to_original via placement-new.
auto original_storage = std::make_unique<
typename std::aligned_storage<sizeof(T), alignof(T)>::type>();
T* const ptr_to_original{new (original_storage.get()) T{value}};
// 2. Create ptr_to_moved from ptr_to_original via memcpy.
auto moved_storage = std::make_unique<
typename std::aligned_storage<sizeof(T), alignof(T)>::type>();
T* const ptr_to_moved{reinterpret_cast<T* const>(moved_storage.get())};
memcpy(static_cast<void*>(ptr_to_moved), ptr_to_original, sizeof(T));
// 3. Free original_storage.
original_storage.reset();
// 4. Check if the invariant between value and ptr_to_moved hold.
const bool out{invariant_pred(value, *ptr_to_moved)};
ptr_to_moved->T::~T();
return out;
}
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/expect_throws_message.h | #pragma once
#include <regex>
#include <stdexcept>
#include <string>
#include "drake/common/drake_assert.h"
// TODO(sherm1) Add unit tests for these macros. See issue #8403.
#ifdef DRAKE_DOXYGEN_CXX
/** Unit test helper macro for "expecting" an exception to be thrown but also
testing the error message against a provided regular expression. This is
like GTest's `EXPECT_THROW` but does not allow for tested the exception subtype
(because checking the message should suffice on its own).
Usage example: @code
DRAKE_EXPECT_THROWS_MESSAGE(
StatementUnderTest(), // You expect this statement to throw ...
".*some important.*phrases.*that must appear.*"); // ... this message.
@endcode
The regular expression must match the entire error message. If there is
boilerplate you don't care to match at the beginning and end, surround with
`.*` to ignore in single-line messages or `[\s\S]*` for multiline
messages.
Following GTest's conventions, failure to perform as expected here is a
non-fatal test error. An `ASSERT` variant is provided to make it fatal. There
are also `*_IF_ARMED` variants. These require an exception in Debug builds (or
any builds where `DRAKE_ENABLE_ASSERTS` has been defined). In Release builds,
the expression will pass if it _doesn't_ throw or if it throws an
exception that would pass the same test as in Debug builds. There is no
mechanism for testing _exclusive_ throwing behavior (i.e., only throws in
Debug).
@see DRAKE_ASSERT_THROWS_MESSAGE
@see DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED, DRAKE_ASSERT_THROWS_MESSAGE_IF_ARMED
*/
#define DRAKE_EXPECT_THROWS_MESSAGE(expression, regexp)
/** Fatal error version of `DRAKE_EXPECT_THROWS_MESSAGE`.
@see DRAKE_EXPECT_THROWS_MESSAGE */
#define DRAKE_ASSERT_THROWS_MESSAGE(expression, regexp)
/** Same as `DRAKE_EXPECT_THROWS_MESSAGE` in Debug builds, but doesn't _require_
a throw in Release builds. However, if the Release build does throw it must
throw the right message. More precisely, the thrown message is required
whenever `DRAKE_ENABLE_ASSERTS` is defined, which Debug builds do be default.
@see DRAKE_EXPECT_THROWS_MESSAGE */
#define DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(expression, regexp)
/** Same as `DRAKE_ASSERT_THROWS_MESSAGE` in Debug builds, but doesn't require
a throw in Release builds. However, if the Release build does throw it must
throw the right message. More precisely, the thrown message is required
whenever `DRAKE_ENABLE_ASSERTS` is defined, which Debug builds do by default.
@see DRAKE_ASSERT_THROWS_MESSAGE */
#define DRAKE_ASSERT_THROWS_MESSAGE_IF_ARMED(expression, regexp)
#else // DRAKE_DOXYGEN_CXX
#define DRAKE_EXPECT_THROWS_MESSAGE_HELPER( \
expression, regexp, must_throw, fatal_failure) \
do { \
try { \
static_cast<void>(expression); \
if (must_throw) { \
std::string message = "\tExpected: " #expression " throws an exception.\n" \
" Actual: it throws nothing"; \
if (fatal_failure) { \
GTEST_FATAL_FAILURE_(message.c_str()); \
} else { \
GTEST_NONFATAL_FAILURE_(message.c_str());\
} \
} \
} catch (const std::exception& err) { \
auto matcher = [](const char* s, const std::string& re) { \
return std::regex_match(s, std::regex(re)); }; \
if (fatal_failure) { \
ASSERT_PRED2(matcher, err.what(), regexp); \
} else { \
EXPECT_PRED2(matcher, err.what(), regexp); \
} \
} catch (...) { \
std::string message = "\tExpected: " #expression " throws an exception.\n" \
" Actual: it throws a non-exception object."; \
if (fatal_failure) { \
GTEST_FATAL_FAILURE_(message.c_str()); \
} else { \
GTEST_NONFATAL_FAILURE_(message.c_str()); \
} \
} \
} while (0)
#define DRAKE_EXPECT_THROWS_MESSAGE(expression, regexp) \
DRAKE_EXPECT_THROWS_MESSAGE_HELPER( \
expression, regexp, \
true /*must_throw*/, false /*non-fatal*/)
#define DRAKE_ASSERT_THROWS_MESSAGE(expression, regexp) \
DRAKE_EXPECT_THROWS_MESSAGE_HELPER( \
expression, regexp, \
true /*must_throw*/, true /*fatal*/)
#define DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED(expression, regexp) \
DRAKE_EXPECT_THROWS_MESSAGE_HELPER( \
expression, regexp, \
::drake::kDrakeAssertIsArmed /*must_throw*/, false /*non-fatal*/)
#define DRAKE_ASSERT_THROWS_MESSAGE_IF_ARMED(expression, regexp) \
DRAKE_EXPECT_THROWS_MESSAGE_HELPER( \
expression, regexp, \
::drake::kDrakeAssertIsArmed /*must_throw*/, true /*fatal*/)
#endif // DRAKE_DOXYGEN_CXX
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/is_dynamic_castable.h | #pragma once
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "drake/common/nice_type_name.h"
namespace drake {
/// Checks if @p ptr, a pointer to `FromType` class, can be safely converted to
/// a pointer to `ToType` class. Our motivation is to provide a good diagnostic
/// for what @p ptr _actually_ was when the test fails.
///
/// Here is an illustrative code snippet. We assume that `Prius` and `Camry` are
/// derived classes of `Car`.
///
/// @code
/// const Car* prius = new Prius{};
///
/// // The following assertion fails without diagnostic info.
/// EXPECT_TRUE(dynamic_cast<Camry>(ptr) != nullptr)
///
/// // The following assertion returns `::testing::AssertionFailure()` with
/// // diagnostic info attached.
/// EXPECT_TRUE(is_dynamic_castable<Camry>(prius));
/// // Output:
/// // Value of: is_dynamic_castable<Camry>(prius)
/// // Actual: false (is_dynamic_castable<Camry>(Car* ptr) failed
/// // because ptr is of dynamic type Prius.)
/// // Expected: true
/// @endcode
template <typename ToType, typename FromType>
[[nodiscard]] ::testing::AssertionResult is_dynamic_castable(
const FromType* ptr) {
if (ptr == nullptr) {
const std::string from_name{NiceTypeName::Get<FromType>()};
const std::string to_name{NiceTypeName::Get<ToType>()};
return ::testing::AssertionFailure()
<< "is_dynamic_castable<" << to_name << ">(" << from_name << "* ptr)"
<< " failed because ptr was already nullptr.";
}
if (dynamic_cast<const ToType* const>(ptr) == nullptr) {
const std::string from_name{NiceTypeName::Get<FromType>()};
const std::string to_name{NiceTypeName::Get<ToType>()};
const std::string dynamic_name{NiceTypeName::Get(*ptr)};
return ::testing::AssertionFailure()
<< "is_dynamic_castable<" << to_name << ">(" << from_name << "* ptr)"
<< " failed because ptr is of dynamic type " << dynamic_name << ".";
}
return ::testing::AssertionSuccess();
}
/// Checks if @p ptr, a shared pointer to `FromType` class, can be safely
/// converted to a shared pointer to `ToType` class. Our motivation is to
/// provide a good diagnostic for what @p ptr _actually_ was when the test
/// fails.
template <typename ToType, typename FromType>
[[nodiscard]] ::testing::AssertionResult is_dynamic_castable(
std::shared_ptr<FromType> ptr) {
return is_dynamic_castable<ToType, FromType>(ptr.get());
}
/// Checks if @p ptr, a shared pointer to `FromType` class, can be safely
/// converted to a shared pointer to `ToType` class. Our motivation is to
/// provide a good diagnostic for what @p ptr _actually_ was when the test
/// fails.
template <typename ToType, typename FromType>
[[nodiscard]] ::testing::AssertionResult is_dynamic_castable(
const std::unique_ptr<FromType>& ptr) {
return is_dynamic_castable<ToType, FromType>(ptr.get());
}
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/maybe_pause_for_user.cc | #include "drake/common/test_utilities/maybe_pause_for_user.h"
#include <cstdlib>
#include <iostream>
#include <limits>
namespace drake {
namespace common {
void MaybePauseForUser() {
bool is_test = (std::getenv("TEST_TMPDIR") != nullptr);
bool is_invoked_by_bazel_run =
(std::getenv("BUILD_WORKSPACE_DIRECTORY") != nullptr);
if (is_test && is_invoked_by_bazel_run) {
// Nothing good will happen here. The prompt may not appear, and the
// program will hang, failing to notice user keyboard input.
return;
}
std::cout << "[Press RETURN to continue]." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test_utilities/eigen_matrix_compare.h | #pragma once
#include <algorithm>
#include <cmath>
#include <limits>
#include <string>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/fmt_eigen.h"
#include "drake/common/text_logging.h"
namespace drake {
enum class MatrixCompareType { absolute, relative };
/**
* Compares two matrices to determine whether they are equal to within a certain
* threshold.
*
* @param m1 The first matrix to compare.
* @param m2 The second matrix to compare.
* @param tolerance The tolerance for determining equivalence.
* @param compare_type Whether the tolereance is absolute or relative.
* @param explanation A pointer to a string variable for saving an explanation
* of why @p m1 and @p m2 are unequal. This parameter is optional and defaults
* to `nullptr`. If this is `nullptr` and @p m1 and @p m2 are not equal, an
* explanation is logged as an error message.
* @return true if the two matrices are equal based on the specified tolerance.
*/
template <typename DerivedA, typename DerivedB>
[[nodiscard]] ::testing::AssertionResult CompareMatrices(
const Eigen::MatrixBase<DerivedA>& m1,
const Eigen::MatrixBase<DerivedB>& m2, double tolerance = 0.0,
MatrixCompareType compare_type = MatrixCompareType::absolute) {
if (m1.rows() != m2.rows() || m1.cols() != m2.cols()) {
const std::string message =
fmt::format("Matrix size mismatch: ({} x {} vs. {} x {})", m1.rows(),
m1.cols(), m2.rows(), m2.cols());
return ::testing::AssertionFailure() << message;
}
for (int ii = 0; ii < m1.rows(); ii++) {
for (int jj = 0; jj < m1.cols(); jj++) {
// First handle the corner cases of positive infinity, negative infinity,
// and NaN
const auto both_positive_infinity =
m1(ii, jj) == std::numeric_limits<double>::infinity() &&
m2(ii, jj) == std::numeric_limits<double>::infinity();
const auto both_negative_infinity =
m1(ii, jj) == -std::numeric_limits<double>::infinity() &&
m2(ii, jj) == -std::numeric_limits<double>::infinity();
using std::isnan;
const auto both_nan = isnan(m1(ii, jj)) && isnan(m2(ii, jj));
if (both_positive_infinity || both_negative_infinity || both_nan)
continue;
// Check for case where one value is NaN and the other is not
if ((isnan(m1(ii, jj)) && !isnan(m2(ii, jj))) ||
(!isnan(m1(ii, jj)) && isnan(m2(ii, jj)))) {
const std::string message =
fmt::format("NaN mismatch at ({}, {}):\nm1 =\n{}\nm2 =\n{}", ii, jj,
fmt_eigen(m1), fmt_eigen(m2));
return ::testing::AssertionFailure() << message;
}
// Determine whether the difference between the two matrices is less than
// the tolerance.
using std::abs;
const auto delta = abs(m1(ii, jj) - m2(ii, jj));
if (compare_type == MatrixCompareType::absolute) {
// Perform comparison using absolute tolerance.
if (delta > tolerance) {
const std::string message = fmt::format(
"Values at ({}, {}) exceed tolerance: {} vs. {}, diff = {}, "
"tolerance = {}\nm1 =\n{}\nm2 =\n{}\ndelta=\n{}",
ii, jj, m1(ii, jj), m2(ii, jj), delta, tolerance, fmt_eigen(m1),
fmt_eigen(m2), fmt_eigen(m1 - m2));
return ::testing::AssertionFailure() << message;
}
} else {
// Perform comparison using relative tolerance, see:
// http://realtimecollisiondetection.net/blog/?p=89
using std::max;
const auto max_value = max(abs(m1(ii, jj)), abs(m2(ii, jj)));
const auto relative_tolerance =
tolerance * max(decltype(max_value){1}, max_value);
if (delta > relative_tolerance) {
const std::string message = fmt::format(
"Values at ({}, {}) exceed tolerance: {} vs. {}, diff = {}, "
"tolerance = {}, relative tolerance = {}\nm1 =\n{}\nm2 "
"=\n{}\ndelta=\n{}",
ii, jj, m1(ii, jj), m2(ii, jj), delta, tolerance,
relative_tolerance, fmt_eigen(m1), fmt_eigen(m2),
fmt_eigen(m1 - m2));
return ::testing::AssertionFailure() << message;
}
}
}
}
const std::string message =
fmt::format("m1 =\n{}\nis approximately equal to m2 =\n{}", fmt_eigen(m1),
fmt_eigen(m2));
return ::testing::AssertionSuccess() << message;
}
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/test_utilities/disable_python_unittest | /home/johnshepherd/drake/common/test_utilities/disable_python_unittest/unittest/__init__.py | # This file is intended for use by the drake_py_test macro defined in
# //tools/skylark:drake_py.bzl and should NOT be used by anything else.
"""A drake_py_test should not `import unittest`. In most cases, your
BUILD.bazel file should use `drake_py_unittest` to declare such tests, which
provides an appropriate main() routine (and will disable this warning).
In the unlikely event that you actually have a unittest and need to write your
own main, set `allow_import_unittest = True` in the drake_py_test rule.
"""
raise RuntimeError(__doc__)
| 0 |
/home/johnshepherd/drake/common/test_utilities | /home/johnshepherd/drake/common/test_utilities/test/limit_malloc_manual_test.cc | #include "drake/common/test_utilities/limit_malloc.h"
int main(void) {
drake::test::LimitMalloc guard;
// Deliberately cause LimitMalloc to report failure. Yes, we leak memory
// here, but it doesn't much matter; the material fact to the test is that a
// disallowed heap allocation happens.
new int;
return 0;
}
| 0 |
/home/johnshepherd/drake/common/test_utilities | /home/johnshepherd/drake/common/test_utilities/test/eigen_matrix_compare_test.cc | #include "drake/common/test_utilities/eigen_matrix_compare.h"
#include <gtest/gtest.h>
namespace drake {
namespace {
// Tests the ability for two identical matrices to be compared.
GTEST_TEST(MatrixCompareTest, CompareIdentical) {
Eigen::MatrixXd m1(2, 2);
m1 << 0, 1, 2, 3;
Eigen::MatrixXd m2(2, 2);
m2 << 0, 1, 2, 3;
Eigen::MatrixXd m3(2, 2);
m3 << 100, 200, 300, 400;
const double tolerance = 1e-8;
EXPECT_TRUE(CompareMatrices(m1, m2, tolerance, MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(m1, m2, tolerance, MatrixCompareType::relative));
EXPECT_FALSE(CompareMatrices(m1, m3, tolerance, MatrixCompareType::absolute));
EXPECT_FALSE(CompareMatrices(m1, m3, tolerance, MatrixCompareType::relative));
}
// Tests absolute tolerance with real numbers.
GTEST_TEST(MatrixCompareTest, AbsoluteCompare) {
Eigen::MatrixXd m1(2, 2);
m1 << 0, 1, 2, 3;
Eigen::MatrixXd m2(2, 2);
m2 << 0, 1 - 1e-10, 2, 3;
Eigen::MatrixXd m3(2, 2);
m3 << 0, 1, 2 - 1e-8, 3;
Eigen::MatrixXd m4(2, 2);
m4 << 0, 1, 2, 3 - 1e-6;
const double tolerance = 1e-8;
// The difference between m1 and m2 is less than the tolerance.
// They should be considered equal.
EXPECT_TRUE(CompareMatrices(m1, m2, tolerance, MatrixCompareType::absolute));
// The difference between m1 and m3 is exactly equal to the tolerance.
// They should be considered equal.
EXPECT_TRUE(CompareMatrices(m1, m3, tolerance, MatrixCompareType::absolute));
// The difference between m1 and m4 is greater than the tolerance.
// They should be considered different.
EXPECT_FALSE(CompareMatrices(m1, m4, tolerance, MatrixCompareType::absolute));
}
// Tests absolute tolerance with NaN values
GTEST_TEST(MatrixCompareTest, AbsoluteNaNCompare) {
Eigen::MatrixXd m1(2, 2);
m1 << 0, 1, std::numeric_limits<double>::quiet_NaN(), 3;
Eigen::MatrixXd m2(2, 2);
m2 << 0, 1, std::numeric_limits<double>::quiet_NaN(), 3;
Eigen::MatrixXd m3(2, 2);
m3 << 0, 1 - 1e-10, std::numeric_limits<double>::quiet_NaN(), 3;
Eigen::MatrixXd m4(2, 2);
m4 << 0, 1, 2, 3;
const double tolerance = 1e-8;
// The difference between m1 and m2 is less than the tolerance.
// They should be considered equal.
EXPECT_TRUE(CompareMatrices(m1, m2, tolerance, MatrixCompareType::absolute));
// The difference between m1 and m3 is exactly equal to the tolerance.
// They should be considered equal.
EXPECT_TRUE(CompareMatrices(m1, m3, tolerance, MatrixCompareType::absolute));
// The difference between m1 and m4 is greater than the tolerance.
// They should be considered different.
EXPECT_FALSE(CompareMatrices(m1, m4, tolerance, MatrixCompareType::absolute));
}
// Tests absolute tolerance with real numbers.
GTEST_TEST(MatrixCompareTest, RelativeCompare) {
Eigen::MatrixXd m1(2, 2);
m1 << 100, 100, 100, 100;
Eigen::MatrixXd m2(2, 2);
m2 << 100, 100 * 0.9, 100, 100;
// The difference between m1 and m2 is more than 1%.
// They should be considered not equal.
EXPECT_FALSE(CompareMatrices(m1, m2, 0.01, MatrixCompareType::relative));
// The difference between m1 and m2 is equal to 10%.
// They should be considered equal.
EXPECT_TRUE(CompareMatrices(m1, m2, 0.1, MatrixCompareType::relative));
// The difference between m1 and m4 is less than 20%.
// They should be considered equal.
EXPECT_TRUE(CompareMatrices(m1, m2, 0.2, MatrixCompareType::relative));
}
} // namespace
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/test_utilities | /home/johnshepherd/drake/common/test_utilities/test/maybe_pause_for_user_test.cc | #include "drake/common/test_utilities/maybe_pause_for_user.h"
#include <gtest/gtest.h>
// Manual test users should verify that:
// - the program does not pause when invoked with "bazel test".
// - the program does not pause when invoked with "bazel run".
// - Prompt is shown and program pauses for user-typed RETURN when invoked
// directly ("bazel-bin/blah").
namespace drake {
namespace common {
namespace {
GTEST_TEST(MaybePauseForUserTest, Test) {
MaybePauseForUser();
}
} // namespace
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/test_utilities | /home/johnshepherd/drake/common/test_utilities/test/limit_malloc_test.cc | #include "drake/common/test_utilities/limit_malloc.h"
#include <cstdlib>
#include <stdexcept>
#include <gtest/gtest.h>
// A global variable to help prevent the compiler from optimizing out the call
// to malloc. (Without this, it can reason that malloc-free is a no-op.)
volatile void* g_dummy;
namespace drake {
namespace test {
namespace {
// Calls malloc (and then immediately frees).
void CallMalloc() {
void* dummy = malloc(16);
g_dummy = dummy;
free(dummy);
if (g_dummy == nullptr) { throw std::runtime_error("null dummy"); }
}
// Calls calloc (and then immediately frees).
void CallCalloc() {
void* dummy = calloc(1, 16);
g_dummy = dummy;
free(dummy);
if (g_dummy == nullptr) { throw std::runtime_error("null dummy"); }
}
// Calls realloc (and then immediately frees).
void CallRealloc() {
void* dummy = realloc(nullptr, 16);
g_dummy = dummy;
free(dummy);
if (g_dummy == nullptr) { throw std::runtime_error("null dummy"); }
}
// A value-parameterized test fixture.
class LimitMallocTest : public ::testing::TestWithParam<int> {
public:
void Allocate() {
switch (GetParam()) {
case 0: CallMalloc(); return;
case 1: CallCalloc(); return;
case 2: CallRealloc(); return;
}
throw std::logic_error("Bad GetParam()");
}
};
// Use the same fixture for death tests, but with a different name. Note that
// Drake's styleguide forbids death tests, but our only choice here is to use
// death tests because our implementations sense failure in contexts where
// exceptions are forbidden. The implementation of max limits must use abort()
// because exceptions cannot propagate through malloc() because it is a C
// ABI. Similarly, the implementation of min limits must use abort() because it
// senses failure within a destructor, which is a C++ `noexcept` context.
using LimitMallocDeathTest = LimitMallocTest;
// @note: The gtest EXPECT* macros can allocate, so cases take care to avoid
// using them in LimitMalloc scopes under test. In particular, any checks on
// LimitMalloc accessors must copy results and check them outside the guarded
// scope.
TEST_P(LimitMallocTest, UnlimitedTest) {
// Choose spoiler values for testing.
int num_allocations = -1;
LimitMallocParams args{10, 20, true};
{
LimitMalloc guard(LimitMallocParams{ /* no limits specified */ });
num_allocations = guard.num_allocations();
args = guard.params();
Allocate(); // Malloc is OK.
Allocate(); // Malloc is OK.
Allocate(); // Malloc is OK.
}
EXPECT_EQ(num_allocations, 0);
EXPECT_EQ(args.max_num_allocations, -1);
EXPECT_EQ(args.min_num_allocations, -1);
EXPECT_EQ(args.ignore_realloc_noops, false);
}
TEST_P(LimitMallocTest, BasicTest) {
Allocate(); // Malloc is OK.
LimitMallocParams args;
{
LimitMalloc guard;
args = guard.params();
// The guarded code would go here; malloc is NOT ok.
}
Allocate(); // Malloc is OK again.
EXPECT_EQ(args.max_num_allocations, 0);
EXPECT_EQ(args.min_num_allocations, -1);
EXPECT_EQ(args.ignore_realloc_noops, false);
}
constexpr const char* const kMaxDeathMessage =
"abort due to malloc #[0-9]+ while"
" max_num_allocations = [0-9]+ in effect";
constexpr const char* const kMinDeathMessage =
"abort due to scope end with [0-9]+ mallocs while"
" min_num_allocations = [0-9]+ in effect";
TEST_P(LimitMallocDeathTest, BasicTest) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
Allocate(); // Malloc is OK.
ASSERT_DEATH({
LimitMalloc guard;
Allocate(); // Malloc is NOT ok.
}, kMaxDeathMessage);
}
TEST_P(LimitMallocTest, MaxLimitTest) {
{
LimitMalloc guard({.max_num_allocations = 1});
Allocate(); // Once is okay.
// Another call here would fail.
}
Allocate(); // Malloc is OK again.
}
TEST_P(LimitMallocTest, MinLimitTest) {
{
LimitMalloc guard({.max_num_allocations = 5, .min_num_allocations = 1});
Allocate(); // Once is necessary.
// Fewer calls here would fail.
}
}
TEST_P(LimitMallocTest, AvoidAsanTest) {
// ASan instrumentation hooks strdup() and returns storage from a separate
// heap. If our hooks are not removed entirely, the alien storage is handed
// to libc free(), with disastrous results. See #14901.
//
// If this test fails, it will abort deep in the call stack of free().
{
LimitMalloc guard({.max_num_allocations = 1, .min_num_allocations = 1});
auto* p = ::strdup("something");
// Fool the optimizer into not deleting all the code here.
ASSERT_NE(p, nullptr);
::free(p);
}
}
TEST_P(LimitMallocDeathTest, MaxLimitTest) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
const auto expected_message =
std::string("Once was okay\n") + kMaxDeathMessage;
ASSERT_DEATH({
LimitMalloc guard({.max_num_allocations = 1});
Allocate();
std::cerr << "Once was okay\n";
// A second allocation will fail.
Allocate();
}, expected_message);
}
TEST_P(LimitMallocDeathTest, ObservationTest) {
// Though not actually a death test, this is a convenient place to test
// that the getter returns a correct count. We must check within a unit test
// that is known to be disabled via the BUILD file for platforms without a
// working implementation.
int num_allocations = -1; // Choose spoiler value for testing.
{
LimitMalloc guard({.max_num_allocations = 1});
Allocate();
num_allocations = guard.num_allocations();
}
EXPECT_EQ(num_allocations, 1);
}
TEST_P(LimitMallocDeathTest, MinLimitTest) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
ASSERT_DEATH({
LimitMalloc guard({.max_num_allocations = 5, .min_num_allocations = 4});
Allocate(); // Some few allocations are not enough.
// The destructor will fail.
}, kMinDeathMessage);
}
INSTANTIATE_TEST_SUITE_P(
All, LimitMallocTest, ::testing::Range(0, 3));
INSTANTIATE_TEST_SUITE_P(
All, LimitMallocDeathTest, ::testing::Range(0, 3));
// When the user whitelists no-op reallocs, a call to realloc() that does not
// change the size should not fail.
GTEST_TEST(LimitReallocTest, ChangingSizeTest) {
void* dummy = malloc(16);
g_dummy = dummy;
ASSERT_TRUE(g_dummy != nullptr);
{
LimitMalloc guard({
.max_num_allocations = 0,
.min_num_allocations = -1,
.ignore_realloc_noops = true
});
dummy = realloc(dummy, 16); // No change.
g_dummy = dummy;
}
dummy = realloc(dummy, 16384); // A change.
g_dummy = dummy;
free(dummy);
}
// When the user whitelists no-op reallocs, a call to realloc() should fail iff
// the size changed.
GTEST_TEST(LimitReallocDeathTest, ChangingSizeTest) {
::testing::FLAGS_gtest_death_test_style = "threadsafe";
void* dummy = malloc(16);
g_dummy = dummy;
ASSERT_TRUE(g_dummy != nullptr);
const auto expected_message =
std::string("Once was okay\n") + kMaxDeathMessage;
ASSERT_DEATH({
LimitMalloc guard({
.max_num_allocations = 0,
.min_num_allocations = -1,
.ignore_realloc_noops = true
});
dummy = realloc(dummy, 16); // No change.
g_dummy = dummy;
std::cerr << "Once was okay\n";
dummy = realloc(dummy, 16384); // A change.
g_dummy = dummy;
}, expected_message);
free(dummy);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/test_utilities | /home/johnshepherd/drake/common/test_utilities/test/is_memcpy_movable_test.cc | #include "drake/common/test_utilities/is_memcpy_movable.h"
#include <memory>
#include <string>
#include <utility>
#include <gtest/gtest.h>
namespace drake {
namespace test {
namespace {
using std::string;
using std::unique_ptr;
using std::make_unique;
// An example class that is memcpy-movable.
class MemcpyMovable {
public:
explicit MemcpyMovable(string name)
: name_{make_unique<string>(move(name))} {}
MemcpyMovable(const MemcpyMovable& m) : MemcpyMovable(*m.name_) {}
MemcpyMovable(MemcpyMovable&& m) = default;
bool operator==(const MemcpyMovable& m) const { return *name_ == *m.name_; }
~MemcpyMovable() = default;
struct EqualTo {
bool operator()(const MemcpyMovable& v1, const MemcpyMovable& v2) const {
return v1 == v2;
}
};
private:
unique_ptr<string> name_;
};
// An example class that is not memcpy-movable.
class NotMemcpyMovable {
public:
NotMemcpyMovable() : self_{this} {};
NotMemcpyMovable(const NotMemcpyMovable&) : self_{this} {};
NotMemcpyMovable(NotMemcpyMovable&&) : self_{this} {}
bool check_invariant() const { return this == self_; }
// It checks if both of v1 and v2 satisfy the invariant.
struct InvariantsHold {
bool operator()(const NotMemcpyMovable& v1,
const NotMemcpyMovable& v2) const {
return v1.check_invariant() && v2.check_invariant();
}
};
private:
NotMemcpyMovable* self_{};
};
GTEST_TEST(IsMemcpyMovableTest, MemcpyMovableTestInt) {
const int v{3};
EXPECT_TRUE(IsMemcpyMovable(v));
}
GTEST_TEST(IsMemcpyMovableTest, MemcpyMovableTestDouble) {
const double v{3.14};
EXPECT_TRUE(IsMemcpyMovable(v));
}
GTEST_TEST(IsMemcpyMovableTest, MemcpyMovableTestStringPtr) {
auto v = make_unique<string>("3.14");
EXPECT_TRUE(IsMemcpyMovable(v.get()));
}
GTEST_TEST(IsMemcpyMovableTest, MemcpyMovableTestClass) {
const MemcpyMovable v{"MemcpyMovable"};
EXPECT_TRUE(IsMemcpyMovable(v, MemcpyMovable::EqualTo()));
}
GTEST_TEST(IsMemcpyMovableTest, NotMemcpyMovableTest) {
const NotMemcpyMovable v{};
EXPECT_FALSE(IsMemcpyMovable(v, NotMemcpyMovable::InvariantsHold()));
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/test_utilities | /home/johnshepherd/drake/common/test_utilities/test/maybe_pause_for_user_manual_test.cc | #include "drake/common/test_utilities/maybe_pause_for_user.h"
// Manual test users should verify that:
// - the prompt string is shown
// - a user-typed RETURN is consumed and the program exits
// These results should work for both direct ("bazel-bin/blah") invocation and
// for invocation with "bazel run".
namespace drake {
namespace common {
namespace {
int do_main() {
MaybePauseForUser();
return 0;
}
} // namespace
} // namespace common
} // namespace drake
int main() { return drake::common::do_main(); }
| 0 |
/home/johnshepherd/drake/common/test_utilities | /home/johnshepherd/drake/common/test_utilities/test/is_dynamic_castable_test.cc | #include "drake/common/test_utilities/is_dynamic_castable.h"
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "drake/common/nice_type_name.h"
namespace drake {
namespace {
struct A {
virtual ~A() {}
};
struct B {
virtual ~B() {}
};
struct C : A, B {
~C() override {}
};
using std::make_shared;
using std::shared_ptr;
using std::string;
class IsDynamicCastableTest : public ::testing::Test {
protected:
const shared_ptr<A> a_a_{make_shared<A>()};
const shared_ptr<A> a_c_{make_shared<C>()};
const shared_ptr<B> b_b_{make_shared<B>()};
const shared_ptr<B> b_c_{make_shared<C>()};
const shared_ptr<C> c_c_{make_shared<C>()};
};
TEST_F(IsDynamicCastableTest, RawPointer) {
EXPECT_TRUE(is_dynamic_castable<A>(a_a_.get()));
EXPECT_FALSE(is_dynamic_castable<B>(a_a_.get()));
EXPECT_FALSE(is_dynamic_castable<C>(a_a_.get()));
EXPECT_TRUE(is_dynamic_castable<A>(a_c_.get()));
EXPECT_TRUE(is_dynamic_castable<B>(a_c_.get())); // sidecasting A -> B
EXPECT_TRUE(is_dynamic_castable<C>(a_c_.get())); // downcasting A -> C
EXPECT_FALSE(is_dynamic_castable<A>(b_b_.get()));
EXPECT_TRUE(is_dynamic_castable<B>(b_b_.get()));
EXPECT_FALSE(is_dynamic_castable<C>(b_b_.get()));
EXPECT_TRUE(is_dynamic_castable<A>(b_c_.get())); // sidecasting B -> A
EXPECT_TRUE(is_dynamic_castable<B>(b_c_.get()));
EXPECT_TRUE(is_dynamic_castable<C>(b_c_.get())); // downcasting B -> C
EXPECT_TRUE(is_dynamic_castable<A>(c_c_.get())); // upcasting C -> A
EXPECT_TRUE(is_dynamic_castable<B>(c_c_.get())); // upcasting C -> B
EXPECT_TRUE(is_dynamic_castable<C>(c_c_.get()));
}
TEST_F(IsDynamicCastableTest, SharedPtr) {
EXPECT_TRUE(is_dynamic_castable<A>(a_a_));
EXPECT_FALSE(is_dynamic_castable<B>(a_a_));
EXPECT_FALSE(is_dynamic_castable<C>(a_a_));
EXPECT_TRUE(is_dynamic_castable<A>(a_c_));
EXPECT_TRUE(is_dynamic_castable<B>(a_c_)); // sidecasting A -> B
EXPECT_TRUE(is_dynamic_castable<C>(a_c_)); // downcasting A -> C
EXPECT_FALSE(is_dynamic_castable<A>(b_b_));
EXPECT_TRUE(is_dynamic_castable<B>(b_b_));
EXPECT_FALSE(is_dynamic_castable<C>(b_b_));
EXPECT_TRUE(is_dynamic_castable<A>(b_c_)); // sidecasting B -> A
EXPECT_TRUE(is_dynamic_castable<B>(b_c_));
EXPECT_TRUE(is_dynamic_castable<C>(b_c_)); // downcasting B -> C
EXPECT_TRUE(is_dynamic_castable<A>(c_c_)); // upcasting C -> A
EXPECT_TRUE(is_dynamic_castable<B>(c_c_)); // upcasting C -> B
EXPECT_TRUE(is_dynamic_castable<C>(c_c_));
}
string ExpectedMessage(const string& derived, const string& base,
const string& dynamic) {
return "is_dynamic_castable<" + derived + ">(" + base +
"* ptr) failed because ptr is of dynamic type " + dynamic + ".";
}
TEST_F(IsDynamicCastableTest, DiagnosticMessage) {
const string a_typename{NiceTypeName::Get<A>()};
const string b_typename{NiceTypeName::Get<B>()};
const string c_typename{NiceTypeName::Get<C>()};
const auto assertion_result1 = is_dynamic_castable<B>(a_a_);
ASSERT_FALSE(assertion_result1);
EXPECT_EQ(assertion_result1.failure_message(),
ExpectedMessage(b_typename, a_typename, a_typename));
const auto assertion_result2 = is_dynamic_castable<C>(a_a_);
ASSERT_FALSE(assertion_result2);
EXPECT_EQ(assertion_result2.failure_message(),
ExpectedMessage(c_typename, a_typename, a_typename));
const auto assertion_result3 = is_dynamic_castable<A>(b_b_);
ASSERT_FALSE(assertion_result3);
EXPECT_EQ(assertion_result3.failure_message(),
ExpectedMessage(a_typename, b_typename, b_typename));
const auto assertion_result4 = is_dynamic_castable<C>(b_b_);
ASSERT_FALSE(assertion_result4);
EXPECT_EQ(assertion_result4.failure_message(),
ExpectedMessage(c_typename, b_typename, b_typename));
}
} // namespace
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/test_utilities | /home/johnshepherd/drake/common/test_utilities/test/expect_no_throw_test.cc | #include "drake/common/test_utilities/expect_no_throw.h"
#include <gtest/gtest-spi.h>
#include <gtest/gtest.h>
namespace drake {
namespace {
void DoesNotThrow() { }
void DoesThrow() { throw std::runtime_error("Big time fail"); }
void DoesThrowCrazy() { throw 42; }
constexpr char failure_message[] =
R"(Expected: Does not throw:
DoesThrow()
Actual: Throws std::runtime_error
Big time fail)";
constexpr char failure_message_crazy[] =
R"(Expected: Does not throw:
DoesThrowCrazy()
Actual: Throws type which does not inherit from std::exception)";
GTEST_TEST(ExpectNoThrowTest, ExpectNoThrow) {
DRAKE_EXPECT_NO_THROW(DoesNotThrow());
EXPECT_NONFATAL_FAILURE(
DRAKE_EXPECT_NO_THROW(DoesThrow()),
failure_message);
EXPECT_NONFATAL_FAILURE(
DRAKE_EXPECT_NO_THROW(DoesThrowCrazy()),
failure_message_crazy);
}
GTEST_TEST(ExpectNoThrowTest, AssertNoThrow) {
DRAKE_ASSERT_NO_THROW(DoesNotThrow());
EXPECT_FATAL_FAILURE(
DRAKE_ASSERT_NO_THROW(DoesThrow()),
failure_message);
EXPECT_FATAL_FAILURE(
DRAKE_ASSERT_NO_THROW(DoesThrowCrazy()),
failure_message_crazy);
}
} // namespace
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/piecewise_trajectory.h | #pragma once
#include <limits>
#include <memory>
#include <random>
#include <vector>
#include <Eigen/Core>
#include "drake/common/default_scalars.h"
#include "drake/common/trajectories/trajectory.h"
namespace drake {
namespace trajectories {
/// Abstract class that implements the basic logic of maintaining consequent
/// segments of time (delimited by `breaks`) to implement a trajectory that
/// is represented by simpler logic in each segment or "piece".
///
/// @tparam_default_scalar
template <typename T>
class PiecewiseTrajectory : public Trajectory<T> {
public:
/// Minimum delta quantity used for comparing time.
static constexpr double kEpsilonTime = std::numeric_limits<double>::epsilon();
~PiecewiseTrajectory() override = default;
int get_number_of_segments() const;
T start_time(int segment_number) const;
T end_time(int segment_number) const;
T duration(int segment_number) const;
T start_time() const override;
T end_time() const override;
/**
* Returns true iff `t >= getStartTime() && t <= getEndTime()`.
*/
boolean<T> is_time_in_range(const T& t) const;
int get_segment_index(const T& t) const;
const std::vector<T>& get_segment_times() const;
void segment_number_range_check(int segment_number) const;
static std::vector<T> RandomSegmentTimes(
// TODO(#2274) Fix this NOLINTNEXTLINE(runtime/references)
int num_segments, std::default_random_engine& generator);
protected:
// Final subclasses are allowed to make copy/move/assign public.
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PiecewiseTrajectory)
PiecewiseTrajectory() = default;
/// @p breaks increments must be greater or equal to kEpsilonTime.
explicit PiecewiseTrajectory(const std::vector<T>& breaks);
bool SegmentTimesEqual(const PiecewiseTrajectory& b,
double tol = kEpsilonTime) const;
const std::vector<T>& breaks() const { return breaks_; }
std::vector<T>& get_mutable_breaks() { return breaks_; }
private:
int GetSegmentIndexRecursive(const T& time, int start, int end) const;
std::vector<T> breaks_;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PiecewiseTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/trajectory.h | #pragma once
#include <memory>
#include <vector>
#include <Eigen/Core>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
namespace drake {
namespace trajectories {
/**
* A Trajectory represents a time-varying matrix, indexed by a single scalar
* time.
*
* @tparam_default_scalar
*/
template <typename T>
class Trajectory {
public:
virtual ~Trajectory() = default;
/**
* @return A deep copy of this Trajectory.
*/
virtual std::unique_ptr<Trajectory<T>> Clone() const = 0;
/**
* Evaluates the trajectory at the given time \p t.
* @param t The time at which to evaluate the trajectory.
* @return The matrix of evaluated values.
*/
virtual MatrixX<T> value(const T& t) const = 0;
/**
* If cols()==1, then evaluates the trajectory at each time @p t, and returns
* the results as a Matrix with the ith column corresponding to the ith time.
* Otherwise, if rows()==1, then evaluates the trajectory at each time @p t,
* and returns the results as a Matrix with the ith row corresponding to
* the ith time.
* @throws std::exception if both cols and rows are not equal to 1.
*/
MatrixX<T> vector_values(const std::vector<T>& t) const;
/**
* If cols()==1, then evaluates the trajectory at each time @p t, and returns
* the results as a Matrix with the ith column corresponding to the ith time.
* Otherwise, if rows()==1, then evaluates the trajectory at each time @p t,
* and returns the results as a Matrix with the ith row corresponding to
* the ith time.
* @throws std::exception if both cols and rows are not equal to 1.
*/
MatrixX<T> vector_values(const Eigen::Ref<const VectorX<T>>& t) const;
/**
* Returns true iff the Trajectory provides and implementation for
* EvalDerivative() and MakeDerivative(). The derivative need not be
* continuous, but should return a result for all t for which value(t) returns
* a result.
*/
bool has_derivative() const;
/**
* Evaluates the derivative of `this` at the given time @p t.
* Returns the nth derivative, where `n` is the value of @p derivative_order.
*
* @throws std::exception if derivative_order is negative.
*/
MatrixX<T> EvalDerivative(const T& t, int derivative_order = 1) const;
/**
* Takes the derivative of this Trajectory.
* @param derivative_order The number of times to take the derivative before
* returning.
* @return The nth derivative of this object.
* @throws std::exception if derivative_order is negative.
*/
std::unique_ptr<Trajectory<T>> MakeDerivative(int derivative_order = 1) const;
/**
* @return The number of rows in the matrix returned by value().
*/
virtual Eigen::Index rows() const = 0;
/**
* @return The number of columns in the matrix returned by value().
*/
virtual Eigen::Index cols() const = 0;
virtual T start_time() const = 0;
virtual T end_time() const = 0;
protected:
// Final subclasses are allowed to make copy/move/assign public.
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Trajectory)
Trajectory() = default;
virtual bool do_has_derivative() const;
virtual MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const;
virtual std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order) const;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::Trajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/composite_trajectory.h | #pragma once
#include <memory>
#include <vector>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/eigen_types.h"
#include "drake/common/trajectories/piecewise_trajectory.h"
namespace drake {
namespace trajectories {
/** A "composite trajectory" is a series of trajectories joined end to end
where the end time of one trajectory coincides with the starting time of the
next.
See also PiecewisePolynomial::ConcatenateInTime(), which might be preferred if
all of the segments are PiecewisePolynomial.
@tparam_default_scalar
*/
template <typename T>
class CompositeTrajectory final : public trajectories::PiecewiseTrajectory<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(CompositeTrajectory);
/** Constructs a composite trajectory from a list of Trajectories.
@pre βi, `segments[i+1].start_time() == segments[i].end_time()`.
@pre βi, `segments[i].rows() == segments[0].rows()` and segments[i].cols() ==
segments[0].cols()`. */
explicit CompositeTrajectory(
std::vector<copyable_unique_ptr<Trajectory<T>>> segments);
virtual ~CompositeTrajectory() = default;
std::unique_ptr<trajectories::Trajectory<T>> Clone() const final;
/** Evaluates the curve at the given time.
@warning If t does not lie in the range [start_time(), end_time()], the
trajectory will silently be evaluated at the closest valid value of time to
`time`. For example, `value(-1)` will return `value(0)` for a trajectory
defined over [0, 1]. */
MatrixX<T> value(const T& time) const final;
Eigen::Index rows() const final;
Eigen::Index cols() const final;
/** Returns a reference to the `segment_index` trajectory. */
const Trajectory<T>& segment(int segment_index) const {
DRAKE_DEMAND(segment_index >= 0);
DRAKE_DEMAND(segment_index < this->get_number_of_segments());
return *segments_[segment_index];
}
private:
bool do_has_derivative() const final;
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const final;
std::unique_ptr<trajectories::Trajectory<T>> DoMakeDerivative(
int derivative_order) const final;
std::vector<copyable_unique_ptr<Trajectory<T>>> segments_{};
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::CompositeTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/piecewise_pose.h | #pragma once
#include <memory>
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/common/trajectories/piecewise_quaternion.h"
#include "drake/common/trajectories/piecewise_trajectory.h"
#include "drake/math/rigid_transform.h"
namespace drake {
namespace trajectories {
/**
* A wrapper class that represents a pose trajectory, whose rotation part is a
* PiecewiseQuaternionSlerp and the translation part is a PiecewisePolynomial.
*
* @tparam_default_scalar
*/
template <typename T>
class PiecewisePose final : public PiecewiseTrajectory<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PiecewisePose)
/**
* Constructs an empty piecewise pose trajectory.
*/
PiecewisePose() {}
/**
* Constructor.
* @param pos_traj Position trajectory.
* @param rot_traj Orientation trajectory.
*/
PiecewisePose(const PiecewisePolynomial<T>& position_trajectory,
const PiecewiseQuaternionSlerp<T>& orientation_trajectory);
/**
* Constructs a PiecewisePose from given @p times and @p poses. The positions
* trajectory is constructed as a first-order hold. The orientation is
* constructed using the quaternion slerp. There must be at least two
* elements in @p times and @p poses.
* @param times Breaks used to build the splines.
* @param poses Knots used to build the splines.
*/
static PiecewisePose<T> MakeLinear(
const std::vector<T>& times,
const std::vector<math::RigidTransform<T>>& poses);
/**
* Constructs a PiecewisePose from given @p times and @p poses.
* A cubic polynomial with given end velocities is used to construct the
* position part. The rotational part is represented by a piecewise quaterion
* trajectory. There must be at least two elements in @p times and @p poses.
* @param times Breaks used to build the splines.
* @param poses Knots used to build the splines.
* @param start_vel Start linear velocity.
* @param end_vel End linear velocity.
*/
static PiecewisePose<T> MakeCubicLinearWithEndLinearVelocity(
const std::vector<T>& times,
const std::vector<math::RigidTransform<T>>& poses,
const Vector3<T>& start_vel = Vector3<T>::Zero(),
const Vector3<T>& end_vel = Vector3<T>::Zero());
std::unique_ptr<Trajectory<T>> Clone() const override;
Eigen::Index rows() const override { return 4; }
Eigen::Index cols() const override { return 4; }
/**
* Returns the interpolated pose at @p time.
*/
math::RigidTransform<T> GetPose(const T& time) const;
MatrixX<T> value(const T& t) const override {
return GetPose(t).GetAsMatrix4();
}
/**
* Returns the interpolated velocity at @p time or zero if @p time is before
* this trajectory's start time or after its end time.
*/
Vector6<T> GetVelocity(const T& time) const;
/**
* Returns the interpolated acceleration at @p time or zero if @p time is
* before this trajectory's start time or after its end time.
*/
Vector6<T> GetAcceleration(const T& time) const;
/**
* Returns true if the position and orientation trajectories are both
* within @p tol from the other's.
*/
bool IsApprox(const PiecewisePose<T>& other, double tol) const;
/**
* Returns the position trajectory.
*/
const PiecewisePolynomial<T>& get_position_trajectory() const {
return position_;
}
/**
* Returns the orientation trajectory.
*/
const PiecewiseQuaternionSlerp<T>& get_orientation_trajectory() const {
return orientation_;
}
private:
bool do_has_derivative() const override;
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const override;
std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order) const override;
PiecewisePolynomial<T> position_;
PiecewisePolynomial<T> velocity_;
PiecewisePolynomial<T> acceleration_;
PiecewiseQuaternionSlerp<T> orientation_;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PiecewisePose)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/derivative_trajectory.cc | #include "drake/common/trajectories/derivative_trajectory.h"
namespace drake {
namespace trajectories {
template <typename T>
DerivativeTrajectory<T>::DerivativeTrajectory(const Trajectory<T>& nominal,
int derivative_order)
: nominal_{nominal.Clone()}, derivative_order_{derivative_order} {
DRAKE_THROW_UNLESS(nominal.has_derivative());
DRAKE_THROW_UNLESS(derivative_order >= 0);
// Currently, we must evaluate the derivative once in order to know the sizes
// of this new object. (See PiecewiseQuaternion, for example, whose nominal
// value has 4 rows, but whose derivative has only 3).
MatrixX<T> v = nominal.EvalDerivative(nominal.start_time(), derivative_order);
rows_ = v.rows();
cols_ = v.cols();
}
template <typename T>
DerivativeTrajectory<T>::~DerivativeTrajectory() = default;
template <typename T>
std::unique_ptr<Trajectory<T>> DerivativeTrajectory<T>::Clone() const {
return std::make_unique<DerivativeTrajectory>(*nominal_, derivative_order_);
}
template <typename T>
MatrixX<T> DerivativeTrajectory<T>::value(const T& t) const {
return nominal_->EvalDerivative(t, derivative_order_);
}
template <typename T>
Eigen::Index DerivativeTrajectory<T>::rows() const {
return rows_;
}
template <typename T>
Eigen::Index DerivativeTrajectory<T>::cols() const {
return cols_;
}
template <typename T>
T DerivativeTrajectory<T>::start_time() const {
return nominal_->start_time();
}
template <typename T>
T DerivativeTrajectory<T>::end_time() const {
return nominal_->end_time();
}
template <typename T>
MatrixX<T> DerivativeTrajectory<T>::DoEvalDerivative(
const T& t, int derivative_order) const {
return nominal_->EvalDerivative(t, derivative_order_ + derivative_order);
}
template <typename T>
std::unique_ptr<Trajectory<T>> DerivativeTrajectory<T>::DoMakeDerivative(
int derivative_order) const {
return std::make_unique<DerivativeTrajectory<T>>(
*nominal_, derivative_order_ + derivative_order);
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::DerivativeTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/bspline_trajectory.cc | #include "drake/common/trajectories/bspline_trajectory.h"
#include <algorithm>
#include <functional>
#include <utility>
#include <fmt/format.h>
#include "drake/common/default_scalars.h"
#include "drake/common/extract_double.h"
#include "drake/common/text_logging.h"
using drake::symbolic::Expression;
using drake::symbolic::Variable;
using drake::trajectories::Trajectory;
namespace drake {
namespace trajectories {
using math::BsplineBasis;
template <typename T>
BsplineTrajectory<T>::BsplineTrajectory(BsplineBasis<T> basis,
std::vector<MatrixX<T>> control_points)
: basis_(std::move(basis)), control_points_(std::move(control_points)) {
CheckInvariants();
}
template <typename T>
std::unique_ptr<Trajectory<T>> BsplineTrajectory<T>::Clone() const {
return std::make_unique<BsplineTrajectory<T>>(*this);
}
template <typename T>
MatrixX<T> BsplineTrajectory<T>::value(const T& time) const {
using std::clamp;
return basis().EvaluateCurve(control_points(),
clamp(time, start_time(), end_time()));
}
template <typename T>
bool BsplineTrajectory<T>::do_has_derivative() const {
return true;
}
template <typename T>
MatrixX<T> BsplineTrajectory<T>::DoEvalDerivative(const T& time,
int derivative_order) const {
if (derivative_order == 0) {
return this->value(time);
} else if (derivative_order >= basis_.order()) {
return MatrixX<T>::Zero(rows(), cols());
} else if (derivative_order >= 1) {
using std::clamp;
T clamped_time = clamp(time, start_time(), end_time());
// For a bspline trajectory of order n, the evaluation of k th derivative
// should take O(k^2) time by leveraging the sparsity of basis value.
// This differs from DoMakeDerivative, which takes O(nk) time.
std::vector<T> derivative_knots(basis_.knots().begin() + derivative_order,
basis_.knots().end() - derivative_order);
BsplineBasis<T> lower_order_basis =
BsplineBasis<T>(basis_.order() - derivative_order, derivative_knots);
std::vector<MatrixX<T>> coefficients(control_points());
std::vector<int> base_indices =
basis_.ComputeActiveBasisFunctionIndices(clamped_time);
for (int j = 1; j <= derivative_order; ++j) {
for (int i = base_indices.front(); i <= base_indices.back() - j; ++i) {
coefficients.at(i) =
(basis_.order() - j) /
(basis_.knots()[i + basis_.order()] - basis_.knots()[i + j]) *
(coefficients[i + 1] - coefficients[i]);
}
}
std::vector<MatrixX<T>> derivative_control_points(
num_control_points() - derivative_order,
MatrixX<T>::Zero(rows(), cols()));
for (int i :
lower_order_basis.ComputeActiveBasisFunctionIndices(clamped_time)) {
derivative_control_points.at(i) = coefficients.at(i);
}
return lower_order_basis.EvaluateCurve(derivative_control_points,
clamped_time);
} else {
throw std::invalid_argument(
fmt::format("Invalid derivative order ({}). The derivative order must "
"be greater than or equal to 0.",
derivative_order));
}
}
template <typename T>
std::unique_ptr<Trajectory<T>> BsplineTrajectory<T>::DoMakeDerivative(
int derivative_order) const {
if (derivative_order == 0) {
return this->Clone();
} else if (derivative_order > basis_.degree()) {
std::vector<T> derivative_knots;
derivative_knots.push_back(basis_.knots().front());
derivative_knots.push_back(basis_.knots().back());
std::vector<MatrixX<T>> control_points(1, MatrixX<T>::Zero(rows(), cols()));
return std::make_unique<BsplineTrajectory<T>>(
BsplineBasis<T>(1, derivative_knots), control_points);
} else if (derivative_order > 1) {
return this->MakeDerivative(1)->MakeDerivative(derivative_order - 1);
} else if (derivative_order == 1) {
std::vector<T> derivative_knots;
const int num_derivative_knots = basis_.knots().size() - 2;
derivative_knots.reserve(num_derivative_knots);
for (int i = 1; i <= num_derivative_knots; ++i) {
derivative_knots.push_back(basis_.knots()[i]);
}
std::vector<MatrixX<T>> derivative_control_points;
derivative_control_points.reserve(num_control_points() - 1);
for (int i = 0; i < num_control_points() - 1; ++i) {
derivative_control_points.push_back(
basis_.degree() /
(basis_.knots()[i + basis_.order()] - basis_.knots()[i + 1]) *
(control_points()[i + 1] - control_points()[i]));
}
return std::make_unique<BsplineTrajectory<T>>(
BsplineBasis<T>(basis_.order() - 1, derivative_knots),
derivative_control_points);
} else {
throw std::invalid_argument(
fmt::format("Invalid derivative order ({}). The derivative order must "
"be greater than or equal to 0.",
derivative_order));
}
}
template <typename T>
MatrixX<T> BsplineTrajectory<T>::InitialValue() const {
return value(start_time());
}
template <typename T>
MatrixX<T> BsplineTrajectory<T>::FinalValue() const {
return value(end_time());
}
template <typename T>
void BsplineTrajectory<T>::InsertKnots(const std::vector<T>& additional_knots) {
if (additional_knots.size() != 1) {
for (const auto& time : additional_knots) {
InsertKnots(std::vector<T>{time});
}
} else {
// Implements Boehm's Algorithm for knot insertion as described in by
// Patrikalakis et al. [1], with a typo corrected in equation 1.76.
//
// [1] http://web.mit.edu/hyperbook/Patrikalakis-Maekawa-Cho/node18.html
// Define short-hand references to match Patrikalakis et al.:
const std::vector<T>& t = basis_.knots();
const T& t_bar = additional_knots.front();
const int k = basis_.order();
DRAKE_DEMAND(start_time() <= t_bar && t_bar <= end_time());
/* Find the index, π, of the greatest knot that is less than or equal to
t_bar and strictly less than end_time(). */
const int ell = basis().FindContainingInterval(t_bar);
std::vector<T> new_knots = t;
new_knots.insert(std::next(new_knots.begin(), ell + 1), t_bar);
std::vector<MatrixX<T>> new_control_points{this->control_points().front()};
for (int i = 1; i < this->num_control_points(); ++i) {
T a{0};
if (i < ell - k + 2) {
a = 1;
} else if (i <= ell) {
// Patrikalakis et al. have t[l + k - 1] in the denominator here ([1],
// equation 1.76). This is contradicted by other references (e.g. [2]),
// and does not yield the desired result (that the addition of the knot
// leaves the values of the original trajectory unchanged). We use
// t[i + k - 1], which agrees with [2] (modulo changes in notation)
// and produces the desired results.
//
// [2] Prautzsch, Hartmut, Wolfgang Boehm, and Marco Paluszny. BΓ©zier
// and B-spline techniques. Springer Science & Business Media, 2013.
a = (t_bar - t[i]) / (t[i + k - 1] - t[i]);
}
new_control_points.push_back((1 - a) * control_points()[i - 1] +
a * control_points()[i]);
}
// Note that since a == 0 for i > ell in the loop above, the final control
// point from the original trajectory is never pushed back into
// new_control_points. Do that now.
new_control_points.push_back(this->control_points().back());
control_points_.swap(new_control_points);
basis_ = BsplineBasis<T>(basis_.order(), new_knots);
}
}
template <typename T>
BsplineTrajectory<T> BsplineTrajectory<T>::CopyWithSelector(
const std::function<MatrixX<T>(const MatrixX<T>&)>& select) const {
std::vector<MatrixX<T>> new_control_points{};
new_control_points.reserve(num_control_points());
for (const MatrixX<T>& control_point : control_points_) {
new_control_points.push_back(select(control_point));
}
return {basis(), new_control_points};
}
template <typename T>
BsplineTrajectory<T> BsplineTrajectory<T>::CopyBlock(int start_row,
int start_col,
int block_rows,
int block_cols) const {
return CopyWithSelector([&start_row, &start_col, &block_rows,
&block_cols](const MatrixX<T>& full) {
return full.block(start_row, start_col, block_rows, block_cols);
});
}
template <typename T>
BsplineTrajectory<T> BsplineTrajectory<T>::CopyHead(int n) const {
DRAKE_DEMAND(cols() == 1);
DRAKE_DEMAND(n > 0);
return CopyBlock(0, 0, n, 1);
}
template <typename T>
boolean<T> BsplineTrajectory<T>::operator==(
const BsplineTrajectory<T>& other) const {
if (this->basis() == other.basis() && this->rows() == other.rows() &&
this->cols() == other.cols()) {
boolean<T> result{true};
for (int i = 0; i < this->num_control_points(); ++i) {
result = result && drake::all(this->control_points()[i].array() ==
other.control_points()[i].array());
if (std::equal_to<boolean<T>>{}(result, boolean<T>{false})) {
break;
}
}
return result;
} else {
return boolean<T>{false};
}
}
template <typename T>
void BsplineTrajectory<T>::CheckInvariants() const {
DRAKE_THROW_UNLESS(static_cast<int>(control_points_.size()) ==
basis_.num_basis_functions());
}
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class BsplineTrajectory);
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/path_parameterized_trajectory.cc | #include "drake/common/trajectories/path_parameterized_trajectory.h"
#include <algorithm>
#include <fmt/format.h>
#include "drake/common/drake_assert.h"
#include "drake/common/trajectories/derivative_trajectory.h"
namespace drake {
namespace trajectories {
template <typename T>
PathParameterizedTrajectory<T>::PathParameterizedTrajectory(
const Trajectory<T>& path, const Trajectory<T>& time_scaling)
: path_{path.Clone()}, time_scaling_{time_scaling.Clone()} {
DRAKE_DEMAND(time_scaling.rows() == 1);
DRAKE_DEMAND(time_scaling.cols() == 1);
}
template <typename T>
std::unique_ptr<Trajectory<T>> PathParameterizedTrajectory<T>::Clone() const {
return std::make_unique<PathParameterizedTrajectory<T>>(*this);
}
template <typename T>
MatrixX<T> PathParameterizedTrajectory<T>::value(const T& t) const {
using std::clamp;
const T time =
clamp(t, time_scaling_->start_time(), time_scaling_->end_time());
return path_->value(time_scaling_->value(time)(0, 0));
}
template <typename T>
T PathParameterizedTrajectory<T>::BellPolynomial(int n, int k,
const VectorX<T>& x) const {
if (n == 0 && k == 0) {
return 1;
} else if (n == 0 || k == 0) {
return 0;
}
T polynomial = 0;
T a = 1;
for (int ii = 1; ii < n - k + 2; ++ii) {
polynomial += a * BellPolynomial(n - ii, k - 1, x) * x[ii - 1];
a = a * (n - ii) / ii;
}
return polynomial;
}
template <typename T>
MatrixX<T> PathParameterizedTrajectory<T>::DoEvalDerivative(
const T& t, int derivative_order) const {
using std::clamp;
const T time =
clamp(t, time_scaling_->start_time(), time_scaling_->end_time());
if (derivative_order == 0) {
return value(time);
} else if (derivative_order > 0) {
VectorX<T> s_derivatives(derivative_order);
for (int order = 0; order < derivative_order; ++order) {
s_derivatives(order) =
time_scaling_->EvalDerivative(time, order + 1)(0, 0);
}
// Derivative is calculated using FaΓ di Bruno's formula with Bell
// polynomials: https://en.wikipedia.org/wiki/Fa%C3%A0_di_Bruno%27s_formula
MatrixX<T> derivative = MatrixX<T>::Zero(rows(), cols());
for (int order = 1; order <= derivative_order; ++order) {
MatrixX<T> path_partial =
path_->EvalDerivative(time_scaling_->value(time)(0, 0), order);
derivative +=
path_partial * BellPolynomial(derivative_order, order, s_derivatives);
}
return derivative;
} else {
throw std::invalid_argument(
fmt::format("Invalid derivative order ({}). The derivative order must "
"be greater than or equal to 0.",
derivative_order));
}
}
template <typename T>
std::unique_ptr<Trajectory<T>> PathParameterizedTrajectory<T>::DoMakeDerivative(
int derivative_order) const {
return std::make_unique<DerivativeTrajectory<T>>(*this, derivative_order);
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PathParameterizedTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/exponential_plus_piecewise_polynomial.cc | #include "drake/common/trajectories/exponential_plus_piecewise_polynomial.h"
#include <memory>
#include <unsupported/Eigen/MatrixFunctions>
namespace drake {
namespace trajectories {
template <typename T>
ExponentialPlusPiecewisePolynomial<T>::ExponentialPlusPiecewisePolynomial(
const PiecewisePolynomial<T>& piecewise_polynomial_part)
: PiecewiseTrajectory<T>(piecewise_polynomial_part),
K_(MatrixX<T>::Zero(piecewise_polynomial_part.rows(), 1)),
A_(MatrixX<T>::Zero(1, 1)),
alpha_(MatrixX<T>::Zero(
1, piecewise_polynomial_part.get_number_of_segments())),
piecewise_polynomial_part_(piecewise_polynomial_part) {
using std::isfinite;
DRAKE_DEMAND(isfinite(piecewise_polynomial_part.start_time()));
DRAKE_ASSERT(piecewise_polynomial_part.cols() == 1);
}
template <typename T>
std::unique_ptr<Trajectory<T>> ExponentialPlusPiecewisePolynomial<T>::Clone()
const {
return std::make_unique<ExponentialPlusPiecewisePolynomial<T>>(*this);
}
template <typename T>
MatrixX<T> ExponentialPlusPiecewisePolynomial<T>::value(const T& t) const {
int segment_index = this->get_segment_index(t);
MatrixX<T> ret = piecewise_polynomial_part_.value(t);
double tj = this->start_time(segment_index);
auto exponential = (A_ * (t - tj)).eval().exp().eval();
ret.noalias() += K_ * exponential * alpha_.col(segment_index);
return ret;
}
template <typename T>
ExponentialPlusPiecewisePolynomial<T>
ExponentialPlusPiecewisePolynomial<T>::derivative(int derivative_order) const {
DRAKE_ASSERT(derivative_order >= 0);
// quite inefficient, especially for high order derivatives due to all the
// temporaries...
MatrixX<T> K_new = K_;
for (int i = 0; i < derivative_order; i++) {
K_new = K_new * A_;
}
return ExponentialPlusPiecewisePolynomial<T>(
K_new, A_, alpha_,
piecewise_polynomial_part_.derivative(derivative_order));
}
template <typename T>
Eigen::Index ExponentialPlusPiecewisePolynomial<T>::rows() const {
return piecewise_polynomial_part_.rows();
}
template <typename T>
Eigen::Index ExponentialPlusPiecewisePolynomial<T>::cols() const {
return piecewise_polynomial_part_.cols();
}
template <typename T>
void ExponentialPlusPiecewisePolynomial<T>::shiftRight(double offset) {
std::vector<double>& breaks = this->get_mutable_breaks();
for (auto it = breaks.begin(); it != breaks.end(); ++it) {
*it += offset;
}
piecewise_polynomial_part_.shiftRight(offset);
}
template class ExponentialPlusPiecewisePolynomial<double>;
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_googletest",
"drake_cc_library",
"drake_cc_package_library",
)
package(default_visibility = ["//visibility:public"])
drake_cc_package_library(
name = "trajectories",
visibility = ["//visibility:public"],
deps = [
":bezier_curve",
":bspline_trajectory",
":composite_trajectory",
":derivative_trajectory",
":discrete_time_trajectory",
":path_parameterized_trajectory",
":piecewise_polynomial",
":piecewise_pose",
":piecewise_quaternion",
":piecewise_trajectory",
":stacked_trajectory",
":trajectory",
],
)
drake_cc_library(
name = "bezier_curve",
srcs = [
"bezier_curve.cc",
],
hdrs = [
"bezier_curve.h",
],
deps = [
":trajectory",
"//common:drake_bool",
"//common/symbolic:polynomial",
"//math:binomial_coefficient",
],
)
drake_cc_library(
name = "bspline_trajectory",
srcs = [
"bspline_trajectory.cc",
],
hdrs = [
"bspline_trajectory.h",
],
deps = [
":trajectory",
"//common:name_value",
"//math:bspline_basis",
],
)
drake_cc_library(
name = "composite_trajectory",
srcs = [
"composite_trajectory.cc",
],
hdrs = [
"composite_trajectory.h",
],
deps = [
":piecewise_trajectory",
],
)
drake_cc_library(
name = "derivative_trajectory",
srcs = ["derivative_trajectory.cc"],
hdrs = ["derivative_trajectory.h"],
deps = [
":trajectory",
"//common:default_scalars",
"//common:essential",
],
)
drake_cc_library(
name = "discrete_time_trajectory",
srcs = ["discrete_time_trajectory.cc"],
hdrs = ["discrete_time_trajectory.h"],
deps = [
":piecewise_polynomial",
":trajectory",
"//common:default_scalars",
"//common:essential",
"//math:matrix_util",
],
)
drake_cc_library(
name = "path_parameterized_trajectory",
srcs = ["path_parameterized_trajectory.cc"],
hdrs = ["path_parameterized_trajectory.h"],
deps = [
":derivative_trajectory",
":trajectory",
"//common:default_scalars",
"//common:essential",
],
)
drake_cc_library(
name = "piecewise_polynomial",
srcs = [
"exponential_plus_piecewise_polynomial.cc",
"piecewise_polynomial.cc",
],
hdrs = [
"exponential_plus_piecewise_polynomial.h",
"piecewise_polynomial.h",
],
deps = [
":piecewise_trajectory",
"//common:default_scalars",
"//common:essential",
"//common:name_value",
"//common:polynomial",
"//math:matrix_util",
"@fmt",
],
)
drake_cc_library(
name = "piecewise_pose",
srcs = ["piecewise_pose.cc"],
hdrs = ["piecewise_pose.h"],
deps = [
":piecewise_polynomial",
":piecewise_quaternion",
"//common:essential",
"//common:pointer_cast",
"//math:geometric_transform",
],
)
drake_cc_library(
name = "piecewise_quaternion",
srcs = ["piecewise_quaternion.cc"],
hdrs = ["piecewise_quaternion.h"],
deps = [
":piecewise_polynomial",
":piecewise_trajectory",
"//common:essential",
"//math:geometric_transform",
],
)
drake_cc_library(
name = "piecewise_trajectory",
srcs = ["piecewise_trajectory.cc"],
hdrs = ["piecewise_trajectory.h"],
deps = [
":trajectory",
"//common:default_scalars",
"//common:essential",
],
)
drake_cc_library(
name = "stacked_trajectory",
srcs = ["stacked_trajectory.cc"],
hdrs = ["stacked_trajectory.h"],
deps = [
":trajectory",
"//common:reset_after_move",
],
)
drake_cc_library(
name = "trajectory",
srcs = ["trajectory.cc"],
hdrs = ["trajectory.h"],
deps = [
"//common:default_scalars",
"//common:essential",
"//common:unused",
],
)
# === test/ ===
drake_cc_googletest(
name = "bezier_curve_test",
deps = [
":bezier_curve",
"//common/symbolic:polynomial",
"//common/test_utilities",
"//geometry/optimization:convex_set",
"//solvers:mathematical_program",
],
)
drake_cc_googletest(
name = "bspline_trajectory_test",
deps = [
":bspline_trajectory",
"//common:find_resource",
"//common/proto:call_python",
"//common/test_utilities",
"//common/yaml",
"//math:compute_numerical_gradient",
"//math:gradient",
],
)
drake_cc_googletest(
name = "composite_trajectory_test",
deps = [
":bezier_curve",
":composite_trajectory",
"//common/test_utilities",
],
)
drake_cc_googletest(
name = "derivative_trajectory_test",
deps = [
":derivative_trajectory",
":discrete_time_trajectory",
":piecewise_polynomial",
":piecewise_quaternion",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "discrete_time_trajectory_test",
deps = [
":discrete_time_trajectory",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "exponential_plus_piecewise_polynomial_test",
deps = [
":piecewise_polynomial",
":random_piecewise_polynomial",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "path_parameterized_trajectory_test",
deps = [
":path_parameterized_trajectory",
":piecewise_polynomial",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "piecewise_polynomial_generation_test",
# Test timeout increased to not timeout when run with Valgrind.
timeout = "moderate",
srcs = ["test/piecewise_polynomial_generation_test.cc"],
deps = [
":piecewise_polynomial",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_no_throw",
],
)
drake_cc_googletest(
name = "piecewise_polynomial_test",
deps = [
":piecewise_polynomial",
":random_piecewise_polynomial",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
"//common/yaml",
"//math:gradient",
],
)
drake_cc_googletest(
name = "piecewise_pose_test",
deps = [
":piecewise_pose",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "piecewise_quaternion_test",
deps = [
":piecewise_quaternion",
"//common/test_utilities:eigen_matrix_compare",
"//math:wrap_to",
],
)
drake_cc_googletest(
name = "piecewise_trajectory_test",
deps = [
":piecewise_trajectory",
],
)
drake_cc_library(
name = "random_piecewise_polynomial",
testonly = 1,
hdrs = ["test/random_piecewise_polynomial.h"],
deps = [
"//common/test_utilities:random_polynomial_matrix",
],
)
drake_cc_googletest(
name = "stacked_trajectory_test",
deps = [
":discrete_time_trajectory",
":piecewise_polynomial",
":stacked_trajectory",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_googletest(
name = "trajectory_test",
deps = [
":trajectory",
"//common/test_utilities:expect_throws_message",
],
)
add_lint_tests()
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/piecewise_trajectory.cc | #include "drake/common/trajectories/piecewise_trajectory.h"
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include "drake/common/drake_assert.h"
using std::uniform_real_distribution;
using std::vector;
namespace drake {
namespace trajectories {
template <typename T>
PiecewiseTrajectory<T>::PiecewiseTrajectory(const std::vector<T>& breaks)
: Trajectory<T>(), breaks_(breaks) {
for (int i = 1; i < get_number_of_segments() + 1; i++) {
DRAKE_DEMAND(breaks_[i] - breaks_[i - 1] >= kEpsilonTime);
}
}
template <typename T>
boolean<T> PiecewiseTrajectory<T>::is_time_in_range(const T& time) const {
return (time >= start_time() && time <= end_time());
}
template <typename T>
int PiecewiseTrajectory<T>::get_number_of_segments() const {
return static_cast<int>(breaks_.size() > 0 ? breaks_.size() - 1 : 0);
}
template <typename T>
T PiecewiseTrajectory<T>::start_time(int segment_number) const {
segment_number_range_check(segment_number);
return breaks_[segment_number];
}
template <typename T>
T PiecewiseTrajectory<T>::end_time(int segment_number) const {
segment_number_range_check(segment_number);
return breaks_[segment_number + 1];
}
template <typename T>
T PiecewiseTrajectory<T>::duration(int segment_number) const {
return end_time(segment_number) - start_time(segment_number);
}
template <typename T>
T PiecewiseTrajectory<T>::start_time() const {
return start_time(0);
}
template <typename T>
T PiecewiseTrajectory<T>::end_time() const {
return end_time(get_number_of_segments() - 1);
}
template <typename T>
int PiecewiseTrajectory<T>::GetSegmentIndexRecursive(const T& time, int start,
int end) const {
DRAKE_DEMAND(end >= start);
DRAKE_DEMAND(end < static_cast<int>(breaks_.size()));
DRAKE_DEMAND(start >= 0);
DRAKE_DEMAND(time <= breaks_[end] && time >= breaks_[start]);
int mid = (start + end) / 2;
// one or two numbers
if (end - start <= 1) return start;
if (time < breaks_[mid])
return GetSegmentIndexRecursive(time, start, mid);
else if (time > breaks_[mid])
return GetSegmentIndexRecursive(time, mid, end);
else
return mid;
}
template <typename T>
int PiecewiseTrajectory<T>::get_segment_index(const T& t) const {
if (breaks_.empty()) return 0;
using std::clamp;
const T time = clamp(t, start_time(), end_time());
return GetSegmentIndexRecursive(time, 0,
static_cast<int>(breaks_.size() - 1));
}
template <typename T>
const std::vector<T>& PiecewiseTrajectory<T>::get_segment_times() const {
return breaks_;
}
template <typename T>
void PiecewiseTrajectory<T>::segment_number_range_check(
int segment_number) const {
if (segment_number < 0 || segment_number >= get_number_of_segments()) {
std::stringstream msg;
msg << "Segment number " << segment_number << " out of range [" << 0 << ", "
<< get_number_of_segments() << ")" << std::endl;
throw std::runtime_error(msg.str().c_str());
}
}
template <typename T>
std::vector<T> PiecewiseTrajectory<T>::RandomSegmentTimes(
// TODO(#2274) Fix this NOLINTNEXTLINE(runtime/references)
int num_segments, std::default_random_engine& generator) {
vector<T> breaks;
uniform_real_distribution<double> uniform(kEpsilonTime, 1);
T t0 = uniform(generator);
breaks.push_back(t0);
for (int i = 0; i < num_segments; ++i) {
T duration = uniform(generator);
breaks.push_back(breaks[i] + duration);
}
return breaks;
}
template <typename T>
bool PiecewiseTrajectory<T>::SegmentTimesEqual(
const PiecewiseTrajectory<T>& other, double tol) const {
if (breaks_.size() != other.breaks_.size()) return false;
using std::abs;
for (size_t i = 0; i < breaks_.size(); i++) {
if (abs(breaks_[i] - other.breaks_[i]) > tol) return false;
}
return true;
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PiecewiseTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/derivative_trajectory.h | #pragma once
#include <memory>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/default_scalars.h"
#include "drake/common/reset_after_move.h"
#include "drake/common/trajectories/trajectory.h"
namespace drake {
namespace trajectories {
/** Trajectory objects provide derivatives by implementing `DoEvalDerivative`
_and_ `DoMakeDerivative`. `DoEvalDerivative` evaluates the derivative value at
a point in time. `DoMakeDerivative` returns a new Trajectory object which
represents the derivative.
In some cases, it is easy to implement `DoEvalDerivative`, but difficult or
inefficient to implement `DoMakeDerivative` natively. And it may be just as
efficient to use `DoEvalDerivative` even in repeated evaluations of the
derivative. The %DerivativeTrajectory class helps with this case -- given a
`nominal` Trajectory, it provides a Trajectory interface that calls
`nominal.EvalDerivative()` to implement `Trajectory::value()`.
@tparam_default_scalar */
template <typename T>
class DerivativeTrajectory final : public Trajectory<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(DerivativeTrajectory)
/** Creates a DerivativeTrajectory representing the `derivative_order`
derivatives of `nominal`. This constructor makes a Clone() of `nominal` and
does not hold on to the reference.
@throws std::exception if `!nominal.has_derivative()`.
@throws std::exception if derivative_order < 0. */
explicit DerivativeTrajectory(const Trajectory<T>& nominal,
int derivative_order = 1);
~DerivativeTrajectory() final;
// Trajectory overrides.
std::unique_ptr<Trajectory<T>> Clone() const final;
MatrixX<T> value(const T& t) const final;
Eigen::Index rows() const final;
Eigen::Index cols() const final;
T start_time() const final;
T end_time() const final;
private:
// Trajectory overrides.
bool do_has_derivative() const final { return true; }
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const final;
std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order) const final;
copyable_unique_ptr<Trajectory<T>> nominal_;
reset_after_move<int> derivative_order_;
reset_after_move<int> rows_;
reset_after_move<int> cols_;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::DerivativeTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/piecewise_pose.cc | #include "drake/common/trajectories/piecewise_pose.h"
#include "drake/common/pointer_cast.h"
#include "drake/common/polynomial.h"
#include "drake/math/rotation_matrix.h"
namespace drake {
namespace trajectories {
template <typename T>
PiecewisePose<T>::PiecewisePose(
const PiecewisePolynomial<T>& position_trajectory,
const PiecewiseQuaternionSlerp<T>& orientation_trajectory)
: PiecewiseTrajectory<T>(position_trajectory.get_segment_times()) {
DRAKE_DEMAND(position_trajectory.rows() == 3);
DRAKE_DEMAND(position_trajectory.cols() == 1);
DRAKE_DEMAND(this->SegmentTimesEqual(orientation_trajectory, 0));
position_ = position_trajectory;
velocity_ = position_.derivative();
acceleration_ = velocity_.derivative();
orientation_ = orientation_trajectory;
}
template <typename T>
PiecewisePose<T> PiecewisePose<T>::MakeLinear(
const std::vector<T>& times,
const std::vector<math::RigidTransform<T>>& poses) {
std::vector<MatrixX<T>> pos_knots(poses.size());
std::vector<math::RotationMatrix<T>> rot_knots(poses.size());
for (size_t i = 0; i < poses.size(); ++i) {
pos_knots[i] = poses[i].translation();
rot_knots[i] = poses[i].rotation();
}
return PiecewisePose<T>(
PiecewisePolynomial<T>::FirstOrderHold(times, pos_knots),
PiecewiseQuaternionSlerp<T>(times, rot_knots));
}
template <typename T>
PiecewisePose<T> PiecewisePose<T>::MakeCubicLinearWithEndLinearVelocity(
const std::vector<T>& times,
const std::vector<math::RigidTransform<T>>& poses,
const Vector3<T>& start_vel, const Vector3<T>& end_vel) {
std::vector<MatrixX<T>> pos_knots(poses.size());
std::vector<math::RotationMatrix<T>> rot_knots(poses.size());
for (size_t i = 0; i < poses.size(); ++i) {
pos_knots[i] = poses[i].translation();
rot_knots[i] = poses[i].rotation();
}
return PiecewisePose<T>(
PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
times, pos_knots, start_vel, end_vel),
PiecewiseQuaternionSlerp<T>(times, rot_knots));
}
template <typename T>
std::unique_ptr<Trajectory<T>> PiecewisePose<T>::Clone() const {
return std::make_unique<PiecewisePose>(*this);
}
template <typename T>
math::RigidTransform<T> PiecewisePose<T>::GetPose(const T& time) const {
return math::RigidTransform<T>(orientation_.orientation(time),
position_.value(time));
}
template <typename T>
Vector6<T> PiecewisePose<T>::GetVelocity(const T& time) const {
Vector6<T> velocity;
if (orientation_.is_time_in_range(time)) {
velocity.template head<3>() = orientation_.angular_velocity(time);
} else {
velocity.template head<3>().setZero();
}
if (position_.is_time_in_range(time)) {
velocity.template tail<3>() = velocity_.value(time);
} else {
velocity.template tail<3>().setZero();
}
return velocity;
}
template <typename T>
Vector6<T> PiecewisePose<T>::GetAcceleration(const T& time) const {
Vector6<T> acceleration;
if (orientation_.is_time_in_range(time)) {
acceleration.template head<3>() = orientation_.angular_acceleration(time);
} else {
acceleration.template head<3>().setZero();
}
if (position_.is_time_in_range(time)) {
acceleration.template tail<3>() = acceleration_.value(time);
} else {
acceleration.template tail<3>().setZero();
}
return acceleration;
}
template <typename T>
bool PiecewisePose<T>::IsApprox(const PiecewisePose<T>& other,
double tol) const {
bool ret = position_.isApprox(other.position_, tol);
ret &= orientation_.is_approx(other.orientation_, tol);
return ret;
}
template <typename T>
bool PiecewisePose<T>::do_has_derivative() const {
return true;
}
template <typename T>
MatrixX<T> PiecewisePose<T>::DoEvalDerivative(const T& t,
int derivative_order) const {
if (derivative_order == 0) {
return value(t);
}
Vector6<T> derivative;
derivative.template head<3>() =
orientation_.EvalDerivative(t, derivative_order);
derivative.template tail<3>() = position_.EvalDerivative(t, derivative_order);
return derivative;
}
template <typename T>
std::unique_ptr<Trajectory<T>> PiecewisePose<T>::DoMakeDerivative(
int derivative_order) const {
if (derivative_order == 0) {
return this->Clone();
}
std::unique_ptr<PiecewisePolynomial<T>> orientation_deriv =
dynamic_pointer_cast<PiecewisePolynomial<T>>(
orientation_.MakeDerivative(derivative_order));
PiecewisePolynomial<T> position_deriv =
position_.derivative(derivative_order);
const std::vector<T>& breaks = position_deriv.get_segment_times();
std::vector<MatrixX<Polynomial<T>>> derivative;
for (size_t ii = 0; ii < breaks.size() - 1; ii++) {
MatrixX<Polynomial<T>> segment_derivative(6, 1);
segment_derivative.template topRows<3>() =
orientation_deriv->getPolynomialMatrix(ii);
segment_derivative.template bottomRows<3>() =
position_deriv.getPolynomialMatrix(ii);
derivative.push_back(segment_derivative);
}
return std::make_unique<PiecewisePolynomial<T>>(derivative, breaks);
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PiecewisePose)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/stacked_trajectory.h | #pragma once
#include <memory>
#include <vector>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/reset_after_move.h"
#include "drake/common/trajectories/trajectory.h"
namespace drake {
namespace trajectories {
/** A %StackedTrajectory stacks the values from one or more underlying
Trajectory objects into a single %Trajectory, without changing the
`%start_time()` or `%end_time()`.
For sequencing trajectories in time instead, see CompositeTrajectory.
All of the underlying %Trajectory objects must have the same `%start_time()`
and `%end_time()`.
When constructed with `rowwise` set to true, all of the underlying %Trajectory
objects must have the same number of `%cols()` and the `value()` matrix will be
the **vstack** of the the trajectories in the order they were added.
When constructed with `rowwise` set to false, all of the underlying %Trajectory
objects must have the same number of `%rows()` and the `value()` matrix will be
the **hstack** of the the trajectories in the order they were added.
@tparam_default_scalar */
template <typename T>
class StackedTrajectory final : public Trajectory<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(StackedTrajectory)
/** Creates an empty trajectory.
@param rowwise governs the stacking order */
explicit StackedTrajectory(bool rowwise = true);
~StackedTrajectory() final;
/** Stacks another sub-Trajectory onto this.
Refer to the class overview documentation for details.
@throws std::exception if the matrix dimension is incompatible. */
void Append(const Trajectory<T>& traj);
// Trajectory overrides.
std::unique_ptr<Trajectory<T>> Clone() const final;
MatrixX<T> value(const T& t) const final;
Eigen::Index rows() const final;
Eigen::Index cols() const final;
T start_time() const final;
T end_time() const final;
private:
void CheckInvariants() const;
// We could make this public, if we ever need it for performance.
void Append(std::unique_ptr<Trajectory<T>> traj);
// Trajectory overrides.
bool do_has_derivative() const final;
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const final;
std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order) const final;
bool rowwise_{};
std::vector<copyable_unique_ptr<Trajectory<T>>> children_;
reset_after_move<int> rows_;
reset_after_move<int> cols_;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::StackedTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/path_parameterized_trajectory.h | #pragma once
#include <memory>
#include <vector>
#include <Eigen/Core>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/default_scalars.h"
#include "drake/common/trajectories/trajectory.h"
namespace drake {
namespace trajectories {
/**
* A trajectory defined by a path and timing trajectory.
*
* Using a path of form `r(s)` and a time_scaling of the form `s(t)`, a full
* trajectory of form `q(t) = r(s(t))` is modeled.
*
* @tparam_default_scalar
*/
template <typename T>
class PathParameterizedTrajectory final : public Trajectory<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PathParameterizedTrajectory)
/** Constructs a trajectory with the given `path` and `time_scaling`.
@pre time_scaling.rows() == time_scaling.cols() == 1 */
PathParameterizedTrajectory(const Trajectory<T>& path,
const Trajectory<T>& time_scaling);
~PathParameterizedTrajectory() final = default;
// Required methods for trajectories::Trajectory interface.
std::unique_ptr<trajectories::Trajectory<T>> Clone() const override;
/** Evaluates the PathParameterizedTrajectory at the given time t.
@param t The time at which to evaluate the %PathParameterizedTrajectory.
@return The matrix of evaluated values.
@pre If T == symbolic::Expression, `t.is_constant()` must be true.
@warning If t does not lie in the range [start_time(), end_time()], the
trajectory will silently be evaluated at the closest
valid value of time to t. For example, `value(-1)` will return
`value(0)` for a trajectory defined over [0, 1]. */
MatrixX<T> value(const T& t) const override;
Eigen::Index rows() const override { return path_->rows(); }
Eigen::Index cols() const override { return path_->cols(); }
T start_time() const override { return time_scaling_->start_time(); }
T end_time() const override { return time_scaling_->end_time(); }
/** Returns the path of this trajectory. */
const trajectories::Trajectory<T>& path() const { return *path_; }
/** Returns the time_scaling of this trajectory. */
const trajectories::Trajectory<T>& time_scaling() const {
return *time_scaling_;
}
private:
// Evaluates the %PathParameterizedTrajectory derivative at the given time @p
// t. Returns the nth derivative, where `n` is the value of @p
// derivative_order.
//
// @warning This method comes with the same caveats as value(). See value()
// @pre derivative_order must be non-negative.
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const override;
// Uses DerivativeTrajectory to provide a derivative object.
std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order) const final;
// Evaluates the Bell Polynomial B_n,k(x) for use in calculating the
// derivative.
// @pre n and k must be non-negative and the length of x must be at least n.
T BellPolynomial(int n, int k, const VectorX<T>& x) const;
bool do_has_derivative() const override {
return path_->has_derivative() && time_scaling_->has_derivative();
}
copyable_unique_ptr<Trajectory<T>> path_;
copyable_unique_ptr<Trajectory<T>> time_scaling_;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PathParameterizedTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/piecewise_quaternion.cc | #include "drake/common/trajectories/piecewise_quaternion.h"
#include <algorithm>
#include <stdexcept>
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/math/quaternion.h"
namespace drake {
namespace trajectories {
using std::abs;
using std::cos;
using std::max;
using std::min;
template <typename T>
bool PiecewiseQuaternionSlerp<T>::is_approx(
const PiecewiseQuaternionSlerp<T>& other, double tol) const {
// Velocities are derived from the quaternions, and I don't want to
// overload units for tol, so I am skipping the checks on velocities.
if (!this->SegmentTimesEqual(other, tol)) {
return false;
}
if (quaternions_.size() != other.quaternions_.size()) {
return false;
}
for (size_t i = 0; i < quaternions_.size(); ++i) {
// A quick reference:
// Page "Metric on sphere of unit quaternions" from
// http://www.cs.cmu.edu/afs/cs/academic/class/16741-s07/www/Lecture8.pdf
double dot =
abs(ExtractDoubleOrThrow(quaternions_[i].dot(other.quaternions_[i])));
if (dot < cos(tol / 2)) {
return false;
}
}
return true;
}
namespace internal {
template <typename T>
Vector3<T> ComputeAngularVelocity(const T& duration, const Quaternion<T>& q,
const Quaternion<T>& qnext) {
// Computes qnext = q_delta * q first, turn q_delta into an axis, which
// turns into an angular velocity.
AngleAxis<T> angle_axis_diff(qnext * q.inverse());
return angle_axis_diff.axis() * angle_axis_diff.angle() / duration;
}
} // namespace internal
template <typename T>
void PiecewiseQuaternionSlerp<T>::Initialize(
const std::vector<T>& breaks,
const std::vector<Quaternion<T>>& quaternions) {
if (quaternions.size() != breaks.size()) {
throw std::logic_error("Quaternions and breaks length mismatch.");
}
if (quaternions.size() < 2) {
throw std::logic_error("Not enough quaternions for slerp.");
}
quaternions_.resize(breaks.size());
angular_velocities_.resize(breaks.size() - 1);
// Set to the closest wrt to the previous, also normalize.
for (size_t i = 0; i < quaternions.size(); ++i) {
if (i == 0) {
quaternions_[i] = quaternions[i].normalized();
} else {
quaternions_[i] =
math::ClosestQuaternion(quaternions_[i - 1], quaternions[i]);
angular_velocities_[i - 1] = internal::ComputeAngularVelocity(
this->duration(i - 1), quaternions_[i - 1], quaternions[i]);
}
}
}
template <typename T>
PiecewiseQuaternionSlerp<T>::PiecewiseQuaternionSlerp(
const std::vector<T>& breaks, const std::vector<Quaternion<T>>& quaternions)
: PiecewiseTrajectory<T>(breaks) {
Initialize(breaks, quaternions);
}
template <typename T>
PiecewiseQuaternionSlerp<T>::PiecewiseQuaternionSlerp(
const std::vector<T>& breaks, const std::vector<Matrix3<T>>& rot_matrices)
: PiecewiseTrajectory<T>(breaks) {
std::vector<Quaternion<T>> quaternions(rot_matrices.size());
for (size_t i = 0; i < rot_matrices.size(); ++i) {
quaternions[i] = Quaternion<T>(rot_matrices[i]);
}
Initialize(breaks, quaternions);
}
template <typename T>
PiecewiseQuaternionSlerp<T>::PiecewiseQuaternionSlerp(
const std::vector<T>& breaks,
const std::vector<math::RotationMatrix<T>>& rot_matrices)
: PiecewiseTrajectory<T>(breaks) {
std::vector<Quaternion<T>> quaternions(rot_matrices.size());
for (size_t i = 0; i < rot_matrices.size(); ++i) {
quaternions[i] = rot_matrices[i].ToQuaternion();
}
Initialize(breaks, quaternions);
}
template <typename T>
PiecewiseQuaternionSlerp<T>::PiecewiseQuaternionSlerp(
const std::vector<T>& breaks, const std::vector<AngleAxis<T>>& ang_axes)
: PiecewiseTrajectory<T>(breaks) {
std::vector<Quaternion<T>> quaternions(ang_axes.size());
for (size_t i = 0; i < ang_axes.size(); ++i) {
quaternions[i] = Quaternion<T>(ang_axes[i]);
}
Initialize(breaks, quaternions);
}
template <typename T>
std::unique_ptr<Trajectory<T>> PiecewiseQuaternionSlerp<T>::Clone() const {
return std::make_unique<PiecewiseQuaternionSlerp>(*this);
}
template <typename T>
T PiecewiseQuaternionSlerp<T>::ComputeInterpTime(int segment_index,
const T& time) const {
T interp_time =
(time - this->start_time(segment_index)) / this->duration(segment_index);
interp_time = max(interp_time, T(0.0));
interp_time = min(interp_time, T(1.0));
return interp_time;
}
template <typename T>
Quaternion<T> PiecewiseQuaternionSlerp<T>::orientation(const T& t) const {
int segment_index = this->get_segment_index(t);
T interp_t = ComputeInterpTime(segment_index, t);
Quaternion<T> q1 = quaternions_.at(segment_index)
.slerp(interp_t, quaternions_.at(segment_index + 1));
q1.normalize();
return q1;
}
template <typename T>
Vector3<T> PiecewiseQuaternionSlerp<T>::angular_velocity(const T& t) const {
int segment_index = this->get_segment_index(t);
return angular_velocities_.at(segment_index);
}
template <typename T>
Vector3<T> PiecewiseQuaternionSlerp<T>::angular_acceleration(const T&) const {
return Vector3<T>::Zero();
}
template <typename T>
void PiecewiseQuaternionSlerp<T>::Append(const T& time,
const Quaternion<T>& quaternion) {
DRAKE_DEMAND(this->breaks().empty() || time > this->breaks().back());
if (quaternions_.empty()) {
quaternions_.push_back(quaternion.normalized());
} else {
angular_velocities_.push_back(internal::ComputeAngularVelocity(
time - this->breaks().back(), quaternions_.back(), quaternion));
quaternions_.push_back(
math::ClosestQuaternion(quaternions_.back(), quaternion));
}
this->get_mutable_breaks().push_back(time);
}
template <typename T>
void PiecewiseQuaternionSlerp<T>::Append(
const T& time, const math::RotationMatrix<T>& rotation_matrix) {
Append(time, rotation_matrix.ToQuaternion());
}
template <typename T>
void PiecewiseQuaternionSlerp<T>::Append(const T& time,
const AngleAxis<T>& angle_axis) {
Append(time, Quaternion<T>(angle_axis));
}
template <typename T>
bool PiecewiseQuaternionSlerp<T>::do_has_derivative() const {
return true;
}
template <typename T>
MatrixX<T> PiecewiseQuaternionSlerp<T>::DoEvalDerivative(
const T& t, int derivative_order) const {
if (derivative_order == 0) {
return value(t);
} else if (derivative_order == 1) {
return angular_velocity(t);
}
// All higher derivatives are zero.
return Vector3<T>::Zero();
}
template <typename T>
std::unique_ptr<Trajectory<T>> PiecewiseQuaternionSlerp<T>::DoMakeDerivative(
int derivative_order) const {
if (derivative_order == 0) {
return this->Clone();
} else if (derivative_order == 1) {
std::vector<MatrixX<T>> m(angular_velocities_.begin(),
angular_velocities_.end());
m.push_back(Vector3<T>::Zero());
return PiecewisePolynomial<T>::ZeroOrderHold(this->get_segment_times(), m)
.Clone();
}
// All higher derivatives are zero.
return std::make_unique<PiecewisePolynomial<T>>(Vector3<T>::Zero());
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PiecewiseQuaternionSlerp)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/piecewise_polynomial.h | #pragma once
#include <limits>
#include <memory>
#include <tuple>
#include <vector>
#include <Eigen/Core>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/name_value.h"
#include "drake/common/polynomial.h"
#include "drake/common/trajectories/piecewise_trajectory.h"
namespace drake {
namespace trajectories {
/**
* A scalar multi-variate piecewise polynomial.
*
* %PiecewisePolynomial represents a list of contiguous segments in a scalar
* independent variable (typically corresponding to time) with Polynomials
* defined at each segment. We call the output from evaluating the
* %PiecewisePolynomial at the scalar independent variable "the output", and
* that output can be either a Eigen MatrixX<T> (if evaluated using value())
* or a scalar (if evaluated using scalar_value()).
*
* An example of a piecewise polynomial is a function of m segments in time,
* where a different polynomial is defined for each segment. For a specific
* example, consider the absolute value function over the interval [-1, 1].
* We can define a %PiecewisePolynomial over this interval using breaks at
* t = { -1.0, 0.0, 1.0 }, and "samples" of abs(t).
*
* @code
* // Construct the PiecewisePolynomial.
* const std::vector<double> breaks = { -1.0, 0.0, 1.0 };
* std::vector<Eigen::MatrixXd> samples(3);
* for (int i = 0; i < static_cast<int>(breaks.size()); ++i) {
* samples[i].resize(1, 1);
* samples[i](0, 0) = std::abs(breaks[i]);
* }
* const auto pp =
* PiecewisePolynomial<double>::FirstOrderHold(breaks, samples);
* const int row = 0, col = 0;
*
* // Evaluate the PiecewisePolynomial at some values.
* std::cout << pp.value(-.5)(row, col) << std::endl; // Outputs 0.5.
* std::cout << pp.value(0.0)(row, col) << std::endl; // Outputs 0.0;
*
* // Show how we can evaluate the first derivative (outputs -1.0).
* std::cout << pp.derivative(1).value(-.5)(row, col) << std::endl;
* @endcode
*
* A note on terminology. For piecewise-polynomial interpolation, we use
* `breaks` to indicate the scalar (e.g. times) which form the boundary of
* each segment. We use `samples` to indicate the function value at the
* `breaks`, e.g. `p(breaks[i]) = samples[i]`. The term `knot` should be
* reserved for the "(x,y)" coordinate, here
* `knot[i] = (breaks[i], samples[i])`, though it is used inconsistently in
* the interpolation literature (sometimes for `breaks`, sometimes for
* `samples`), so we try to mostly avoid it here.
*
* PiecewisePolynomial objects can be added, subtracted, and multiplied.
* They cannot be divided because Polynomials are not closed
* under division.
*
* @warning %PiecewisePolynomial silently clips input evaluations outside of
* the range defined by the breaks. So `pp.value(-2.0, row, col)` in the example
* above would evaluate to -1.0. See value().
*
* @tparam_default_scalar
*/
template <typename T>
class PiecewisePolynomial final : public PiecewiseTrajectory<T> {
public:
/**
* Constructs an empty piecewise polynomial.
*/
PiecewisePolynomial() = default;
// We are final, so this is okay.
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PiecewisePolynomial)
typedef MatrixX<Polynomial<T>> PolynomialMatrix;
/**
* Single segment, constant value constructor over the interval [-β, β].
* The constructed %PiecewisePolynomial will return `constant_value` at
* every evaluated point (i.e., `value(t) = constant_value` βt β [-β, β]).
*/
template <typename Derived>
explicit PiecewisePolynomial(const Eigen::MatrixBase<Derived>& constant_value)
: PiecewiseTrajectory<T>(
std::vector<T>({-std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::infinity()})) {
polynomials_.push_back(constant_value.template cast<Polynomial<T>>());
}
/**
* @anchor polynomial_construction_methods
* @name Polynomial-based construction methods.
* Various methods for constructing a %PiecewisePolynomial using vectors
* of matrices of polynomials, one for each output dimension. Unlike the
* coefficient-based methods, the number of polynomials must equal the number
* of segments, which will be one fewer than the number of breaks.
*
* The following shows how such a %PiecewisePolynomial might be constructed
* and used:
* @code
* // Construct the PiecewisePolynomial.
* const std::vector<double> breaks = { -1.0, 0.0, 1.0 };
* Polynomiald t("t");
* std::vector<Polynomiald> polynomials = { -(t*t), (t*t) };
* const PiecewisePolynomial<double> pp(polynomials, breaks);
*
* // Evaluate the PiecewisePolynomial at some values.
* std::cout << pp.scalar_value(-1.0) << std::endl; // Outputs -1.0
* std::cout << pp.scalar_value(1.0) << std::endl; // Outputs 1.0
* @endcode
*
* @anchor polynomial_warning
* <b>WARNING:</b> For robust floating point arithmetic, the polynomial for
* a segment will be evaluated (using value()) by first
* subtracting the break time from the evaluation time. In other words, when t
* lies in the half-open interval `[breaks[i], breaks[i+1])` then:
* @code
* value(t) == polynomials[i].eval(t - breaks[i])
* @endcode
* meaning that constructing the polynomial like:
* @code
* const std::vector<double> breaks = { 0.0, 1.0, 2.0 };
* Polynomiald t("t");
* std::vector<Polynomiald> polynomials = { (t*t), (t*t) };
* const PiecewisePolynomial<double> pp(polynomials, breaks);
* @endcode
* would give the following result:
* @code
* // Evaluate the PiecewisePolynomial on both sides of a break.
* const int row = 0, col = 0;
* const double eps = 0.5 * std::numeric_limits<double>::epsilon();
* std::cout << pp.value(1.0-eps)(row, col) << std::endl; // Outputs 1.0
* std::cout << pp.value(1.0+eps)(row, col) << std::endl; // Outputs 1e-32
* @endcode
* because the second polynomial will be evaluated at 1.0+eps minus the break
* time for that polynomial (1.0), i.e., t=eps.
* The intended result for the above example can be obtained by shifting the
* piecewise polynomial like so:
* @code
* const std::vector<double> breaks = { 0.0, 1.0, 2.0 };
* Polynomiald t("t");
* std::vector<Polynomiald> polynomials = { (t*t),
* ((t+breaks[1])*(t+breaks[1])) };
* const PiecewisePolynomial<double> pp(polynomials, breaks);
*
* // Evaluate the PiecewisePolynomial on both sides of a break.
* const double eps = 0.5 * std::numeric_limits<double>::epsilon();
* std::cout << pp.value(1.0-eps)(row, col) << std::endl; // Outputs 1.0
* std::cout << pp.value(1.0+eps)(row, col) << std::endl; // Outputs 1.0
* @endcode
*/
// @{
/**
* Constructs a %PiecewisePolynomial using matrix-output Polynomials defined
* over each segment.
*
* @pre `polynomials.size() == breaks.size() - 1`
*/
PiecewisePolynomial(const std::vector<PolynomialMatrix>& polynomials_matrix,
const std::vector<T>& breaks);
/**
* Constructs a %PiecewisePolynomial using scalar-output Polynomials defined
* over each segment.
*
* @pre `polynomials.size() == breaks.size() - 1`
*/
PiecewisePolynomial(const std::vector<Polynomial<T>>& polynomials,
const std::vector<T>& breaks);
// @}
~PiecewisePolynomial() override = default;
std::unique_ptr<Trajectory<T>> Clone() const override;
/**
* @anchor coefficient_construction_methods
* @name Coefficient-based construction methods.
* Various methods for constructing a %PiecewisePolynomial using samples of
* coefficient matrices. Under the hood, %PiecewisePolynomial constructs
* interpolating Polynomial objects that pass through the sample points. These
* methods differ by the continuity constraints that they enforce at break
* points and whether each sample represents a full matrix (versions taking
* `const std::vector<MatrixX<T>>&`) or a column vector (versions
* taking `const Eigen::Ref<const MatrixX<T>>&`).
*
* These methods will throw `std::exception` if:
* - the breaks and samples have different length,
* - the breaks are not strictly increasing,
* - the samples have inconsistent dimensions (i.e., the matrices do not all
* have identical dimensions),
* - the breaks vector has length smaller than 2.
*/
// @{
/**
* Constructs a piecewise constant %PiecewisePolynomial using matrix samples.
* Note that constructing a %PiecewisePolynomial requires at least two sample
* points, although in this case, the second sample point's value is ignored,
* and only its break time is used.
*
* @throws std::exception under the conditions specified under
* @ref coefficient_construction_methods.
* @pydrake_mkdoc_identifier{matrix}
*/
static PiecewisePolynomial<T> ZeroOrderHold(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples);
/**
* Version of ZeroOrderHold(breaks, samples) that uses vector samples and
* Eigen VectorXd/MatrixX<T> arguments. Each column of `samples` represents a
* sample point.
*
* @pre `samples.cols() == breaks.size()`
* @throws std::exception under the conditions specified under
* @ref coefficient_construction_methods.
* @pydrake_mkdoc_identifier{vector}
*/
static PiecewisePolynomial<T> ZeroOrderHold(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples);
/**
* Constructs a piecewise linear %PiecewisePolynomial using matrix samples.
*
* @throws std::exception under the conditions specified under
* @ref coefficient_construction_methods.
* @pydrake_mkdoc_identifier{matrix}
*/
static PiecewisePolynomial<T> FirstOrderHold(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples);
/**
* Version of FirstOrderHold(breaks, samples) that uses vector samples and
* Eigen VectorXd / MatrixX<T> arguments. Each column of `samples` represents
* a sample point.
*
* @pre `samples.cols() == breaks.size()`
* @throws std::exception under the conditions specified under
* @ref coefficient_construction_methods.
* @pydrake_mkdoc_identifier{vector}
*/
static PiecewisePolynomial<T> FirstOrderHold(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples);
// TODO(russt): This version of the method is not exposed in pydrake, but
// the version that is has limited documentation that refers back to this
// verbose version. Either add support for this in pydrake, or flip the
// documentation so that pydrake gets the verbose/stand-along version.
/**
* Constructs a third order %PiecewisePolynomial using vector samples,
* where each column of `samples` represents a sample point. First derivatives
* are chosen to be "shape preserving", i.e. if `samples` is monotonic
* within some interval, the interpolated data will also be monotonic. The
* second derivative is not guaranteed to be smooth across the entire spline.
*
* MATLAB calls this method "pchip" (short for "Piecewise Cubic Hermite
* Interpolating Polynomial"), and provides a nice description in their
* documentation.
* http://home.uchicago.edu/~sctchoi/courses/cs138/interp.pdf is also a good
* reference.
*
* If `zero_end_point_derivatives` is `false`, the first and last first
* derivative is chosen using a non-centered, shape-preserving three-point
* formulae. See equation (2.10) in the following reference for more details.
* http://www.mi.sanu.ac.rs/~gvm/radovi/mon.pdf
* If `zero_end_point_derivatives` is `true`, they are set to zeros.
*
* If `zero_end_point_derivatives` is `false`, `breaks` and `samples` must
* have at least 3 elements for the algorithm to determine the first
* derivatives.
*
* If `zero_end_point_derivatives` is `true`, `breaks` and `samples` may have
* 2 or more elements. For the 2 elements case, the result is equivalent to
* computing a cubic polynomial whose values are given by `samples`, and
* derivatives set to zero.
*
* @throws std::exception if:
* - `breaks` has length smaller than 3 and `zero_end_point_derivatives` is
* `false`,
* - `breaks` has length smaller than 2 and `zero_end_point_derivatives` is
* true.
*
* @throws std::exception under the conditions specified under
* @ref coefficient_construction_methods.
* @pydrake_mkdoc_identifier{matrix}
*/
static PiecewisePolynomial<T> CubicShapePreserving(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
bool zero_end_point_derivatives = false);
/**
* Version of CubicShapePreserving(breaks, samples,
* zero_end_point_derivatives) that uses vector samples and Eigen VectorXd and
* MatrixX<T> arguments. Each column of `samples` represents a sample point.
*
* @pre `samples.cols() == breaks.size()`.
* @throws std::exception under the conditions specified under
* @ref coefficient_construction_methods.
* @pydrake_mkdoc_identifier{vector}
*/
static PiecewisePolynomial<T> CubicShapePreserving(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples,
bool zero_end_point_derivatives = false);
/**
* Constructs a third order %PiecewisePolynomial using matrix samples.
* The %PiecewisePolynomial is constructed such that the interior segments
* have the same value, first and second derivatives at `breaks`.
* `sample_dot_at_start` and `sample_dot_at_end` are used for the first and
* last first derivatives.
*
* @throws std::exception if `sample_dot_at_start` or `sample_dot_at_end`
* and `samples` have inconsistent dimensions.
* @throws std::exception under the conditions specified under
* @ref coefficient_construction_methods.
* @pydrake_mkdoc_identifier{4args_matrix}
*/
static PiecewisePolynomial<T> CubicWithContinuousSecondDerivatives(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
const MatrixX<T>& sample_dot_at_start,
const MatrixX<T>& sample_dot_at_end);
/**
* Version of CubicWithContinuousSecondDerivatives() that uses vector
* samples and Eigen VectorXd / MatrixX<T> arguments. Each column of
* `samples` represents a sample point.
*
* @pre `samples.cols() == breaks.size()`.
* @throws std::exception under the conditions specified under
* @ref coefficient_construction_methods.
* @pydrake_mkdoc_identifier{4args_vector}
*/
static PiecewisePolynomial<T> CubicWithContinuousSecondDerivatives(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples,
const Eigen::Ref<const VectorX<T>>& sample_dot_at_start,
const Eigen::Ref<const VectorX<T>>& sample_dot_at_end);
/**
* Constructs a third order %PiecewisePolynomial using matrix samples and
* derivatives of samples (`samples_dot`); each matrix element of
* `samples_dot` represents the derivative with respect to the independent
* variable (e.g., the time derivative) of the corresponding entry in
* `samples`. Each segment is fully specified by `samples` and `sample_dot` at
* both ends. Second derivatives are not continuous.
*
* @pydrake_mkdoc_identifier{matrix}
*/
static PiecewisePolynomial<T> CubicHermite(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
const std::vector<MatrixX<T>>& samples_dot);
/**
* Version of CubicHermite(breaks, samples, samples_dot) that uses vector
* samples and Eigen VectorXd / MatrixX<T> arguments. Corresponding columns of
* `samples` and `samples_dot` are used as the sample point and independent
* variable derivative, respectively.
*
* @pre `samples.cols() == samples_dot.cols() == breaks.size()`.
* @pydrake_mkdoc_identifier{vector}
*/
static PiecewisePolynomial<T> CubicHermite(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples,
const Eigen::Ref<const MatrixX<T>>& samples_dot);
/**
* Constructs a third order %PiecewisePolynomial using matrix samples.
* The %PiecewisePolynomial is constructed such that the interior segments
* have the same value, first and second derivatives at `breaks`. If
* `periodic_end_condition` is `false` (default), then the "Not-a-sample" end
* condition is used here, which means the third derivatives are
* continuous for the first two and last two segments. If
* `periodic_end_condition` is `true`, then the first and second derivatives
* between the end of the last segment and the beginning of the first
* segment will be continuous. Note that the periodic end condition does
* not require the first and last sample to be collocated, nor does it add
* an additional sample to connect the first and last segments. Only first
* and second derivative continuity is enforced.
* See https://en.wikipedia.org/wiki/Spline_interpolation and
* https://web.archive.org/web/20140125011904/https://www.math.uh.edu/~jingqiu/math4364/spline.pdf
* for more about cubic splines and their end conditions.
* The MATLAB docs for methods "spline" and "csape" are also good
* references.
*
* @pre `breaks` and `samples` must have at least 3 elements. If
* `periodic_end_condition` is `true`, then for two samples, it would
* produce a straight line (use `FirstOrderHold` for this instead), and if
* `periodic_end_condition` is `false` the problem is ill-defined.
* @pydrake_mkdoc_identifier{3args_matrix}
*/
static PiecewisePolynomial<T> CubicWithContinuousSecondDerivatives(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
bool periodic_end_condition = false);
/**
* Version of CubicWithContinuousSecondDerivatives(breaks, samples) that
* uses vector samples and Eigen VectorXd / MatrixX<T> arguments. Each column
* of `samples` represents a sample point.
*
* @pre `samples.cols() == breaks.size()`.
* @pydrake_mkdoc_identifier{3args_vector}
*/
static PiecewisePolynomial<T> CubicWithContinuousSecondDerivatives(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples,
bool periodic_end_condition = false);
/**
* Constructs a polynomial with a *single segment* of the lowest possible
* degree that passes through all of the sample points. See "polynomial
* interpolation" and/or "Lagrange polynomial" on Wikipedia for more
* information.
* @pre `times` must be monotonically increasing.
* @pre `samples.size() == times.size()`.
* @pydrake_mkdoc_identifier{matrix}
*/
static PiecewisePolynomial LagrangeInterpolatingPolynomial(
const std::vector<T>& times, const std::vector<MatrixX<T>>& samples);
/**
* Version of LagrangeInterpolatingPolynomial(times, samples) that
* uses vector samples and Eigen VectorXd / MatrixX<T> arguments. Each column
* of `samples` represents a sample point.
*
* @pre `samples.cols() == times.size()`.
* @pydrake_mkdoc_identifier{vector}
*/
static PiecewisePolynomial<T> LagrangeInterpolatingPolynomial(
const Eigen::Ref<const VectorX<T>>& times,
const Eigen::Ref<const MatrixX<T>>& samples);
// @}
/**
* Returns a %PiecewisePolynomial where each segment is the specified
* derivative of the corresponding segment in `this`. Any rules or limitations
* of Polynomial::derivative() also apply to this function.
*
* Derivatives evaluated at non-differentiable points return the value at the
* left hand side of the interval.
* @param derivative_order The order of the derivative, namely, if
* `derivative_order` = n, the n'th derivative of the polynomial will
* be returned.
* @warning In the event of discontinuous derivatives evaluated at breaks,
* it is not defined which polynomial (i.e., to the left or right
* of the break) will be the one that is evaluated at the break.
*/
PiecewisePolynomial<T> derivative(int derivative_order = 1) const;
/**
* Returns a %PiecewisePolynomial that is the indefinite integral of this one.
* Any rules or limitations of Polynomial::integral() also apply to this
* function.
*
* If `value_at_start_time` is given, it does the following only for the
* first segment: adds that constant as the constant term
* (zeroth-order coefficient) of the resulting Polynomial.
*/
PiecewisePolynomial<T> integral(const T& value_at_start_time = 0.0) const;
/**
* Returns a %PiecewisePolynomial that is the indefinite integral of this one.
* Any rules or limitations of Polynomial::integral() also apply to this
* function.
*
* If `value_at_start_time` is given, it does the following only for the
* first segment: adds `value_at_start_time(row,col)` as the constant term
* (zeroth-order coefficient) of the resulting Polynomial.
*/
PiecewisePolynomial<T> integral(
const Eigen::Ref<MatrixX<T>>& value_at_start_time) const;
/**
* Returns `true` if this trajectory has no breaks/samples/polynomials.
*/
bool empty() const { return polynomials_.empty(); }
/**
* Evaluates the trajectory at the given time without returning the entire
* matrix. Equivalent to value(t)(row, col).
* @warning See warnings in value().
*/
T scalarValue(const T& t, Eigen::Index row = 0, Eigen::Index col = 0) const;
/**
* Evaluates the %PiecewisePolynomial at the given time t.
*
* @param t The time at which to evaluate the %PiecewisePolynomial.
* @return The matrix of evaluated values.
* @pre If T == symbolic::Expression, `t.is_constant()` must be true.
*
* @warning If t does not lie in the range that the polynomial is defined
* over, the polynomial will silently be evaluated at the closest
* point to t. For example, `value(-1)` will return `value(0)` for a
* polynomial defined over [0, 1].
* @warning See warning in the @ref polynomial_warning "constructor overview"
* above.
*/
MatrixX<T> value(const T& t) const override {
const int derivative_order = 0;
return DoEvalDerivative(t, derivative_order);
}
/**
* Gets the matrix of Polynomials corresponding to the given segment index.
* @warning `segment_index` is not checked for validity.
*/
const PolynomialMatrix& getPolynomialMatrix(int segment_index) const;
/**
* Gets the Polynomial with the given matrix row and column index that
* corresponds to the given segment index.
* Equivalent to `getPolynomialMatrix(segment_index)(row, col)`.
* @note Calls PiecewiseTrajectory<T>::segment_number_range_check() to
* validate `segment_index`.
*/
const Polynomial<T>& getPolynomial(int segment_index, Eigen::Index row = 0,
Eigen::Index col = 0) const;
/**
* Gets the degree of the Polynomial with the given matrix row and column
* index that corresponds to the given segment index. Equivalent to
* `getPolynomial(segment_index, row, col).GetDegree()`.
*/
int getSegmentPolynomialDegree(int segment_index, Eigen::Index row = 0,
Eigen::Index col = 0) const;
/**
* Returns the row count of the output matrices.
* @throws std::exception if empty().
*/
Eigen::Index rows() const override;
/**
* Returns the column count of the output matrices.
* @throws std::exception if empty().
*/
Eigen::Index cols() const override;
/**
* Reshapes the dimensions of the Eigen::MatrixX<T> returned by value(),
* EvalDerivative(), etc.
*
* @pre @p rows x @p cols must equal this.rows() * this.cols().
* @see Eigen::PlainObjectBase::resize().
*/
void Reshape(int rows, int cols);
/** Constructs a new PiecewisePolynomial for which value(t) ==
* this.value(t).transpose(). */
PiecewisePolynomial Transpose() const;
/**
* Extracts a trajectory representing a block of size (block_rows, block_cols)
* starting at (start_row, start_col) from the PiecewisePolynomial.
* @returns a PiecewisePolynomial such that
* ret.value(t) = this.value(t).block(i,j,p,q);
*/
PiecewisePolynomial Block(int start_row, int start_col, int block_rows,
int block_cols) const;
/**
* Adds each Polynomial in the PolynomialMatrix of `other` to the
* corresponding Polynomial in the PolynomialMatrix of `this`, storing the
* result in `this`. If `this` corresponds to tΒ² and `other` corresponds to
* tΒ³, `this += other` will correspond to tΒ³ + tΒ².
* @throws std::exception if every element of `other.get_segment_times()`
* is not within PiecewiseTrajectory::kEpsilonTime from
* `this->get_segment_times().
*/
PiecewisePolynomial& operator+=(const PiecewisePolynomial& other);
/**
* Subtracts each Polynomial in the PolynomialMatrix of `other` from the
* corresponding Polynomial in the PolynomialMatrix of `this`, storing the
* result in `this`. If `this` corresponds to tΒ² and `other` corresponds to
* tΒ³, `this -= other` will correspond to tΒ² - tΒ³.
* @throws std::exception if every element of `other.get_segment_times()`
* is not within PiecewiseTrajectory::kEpsilonTime from
* `this->get_segment_times().
*/
PiecewisePolynomial& operator-=(const PiecewisePolynomial& other);
/**
* Multiplies each Polynomial in the PolynomialMatrix of `other` by the
* corresponding Polynomial in the PolynomialMatrix of `this` (i.e., a
* coefficient-wise multiplication), storing the result in `this`. If `this`
* corresponds to tΒ² and `other` corresponds to tΒ³, `this *= other` will
* correspond to tβ΅.
* @throws std::exception if every element of `other.get_segment_times()`
* is not within PiecewiseTrajectory::kEpsilonTime from
* `this->get_segment_times().
*/
PiecewisePolynomial& operator*=(const PiecewisePolynomial& other);
PiecewisePolynomial& operator+=(const MatrixX<T>& coeff);
PiecewisePolynomial& operator-=(const MatrixX<T>& coeff);
/**
* Adds each Polynomial in the PolynomialMatrix of `other` to the
* corresponding Polynomial in the PolynomialMatrix of `this`.
* If `this` corresponds to tΒ² and `other` corresponds to
* tΒ³, `this + other` will correspond to tΒ³ + tΒ².
* @throws std::exception if every element of `other.get_segment_times()`
* is not within PiecewiseTrajectory::kEpsilonTime from
* `this->get_segment_times().
*/
const PiecewisePolynomial operator+(const PiecewisePolynomial& other) const;
/**
* Subtracts each Polynomial in the PolynomialMatrix of `other` from the
* corresponding Polynomial in the PolynomialMatrix of `this`.
* If `this` corresponds to tΒ² and `other` corresponds to
* tΒ³, `this - other` will correspond to tΒ² - tΒ³.
* @throws std::exception if every element of `other.get_segment_times()`
* is not within PiecewiseTrajectory::kEpsilonTime from
* `this->get_segment_times().
*/
const PiecewisePolynomial operator-(const PiecewisePolynomial& other) const;
/**
* Implements unary minus operator. Multiplies each Polynomial in `this` by
* -1.
*/
const PiecewisePolynomial operator-() const;
/**
* Multiplies each Polynomial in the PolynomialMatrix of `other` by the
* corresponding Polynomial in the PolynomialMatrix of `this` (i.e., a
* coefficient-wise multiplication). If `this` corresponds to tΒ² and `other`
* corresponds to tΒ³, `this *= other` will correspond to tβ΅.
* @throws std::exception if every element of `other.get_segment_times()`
* is not within PiecewiseTrajectory::kEpsilonTime from
* `this->get_segment_times()1.
*/
const PiecewisePolynomial operator*(const PiecewisePolynomial& other) const;
const PiecewisePolynomial operator+(const MatrixX<T>& coeff) const;
const PiecewisePolynomial operator-(const MatrixX<T>& coeff) const;
// TODO(russt): Update return type to boolean<T> so that callers can obtain a
// Formula when T=symbolic::Expression.
/**
* Checks whether a %PiecewisePolynomial is approximately equal to this one by
* calling Polynomial<T>::CoefficientsAlmostEqual() on every element of every
* segment.
*
* @see Polynomial<T>::CoefficientsAlmostEqual().
*
*/
bool isApprox(const PiecewisePolynomial& other, double tol,
const ToleranceType& tol_type = ToleranceType::kRelative) const;
/**
* Concatenates `other` to the end of `this`.
*
* @warning The resulting %PiecewisePolynomial will only be continuous to the
* degree that the first Polynomial of `other` is continuous with
* the last Polynomial of `this`. See warning about evaluating
* discontinuous derivatives at breaks in derivative().
* @param other %PiecewisePolynomial instance to concatenate.
* @throws std::exception if trajectories' dimensions do not match
* each other (either rows() or cols() does
* not match between this and `other`).
* @throws std::exception if `this->end_time()` and `other->start_time()`
* are not within
* PiecewiseTrajectory<T>::kEpsilonTime from
* each other.
*/
void ConcatenateInTime(const PiecewisePolynomial& other);
/**
* The CubicHermite spline construction has a nice property of being
* incremental (each segment can be solved independently). Given a new sample
* and it's derivative, this method adds one segment to the end of `this`
* where the start sample and derivative are taken as the value and derivative
* at the final break of `this`.
*
* @pre `this` is not empty()
* @pre `time` > end_time()
* @pre `sample` and `sample_dot` must have size rows() x cols().
*/
void AppendCubicHermiteSegment(
const T& time, const Eigen::Ref<const MatrixX<T>>& sample,
const Eigen::Ref<const MatrixX<T>>& sample_dot);
/**
* Given a new sample, this method adds one segment to the end of `this` using
* a first-order hold, where the start sample is taken as the value at the
* final break of `this`. */
void AppendFirstOrderSegment(const T& time,
const Eigen::Ref<const MatrixX<T>>& sample);
/** Removes the final segment from the trajectory, reducing the number of
* segments by 1.
* @pre `this` is not empty()
*/
void RemoveFinalSegment();
/**
* Modifies the trajectory so that pp_after(t) = pp_before(-t).
*
* @note The new trajectory will evaluate differently at precisely the break
* points if the original trajectory was discontinuous at the break points.
* This is because the segments are defined on the half-open intervals
* [breaks(i), breaks(i+1)), and the order of the breaks have been reversed.
*/
void ReverseTime();
/**
* Scales the time of the trajectory by non-negative `scale` (use
* ReverseTime() if you want to also negate time). The resulting polynomial
* evaluates to pp_after(t) = pp_before(t/scale).
*
* As an example, `scale`=2 will result in a trajectory that is twice as long
* (start_time() and end_time() have both doubled).
*/
void ScaleTime(const T& scale);
/**
* Adds `offset` to all of the breaks. `offset` need not be a non-negative
* number. The resulting polynomial will evaluate to pp_after(t) =
* pp_before(t-offset).
*
* As an example, `offset`=2 will result in the start_time() and end_time()
* being 2 seconds later.
*/
void shiftRight(const T& offset);
/**
* Replaces the specified block of the PolynomialMatrix at the given
* segment index.
* @note Calls PiecewiseTrajectory<T>::segment_number_range_check() to
* validate `segment_index`.
* @warning This code relies upon Eigen to verify that the replacement
* block is not too large.
*/
void setPolynomialMatrixBlock(const PolynomialMatrix& replacement,
int segment_index, Eigen::Index row_start = 0,
Eigen::Index col_start = 0);
/**
* Returns the %PiecewisePolynomial comprising the `num_segments` segments
* starting at the specified `start_segment_index`.
* @note Calls PiecewiseTrajectory<T>::segment_number_range_check() to
* validate `segment_index`.
*/
PiecewisePolynomial slice(int start_segment_index, int num_segments) const;
/** Passes this object to an Archive.
* Refer to @ref yaml_serialization "YAML Serialization" for background.
* This method is only available when T = double. */
template <typename Archive>
#ifdef DRAKE_DOXYGEN_CXX
void
#else
// Restrict this method to T = double only; we must mix "Archive" into the
// conditional type for SFINAE to work, so we just check it against void.
std::enable_if_t<std::is_same_v<T, double> && !std::is_void_v<Archive>>
#endif
Serialize(Archive* a) {
auto [breaks, polynomials] = this->GetSerialized();
a->Visit(DRAKE_NVP(breaks));
a->Visit(DRAKE_NVP(polynomials));
SetSerialized(breaks, polynomials);
}
private:
// Evaluates the %PiecwisePolynomial derivative at the given time @p t.
// Returns the nth derivative, where `n` is the value of @p derivative_order.
//
// @warning This method comes with the same caveats as value(). See value()
// @pre derivative_order must be non-negative.
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const override;
std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order) const override {
return derivative(derivative_order).Clone();
}
bool do_has_derivative() const override { return true; }
T EvaluateSegmentAbsoluteTime(int segment_index, const T& t, Eigen::Index row,
Eigen::Index col,
int derivative_order = 0) const;
/* Returns (breaks_, polynomials_) in serializable form, where each Polynomial
in PolynomialMatrix serializes its coefficients as a vector indexed by the
variable power. */
std::tuple<std::vector<double>, std::vector<MatrixX<Eigen::VectorXd>>>
GetSerialized() const;
/* Resets `this` to the data returned by a previous call to GetSerialized. */
void SetSerialized(const std::vector<double>& breaks,
const std::vector<MatrixX<Eigen::VectorXd>>& polynomials);
// a PolynomialMatrix for each piece (segment).
std::vector<PolynomialMatrix> polynomials_;
// Computes coeffecients for a cubic spline given the value and first
// derivatives at the end points.
// Throws `std::exception` if `dt < PiecewiseTrajectory::kEpsilonTime`.
static Eigen::Matrix<T, 4, 1> ComputeCubicSplineCoeffs(const T& dt, T y0,
T y1, T yd0, T yd1);
// For a cubic spline, there are 4 unknowns for each segment Pi, namely
// the coefficients for Pi = a0 + a1 * t + a2 * t^2 + a3 * t^3.
// Let N be the size of breaks and samples, there are N-1 segments,
// and thus 4*(N-1) unknowns to fully specified a cubic spline for the given
// data.
//
// If we are also given N sample_dot (velocity), each Pi will be fully
// specified by (samples[i], sample_dot[i]) and (samples[i+1],
// sample_dot[i+1]). When sample_dot are not specified, we make the design
// choice to enforce continuity up to the second order (Yddot) for
// the interior points, i.e. Pi'(duration_i) = Pi+1'(0), and
// Pi''(duration_i) = Pi+1''(0), where ' means time derivative, and
// duration_i = breaks[i+1] - breaks[i] is the duration for the ith segment.
//
// At this point, we have 2 * (N - 1) position constraints:
// Pi(0) = samples[i], for i in [0, N - 2]
// Pi(duration_i) = samples[i+1], for i in [0, N - 2]
// N - 2 velocity constraints for the interior points:
// Pi'(duration_i) = Pi+1'(0), for i in [0, N - 3]
// N - 2 acceleration constraints for the interior points:
// Pi''(duration_i) = Pi+1''(0), for i in [0, N - 3]
//
// The first N - 1 position constraints can be used to directly eliminate the
// constant term of each segment as Pi(0) = a0_i. This reduces the number of
// unknowns to 3 * (N-1) and leaves 3 * (N-1) - 2 constraints. This function
// sets up the remaining constraints. There are still 2 constraints missing,
// which can be resolved by various end point conditions (velocity at the end
// points / "not-a-sample" / etc). These will be specified by the callers.
//
// This function performs the constraint setup for the row and column of the
// sample matrix specified by `row` & `col`. The coefficients for the
// left-hand-side of the constraint equations are prepared for loading into a
// sparse matrix by creating a vector of Triplets, `triplet_list` with each
// representing the row, column and value to add to the sparse matrix. The
// right-hand side of the constraint equations is loaded into `b`.
static int SetupCubicSplineInteriorCoeffsLinearSystem(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
int row, int col, std::vector<Eigen::Triplet<T>>* triplet_list,
VectorX<T>* b);
// Throws std::exception if
// `breaks` and `samples` have different length,
// `breaks` is not strictly increasing,
// `samples` has inconsistent dimensions,
// `breaks` has length smaller than min_length.
static void CheckSplineGenerationInputValidityOrThrow(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
int min_length);
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PiecewisePolynomial)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/bspline_trajectory.h | #pragma once
#include <memory>
#include <vector>
#include "drake/common/drake_bool.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/common/eigen_types.h"
#include "drake/common/name_value.h"
#include "drake/common/trajectories/trajectory.h"
#include "drake/math/bspline_basis.h"
namespace drake {
namespace trajectories {
/** Represents a B-spline curve using a given `basis` with ordered
`control_points` such that each control point is a matrix in βΚ³α΅Κ·Λ’ Λ£ αΆα΅Λ‘Λ’.
@see math::BsplineBasis
@tparam_default_scalar
*/
template <typename T>
class BsplineTrajectory final : public trajectories::Trajectory<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(BsplineTrajectory);
BsplineTrajectory() : BsplineTrajectory<T>({}, {}) {}
/** Constructs a B-spline trajectory with the given `basis` and
`control_points`.
@pre control_points.size() == basis.num_basis_functions() */
BsplineTrajectory(math::BsplineBasis<T> basis,
std::vector<MatrixX<T>> control_points);
#ifdef DRAKE_DOXYGEN_CXX
/** Constructs a T-valued B-spline trajectory from a double-valued `basis` and
T-valued `control_points`.
@pre control_points.size() == basis.num_basis_functions() */
BsplineTrajectory(math::BsplineBasis<double> basis,
std::vector<MatrixX<T>> control_points);
#else
template <typename U = T>
BsplineTrajectory(math::BsplineBasis<double> basis,
std::vector<MatrixX<T>> control_points,
typename std::enable_if_t<!std::is_same_v<U, double>>* = {})
: BsplineTrajectory(math::BsplineBasis<T>(basis), control_points) {}
#endif
virtual ~BsplineTrajectory() = default;
// Required methods for trajectories::Trajectory interface.
std::unique_ptr<trajectories::Trajectory<T>> Clone() const override;
/** Evaluates the BsplineTrajectory at the given time t.
@param t The time at which to evaluate the %BsplineTrajectory.
@return The matrix of evaluated values.
@pre If T == symbolic::Expression, `t.is_constant()` must be true.
@warning If t does not lie in the range [start_time(), end_time()], the
trajectory will silently be evaluated at the closest
valid value of time to t. For example, `value(-1)` will return
`value(0)` for a trajectory defined over [0, 1]. */
MatrixX<T> value(const T& time) const override;
Eigen::Index rows() const override { return control_points()[0].rows(); }
Eigen::Index cols() const override { return control_points()[0].cols(); }
T start_time() const override { return basis_.initial_parameter_value(); }
T end_time() const override { return basis_.final_parameter_value(); }
// Other methods
/** Returns the number of control points in this curve. */
int num_control_points() const { return basis_.num_basis_functions(); }
/** Returns the control points of this curve. */
const std::vector<MatrixX<T>>& control_points() const {
return control_points_;
}
/** Returns this->value(this->start_time()) */
MatrixX<T> InitialValue() const;
/** Returns this->value(this->end_time()) */
MatrixX<T> FinalValue() const;
/** Returns the basis of this curve. */
const math::BsplineBasis<T>& basis() const { return basis_; }
/** Adds new knots at the specified `additional_knots` without changing the
behavior of the trajectory. The basis and control points of the trajectory are
adjusted such that it produces the same value for any valid time before and
after this method is called. The resulting trajectory is guaranteed to have
the same level of continuity as the original, even if knot values are
duplicated. Note that `additional_knots` need not be sorted.
@pre start_time() <= t <= end_time() for all t in `additional_knots` */
void InsertKnots(const std::vector<T>& additional_knots);
/** Returns a new BsplineTrajectory that uses the same basis as `this`, and
whose control points are the result of calling `select(point)` on each `point`
in `this->control_points()`.*/
BsplineTrajectory<T> CopyWithSelector(
const std::function<MatrixX<T>(const MatrixX<T>&)>& select) const;
/** Returns a new BsplineTrajectory that uses the same basis as `this`, and
whose control points are the result of calling
`point.block(start_row, start_col, block_rows, block_cols)` on each `point`
in `this->control_points()`.*/
BsplineTrajectory<T> CopyBlock(int start_row, int start_col, int block_rows,
int block_cols) const;
/** Returns a new BsplineTrajectory that uses the same basis as `this`, and
whose control points are the result of calling `point.head(n)` on each `point`
in `this->control_points()`.
@pre this->cols() == 1
@pre control_points()[0].head(n) must be a valid operation. */
BsplineTrajectory<T> CopyHead(int n) const;
boolean<T> operator==(const BsplineTrajectory<T>& other) const;
/** Passes this object to an Archive.
Refer to @ref yaml_serialization "YAML Serialization" for background.
This method is only available when T = double. */
template <typename Archive>
#ifdef DRAKE_DOXYGEN_CXX
void
#else
// Restrict this method to T = double only; we must mix "Archive" into the
// conditional type for SFINAE to work, so we just check it against void.
std::enable_if_t<std::is_same_v<T, double> && !std::is_void_v<Archive>>
#endif
Serialize(Archive* a) {
a->Visit(MakeNameValue("basis", &basis_));
a->Visit(MakeNameValue("control_points", &control_points_));
CheckInvariants();
}
private:
bool do_has_derivative() const override;
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const override;
std::unique_ptr<trajectories::Trajectory<T>> DoMakeDerivative(
int derivative_order) const override;
void CheckInvariants() const;
math::BsplineBasis<T> basis_;
std::vector<MatrixX<T>> control_points_;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::BsplineTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/exponential_plus_piecewise_polynomial.h | #pragma once
#include <memory>
#include <vector>
#include <Eigen/Core>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
namespace drake {
namespace trajectories {
/**
Represents a piecewise-trajectory with piece @f$j@f$ given by:
@f[
x(t) = K e^{A (t - t_j)} \alpha_j + \sum_{i=0}^k \beta_{j,i}(t-t_j)^i,
@f]
where @f$k@f$ is the order of the `piecewise_polynomial_part` and @f$t_j@f$ is
the start time of the @f$j@f$-th segment.
This particular form can represent the solution to a linear dynamical system
driven by a piecewise-polynomial input:
@f[
\dot{x}(t) = A x(t) + B u(t),
@f]
where the input @f$ u(t) @f$ is a piecewise-polynomial function of time. See
[1] for details and a motivating use case.
[1] R. Tedrake, S. Kuindersma, R. Deits and K. Miura, "A closed-form solution
for real-time ZMP gait generation and feedback stabilization,"
2015 IEEE-RAS 15th International Conference on Humanoid Robots (Humanoids),
Seoul, 2015, pp. 936-940.
@tparam_double_only
*/
template <typename T>
class ExponentialPlusPiecewisePolynomial final : public PiecewiseTrajectory<T> {
public:
// We are final, so this is okay.
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ExponentialPlusPiecewisePolynomial)
ExponentialPlusPiecewisePolynomial() = default;
template <typename DerivedK, typename DerivedA, typename DerivedAlpha>
ExponentialPlusPiecewisePolynomial(
const Eigen::MatrixBase<DerivedK>& K,
const Eigen::MatrixBase<DerivedA>& A,
const Eigen::MatrixBase<DerivedAlpha>& alpha,
const PiecewisePolynomial<T>& piecewise_polynomial_part)
: PiecewiseTrajectory<T>(piecewise_polynomial_part),
K_(K),
A_(A),
alpha_(alpha),
piecewise_polynomial_part_(piecewise_polynomial_part) {
DRAKE_ASSERT(K.rows() == rows());
DRAKE_ASSERT(K.cols() == A.rows());
DRAKE_ASSERT(A.rows() == A.cols());
DRAKE_ASSERT(alpha.rows() == A.cols());
DRAKE_ASSERT(alpha.cols() ==
piecewise_polynomial_part.get_number_of_segments());
DRAKE_ASSERT(piecewise_polynomial_part.rows() == rows());
DRAKE_ASSERT(piecewise_polynomial_part.cols() == 1);
}
// from PiecewisePolynomial
ExponentialPlusPiecewisePolynomial(
const PiecewisePolynomial<T>& piecewise_polynomial_part);
~ExponentialPlusPiecewisePolynomial() override = default;
std::unique_ptr<Trajectory<T>> Clone() const override;
MatrixX<T> value(const T& t) const override;
ExponentialPlusPiecewisePolynomial derivative(int derivative_order = 1) const;
Eigen::Index rows() const override;
Eigen::Index cols() const override;
void shiftRight(double offset);
private:
std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order = 1) const override {
return derivative(derivative_order).Clone();
};
MatrixX<T> K_;
MatrixX<T> A_;
MatrixX<T> alpha_;
PiecewisePolynomial<T> piecewise_polynomial_part_;
};
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/piecewise_quaternion.h | #pragma once
#include <memory>
#include <vector>
#include "drake/common/default_scalars.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/trajectories/piecewise_trajectory.h"
#include "drake/math/rotation_matrix.h"
namespace drake {
namespace trajectories {
/**
* A class representing a trajectory for quaternions that are interpolated
* using piecewise slerp (spherical linear interpolation).
* All the orientation samples are expected to be with respect to the same
* parent reference frame, i.e. q_i represents the rotation R_PBi for the
* orientation of frame B at the ith sample in a fixed parent frame P.
* The world frame is a common choice for the parent frame.
* The angular velocity and acceleration are also relative to the parent frame
* and expressed in the parent frame.
* Since there is a sign ambiguity when using quaternions to represent
* orientation, namely q and -q represent the same orientation, the internal
* quaternion representations ensure that q_n.dot(q_{n+1}) >= 0.
* Another intuitive way to think about this is that consecutive quaternions
* have the shortest geodesic distance on the unit sphere.
* Note that the quarternion value is in w, x, y, z order when represented as
* a Vector4.
*
* @tparam_default_scalar
*/
template <typename T>
class PiecewiseQuaternionSlerp final : public PiecewiseTrajectory<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PiecewiseQuaternionSlerp)
/**
* Builds an empty PiecewiseQuaternionSlerp.
*/
PiecewiseQuaternionSlerp() = default;
/**
* Builds a PiecewiseQuaternionSlerp.
* @throws std::exception if breaks and quaternions have different length,
* or breaks have length < 2.
*/
PiecewiseQuaternionSlerp(const std::vector<T>& breaks,
const std::vector<Quaternion<T>>& quaternions);
/**
* Builds a PiecewiseQuaternionSlerp.
* @throws std::exception if breaks and rot_matrices have different length,
* or breaks have length < 2.
*/
PiecewiseQuaternionSlerp(const std::vector<T>& breaks,
const std::vector<Matrix3<T>>& rotation_matrices);
/**
* Builds a PiecewiseQuaternionSlerp.
* @throws std::exception if breaks and rot_matrices have different length,
* or breaks have length < 2.
*/
PiecewiseQuaternionSlerp(
const std::vector<T>& breaks,
const std::vector<math::RotationMatrix<T>>& rotation_matrices);
/**
* Builds a PiecewiseQuaternionSlerp.
* @throws std::exception if breaks and ang_axes have different length,
* or breaks have length < 2.
*/
PiecewiseQuaternionSlerp(const std::vector<T>& breaks,
const std::vector<AngleAxis<T>>& angle_axes);
~PiecewiseQuaternionSlerp() override = default;
std::unique_ptr<Trajectory<T>> Clone() const override;
Eigen::Index rows() const override { return 4; }
Eigen::Index cols() const override { return 1; }
/**
* Interpolates orientation.
* @param time Time for interpolation.
* @return The interpolated quaternion at `time`.
*/
Quaternion<T> orientation(const T& time) const;
MatrixX<T> value(const T& time) const override {
const Quaternion<T> quat = orientation(time);
return Vector4<T>(quat.w(), quat.x(), quat.y(), quat.z());
}
/**
* Interpolates angular velocity.
* @param time Time for interpolation.
* @return The interpolated angular velocity at `time`,
* which is constant per segment.
*/
Vector3<T> angular_velocity(const T& time) const;
/**
* Interpolates angular acceleration.
* @param time Time for interpolation.
* @return The interpolated angular acceleration at `time`,
* which is always zero for slerp.
*/
Vector3<T> angular_acceleration(const T& time) const;
/**
* Getter for the internal quaternion samples.
*
* @note The returned quaternions might be different from the ones used for
* construction because the internal representations are set to always be
* the "closest" w.r.t to the previous one.
*
* @return the internal sample points.
*/
const std::vector<Quaternion<T>>& get_quaternion_samples() const {
return quaternions_;
}
/**
* Returns true if all the corresponding segment times are within
* @p tol seconds, and the angle difference between the corresponding
* quaternion sample points are within @p tol (using `ExtractDoubleOrThrow`).
*/
bool is_approx(const PiecewiseQuaternionSlerp<T>& other, double tol) const;
/**
* Given a new Quaternion, this method adds one segment to the end of `this`.
*/
void Append(const T& time, const Quaternion<T>& quaternion);
/**
* Given a new RotationMatrix, this method adds one segment to the end of
* `this`.
*/
void Append(const T& time, const math::RotationMatrix<T>& rotation_matrix);
/**
* Given a new AngleAxis, this method adds one segment to the end of `this`.
*/
void Append(const T& time, const AngleAxis<T>& angle_axis);
private:
// Initialize quaternions_ and computes angular velocity for each segment.
void Initialize(const std::vector<T>& breaks,
const std::vector<Quaternion<T>>& quaternions);
// Computes the interpolation time within each segment. Result is in [0, 1].
T ComputeInterpTime(int segment_index, const T& time) const;
bool do_has_derivative() const override;
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const override;
std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order) const override;
std::vector<Quaternion<T>> quaternions_;
std::vector<Vector3<T>> angular_velocities_;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PiecewiseQuaternionSlerp)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/composite_trajectory.cc | #include "drake/common/trajectories/composite_trajectory.h"
#include <utility>
#include "drake/common/text_logging.h"
#include "drake/common/trajectories/piecewise_trajectory.h"
namespace drake {
namespace trajectories {
namespace {
template <typename T>
std::vector<T> ExtractBreaks(
const std::vector<copyable_unique_ptr<Trajectory<T>>>& segments) {
std::vector<T> breaks(segments.size() + 1);
if (segments.empty()) {
breaks[0] = 0;
return breaks;
}
for (int i = 0; i < static_cast<int>(segments.size()); ++i) {
if (i > 0) {
DRAKE_DEMAND(segments[i]->start_time() == segments[i - 1]->end_time());
}
breaks[i] = segments[i]->start_time();
}
breaks.back() = segments.back()->end_time();
return breaks;
}
} // namespace
template <typename T>
CompositeTrajectory<T>::CompositeTrajectory(
std::vector<copyable_unique_ptr<Trajectory<T>>> segments)
: PiecewiseTrajectory<T>(ExtractBreaks(segments)),
segments_(std::move(segments)) {
for (int i = 1; i < static_cast<int>(segments_.size()); ++i) {
DRAKE_DEMAND(segments_[i]->rows() == segments_[0]->rows());
DRAKE_DEMAND(segments_[i]->cols() == segments_[0]->cols());
}
}
template <typename T>
std::unique_ptr<Trajectory<T>> CompositeTrajectory<T>::Clone() const {
return std::make_unique<CompositeTrajectory<T>>(segments_);
}
template <typename T>
Eigen::Index CompositeTrajectory<T>::rows() const {
if (segments_.size() > 0) {
return segments_[0]->rows();
} else {
throw std::runtime_error(
"CompositeTrajectory has no segments. Number of rows is undefined.");
}
}
template <typename T>
Eigen::Index CompositeTrajectory<T>::cols() const {
if (segments_.size() > 0) {
return segments_[0]->cols();
} else {
throw std::runtime_error(
"CompositeTrajectory has no segments. Number of cols is undefined.");
}
}
template <typename T>
MatrixX<T> CompositeTrajectory<T>::value(const T& time) const {
const int segment_index = this->get_segment_index(time);
DRAKE_DEMAND(static_cast<int>(segments_.size()) > segment_index);
return this->segments_[segment_index]->value(time);
}
template <typename T>
bool CompositeTrajectory<T>::do_has_derivative() const {
return std::all_of(segments_.begin(), segments_.end(),
[](const auto& segment) {
return segment->has_derivative();
});
}
template <typename T>
MatrixX<T> CompositeTrajectory<T>::DoEvalDerivative(
const T& time, int derivative_order) const {
const int segment_index = this->get_segment_index(time);
DRAKE_DEMAND(static_cast<int>(segments_.size()) > segment_index);
return this->segments_[segment_index]->EvalDerivative(time, derivative_order);
}
template <typename T>
std::unique_ptr<Trajectory<T>> CompositeTrajectory<T>::DoMakeDerivative(
int derivative_order) const {
DRAKE_DEMAND(derivative_order >= 0);
if (derivative_order == 0) {
return this->Clone();
}
std::vector<copyable_unique_ptr<Trajectory<T>>> derivative_curves(
segments_.size());
for (int i = 0; i < static_cast<int>(segments_.size()); ++i) {
derivative_curves[i] = segments_[i]->MakeDerivative(derivative_order);
}
return std::make_unique<CompositeTrajectory<T>>(std::move(derivative_curves));
}
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class CompositeTrajectory);
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/piecewise_polynomial.cc | #include "drake/common/trajectories/piecewise_polynomial.h"
#include <algorithm>
#include <memory>
#include <utility>
#include <Eigen/SparseCore>
#include <Eigen/SparseLU>
#include <fmt/format.h>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
#include "drake/common/unused.h"
#include "drake/math/matrix_util.h"
using Eigen::VectorXd;
using std::abs;
using std::clamp;
using std::max;
using std::runtime_error;
using std::vector;
namespace drake {
namespace trajectories {
using math::EigenToStdVector;
template <typename T>
PiecewisePolynomial<T>::PiecewisePolynomial(
const std::vector<PolynomialMatrix>& polynomials,
const std::vector<T>& breaks)
: PiecewiseTrajectory<T>(breaks), polynomials_(polynomials) {
DRAKE_ASSERT(breaks.size() == (polynomials.size() + 1));
for (int i = 1; i < this->get_number_of_segments(); i++) {
if (polynomials[i].rows() != polynomials[0].rows())
throw std::runtime_error(
"The polynomial matrix for each segment must have the same number of "
"rows.");
if (polynomials[i].cols() != polynomials[0].cols())
throw std::runtime_error(
"The polynomial matrix for each segment must have the same number of "
"columns.");
}
}
template <typename T>
PiecewisePolynomial<T>::PiecewisePolynomial(
const std::vector<Polynomial<T>>& polynomials, const std::vector<T>& breaks)
: PiecewiseTrajectory<T>(breaks) {
DRAKE_ASSERT(breaks.size() == (polynomials.size() + 1));
for (size_t i = 0; i < polynomials.size(); i++) {
PolynomialMatrix matrix(1, 1);
matrix(0, 0) = polynomials[i];
polynomials_.push_back(matrix);
}
}
template <typename T>
std::unique_ptr<Trajectory<T>> PiecewisePolynomial<T>::Clone() const {
return std::make_unique<PiecewisePolynomial<T>>(*this);
}
template <typename T>
std::tuple<std::vector<double>, std::vector<MatrixX<VectorXd>>>
PiecewisePolynomial<T>::GetSerialized() const {
if constexpr (!std::is_same_v<T, double>) {
DRAKE_UNREACHABLE();
} else {
std::vector<MatrixX<VectorXd>> polynomials(polynomials_.size());
// Copy the polynomials_'s coefficients into polynomials.
int max_degree = 0;
for (int i = 0; i < static_cast<int>(polynomials.size()); ++i) {
const MatrixX<Polynomial<double>>& ith_in = polynomials_[i];
MatrixX<VectorXd>& ith_out = polynomials[i];
ith_out.resize(ith_in.rows(), ith_in.cols());
for (int j = 0; j < ith_in.rows(); ++j) {
for (int k = 0; k < ith_in.cols(); ++k) {
ith_out(j, k) = ith_in(j, k).GetCoefficients();
max_degree = std::max(max_degree, ith_in(j, k).GetDegree());
}
}
}
// Always output a square ndarray with shape=(npoly, nrow, ncol, ncoeff).
for (int i = 0; i < static_cast<int>(polynomials.size()); ++i) {
MatrixX<VectorXd>& ith_out = polynomials[i];
for (int j = 0; j < ith_out.rows(); ++j) {
for (int k = 0; k < ith_out.cols(); ++k) {
const int old_size = ith_out(j, k).size();
ith_out(j, k).conservativeResize(max_degree + 1);
for (int z = old_size; z < max_degree + 1; ++z) {
ith_out(j, k)(z) = 0.0;
}
}
}
}
return std::make_tuple(this->breaks(), std::move(polynomials));
}
}
template <typename T>
void PiecewisePolynomial<T>::SetSerialized(
const std::vector<double>& breaks,
const std::vector<MatrixX<VectorXd>>& polynomials) {
if constexpr (!std::is_same_v<T, double>) {
unused(breaks, polynomials);
DRAKE_UNREACHABLE();
} else {
if (breaks.empty() && polynomials.empty()) {
*this = PiecewisePolynomial<double>();
return;
}
if (breaks.size() != polynomials.size() + 1) {
throw std::logic_error(fmt::format(
"PiecewisePolynomial deserialization must provide "
"len(breaks) == len(polynomials) + 1, but had len(breaks) == {} and "
"len(polynomials) == {}",
breaks.size(), polynomials.size()));
}
for (int n = 1; n < static_cast<int>(polynomials.size()); ++n) {
if ((polynomials[n].rows() != polynomials[0].rows()) ||
(polynomials[n].cols() != polynomials[0].cols())) {
throw std::logic_error(fmt::format(
"PiecewisePolynomial deserialization must provide consistently "
"sized polynomial matrices, but polynomials[{}] had shape ({}, {}) "
"yet all prior polynomials had shape ({}, {})",
n, polynomials[n].rows(), polynomials[n].cols(),
polynomials[0].rows(), polynomials[0].cols()));
}
}
this->get_mutable_breaks() = breaks;
polynomials_.resize(polynomials.size());
for (int i = 0; i < static_cast<int>(polynomials.size()); ++i) {
const MatrixX<VectorXd>& ith_in = polynomials[i];
MatrixX<Polynomial<double>>& ith_out = polynomials_[i];
ith_out.resize(ith_in.rows(), ith_in.cols());
for (int j = 0; j < ith_in.rows(); ++j) {
for (int k = 0; k < ith_in.cols(); ++k) {
ith_out(j, k) = Polynomial<double>(ith_in(j, k));
}
}
}
}
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::derivative(
int derivative_order) const {
DRAKE_DEMAND(derivative_order >= 0);
PiecewisePolynomial ret = *this;
if (derivative_order == 0) {
return ret;
}
for (auto it = ret.polynomials_.begin(); it != ret.polynomials_.end(); ++it) {
PolynomialMatrix& matrix = *it;
for (Eigen::Index row = 0; row < rows(); row++) {
for (Eigen::Index col = 0; col < cols(); col++) {
matrix(row, col) = matrix(row, col).Derivative(derivative_order);
}
}
}
return ret;
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::integral(
const T& value_at_start_time) const {
MatrixX<T> matrix_value_at_start_time =
MatrixX<T>::Constant(rows(), cols(), value_at_start_time);
return integral(matrix_value_at_start_time);
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::integral(
const Eigen::Ref<MatrixX<T>>& value_at_start_time) const {
PiecewisePolynomial ret = *this;
for (int segment_index = 0; segment_index < this->get_number_of_segments();
segment_index++) {
PolynomialMatrix& matrix = ret.polynomials_[segment_index];
for (Eigen::Index row = 0; row < rows(); row++) {
for (Eigen::Index col = 0; col < cols(); col++) {
if (segment_index == 0) {
matrix(row, col) =
matrix(row, col).Integral(value_at_start_time(row, col));
} else {
matrix(row, col) =
matrix(row, col).Integral(ret.EvaluateSegmentAbsoluteTime(
segment_index - 1, this->start_time(segment_index), row,
col));
}
}
}
}
return ret;
}
template <typename T>
T PiecewisePolynomial<T>::scalarValue(const T& t, Eigen::Index row,
Eigen::Index col) const {
int segment_index = this->get_segment_index(t);
return EvaluateSegmentAbsoluteTime(segment_index, t, row, col);
}
template <typename T>
MatrixX<T> PiecewisePolynomial<T>::DoEvalDerivative(
const T& t, int derivative_order) const {
const int segment_index = this->get_segment_index(t);
const T time = clamp(t, this->start_time(), this->end_time());
Eigen::Matrix<T, PolynomialMatrix::RowsAtCompileTime,
PolynomialMatrix::ColsAtCompileTime>
ret(rows(), cols());
for (Eigen::Index row = 0; row < rows(); row++) {
for (Eigen::Index col = 0; col < cols(); col++) {
ret(row, col) = EvaluateSegmentAbsoluteTime(segment_index, time, row, col,
derivative_order);
}
}
return ret;
}
template <typename T>
const typename PiecewisePolynomial<T>::PolynomialMatrix&
PiecewisePolynomial<T>::getPolynomialMatrix(int segment_index) const {
return polynomials_[segment_index];
}
template <typename T>
const Polynomial<T>& PiecewisePolynomial<T>::getPolynomial(
int segment_index, Eigen::Index row, Eigen::Index col) const {
this->segment_number_range_check(segment_index);
return polynomials_[segment_index](row, col);
}
template <typename T>
int PiecewisePolynomial<T>::getSegmentPolynomialDegree(int segment_index,
Eigen::Index row,
Eigen::Index col) const {
this->segment_number_range_check(segment_index);
return polynomials_[segment_index](row, col).GetDegree();
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator+=(
const PiecewisePolynomial<T>& other) {
if (!this->SegmentTimesEqual(other))
throw runtime_error(
"Addition not yet implemented when segment times are not equal");
for (size_t i = 0; i < polynomials_.size(); i++)
polynomials_[i] += other.polynomials_[i];
return *this;
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator-=(
const PiecewisePolynomial<T>& other) {
if (!this->SegmentTimesEqual(other))
throw runtime_error(
"Subtraction not yet implemented when segment times are not equal");
for (size_t i = 0; i < polynomials_.size(); i++)
polynomials_[i] -= other.polynomials_[i];
return *this;
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator*=(
const PiecewisePolynomial<T>& other) {
if (!this->SegmentTimesEqual(other))
throw runtime_error(
"Multiplication not yet implemented when segment times are not equal");
for (size_t i = 0; i < polynomials_.size(); i++) {
polynomials_[i] *= other.polynomials_[i];
}
return *this;
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator+=(
const MatrixX<T>& offset) {
for (size_t i = 0; i < polynomials_.size(); i++)
polynomials_[i] += offset.template cast<Polynomial<T>>();
return *this;
}
template <typename T>
PiecewisePolynomial<T>& PiecewisePolynomial<T>::operator-=(
const MatrixX<T>& offset) {
for (size_t i = 0; i < polynomials_.size(); i++)
polynomials_[i] -= offset.template cast<Polynomial<T>>();
return *this;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator+(
const PiecewisePolynomial<T>& other) const {
PiecewisePolynomial<T> ret = *this;
ret += other;
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator-(
const PiecewisePolynomial<T>& other) const {
PiecewisePolynomial<T> ret = *this;
ret -= other;
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator-() const {
PiecewisePolynomial<T> ret = *this;
for (size_t i = 0; i < polynomials_.size(); i++) {
ret.polynomials_[i] = -polynomials_[i];
}
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator*(
const PiecewisePolynomial<T>& other) const {
PiecewisePolynomial<T> ret = *this;
ret *= other;
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator+(
const MatrixX<T>& offset) const {
PiecewisePolynomial<T> ret = *this;
ret += offset;
return ret;
}
template <typename T>
const PiecewisePolynomial<T> PiecewisePolynomial<T>::operator-(
const MatrixX<T>& offset) const {
PiecewisePolynomial<T> ret = *this;
ret -= offset;
return ret;
}
template <typename T>
bool PiecewisePolynomial<T>::isApprox(const PiecewisePolynomial<T>& other,
double tol,
const ToleranceType& tol_type) const {
if (rows() != other.rows() || cols() != other.cols()) return false;
if (!this->SegmentTimesEqual(other, tol)) return false;
for (int segment_index = 0; segment_index < this->get_number_of_segments();
segment_index++) {
const PolynomialMatrix& matrix = polynomials_[segment_index];
const PolynomialMatrix& other_matrix = other.polynomials_[segment_index];
for (Eigen::Index row = 0; row < rows(); row++) {
for (Eigen::Index col = 0; col < cols(); col++) {
if (!matrix(row, col).CoefficientsAlmostEqual(other_matrix(row, col),
tol, tol_type)) {
return false;
}
}
}
}
return true;
}
template <typename T>
void PiecewisePolynomial<T>::ConcatenateInTime(
const PiecewisePolynomial<T>& other) {
if (!empty()) {
// Performs basic sanity checks.
DRAKE_THROW_UNLESS(this->rows() == other.rows());
DRAKE_THROW_UNLESS(this->cols() == other.cols());
const T time_offset = other.start_time() - this->end_time();
// Absolute tolerance is scaled along with the time scale.
const T absolute_tolerance = max(abs(this->end_time()), 1.0) *
std::numeric_limits<double>::epsilon();
DRAKE_THROW_UNLESS(abs(time_offset) < absolute_tolerance);
// Gets instance breaks.
std::vector<T>& breaks = this->get_mutable_breaks();
// Drops first break to avoid duplication.
breaks.pop_back();
// Concatenates other breaks, while shifting them appropriately
// for both trajectories to be time-aligned.
for (const T& other_break : other.breaks()) {
breaks.push_back(other_break - time_offset);
}
// Concatenates other polynomials.
polynomials_.insert(polynomials_.end(), other.polynomials_.begin(),
other.polynomials_.end());
} else {
std::vector<T>& breaks = this->get_mutable_breaks();
breaks = other.breaks();
polynomials_ = other.polynomials_;
}
}
template <typename T>
void PiecewisePolynomial<T>::AppendCubicHermiteSegment(
const T& time, const Eigen::Ref<const MatrixX<T>>& sample,
const Eigen::Ref<const MatrixX<T>>& sample_dot) {
DRAKE_DEMAND(!empty());
DRAKE_DEMAND(time > this->end_time());
DRAKE_DEMAND(sample.rows() == rows());
DRAKE_DEMAND(sample.cols() == cols());
DRAKE_DEMAND(sample_dot.rows() == rows());
DRAKE_DEMAND(sample_dot.cols() == cols());
const int segment_index = polynomials_.size() - 1;
const T dt = time - this->end_time();
PolynomialMatrix matrix(rows(), cols());
for (int row = 0; row < rows(); ++row) {
for (int col = 0; col < cols(); ++col) {
const T start = EvaluateSegmentAbsoluteTime(segment_index,
this->end_time(), row, col);
const int derivative_order = 1;
const T start_dot = EvaluateSegmentAbsoluteTime(
segment_index, this->end_time(), row, col, derivative_order);
Vector4<T> coeffs = ComputeCubicSplineCoeffs(
dt, start, sample(row, col), start_dot, sample_dot(row, col));
matrix(row, col) = Polynomial<T>(coeffs);
}
}
polynomials_.push_back(std::move(matrix));
this->get_mutable_breaks().push_back(time);
}
template <typename T>
void PiecewisePolynomial<T>::AppendFirstOrderSegment(
const T& time, const Eigen::Ref<const MatrixX<T>>& sample) {
DRAKE_DEMAND(!empty());
DRAKE_DEMAND(time > this->end_time());
DRAKE_DEMAND(sample.rows() == rows());
DRAKE_DEMAND(sample.cols() == cols());
const int segment_index = polynomials_.size() - 1;
const T dt = time - this->end_time();
PolynomialMatrix matrix(rows(), cols());
for (int row = 0; row < rows(); ++row) {
for (int col = 0; col < cols(); ++col) {
const T start = EvaluateSegmentAbsoluteTime(segment_index,
this->end_time(), row, col);
matrix(row, col) = Polynomial<T>(
Eigen::Matrix<T, 2, 1>(start, (sample(row, col) - start) / dt));
}
}
polynomials_.push_back(std::move(matrix));
this->get_mutable_breaks().push_back(time);
}
template <typename T>
void PiecewisePolynomial<T>::RemoveFinalSegment() {
DRAKE_DEMAND(!empty());
polynomials_.pop_back();
this->get_mutable_breaks().pop_back();
}
template <typename T>
void PiecewisePolynomial<T>::ReverseTime() {
using std::pow;
const std::vector<T>& b = this->breaks();
// Update the coefficients.
for (int i = 0; i < this->get_number_of_segments(); i++) {
PolynomialMatrix& matrix = polynomials_[i];
const T h = b[i + 1] - b[i];
for (int row = 0; row < rows(); row++) {
for (int col = 0; col < cols(); col++) {
const int d = matrix(row, col).GetDegree();
if (d == 0) continue;
// Must shift this segment by h, because it will now be evaluated
// relative to breaks[i+1] instead of breaks[i], via p_after(t) =
// p_before(t+h). But we can perform the time-reversal at the same
// time, using the variant p_after(t) = p_before(h-t).
const auto& vars = matrix(row, col).GetVariables();
DRAKE_ASSERT(vars.size() == 1);
const typename Polynomial<T>::VarType& t = *vars.begin();
matrix(row, col) =
matrix(row, col).Substitute(t, h - Polynomial<T>(1.0, t));
}
}
}
// Reverse the order of the breaks and polynomials.
std::vector<T>& breaks = this->get_mutable_breaks();
std::reverse(breaks.begin(), breaks.end());
std::reverse(polynomials_.begin(), polynomials_.end());
// Update the breaks.
for (auto it = breaks.begin(); it != breaks.end(); ++it) {
*it *= -1.0;
}
}
template <typename T>
void PiecewisePolynomial<T>::ScaleTime(const T& scale) {
using std::pow;
DRAKE_DEMAND(scale > 0.0);
// Update the coefficients.
for (int i = 0; i < this->get_number_of_segments(); i++) {
PolynomialMatrix& matrix = polynomials_[i];
for (int row = 0; row < rows(); row++) {
for (int col = 0; col < cols(); col++) {
const int d = matrix(row, col).GetDegree();
if (d == 0) continue;
VectorX<T> coeffs = matrix(row, col).GetCoefficients();
for (int p = 1; p < d + 1; p++) {
coeffs(p) /= pow(scale, p);
}
matrix(row, col) = Polynomial<T>(coeffs);
}
}
}
// Update the breaks.
std::vector<T>& breaks = this->get_mutable_breaks();
for (auto it = breaks.begin(); it != breaks.end(); ++it) {
*it *= scale;
}
}
template <typename T>
void PiecewisePolynomial<T>::shiftRight(const T& offset) {
std::vector<T>& breaks = this->get_mutable_breaks();
for (auto it = breaks.begin(); it != breaks.end(); ++it) {
*it += offset;
}
}
template <typename T>
void PiecewisePolynomial<T>::setPolynomialMatrixBlock(
const typename PiecewisePolynomial<T>::PolynomialMatrix& replacement,
int segment_number, Eigen::Index row_start, Eigen::Index col_start) {
this->segment_number_range_check(segment_number);
polynomials_[segment_number].block(row_start, col_start, replacement.rows(),
replacement.cols()) = replacement;
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::slice(int start_segment_index,
int num_segments) const {
this->segment_number_range_check(start_segment_index);
this->segment_number_range_check(start_segment_index + num_segments - 1);
auto breaks_start_it = this->breaks().begin() + start_segment_index;
auto breaks_slice = vector<T>(
breaks_start_it,
breaks_start_it + num_segments +
1); // + 1 because there's one more segment times than segments.
auto polynomials_start_it = polynomials_.begin() + start_segment_index;
auto polynomials_slice = vector<PolynomialMatrix>(
polynomials_start_it, polynomials_start_it + num_segments);
return PiecewisePolynomial<T>(polynomials_slice, breaks_slice);
}
template <typename T>
T PiecewisePolynomial<T>::EvaluateSegmentAbsoluteTime(
int segment_index, const T& t, Eigen::Index row, Eigen::Index col,
int derivative_order) const {
DRAKE_DEMAND(static_cast<int>(polynomials_.size()) > segment_index);
return polynomials_[segment_index](row, col).EvaluateUnivariate(
t - this->start_time(segment_index), derivative_order);
}
template <typename T>
Eigen::Index PiecewisePolynomial<T>::rows() const {
if (polynomials_.size() > 0) {
return polynomials_[0].rows();
} else {
throw std::runtime_error(
"PiecewisePolynomial has no segments. Number of rows is undefined.");
}
}
template <typename T>
Eigen::Index PiecewisePolynomial<T>::cols() const {
if (polynomials_.size() > 0) {
return polynomials_[0].cols();
} else {
throw std::runtime_error(
"PiecewisePolynomial has no segments. Number of columns is undefined.");
}
}
template <typename T>
void PiecewisePolynomial<T>::Reshape(int rows, int cols) {
DRAKE_DEMAND(rows * cols == this->rows() * this->cols());
for (auto& p : polynomials_) {
// Accordining to the Eigen documentation, data is preserved when the total
// number of elements does not change.
p.resize(rows, cols);
}
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::Transpose() const {
std::vector<PolynomialMatrix> transposed;
std::transform(polynomials_.begin(), polynomials_.end(),
std::back_inserter(transposed),
[](const PolynomialMatrix& matrix) {
return matrix.transpose();
});
return PiecewisePolynomial<T>(transposed, this->breaks());
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::Block(int start_row,
int start_col,
int block_rows,
int block_cols) const {
DRAKE_DEMAND(start_row >= 0 && start_row < rows());
DRAKE_DEMAND(start_col >= 0 && start_col < cols());
DRAKE_DEMAND(block_rows >= 0 && start_row + block_rows <= rows());
DRAKE_DEMAND(block_cols >= 0 && start_col + block_cols <= cols());
std::vector<PolynomialMatrix> block_polynomials;
std::transform(polynomials_.begin(), polynomials_.end(),
std::back_inserter(block_polynomials),
[start_row, start_col, block_rows,
block_cols](const PolynomialMatrix& matrix) {
return matrix.block(start_row, start_col, block_rows,
block_cols);
});
return PiecewisePolynomial<T>(block_polynomials, this->breaks());
}
// Static generators for splines.
// Throws std::runtime_error if these conditions are true:
// `breaks` and `samples` have different length,
// `samples` have inconsistent dimensions,
// any `samples` have either 0 rows or 0 cols,
// `breaks` is not strictly increasing by at least kEpsilonTime per break,
// `breaks` has length smaller than `min_length`.
template <typename T>
void PiecewisePolynomial<T>::CheckSplineGenerationInputValidityOrThrow(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
int min_length) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
if (times.size() != Y.size()) {
throw std::runtime_error(fmt::format(
"Number of break points {} does not match number of samples {}.",
times.size(), Y.size()));
}
if (static_cast<int>(times.size()) < min_length) {
throw std::runtime_error(fmt::format(
"{} samples is not enough samples (this method requires at least {}).",
times.size(), min_length));
}
Eigen::Index rows = Y.front().rows();
Eigen::Index cols = Y.front().cols();
if (rows < 1 || cols < 1) {
throw std::runtime_error("Knots need to be non-empty.");
}
for (const auto& y : Y) {
if (y.rows() != rows || y.cols() != cols) {
throw std::runtime_error("Knots have inconsistent dimensions.");
}
}
for (size_t i = 0; i < times.size() - 1; i++) {
if (times[i + 1] <= times[i]) {
throw std::runtime_error("Times must be in increasing order.");
}
if (times[i + 1] - times[i] < PiecewiseTrajectory<T>::kEpsilonTime) {
throw std::runtime_error(
fmt::format("Times must be at least {} apart.",
PiecewiseTrajectory<T>::kEpsilonTime));
}
}
}
// Makes a piecewise constant polynomial.
// The value for each segment is set to the value at the beginning of each
// segment.
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::ZeroOrderHold(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples) {
CheckSplineGenerationInputValidityOrThrow(breaks, samples, 2);
std::vector<PolynomialMatrix> polys;
polys.reserve(breaks.size() - 1);
// For each of the breaks, creates a PolynomialMatrix which can contain joint
// positions.
for (int i = 0; i < static_cast<int>(breaks.size()) - 1; ++i) {
PolynomialMatrix poly_matrix(samples[0].rows(), samples[0].cols());
for (int j = 0; j < samples[i].rows(); ++j) {
for (int k = 0; k < samples[i].cols(); ++k) {
poly_matrix(j, k) =
Polynomial<T>(Eigen::Matrix<T, 1, 1>(samples[i](j, k)));
}
}
polys.push_back(poly_matrix);
}
return PiecewisePolynomial<T>(polys, breaks);
}
// Makes a piecewise linear polynomial.
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::FirstOrderHold(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples) {
CheckSplineGenerationInputValidityOrThrow(breaks, samples, 2);
std::vector<PolynomialMatrix> polys;
polys.reserve(breaks.size() - 1);
// For each of the breaks, creates a PolynomialMatrix which can contain joint
// positions.
for (int i = 0; i < static_cast<int>(breaks.size()) - 1; ++i) {
PolynomialMatrix poly_matrix(samples[0].rows(), samples[0].cols());
for (int j = 0; j < samples[i].rows(); ++j) {
for (int k = 0; k < samples[i].cols(); ++k) {
poly_matrix(j, k) = Polynomial<T>(Eigen::Matrix<T, 2, 1>(
samples[i](j, k), (samples[i + 1](j, k) - samples[i](j, k)) /
(breaks[i + 1] - breaks[i])));
}
}
polys.push_back(poly_matrix);
}
return PiecewisePolynomial<T>(polys, breaks);
}
template <typename T>
static int sign(T val, T tol) {
if (val < -tol)
return -1;
else if (val > tol)
return 1;
return 0;
}
namespace {
// Computes the first derivative for either the starting or the end sample
// point. This is an internal helpful function for pchip.
// The first derivative is computed using a non-centered, shape-preserving
// three-point formulae.
// See equation (2.10) in the following reference for more details.
// http://www.mi.sanu.ac.rs/~gvm/radovi/mon.pdf
template <typename T>
MatrixX<T> ComputePchipEndSlope(const T& dt0, const T& dt1,
const MatrixX<T>& slope0,
const MatrixX<T>& slope1) {
const T kSlopeEpsilon = 1e-10;
MatrixX<T> deriv = ((2.0 * dt0 + dt1) * slope0 - dt0 * slope1) / (dt0 + dt1);
for (int i = 0; i < deriv.rows(); ++i) {
for (int j = 0; j < deriv.cols(); ++j) {
if (sign(deriv(i, j), kSlopeEpsilon) !=
sign(slope0(i, j), kSlopeEpsilon)) {
deriv(i, j) = 0.;
} else if (sign(slope0(i, j), kSlopeEpsilon) !=
sign(slope1(i, j), kSlopeEpsilon) &&
abs(deriv(i, j)) > abs(3. * slope0(i, j))) {
deriv(i, j) = 3. * slope0(i, j);
}
}
}
return deriv;
}
} // namespace
// Makes a cubic piecewise polynomial.
// It first computes the first derivatives at each break, and solves for each
// segment's coefficients using the derivatives and samples.
// The derivatives are computed using a weighted harmonic mean for internal
// points, and ComputePchipEndSlope is used for computing the end points'
// derivatives.
// See pg 9 in http://home.uchicago.edu/~sctchoi/courses/cs138/interp.pdf for
// more details.
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::CubicShapePreserving(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
bool zero_end_point_derivatives) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
if (zero_end_point_derivatives) {
CheckSplineGenerationInputValidityOrThrow(times, Y, 2);
} else {
CheckSplineGenerationInputValidityOrThrow(times, Y, 3);
}
int N = static_cast<int>(times.size());
int rows = Y.front().rows();
int cols = Y.front().cols();
std::vector<PolynomialMatrix> polynomials(N - 1);
std::vector<MatrixX<T>> slope(N - 1);
std::vector<T> dt(N - 1);
std::vector<MatrixX<T>> Ydot(N, MatrixX<T>::Zero(rows, cols));
Eigen::Matrix<T, 4, 1> coeffs;
// Computes the end slopes.
MatrixX<T> Ydot_start = MatrixX<T>::Zero(rows, cols);
MatrixX<T> Ydot_end = MatrixX<T>::Zero(rows, cols);
if (!zero_end_point_derivatives) {
Ydot_start =
ComputePchipEndSlope<T>(times[1] - times[0], times[2] - times[1],
(Y[1] - Y[0]) / (times[1] - times[0]),
(Y[2] - Y[1]) / (times[2] - times[1]));
Ydot_end = ComputePchipEndSlope<T>(
times[N - 1] - times[N - 2], times[N - 2] - times[N - 3],
(Y[N - 1] - Y[N - 2]) / (times[N - 1] - times[N - 2]),
(Y[N - 2] - Y[N - 3]) / (times[N - 2] - times[N - 3]));
}
for (int t = 0; t < N - 1; ++t) {
dt[t] = times[t + 1] - times[t];
slope[t] = (Y[t + 1] - Y[t]) / dt[t];
polynomials[t].resize(Y[t].rows(), Y[t].cols());
}
for (int j = 0; j < rows; ++j) {
for (int k = 0; k < cols; ++k) {
// Computes Ydot.
for (size_t t = 0; t < dt.size() - 1; ++t) {
// sample[t+1] is local extrema.
if (slope[t](j, k) * slope[t + 1](j, k) <= 0) {
Ydot[t + 1](j, k) = 0;
} else {
// Computed with using weighted harmonic mean.
T common = dt[t] + dt[t + 1];
Ydot[t + 1](j, k) = 3 * common /
((common + dt[t + 1]) / slope[t](j, k) +
(common + dt[t]) / slope[t + 1](j, k));
}
}
// Fixes end point slopes.
Ydot[0](j, k) = Ydot_start(j, k);
Ydot[N - 1](j, k) = Ydot_end(j, k);
// Computes coeffs given Y and Ydot at the end points for each segment.
for (int t = 0; t < N - 1; ++t) {
coeffs = ComputeCubicSplineCoeffs(dt[t], Y[t](j, k), Y[t + 1](j, k),
Ydot[t](j, k), Ydot[t + 1](j, k));
polynomials[t](j, k) = Polynomial<T>(coeffs);
}
}
}
return PiecewisePolynomial<T>(polynomials, times);
}
// Makes a cubic piecewise polynomial using the given samples and their
// derivatives at each break.
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::CubicHermite(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
const std::vector<MatrixX<T>>& samples_dot) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
const std::vector<MatrixX<T>>& Ydot = samples_dot;
CheckSplineGenerationInputValidityOrThrow(times, Y, 2);
int N = static_cast<int>(times.size());
int rows = Y.front().rows();
int cols = Y.front().cols();
if (times.size() != Ydot.size()) {
throw std::runtime_error("Y and Ydot have different length.");
}
for (int t = 0; t < N; ++t) {
if (rows != Ydot[t].rows() || cols != Ydot[t].cols()) {
throw std::runtime_error("Y and Ydot dimension mismatch.");
}
}
std::vector<PolynomialMatrix> polynomials(N - 1);
for (int t = 0; t < N - 1; ++t) {
polynomials[t].resize(Y[t].rows(), Y[t].cols());
const T dt = times[t + 1] - times[t];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
Eigen::Matrix<T, 4, 1> coeffs = ComputeCubicSplineCoeffs(
dt, Y[t](i, j), Y[t + 1](i, j), Ydot[t](i, j), Ydot[t + 1](i, j));
polynomials[t](i, j) = Polynomial<T>(coeffs);
}
}
}
return PiecewisePolynomial<T>(polynomials, times);
}
// Sets up the linear system for solving for the cubic piecewise polynomial
// coefficients.
// See the header file for more information.
template <typename T>
int PiecewisePolynomial<T>::SetupCubicSplineInteriorCoeffsLinearSystem(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
int row, int col, std::vector<Eigen::Triplet<T>>* triplet_list,
VectorX<T>* b) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
int N = static_cast<int>(times.size());
DRAKE_DEMAND(triplet_list != nullptr);
DRAKE_DEMAND(b != nullptr);
DRAKE_DEMAND(b->rows() == 3 * (N - 1));
int row_idx = 0;
std::vector<Eigen::Triplet<T>>& triplet_ref = *triplet_list;
VectorX<T>& bref = *b;
for (int i = 0; i < N - 1; ++i) {
const T dt = times[i + 1] - times[i];
// y_i(x_{i+1}) = y_{i+1}(x_{i}) =>
// Y[i] + a1i*(x_{i+1} - x_i) + a2i(x_{i+1} - x_i)^2 + a3i(x_{i+1} -
// x_i)^3 = Y[i+1]
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 0, dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 1, dt * dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 2, dt * dt * dt));
bref(row_idx++) = Y[i + 1](row, col) - Y[i](row, col);
// y_i'(x_{i+1}) = y_{i+1}'(x_{i}) =>
// a1i + 2*a2i(x_{i+1} - x_i) + 3*a3i(x_{i+1} - x_i)^2 = a1{i+1}
if (i != N - 2) {
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 0, 1));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 1, 2 * dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 2, 3 * dt * dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx++, 3 * (i + 1), -1));
}
if (i != N - 2) {
// y_i''(x_{i+1}) = y_{i+1}''(x_{i}) =>
// 2*a2i + 6*a3i(x_{i+1} - x_i) = 2*a2{i+1}
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 1, 2));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx, 3 * i + 2, 6 * dt));
triplet_ref.push_back(Eigen::Triplet<T>(row_idx++, 3 * (i + 1) + 1, -2));
}
}
DRAKE_DEMAND(row_idx == 3 * (N - 1) - 2);
return row_idx;
}
// Makes a cubic piecewise polynomial.
// Internal sample points have continuous values, first and second derivatives,
// and first derivatives at both end points are set to `sample_dot_at_start`
// and `sample_dot_at_end`.
template <typename T>
PiecewisePolynomial<T>
PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
const MatrixX<T>& sample_dot_at_start,
const MatrixX<T>& sample_dot_at_end) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
const MatrixX<T>& Ydot_start = sample_dot_at_start;
const MatrixX<T>& Ydot_end = sample_dot_at_end;
CheckSplineGenerationInputValidityOrThrow(times, Y, 2);
int N = static_cast<int>(times.size());
int rows = Y.front().rows();
int cols = Y.front().cols();
if (Ydot_start.rows() != rows || Ydot_start.cols() != cols) {
throw std::runtime_error("Ydot_start and Y dimension mismatch");
}
if (Ydot_end.rows() != rows || Ydot_end.cols() != cols) {
throw std::runtime_error("Ydot_end and Y dimension mismatch");
}
std::vector<PolynomialMatrix> polynomials(N - 1);
for (int i = 0; i < N - 1; ++i) {
polynomials[i].resize(rows, cols);
}
Eigen::SparseMatrix<T> A(3 * (N - 1), 3 * (N - 1));
VectorX<T> b(3 * (N - 1));
VectorX<T> solution;
VectorX<T> coeffs(4);
Eigen::SparseLU<Eigen::SparseMatrix<T>> solver;
b.setZero();
// Sets up a linear equation to solve for the coefficients.
for (int j = 0; j < rows; ++j) {
for (int k = 0; k < cols; ++k) {
std::vector<Eigen::Triplet<T>> triplet_list;
// 10 coefficients are needed for the constraints that ensure continuity
// between adjacent segments: 3 for position, 4 for velocity, 3 for
// acceleration. The additional coefficients consist of: 3 for final
// position constraint, 1 for initial velocity constraint & 3 for final
// velocity constraint.
triplet_list.reserve(10 * (N - 2) + 7);
int row_idx = SetupCubicSplineInteriorCoeffsLinearSystem(
times, Y, j, k, &triplet_list, &b);
// Endpoints' velocity matches the given ones.
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 0, 1));
b(row_idx++) = Ydot_start(j, k);
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 3 * (N - 2) + 0, 1));
triplet_list.push_back(Eigen::Triplet<T>(
row_idx, 3 * (N - 2) + 1, 2 * (times[N - 1] - times[N - 2])));
triplet_list.push_back(Eigen::Triplet<T>(
row_idx, 3 * (N - 2) + 2,
3 * (times[N - 1] - times[N - 2]) * (times[N - 1] - times[N - 2])));
b(row_idx++) = Ydot_end(j, k);
A.setFromTriplets(triplet_list.begin(), triplet_list.end());
if (j == 0 && k == 0) {
solver.analyzePattern(A);
}
solver.factorize(A);
solution = solver.solve(b);
for (int i = 0; i < N - 1; ++i) {
coeffs(0) = Y[i](j, k);
coeffs.tail(3) = solution.template segment<3>(3 * i);
polynomials[i](j, k) = Polynomial<T>(coeffs);
}
}
}
return PiecewisePolynomial<T>(polynomials, times);
}
// Makes a cubic piecewise polynomial.
// Internal sample points have continuous values, first and second derivatives.
// If `periodic_end_condition` is `true`, the first and second derivatives will
// be continuous between the end of the last segment and the beginning of
// the first. Otherwise, the third derivative is made continuous between the
// first two segments and between the last two segments (the "not-a-sample"
// end condition).
template <typename T>
PiecewisePolynomial<T>
PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
const std::vector<T>& breaks, const std::vector<MatrixX<T>>& samples,
bool periodic_end_condition) {
const std::vector<T>& times = breaks;
const std::vector<MatrixX<T>>& Y = samples;
CheckSplineGenerationInputValidityOrThrow(times, Y, 3);
int N = static_cast<int>(times.size());
int rows = Y.front().rows();
int cols = Y.front().cols();
std::vector<PolynomialMatrix> polynomials(N - 1);
for (int i = 0; i < N - 1; ++i) {
polynomials[i].resize(rows, cols);
}
Eigen::SparseMatrix<T> A(3 * (N - 1), 3 * (N - 1));
VectorX<T> b(3 * (N - 1));
VectorX<T> solution;
VectorX<T> coeffs(4);
Eigen::SparseLU<Eigen::SparseMatrix<T>> solver;
b.setZero();
// Sets up a linear equation to solve for the coefficients.
for (int j = 0; j < rows; ++j) {
for (int k = 0; k < cols; ++k) {
std::vector<Eigen::Triplet<T>> triplet_list;
// 10 coefficients are needed for the constraints that ensure continuity
// between adjacent segments: 3 for position, 4 for velocity, 3 for
// acceleration. The additional coefficients consist of: 3 for final
// position constraint, 4 for periodic velocity constraint & 3 for
// periodic acceleration constraint. In the case of "not-a-sample" end
// condition, fewer coefficients are needed.
triplet_list.reserve(10 * (N - 2) + 10);
int row_idx = SetupCubicSplineInteriorCoeffsLinearSystem(
times, Y, j, k, &triplet_list, &b);
if (periodic_end_condition) {
// Time during the last segment.
const T end_dt = times[times.size() - 1] - times[times.size() - 2];
// Enforce velocity between end-of-last and beginning-of-first segments
// is continuous.
// Linear term of 1st segment.
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 0, -1));
// Linear term of last segment.
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 3 * (N - 2) + 0, 1));
// Squared term of last segment.
triplet_list.push_back(
Eigen::Triplet<T>(row_idx, 3 * (N - 2) + 1, 2 * end_dt));
// Cubic term of last segment.
triplet_list.push_back(
Eigen::Triplet<T>(row_idx, 3 * (N - 2) + 2, 3 * end_dt * end_dt));
b(row_idx++) = 0;
// Enforce that acceleration between end-of-last and beginning-of-first
// segments is continuous.
// Quadratic term of 1st segment.
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 1, -2));
// Quadratic term of last segment.
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 3 * (N - 2) + 1, 2));
// Cubic term of last segment.
triplet_list.push_back(
Eigen::Triplet<T>(row_idx, 3 * (N - 2) + 2, 6 * end_dt));
b(row_idx++) = 0;
} else {
if (N > 3) {
// Ydddot(times[1]) is continuous.
// Cubic term of 1st segment.
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 2, 1));
// Cubic term of 2nd segment.
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 3 + 2, -1));
b(row_idx++) = 0;
// Ydddot(times[N-2]) is continuous.
triplet_list.push_back(
Eigen::Triplet<T>(row_idx, 3 * (N - 3) + 2, 1));
triplet_list.push_back(
Eigen::Triplet<T>(row_idx, 3 * (N - 2) + 2, -1));
b(row_idx++) = 0;
} else {
// Set Jerk to zero if only have 3 points, becomes a quadratic.
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 2, 1));
b(row_idx++) = 0;
triplet_list.push_back(Eigen::Triplet<T>(row_idx, 3 + 2, 1));
b(row_idx++) = 0;
}
}
A.setFromTriplets(triplet_list.begin(), triplet_list.end());
if (j == 0 && k == 0) {
solver.analyzePattern(A);
}
solver.factorize(A);
solution = solver.solve(b);
for (int i = 0; i < N - 1; ++i) {
coeffs(0) = Y[i](j, k);
coeffs.tail(3) = solution.template segment<3>(3 * i);
polynomials[i](j, k) = Polynomial<T>(coeffs);
}
}
}
return PiecewisePolynomial<T>(polynomials, times);
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::LagrangeInterpolatingPolynomial(
const std::vector<T>& times, const std::vector<MatrixX<T>>& samples) {
using std::pow;
// Check the inputs.
DRAKE_DEMAND(times.size() > 1);
DRAKE_DEMAND(samples.size() == times.size());
const int rows = samples[0].rows();
const int cols = samples[0].cols();
for (size_t i = 1; i < times.size(); ++i) {
DRAKE_DEMAND(times[i] - times[i - 1] >
PiecewiseTrajectory<T>::kEpsilonTime);
DRAKE_DEMAND(samples[i].rows() == rows);
DRAKE_DEMAND(samples[i].cols() == cols);
}
// https://en.wikipedia.org/wiki/Polynomial_interpolation notes that
// this Vandermonde matrix can be poorly conditioned if times are close
// together, and suggests that there are special O(n^2) algorithms available
// for this particular problem. But we just implement the simple algorithm
// here for now.
// Set up the system of linear equations to solve for the coefficients.
MatrixX<T> A(times.size(), times.size());
VectorX<T> b(times.size());
// Only need to set up the A matrix once.
for (size_t i = 0; i < times.size(); ++i) {
const T relative_time = times[i] - times[0];
A(i, 0) = 1.0;
for (size_t j = 1; j < times.size(); ++j) {
A(i, j) = A(i, j - 1) * relative_time;
}
}
Eigen::ColPivHouseholderQR<MatrixX<T>> Aqr(A);
// Solve for the coefficient matrices.
PolynomialMatrix polynomials(rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
for (size_t k = 0; k < times.size(); ++k) {
b(k) = samples[k](i, j);
}
polynomials(i, j) = Polynomial<T>(Aqr.solve(b));
}
}
return PiecewisePolynomial<T>({polynomials},
{times[0], times[times.size() - 1]});
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::ZeroOrderHold(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples) {
DRAKE_DEMAND(samples.cols() == breaks.size());
std::vector<T> my_breaks(breaks.data(), breaks.data() + breaks.size());
return PiecewisePolynomial<T>::ZeroOrderHold(my_breaks,
EigenToStdVector(samples));
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::FirstOrderHold(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples) {
DRAKE_DEMAND(samples.cols() == breaks.size());
std::vector<T> my_breaks(breaks.data(), breaks.data() + breaks.size());
return PiecewisePolynomial<T>::FirstOrderHold(my_breaks,
EigenToStdVector(samples));
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::CubicShapePreserving(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples,
bool zero_end_point_derivatives) {
DRAKE_DEMAND(samples.cols() == breaks.size());
std::vector<T> my_breaks(breaks.data(), breaks.data() + breaks.size());
return PiecewisePolynomial<T>::CubicShapePreserving(
my_breaks, EigenToStdVector(samples), zero_end_point_derivatives);
}
template <typename T>
PiecewisePolynomial<T>
PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples,
const Eigen::Ref<const VectorX<T>>& samples_dot_start,
const Eigen::Ref<const VectorX<T>>& samples_dot_end) {
DRAKE_DEMAND(samples.cols() == breaks.size());
std::vector<T> my_breaks(breaks.data(), breaks.data() + breaks.size());
return PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
my_breaks, EigenToStdVector(samples), samples_dot_start.eval(),
samples_dot_end.eval());
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::CubicHermite(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples,
const Eigen::Ref<const MatrixX<T>>& samples_dot) {
DRAKE_DEMAND(samples.cols() == breaks.size());
std::vector<T> my_breaks(breaks.data(), breaks.data() + breaks.size());
return PiecewisePolynomial<T>::CubicHermite(
my_breaks, EigenToStdVector(samples), EigenToStdVector(samples_dot));
}
template <typename T>
PiecewisePolynomial<T>
PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
const Eigen::Ref<const VectorX<T>>& breaks,
const Eigen::Ref<const MatrixX<T>>& samples, bool periodic_end_condition) {
DRAKE_DEMAND(samples.cols() == breaks.size());
std::vector<T> my_breaks(breaks.data(), breaks.data() + breaks.size());
return PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
my_breaks, EigenToStdVector(samples), periodic_end_condition);
}
template <typename T>
PiecewisePolynomial<T> PiecewisePolynomial<T>::LagrangeInterpolatingPolynomial(
const Eigen::Ref<const VectorX<T>>& times,
const Eigen::Ref<const MatrixX<T>>& samples) {
DRAKE_DEMAND(samples.cols() == times.size());
std::vector<T> my_times(times.data(), times.data() + times.size());
return PiecewisePolynomial<T>::LagrangeInterpolatingPolynomial(
my_times, EigenToStdVector(samples));
}
// Computes the cubic spline coefficients based on the given values and first
// derivatives at both end points.
template <typename T>
Eigen::Matrix<T, 4, 1> PiecewisePolynomial<T>::ComputeCubicSplineCoeffs(
const T& dt, T y0, T y1, T yd0, T yd1) {
if (dt < PiecewiseTrajectory<T>::kEpsilonTime) {
throw std::runtime_error("dt < epsilon.");
}
T dt2 = dt * dt;
T c4 = y0;
T c3 = yd0;
T common = (yd1 - c3 - 2. / dt * (y1 - c4 - dt * c3));
T c1 = 1. / dt2 * common;
T c2 = 1. / dt2 * (y1 - c4 - dt * c3 - dt * common);
return Vector4<T>(c4, c3, c2, c1);
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::PiecewisePolynomial)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/stacked_trajectory.cc | #include "drake/common/trajectories/stacked_trajectory.h"
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
namespace drake {
namespace trajectories {
using Eigen::Index;
template <typename T>
StackedTrajectory<T>::StackedTrajectory(bool rowwise) : rowwise_{rowwise} {
DRAKE_ASSERT_VOID(CheckInvariants());
}
template <typename T>
StackedTrajectory<T>::~StackedTrajectory() = default;
template <typename T>
void StackedTrajectory<T>::Append(const Trajectory<T>& traj) {
Append(traj.Clone());
}
template <typename T>
void StackedTrajectory<T>::Append(std::unique_ptr<Trajectory<T>> traj) {
DRAKE_DEMAND(traj != nullptr);
// Check for valid times.
if (!children_.empty()) {
DRAKE_THROW_UNLESS(traj->start_time() == start_time());
DRAKE_THROW_UNLESS(traj->end_time() == end_time());
}
// Check for valid sizes.
if (rowwise_) {
DRAKE_THROW_UNLESS(children_.empty() || traj->cols() == cols());
} else {
DRAKE_THROW_UNLESS(children_.empty() || traj->rows() == rows());
}
// Take ownership and update our internal sizes.
if (rowwise_) {
rows_ += traj->rows();
if (children_.empty()) {
cols_ = traj->cols();
}
} else {
cols_ += traj->cols();
if (children_.empty()) {
rows_ = traj->rows();
}
}
children_.emplace_back(std::move(traj));
DRAKE_ASSERT_VOID(CheckInvariants());
}
template <typename T>
void StackedTrajectory<T>::CheckInvariants() const {
// Sanity-check that our extent on the stacking axis matches the sum over all
// of our children.
const Index expected_stacked_size = rowwise_ ? rows_ : cols_;
const Index actual_stacked_size = std::transform_reduce(
children_.begin(), children_.end(), 0, std::plus<Index>{},
[this](const auto& child) -> Index {
return rowwise_ ? child->rows() : child->cols();
});
DRAKE_DEMAND(actual_stacked_size == expected_stacked_size);
// Sanity-check that our extent in the non-stacking axis is the same over all
// of our children.
const Index expected_matched_size = rowwise_ ? cols_ : rows_;
for (const auto& child : children_) {
const Index actual_matched_size = rowwise_ ? child->cols() : child->rows();
DRAKE_DEMAND(actual_matched_size == expected_matched_size);
}
// Sanity-check that the time span is the same for all children.
for (const auto& child : children_) {
DRAKE_DEMAND(child->start_time() == start_time());
DRAKE_DEMAND(child->end_time() == end_time());
}
}
template <typename T>
std::unique_ptr<Trajectory<T>> StackedTrajectory<T>::Clone() const {
using Self = StackedTrajectory<T>;
auto result = std::unique_ptr<Self>(new Self(*this));
DRAKE_ASSERT_VOID(CheckInvariants());
DRAKE_ASSERT_VOID(result->CheckInvariants());
return result;
}
template <typename T>
MatrixX<T> StackedTrajectory<T>::value(const T& t) const {
MatrixX<T> result(rows(), cols());
Index row = 0;
Index col = 0;
for (const auto& child : children_) {
const MatrixX<T> child_result = child->value(t);
const Index child_rows = child_result.rows();
const Index child_cols = child_result.cols();
result.block(row, col, child_rows, child_cols) = child_result;
if (rowwise_) {
row += child_rows;
} else {
col += child_cols;
}
}
return result;
}
template <typename T>
Index StackedTrajectory<T>::rows() const {
return rows_;
}
template <typename T>
Index StackedTrajectory<T>::cols() const {
return cols_;
}
template <typename T>
T StackedTrajectory<T>::start_time() const {
return children_.empty() ? 0 : children_.front()->start_time();
}
template <typename T>
T StackedTrajectory<T>::end_time() const {
return children_.empty() ? 0 : children_.front()->end_time();
}
template <typename T>
bool StackedTrajectory<T>::do_has_derivative() const {
return std::all_of(children_.begin(), children_.end(), [](const auto& child) {
return child->has_derivative();
});
}
template <typename T>
MatrixX<T> StackedTrajectory<T>::DoEvalDerivative(const T& t,
int derivative_order) const {
MatrixX<T> result(rows(), cols());
Index row = 0;
Index col = 0;
for (const auto& child : children_) {
const MatrixX<T> child_result = child->EvalDerivative(t, derivative_order);
const Index child_rows = child_result.rows();
const Index child_cols = child_result.cols();
result.block(row, col, child_rows, child_cols) = child_result;
if (rowwise_) {
row += child_rows;
} else {
col += child_cols;
}
}
return result;
}
template <typename T>
std::unique_ptr<Trajectory<T>> StackedTrajectory<T>::DoMakeDerivative(
int derivative_order) const {
auto result = std::make_unique<StackedTrajectory<T>>(rowwise_);
for (const auto& child : children_) {
result->Append(child->MakeDerivative(derivative_order));
}
return result;
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::StackedTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/discrete_time_trajectory.cc | #include "drake/common/trajectories/discrete_time_trajectory.h"
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <fmt/format.h>
#include "drake/common/drake_assert.h"
#include "drake/math/matrix_util.h"
namespace drake {
namespace trajectories {
using math::EigenToStdVector;
template <typename T>
DiscreteTimeTrajectory<T>::DiscreteTimeTrajectory(
const Eigen::Ref<const VectorX<T>>& times,
const Eigen::Ref<const MatrixX<T>>& values,
const double time_comparison_tolerance)
: DiscreteTimeTrajectory(
std::vector<T>(times.data(), times.data() + times.size()),
EigenToStdVector(values), time_comparison_tolerance) {}
template <typename T>
DiscreteTimeTrajectory<T>::DiscreteTimeTrajectory(
const std::vector<T>& times, const std::vector<MatrixX<T>>& values,
const double time_comparison_tolerance)
: times_(times),
values_(values),
time_comparison_tolerance_(time_comparison_tolerance) {
DRAKE_DEMAND(times.size() == values.size());
// Ensure that times are convertible to double.
for (const auto& t : times) {
ExtractDoubleOrThrow(t);
}
for (int i = 1; i < static_cast<int>(times_.size()); i++) {
DRAKE_DEMAND(times[i] - times[i - 1] >= time_comparison_tolerance_);
DRAKE_DEMAND(values[i].rows() == values[0].rows());
DRAKE_DEMAND(values[i].cols() == values[0].cols());
}
DRAKE_DEMAND(time_comparison_tolerance_ >= 0);
}
template <typename T>
PiecewisePolynomial<T> DiscreteTimeTrajectory<T>::ToZeroOrderHold() const {
return PiecewisePolynomial<T>::ZeroOrderHold(times_, values_);
}
template <typename T>
double DiscreteTimeTrajectory<T>::time_comparison_tolerance() const {
return time_comparison_tolerance_;
}
template <typename T>
int DiscreteTimeTrajectory<T>::num_times() const {
return times_.size();
}
template <typename T>
const std::vector<T>& DiscreteTimeTrajectory<T>::get_times() const {
return times_;
}
template <typename T>
std::unique_ptr<Trajectory<T>> DiscreteTimeTrajectory<T>::Clone() const {
return std::make_unique<DiscreteTimeTrajectory<T>>(
times_, values_, time_comparison_tolerance_);
}
template <typename T>
MatrixX<T> DiscreteTimeTrajectory<T>::value(const T& t) const {
using std::abs;
const double time = ExtractDoubleOrThrow(t);
static constexpr const char* kNoMatchingTimeStr =
"Value requested at time {} does not match any of the trajectory times "
"within tolerance {}.";
for (int i = 0; i < static_cast<int>(times_.size()); ++i) {
if (time < times_[i] - time_comparison_tolerance_) {
throw std::runtime_error(
fmt::format(kNoMatchingTimeStr, time, time_comparison_tolerance_));
}
if (abs(time - times_[i]) <= time_comparison_tolerance_) {
return values_[i];
}
}
throw std::runtime_error(
fmt::format(kNoMatchingTimeStr, time, time_comparison_tolerance_));
}
template <typename T>
Eigen::Index DiscreteTimeTrajectory<T>::rows() const {
DRAKE_DEMAND(times_.size() > 0);
return values_[0].rows();
}
template <typename T>
Eigen::Index DiscreteTimeTrajectory<T>::cols() const {
DRAKE_DEMAND(times_.size() > 0);
return values_[0].cols();
}
template <typename T>
T DiscreteTimeTrajectory<T>::start_time() const {
DRAKE_DEMAND(times_.size() > 0);
return times_[0];
}
template <typename T>
T DiscreteTimeTrajectory<T>::end_time() const {
DRAKE_DEMAND(times_.size() > 0);
return times_[times_.size() - 1];
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::DiscreteTimeTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/bezier_curve.h | #pragma once
#include <memory>
#include <optional>
#include "drake/common/eigen_types.h"
#include "drake/common/trajectories/trajectory.h"
namespace drake {
namespace trajectories {
/** A BΓ©zier curve is defined by a set of control points pβ through pβ, where n
is called the order of the curve (n = 1 for linear, 2 for quadratic, 3 for
cubic, etc.). The first and last control points are always the endpoints of
the curve; however, the intermediate control points (if any) generally do not
lie on the curve, but the curve is guaranteed to stay within the convex hull
of the control points.
See also BsplineTrajectory. A B-spline can be thought of as a composition of
overlapping BΓ©zier curves (where each evaluation only depends on a local
subset of the control points). In contrast, evaluating a BΓ©zier curve will use
all of the control points.
@tparam_default_scalar
*/
template <typename T>
class BezierCurve final : public trajectories::Trajectory<T> {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(BezierCurve);
/** Default initializer. Constructs an empty BΓ©zier curve over the interval
t β [0, 1].*/
BezierCurve() : BezierCurve<T>(0, 1, MatrixX<T>()) {}
/** Constructs a BΓ©zier curve over the interval t β [`start_time`,
`end_time`] with control points defined in the columns of `control_points`.
@pre end_time >= start_time.
*/
BezierCurve(double start_time, double end_time,
const Eigen::Ref<const MatrixX<T>>& control_points);
// TODO(russt): Add support for MatrixX control points, but only if we have a
// use case for it.
virtual ~BezierCurve() = default;
/** Returns the order of the curve (1 for linear, 2 for quadratic, etc.). */
int order() const { return control_points_.cols() - 1; }
/** Returns the value of the ith basis function of `order` (1 for linear, 2
for quadratic, etc) evaluated at `time`. The default value for the optional
argument `order` is the `order()` of `this`. */
T BernsteinBasis(int i, const T& time,
std::optional<int> order = std::nullopt) const;
/** Returns a const reference to the control points which define the curve. */
const MatrixX<T>& control_points() const { return control_points_; }
/** Supports writing optimizations using the control points as decision
variables. This method returns the matrix, `M`, defining the control points
of the `order` derivative in the form:
<pre>
derivative.control_points() = this.control_points() * M
</pre>
For instance, since we have
<pre>
derivative.control_points().col(k) = this.control_points() * M.col(k),
</pre>
constraining the kth control point of the `n`th derivative to be in [ub,
lb], could be done with:
@code
auto M = curve.AsLinearInControlPoints(n);
for (int i=0; i<curve.rows(); ++i) {
auto c = std::make_shared<solvers::LinearConstraint>(
M.col(k).transpose(), Vector1d(lb(i)), Vector1d(ub(i)));
prog.AddConstraint(c, curve.row(i).transpose());
}
@endcode
Iterating over the rows of the control points is the natural sparsity pattern
here (since `M` is the same for all rows). For instance, we also have
<pre>
derivative.control_points().row(k).T = M.T * this.control_points().row(k).T,
</pre> or
<pre>
vec(derivative.control_points().T) = blockMT * vec(this.control_points().T),
blockMT = [ M.T, 0, .... 0 ]
[ 0, M.T, 0, ... ]
[ ... ]
[ ... , 0, M.T ].
</pre>
@pre derivative_order >= 0. */
Eigen::SparseMatrix<double> AsLinearInControlPoints(
int derivative_order = 1) const;
// Required methods for trajectories::Trajectory interface.
std::unique_ptr<trajectories::Trajectory<T>> Clone() const override;
/** Evaluates the curve at the given time.
@warning If t does not lie in the range [start_time(), end_time()], the
trajectory will silently be evaluated at the closest valid value of
time to `time`. For example, `value(-1)` will return `value(0)` for
a trajectory defined over [0, 1]. */
MatrixX<T> value(const T& time) const override;
/** Extracts the expanded underlying polynomial expression of this curve in
terms of variable `time`. */
VectorX<symbolic::Expression> GetExpression(
symbolic::Variable time = symbolic::Variable("t")) const;
/** Increases the order of the curve by 1. A BΓ©zier curve of order n can be
converted into a BΓ©zier curve of order n +β1 with the same shape. The
control points of `this` are modified to obtain the equivalent curve. */
void ElevateOrder();
Eigen::Index rows() const override { return control_points_.rows(); }
Eigen::Index cols() const override { return 1; }
T start_time() const override { return start_time_; }
T end_time() const override { return end_time_; }
private:
/* Calculates the control points of the derivative curve. */
MatrixX<T> CalcDerivativePoints(int derivative_order) const;
bool do_has_derivative() const override { return true; }
MatrixX<T> DoEvalDerivative(const T& t, int derivative_order) const override;
std::unique_ptr<trajectories::Trajectory<T>> DoMakeDerivative(
int derivative_order) const override;
VectorX<T> EvaluateT(const T& time) const;
double start_time_{};
double end_time_{};
MatrixX<T> control_points_;
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::BezierCurve)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/bezier_curve.cc | #include "drake/common/trajectories/bezier_curve.h"
#include <utility>
#include <vector>
#include "drake/common/drake_bool.h"
#include "drake/common/symbolic/polynomial.h"
#include "drake/math/binomial_coefficient.h"
namespace drake {
namespace trajectories {
using Eigen::SparseMatrix;
using math::BinomialCoefficient;
template <typename T>
BezierCurve<T>::BezierCurve(double start_time, double end_time,
const Eigen::Ref<const MatrixX<T>>& control_points)
: start_time_{start_time},
end_time_{end_time},
control_points_{control_points} {
DRAKE_DEMAND(end_time >= start_time);
}
template <typename T>
T BezierCurve<T>::BernsteinBasis(int i, const T& time,
std::optional<int> order) const {
using std::pow;
int n = order.value_or(this->order());
int coeff = BinomialCoefficient(n, i);
T s = (time - start_time_) / (end_time_ - start_time_);
return coeff * pow(s, i) * pow(1 - s, n - i);
}
template <typename T>
std::unique_ptr<Trajectory<T>> BezierCurve<T>::Clone() const {
return std::make_unique<BezierCurve<T>>(start_time_, end_time_,
control_points_);
}
template <typename T>
MatrixX<T> BezierCurve<T>::value(const T& time) const {
using std::clamp;
return EvaluateT(clamp(time, T{start_time_}, T{end_time_}));
}
template <typename T>
VectorX<symbolic::Expression> BezierCurve<T>::GetExpression(
symbolic::Variable time) const {
if constexpr (scalar_predicate<T>::is_bool) {
MatrixX<symbolic::Expression> control_points{control_points_.rows(),
control_points_.cols()};
if constexpr (std::is_same_v<T, double>) {
control_points = control_points_.template cast<symbolic::Expression>();
} else {
// AutoDiffXd.
for (int r = 0; r < control_points.rows(); ++r) {
for (int c = 0; c < control_points.cols(); ++c) {
control_points(r, c) =
symbolic::Expression(control_points_(r, c).value());
}
}
}
return BezierCurve<symbolic::Expression>(start_time_, end_time_,
control_points)
.GetExpression(time);
} else {
VectorX<symbolic::Expression> ret{EvaluateT(symbolic::Expression(time))};
for (int i = 0; i < ret.rows(); ++i) {
ret(i) = ret(i).Expand();
}
return ret;
}
}
template <typename T>
void BezierCurve<T>::ElevateOrder() {
if (order() < 0) {
control_points_ = MatrixX<T>::Zero(rows(), cols());
return;
}
// https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-elev.html
const int n = order();
MatrixX<T> Q(control_points_.rows(), n + 2);
Q.col(0) = control_points_.col(0);
Q.col(n + 1) = control_points_.col(n);
for (int i = 1; i <= n; ++i) {
Q.col(i) = control_points_.col(i - 1) * static_cast<double>(i) / (n + 1) +
control_points_.col(i) * (1 - static_cast<double>(i) / (n + 1));
}
control_points_ = std::move(Q);
}
template <typename T>
SparseMatrix<double> BezierCurve<T>::AsLinearInControlPoints(
int derivative_order) const {
DRAKE_THROW_UNLESS(derivative_order >= 0);
if (derivative_order > order()) {
return SparseMatrix<double>(order() + 1, 0); // Return the empty matrix.
} else if (derivative_order == 0) {
SparseMatrix<double> M(order() + 1, order() + 1);
M.setIdentity();
return M;
}
const double duration = end_time_ - start_time_;
int n = order();
// Note: The derivation of M here follows simply from the
// CalcDerivativePoints implementation below.
SparseMatrix<double> M(n + 1, n);
double coeff = n / duration;
std::vector<Eigen::Triplet<double>> tripletList;
tripletList.reserve(2 * n);
for (int i = 0; i < n; ++i) {
tripletList.push_back(Eigen::Triplet<double>(i + 1, i, coeff));
tripletList.push_back(Eigen::Triplet<double>(i, i, -coeff));
}
M.setFromTriplets(tripletList.begin(), tripletList.end());
for (int o = 1; o < derivative_order; ++o) {
n -= 1;
SparseMatrix<double> deltaM(n + 1, n);
coeff = n / duration;
tripletList.clear();
for (int i = 0; i < n; ++i) {
tripletList.push_back(Eigen::Triplet<double>(i + 1, i, coeff));
tripletList.push_back(Eigen::Triplet<double>(i, i, -coeff));
}
deltaM.setFromTriplets(tripletList.begin(), tripletList.end());
// Avoid aliasing. SparseMatrix does not offer the *= operatior.
SparseMatrix<double> Mprev = std::move(M);
M = Mprev * deltaM;
}
return M;
}
template <typename T>
MatrixX<T> BezierCurve<T>::CalcDerivativePoints(int derivative_order) const {
DRAKE_DEMAND(derivative_order <= order());
int n = order();
MatrixX<T> points =
(control_points_.rightCols(order()) - control_points_.leftCols(order())) *
order() / (end_time_ - start_time_);
for (int i = 1; i < derivative_order; ++i) {
n -= 1;
points = (points.rightCols(n) - points.leftCols(n)).eval() * n /
(end_time_ - start_time_);
}
return points;
}
template <typename T>
MatrixX<T> BezierCurve<T>::DoEvalDerivative(const T& time,
int derivative_order) const {
DRAKE_DEMAND(derivative_order >= 0);
if (derivative_order == 0) {
return this->value(time);
}
if (derivative_order > order()) {
return VectorX<T>::Zero(rows());
}
MatrixX<T> points = CalcDerivativePoints(derivative_order);
using std::clamp;
const T ctime = clamp(time, T{start_time_}, T{end_time_});
MatrixX<T> v = VectorX<T>::Zero(rows());
for (int i = 0; i < points.cols(); ++i) {
v += BernsteinBasis(i, ctime, order() - derivative_order) * points.col(i);
}
return v;
}
template <typename T>
VectorX<T> BezierCurve<T>::EvaluateT(const T& time) const {
VectorX<T> v = VectorX<T>::Zero(rows());
for (int i = 0; i < control_points_.cols(); ++i) {
v += BernsteinBasis(i, time) * control_points_.col(i);
}
return v;
}
template <typename T>
std::unique_ptr<Trajectory<T>> BezierCurve<T>::DoMakeDerivative(
int derivative_order) const {
DRAKE_DEMAND(derivative_order >= 0);
if (derivative_order == 0) {
return this->Clone();
}
if (derivative_order > order()) {
// Then return the zero curve.
return std::make_unique<BezierCurve<T>>(start_time_, end_time_,
VectorX<T>::Zero(rows()));
}
return std::make_unique<BezierCurve<T>>(
start_time_, end_time_, CalcDerivativePoints(derivative_order));
}
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class BezierCurve);
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/discrete_time_trajectory.h | #pragma once
#include <limits>
#include <memory>
#include <vector>
#include <Eigen/Core>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/common/trajectories/trajectory.h"
namespace drake {
namespace trajectories {
/** A DiscreteTimeTrajectory is a Trajectory whose value is only defined at
discrete time points. Calling `value()` at a time that is not equal to one of
those times (up to a tolerance) will throw. This trajectory does *not* have
well-defined time-derivatives.
In some applications, it may be preferable to use
PiecewisePolynomial<T>::ZeroOrderHold instead of a DiscreteTimeTrajectory (and
we offer a method here to easily convert). Note if the breaks are periodic,
then one can also achieve a similar result in a Diagram by using the
DiscreteTimeTrajectory in a TrajectorySource and connecting a ZeroOrderHold
system to the output port, but remember that this will add discrete state to
your diagram.
So why not always use the zero-order hold (ZOH) trajectory? This class forces
us to be more precise in our implementations. For instance, consider the case
of a solution to a discrete-time finite-horizon linear quadratic regulator
(LQR) problem. In this case, the solution to the Riccati equation is a
DiscreteTimeTrajectory, K(t). Implementing
@verbatim
x(t) -> MatrixGain(-K(t)) -> u(t)
@verbatim
in a block diagram is perfectly correct, and if the u(t) is only connected to
the original system that it was designed for, then K(t) will only get evaluated
at the defined sample times, and all is well. But if you wire it up to a
continuous-time system, then K(t) may be evaluated at arbitrary times, and may
throw. If one wishes to use the K(t) solution on a continuous-time system, then
we can use
@verbatim
x(t) -> MatrixGain(-K(t)) -> ZOH -> u(t).
@verbatim
This is different, and *more correct* than implementing K(t) as a zero-order
hold trajectory, because in this version, both K(t) and the inputs x(t) will
only be evaluated at the discrete-time input. If `t_s` was the most recent
discrete sample time, then this means u(t) = -K(t_s)*x(t_s) instead of u(t) =
-K(t_s)*x(t). Using x(t_s) and having a true zero-order hold on u(t) is the
correct model for the discrete-time LQR result.
@tparam_default_scalar
*/
template <typename T>
class DiscreteTimeTrajectory final : public Trajectory<T> {
public:
// We are final, so this is okay.
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(DiscreteTimeTrajectory)
/** Default constructor creates the empty trajectory. */
DiscreteTimeTrajectory() = default;
/** Constructs a trajectory of vector @p values at the specified @p times.
@pre @p times must differ by more than @p time_comparison_tolerance and be
monotonically increasing.
@pre @p values must have times.size() columns.
@pre @p time_comparison_tolerance must be >= 0.
@throw if T=symbolic:Expression and @p times are not constants. */
DiscreteTimeTrajectory(const Eigen::Ref<const VectorX<T>>& times,
const Eigen::Ref<const MatrixX<T>>& values,
double time_comparison_tolerance =
std::numeric_limits<double>::epsilon());
/** Constructs a trajectory of matrix @p values at the specified @p times.
@pre @p times should differ by more than @p time_comparison_tolerance and be
monotonically increasing.
@pre @p values must have times.size() elements, each with the same number of
rows and columns.
@pre @p time_comparison_tolerance must be >= 0.
@throw if T=symbolic:Expression and @p times are not constants. */
DiscreteTimeTrajectory(const std::vector<T>& times,
const std::vector<MatrixX<T>>& values,
double time_comparison_tolerance =
std::numeric_limits<double>::epsilon());
/** Converts the discrete-time trajectory using
PiecewisePolynomial<T>::ZeroOrderHold(). */
PiecewisePolynomial<T> ToZeroOrderHold() const;
/** The trajectory is only defined at finite sample times. This method
returns the tolerance used determine which time sample (if any) matches a
query time on calls to value(t). */
double time_comparison_tolerance() const;
/** Returns the number of discrete times where the trajectory value is
defined. */
int num_times() const;
/** Returns the times where the trajectory value is defined. */
const std::vector<T>& get_times() const;
/** Returns a deep copy of the trajectory. */
std::unique_ptr<Trajectory<T>> Clone() const override;
/** Returns the value of the trajectory at @p t.
@throws std::exception if t is not within tolerance of one of the sample
times. */
MatrixX<T> value(const T& t) const override;
/** Returns the number of rows in the MatrixX<T> returned by value().
@pre num_times() > 0. */
Eigen::Index rows() const override;
/** Returns the number of cols in the MatrixX<T> returned by value().
@pre num_times() > 0. */
Eigen::Index cols() const override;
/** Returns the minimum value of get_times().
@pre num_times() > 0. */
T start_time() const override;
/** Returns the maximum value of get_times().
@pre num_times() > 0. */
T end_time() const override;
private:
std::vector<T> times_;
std::vector<MatrixX<T>> values_;
double time_comparison_tolerance_{};
};
} // namespace trajectories
} // namespace drake
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::DiscreteTimeTrajectory)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/trajectories/trajectory.cc | #include "drake/common/trajectories/trajectory.h"
#include "drake/common/unused.h"
namespace drake {
namespace trajectories {
template <typename T>
MatrixX<T> Trajectory<T>::vector_values(const std::vector<T>& t) const {
return vector_values(Eigen::Map<const VectorX<T>>(t.data(), t.size()));
}
template <typename T>
MatrixX<T> Trajectory<T>::vector_values(
const Eigen::Ref<const VectorX<T>>& t) const {
if (cols() != 1 && rows() != 1) {
throw std::runtime_error(
"This method only supports vector-valued trajectories.");
}
if (cols() == 1) {
MatrixX<T> values(rows(), t.size());
for (int i = 0; i < static_cast<int>(t.size()); ++i) {
values.col(i) = value(t[i]);
}
return values;
}
MatrixX<T> values(t.size(), cols());
for (int i = 0; i < static_cast<int>(t.size()); ++i) {
values.row(i) = value(t[i]);
}
return values;
}
template <typename T>
bool Trajectory<T>::has_derivative() const {
return do_has_derivative();
}
template <typename T>
bool Trajectory<T>::do_has_derivative() const {
return false;
}
template <typename T>
MatrixX<T> Trajectory<T>::EvalDerivative(const T& t,
int derivative_order) const {
DRAKE_THROW_UNLESS(derivative_order >= 0);
return DoEvalDerivative(t, derivative_order);
}
template <typename T>
MatrixX<T> Trajectory<T>::DoEvalDerivative(const T& t,
int derivative_order) const {
unused(t);
unused(derivative_order);
if (has_derivative()) {
throw std::logic_error(
"Trajectory classes that promise derivatives via do_has_derivative() "
"must implement DoEvalDerivative().");
} else {
throw std::logic_error(
"You asked for derivatives from a class that does not support "
"derivatives.");
}
}
template <typename T>
std::unique_ptr<Trajectory<T>> Trajectory<T>::MakeDerivative(
int derivative_order) const {
DRAKE_THROW_UNLESS(derivative_order >= 0);
return DoMakeDerivative(derivative_order);
}
template <typename T>
std::unique_ptr<Trajectory<T>> Trajectory<T>::DoMakeDerivative(
int derivative_order) const {
unused(derivative_order);
if (has_derivative()) {
throw std::logic_error(
"Trajectory classes that promise derivatives via do_has_derivative() "
"must implement DoMakeDerivative().");
} else {
throw std::logic_error(
"You asked for derivatives from a class that does not support "
"derivatives.");
}
}
} // namespace trajectories
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::trajectories::Trajectory)
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/piecewise_polynomial_test.cc | #include "drake/common/trajectories/piecewise_polynomial.h"
#include <random>
#include <stdexcept>
#include <vector>
#include <Eigen/Core>
#include <gtest/gtest.h>
#include "drake/common/drake_assert.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/trajectories/test/random_piecewise_polynomial.h"
#include "drake/common/yaml/yaml_io.h"
#include "drake/math/autodiff_gradient.h"
using drake::math::DiscardGradient;
using drake::math::ExtractGradient;
using drake::yaml::SaveYamlString;
using Eigen::Matrix;
using std::default_random_engine;
using std::normal_distribution;
using std::runtime_error;
using std::uniform_int_distribution;
using std::uniform_real_distribution;
using std::vector;
namespace drake {
namespace trajectories {
namespace {
template <typename T>
void testIntegralAndDerivative() {
int num_coefficients = 5;
int num_segments = 3;
int rows = 3;
int cols = 5;
default_random_engine generator;
vector<double> segment_times =
PiecewiseTrajectory<double>::RandomSegmentTimes(num_segments, generator);
PiecewisePolynomial<T> piecewise = test::MakeRandomPiecewisePolynomial<T>(
rows, cols, num_coefficients, segment_times);
// derivative(0) should be same as original piecewise.
EXPECT_TRUE(
CompareMatrices(piecewise.value(piecewise.start_time()),
piecewise.derivative(0).value(piecewise.start_time()),
1e-10, MatrixCompareType::absolute));
// differentiate integral, get original back
PiecewisePolynomial<T> piecewise_back = piecewise.integral().derivative();
if (!piecewise.isApprox(piecewise_back, 1e-10)) throw runtime_error("wrong");
// check value at start time
MatrixX<T> desired_value_at_t0 =
MatrixX<T>::Random(piecewise.rows(), piecewise.cols());
PiecewisePolynomial<T> integral = piecewise.integral(desired_value_at_t0);
auto value_at_t0 = integral.value(piecewise.start_time());
EXPECT_TRUE(CompareMatrices(desired_value_at_t0, value_at_t0, 1e-10,
MatrixCompareType::absolute));
// check continuity at sample points
for (int i = 0; i < piecewise.get_number_of_segments() - 1; ++i) {
EXPECT_EQ(
integral.getPolynomial(i).EvaluateUnivariate(integral.duration(i)),
integral.getPolynomial(i + 1).EvaluateUnivariate(0.0));
}
}
template <typename T>
void testBasicFunctionality() {
int max_num_coefficients = 6;
int num_tests = 100;
default_random_engine generator;
uniform_int_distribution<> int_distribution(1, max_num_coefficients);
for (int i = 0; i < num_tests; ++i) {
int num_coefficients = int_distribution(generator);
int num_segments = int_distribution(generator);
int rows = int_distribution(generator);
int cols = int_distribution(generator);
vector<double> segment_times =
PiecewiseTrajectory<double>::RandomSegmentTimes(num_segments,
generator);
PiecewisePolynomial<T> piecewise1 = test::MakeRandomPiecewisePolynomial<T>(
rows, cols, num_coefficients, segment_times);
PiecewisePolynomial<T> piecewise2 = test::MakeRandomPiecewisePolynomial<T>(
rows, cols, num_coefficients, segment_times);
PiecewisePolynomial<T> piecewise3_not_matching_rows =
test::MakeRandomPiecewisePolynomial<T>(rows + 1, cols, num_coefficients,
segment_times);
PiecewisePolynomial<T> piecewise4_not_matching_cols =
test::MakeRandomPiecewisePolynomial<T>(rows, cols + 1, num_coefficients,
segment_times);
PiecewisePolynomial<T> piecewise5 = test::MakeRandomPiecewisePolynomial<T>(
cols, rows, num_coefficients, segment_times);
normal_distribution<double> normal;
double shift = normal(generator);
MatrixX<T> offset =
MatrixX<T>::Random(piecewise1.rows(), piecewise1.cols());
PiecewisePolynomial<T> sum = piecewise1 + piecewise2;
PiecewisePolynomial<T> difference = piecewise2 - piecewise1;
PiecewisePolynomial<T> piecewise1_plus_offset = piecewise1 + offset;
PiecewisePolynomial<T> piecewise1_minus_offset = piecewise1 - offset;
PiecewisePolynomial<T> piecewise1_shifted = piecewise1;
piecewise1_shifted.shiftRight(shift);
PiecewisePolynomial<T> product = piecewise1 * piecewise5;
PiecewisePolynomial<T> unary_minus = -piecewise1;
const double total_time = segment_times.back() - segment_times.front();
PiecewisePolynomial<T> piecewise2_twice = piecewise2;
PiecewisePolynomial<T> piecewise2_shifted = piecewise2;
piecewise2_shifted.shiftRight(total_time);
// Checks that concatenation of trajectories that are not time
// aligned at the connecting ends is a failure.
PiecewisePolynomial<T> piecewise2_shifted_twice = piecewise2;
piecewise2_shifted_twice.shiftRight(2. * total_time);
EXPECT_THROW(piecewise2_twice.ConcatenateInTime(piecewise2_shifted_twice),
std::runtime_error);
// Checks that concatenation of trajectories that have different
// row counts is a failure.
PiecewisePolynomial<T> piecewise3_not_matching_rows_shifted =
piecewise3_not_matching_rows;
piecewise3_not_matching_rows_shifted.shiftRight(total_time);
EXPECT_THROW(piecewise2_twice.ConcatenateInTime(
piecewise3_not_matching_rows_shifted),
std::runtime_error);
// Checks that concatenation of trajectories that have different
// col counts is a failure.
PiecewisePolynomial<T> piecewise4_not_matching_cols_shifted =
piecewise4_not_matching_cols;
piecewise4_not_matching_cols_shifted.shiftRight(total_time);
EXPECT_THROW(piecewise2_twice.ConcatenateInTime(
piecewise4_not_matching_cols_shifted),
std::runtime_error);
piecewise2_twice.ConcatenateInTime(piecewise2_shifted);
uniform_real_distribution<double> uniform(piecewise1.start_time(),
piecewise1.end_time());
double t = uniform(generator);
EXPECT_TRUE(CompareMatrices(sum.value(t),
piecewise1.value(t) + piecewise2.value(t), 1e-8,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(difference.value(t),
piecewise2.value(t) - piecewise1.value(t), 1e-8,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(piecewise1_plus_offset.value(t),
piecewise1.value(t) + offset, 1e-8,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(piecewise1_minus_offset.value(t),
piecewise1.value(t) - offset, 1e-8,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(piecewise1_shifted.value(t),
piecewise1.value(t - shift), 1e-8,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(product.value(t),
piecewise1.value(t) * piecewise5.value(t), 1e-8,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(unary_minus.value(t), -(piecewise1.value(t))));
// Checks that `piecewise2_twice` is effectively the concatenation of
// `piecewise2` and a copy of `piecewise2` that is shifted to the right
// (i.e. towards increasing values of t) by an amount equal to its entire
// time length. To this end, it verifies that R(tβ) = R(tβ + d), where
// R(t) = P(t) for t0 <= t <= t1, R(t) = Q(t) for t1 <= t <= t2,
// Q(t) = P(t - d) for t1 <= t <= t2, d = t1 - t0 = t2 - t1 and
// t0 < tβ < t1, with P, Q and R functions being piecewise polynomials.
EXPECT_TRUE(CompareMatrices(piecewise2_twice.value(t),
piecewise2_twice.value(t + total_time), 1e-8,
MatrixCompareType::absolute));
}
}
template <typename T>
void testValueOutsideOfRange() {
default_random_engine generator;
vector<double> segment_times =
PiecewiseTrajectory<double>::RandomSegmentTimes(6, generator);
PiecewisePolynomial<T> piecewise =
test::MakeRandomPiecewisePolynomial<T>(3, 4, 5, segment_times);
EXPECT_TRUE(CompareMatrices(piecewise.value(piecewise.start_time()),
piecewise.value(piecewise.start_time() - 1.0),
1e-10, MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(piecewise.value(piecewise.end_time()),
piecewise.value(piecewise.end_time() + 1.0),
1e-10, MatrixCompareType::absolute));
}
// Test the generation of cubic splines with first and second derivatives
// continuous between the end of the last segment and the beginning of the
// first.
GTEST_TEST(testPiecewisePolynomial, CubicSplinePeriodicBoundaryConditionTest) {
Eigen::VectorXd breaks(5);
breaks << 0, 1, 2, 3, 4;
// Spline in 3d.
// clang-format off
Eigen::MatrixXd samples(3, 5);
samples << 1, 1, 1,
2, 2, 2,
0, 3, 3,
-2, 2, 2,
1, 1, 1;
// clang-format on
const bool periodic_endpoint = true;
PiecewisePolynomial<double> periodic_spline =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
breaks, samples, periodic_endpoint);
std::unique_ptr<Trajectory<double>> spline_dt =
periodic_spline.MakeDerivative(1);
std::unique_ptr<Trajectory<double>> spline_ddt =
periodic_spline.MakeDerivative(2);
Eigen::VectorXd begin_dt = spline_dt->value(breaks(0));
Eigen::VectorXd end_dt = spline_dt->value(breaks(breaks.size() - 1));
Eigen::VectorXd begin_ddt = spline_ddt->value(breaks(0));
Eigen::VectorXd end_ddt = spline_ddt->value(breaks(breaks.size() - 1));
EXPECT_TRUE(CompareMatrices(end_dt, begin_dt, 1e-14));
EXPECT_TRUE(CompareMatrices(end_ddt, begin_ddt, 1e-14));
// Test that evaluating the derivative directly gives the same results.
const double t = 1.234;
EXPECT_TRUE(CompareMatrices(periodic_spline.EvalDerivative(t, 1),
spline_dt->value(t), 1e-14));
EXPECT_TRUE(CompareMatrices(periodic_spline.EvalDerivative(t, 2),
spline_ddt->value(t), 1e-14));
}
// Test various exception cases. We want to check that these throw rather
// than crash (or return potentially bad data).
GTEST_TEST(testPiecewisePolynomial, ExceptionsTest) {
Eigen::VectorXd breaks(5);
breaks << 0, 1, 2, 3, 4;
// Spline in 3d.
// clang-format off
Eigen::MatrixXd samples(3, 5);
samples << 1, 1, 1,
2, 2, 2,
0, 3, 3,
-2, 2, 2,
1, 1, 1;
// clang-format on
// No throw with monotonic breaks.
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
breaks, samples, true);
// Throw when breaks are not strictly monotonic.
breaks[1] = 0;
DRAKE_EXPECT_THROWS_MESSAGE(
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
breaks, samples, true),
"Times must be in increasing order.");
}
GTEST_TEST(testPiecewisePolynomial, AllTests) {
testIntegralAndDerivative<double>();
testBasicFunctionality<double>();
testValueOutsideOfRange<double>();
}
GTEST_TEST(testPiecewisePolynomial, VectorValueTest) {
// Note: Keep one negative time to confirm that negative values can work for
// constant trajectories.
const std::vector<double> times = {-1.5, 0, .5, 1, 1.5};
const Eigen::Map<const Eigen::VectorXd> etimes(times.data(), times.size());
const Eigen::Vector3d value(1, 2, 3);
const PiecewisePolynomial<double> col(value);
Eigen::MatrixXd out = col.vector_values(times);
EXPECT_EQ(out.rows(), 3);
EXPECT_EQ(out.cols(), 5);
for (int i = 0; i < 4; ++i) {
EXPECT_TRUE(CompareMatrices(out.col(i), value, 0));
}
out = col.vector_values(etimes);
EXPECT_EQ(out.rows(), 3);
EXPECT_EQ(out.cols(), 5);
for (int i = 0; i < 4; ++i) {
EXPECT_TRUE(CompareMatrices(out.col(i), value, 0));
}
PiecewisePolynomial<double> row(value.transpose());
out = row.vector_values(times);
EXPECT_EQ(out.rows(), 5);
EXPECT_EQ(out.cols(), 3);
for (int i = 0; i < 4; ++i) {
EXPECT_TRUE(CompareMatrices(out.row(i), value.transpose(), 0));
}
out = row.vector_values(etimes);
EXPECT_EQ(out.rows(), 5);
EXPECT_EQ(out.cols(), 3);
for (int i = 0; i < 4; ++i) {
EXPECT_TRUE(CompareMatrices(out.row(i), value.transpose(), 0));
}
PiecewisePolynomial<double> mat(Eigen::Matrix3d::Identity());
DRAKE_EXPECT_THROWS_MESSAGE(
mat.vector_values(times),
"This method only supports vector-valued trajectories.");
}
GTEST_TEST(testPiecewisePolynomial, RemoveFinalSegmentTest) {
Eigen::VectorXd breaks(3);
breaks << 0, .5, 1.;
// clang-format off
Eigen::MatrixXd samples(2, 3);
samples << 1, 1, 2,
2, 0, 3;
// clang-format on
PiecewisePolynomial<double> pp =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
breaks, samples);
EXPECT_EQ(pp.end_time(), 1.);
EXPECT_EQ(pp.get_number_of_segments(), 2);
pp.RemoveFinalSegment();
EXPECT_EQ(pp.end_time(), .5);
EXPECT_EQ(pp.get_number_of_segments(), 1);
pp.RemoveFinalSegment();
EXPECT_TRUE(pp.empty());
}
std::unique_ptr<Trajectory<double>> TestReverseTime(
const PiecewisePolynomial<double>& pp_orig) {
std::unique_ptr<Trajectory<double>> pp_ptr = pp_orig.Clone();
PiecewisePolynomial<double>* pp =
dynamic_cast<PiecewisePolynomial<double>*>(pp_ptr.get());
pp->ReverseTime();
// Start time and end time have been switched.
EXPECT_NEAR(pp->start_time(), -pp_orig.end_time(), 1e-14);
EXPECT_NEAR(pp->end_time(), -pp_orig.start_time(), 1e-14);
for (const double t : {0.1, .2, .52, .77}) {
EXPECT_TRUE(CompareMatrices(pp->value(t), pp_orig.value(-t), 1e-14));
}
return pp_ptr;
}
void TestScaling(const PiecewisePolynomial<double>& pp_orig,
const double scale) {
std::unique_ptr<Trajectory<double>> pp_ptr = pp_orig.Clone();
PiecewisePolynomial<double>* pp =
dynamic_cast<PiecewisePolynomial<double>*>(pp_ptr.get());
pp->ScaleTime(scale);
EXPECT_NEAR(pp->start_time(), scale * pp_orig.start_time(), 1e-14);
EXPECT_NEAR(pp->end_time(), scale * pp_orig.end_time(), 1e-14);
for (const double trel : {0.1, .2, .52, .77}) {
const double t = pp_orig.start_time() +
trel * (pp_orig.end_time() - pp_orig.start_time());
EXPECT_TRUE(CompareMatrices(pp->value(scale * t), pp_orig.value(t), 1e-14));
}
}
GTEST_TEST(testPiecewisePolynomial, ReverseAndScaleTimeTest) {
Eigen::VectorXd breaks(3);
breaks << 0, .5, 1.;
// clang-format off
Eigen::MatrixXd samples(2, 3);
samples << 1, 1, 2,
2, 0, 3;
// clang-format on
const PiecewisePolynomial<double> zoh =
PiecewisePolynomial<double>::ZeroOrderHold(breaks, samples);
auto reversed_zoh = TestReverseTime(zoh);
// Confirm that the documentation is correct about the subtle behavior at the
// break-points due to the switch in the half-open interval (since zoh is
// discontinuous at the breaks).
EXPECT_FALSE(
CompareMatrices(reversed_zoh->value(-breaks(1)), zoh.value(breaks(1))));
EXPECT_TRUE(CompareMatrices(reversed_zoh->value(-breaks(1)),
zoh.value(breaks(1) - 1e-14)));
TestScaling(zoh, 2.3);
const PiecewisePolynomial<double> foh =
PiecewisePolynomial<double>::FirstOrderHold(breaks, samples);
TestReverseTime(foh);
TestScaling(foh, 1.2);
TestScaling(foh, 3.6);
const PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
breaks, samples);
TestReverseTime(spline);
TestScaling(spline, 2.0);
TestScaling(spline, 4.3);
}
GTEST_TEST(testPiecewisePolynomial, ReshapeBlockAndTranspose) {
std::vector<double> breaks = {0, .5, 1.};
std::vector<Eigen::MatrixXd> samples(3);
samples[0].resize(2, 3);
samples[0] << 1, 1, 2, 2, 0, 3;
samples[1].resize(2, 3);
samples[1] << 3, 4, 5, 6, 7, 8;
samples[2].resize(2, 3);
samples[2] << -.2, 33., 5.4, -2.1, 52, 12;
PiecewisePolynomial<double> zoh =
PiecewisePolynomial<double>::ZeroOrderHold(breaks, samples);
EXPECT_EQ(zoh.rows(), 2);
EXPECT_EQ(zoh.cols(), 3);
zoh.Reshape(3, 2);
EXPECT_EQ(zoh.rows(), 3);
EXPECT_EQ(zoh.cols(), 2);
samples[0].resize(3, 2);
samples[1].resize(3, 2);
EXPECT_TRUE(CompareMatrices(zoh.value(0.25), samples[0]));
EXPECT_TRUE(CompareMatrices(zoh.value(0.75), samples[1]));
PiecewisePolynomial<double> block = zoh.Block(1, 1, 2, 1);
EXPECT_EQ(block.rows(), 2);
EXPECT_EQ(block.cols(), 1);
EXPECT_EQ(block.start_time(), zoh.start_time());
EXPECT_EQ(block.end_time(), zoh.end_time());
EXPECT_EQ(block.get_number_of_segments(), zoh.get_number_of_segments());
EXPECT_EQ(zoh.Block(0, 0, 1, 1).value(0.25), samples[0].block(0, 0, 1, 1));
EXPECT_EQ(zoh.Block(2, 1, 1, 1).value(0.75), samples[1].block(2, 1, 1, 1));
EXPECT_EQ(zoh.Block(1, 1, 2, 1).value(0.75), samples[1].block(1, 1, 2, 1));
PiecewisePolynomial<double> transposed = zoh.Transpose();
EXPECT_EQ(transposed.rows(), 2);
EXPECT_EQ(transposed.cols(), 3);
EXPECT_TRUE(CompareMatrices(transposed.value(0.25), samples[0].transpose()));
EXPECT_TRUE(CompareMatrices(transposed.value(0.75), samples[1].transpose()));
}
GTEST_TEST(testPiecewisePolynomial, IsApproxTest) {
Eigen::VectorXd breaks(3);
breaks << 0, .5, 1.;
Eigen::MatrixXd samples(2, 3);
samples << 1, 2, 3, -5, -4, -3;
// Make the numbers bigger to exaggerate the tolerance test.
samples *= 1000;
const PiecewisePolynomial<double> pp1 =
PiecewisePolynomial<double>::FirstOrderHold(breaks, samples);
const PiecewisePolynomial<double> pp2 = pp1 + Eigen::Vector2d::Ones();
EXPECT_FALSE(pp1.isApprox(pp2, 0.1, ToleranceType::kAbsolute));
EXPECT_TRUE(pp1.isApprox(pp2, 0.1, ToleranceType::kRelative));
}
template <typename T>
void TestScalarType() {
VectorX<T> breaks(3);
breaks << 0, .5, 1.;
MatrixX<T> samples(2, 3);
samples << 1, 1, 2, 2, 0, 3;
const PiecewisePolynomial<T> spline =
PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(breaks,
samples);
const MatrixX<T> value = spline.value(0.5);
EXPECT_NEAR(ExtractDoubleOrThrow(value(0)),
ExtractDoubleOrThrow(samples(0, 1)), 1e-14);
EXPECT_NEAR(ExtractDoubleOrThrow(value(1)),
ExtractDoubleOrThrow(samples(1, 1)), 1e-14);
}
GTEST_TEST(PiecewiseTrajectoryTest, ScalarTypes) {
TestScalarType<double>();
TestScalarType<AutoDiffXd>();
TestScalarType<symbolic::Expression>();
}
// Confirm the expected behavior of PiecewisePolynomial<Expression>.
GTEST_TEST(PiecewiseTrajectoryTest, SymbolicValues) {
using symbolic::Expression;
using symbolic::Variable;
const Vector3<Expression> breaks(0, .5, 1.);
const RowVector3<Expression> samples(6, 5, 4);
const PiecewisePolynomial<Expression> foh =
PiecewisePolynomial<Expression>::FirstOrderHold(breaks, samples);
// value() works if breaks and coefficients are Expressions holding double
// values, evaluated at a double-valued time.
EXPECT_NEAR(ExtractDoubleOrThrow(foh.value(0.25)(0)), 5.5, 1e-14);
// Symbolic time throws (because GetSegmentIndex returns an int in the middle
// of the evaluation stack, breaking the Expression pipeline),
EXPECT_THROW(foh.value(Variable("t")), std::runtime_error);
// Symbolic breaks causes the construction methods to throw.
const Vector3<Expression> symbolic_breaks(Variable("t0"), Variable("t1"),
Variable("t2"));
EXPECT_THROW(
PiecewisePolynomial<Expression>::FirstOrderHold(symbolic_breaks, samples),
std::runtime_error);
// For symbolic samples (and therefore coefficients), value() returns the
// symbolic form at the specified time.
const Variable x0("x0");
const Variable x1("x1");
const Variable x2("x2");
const RowVector3<Expression> symbolic_samples(x0, x1, x2);
const PiecewisePolynomial<Expression> foh_w_symbolic_coeffs =
PiecewisePolynomial<Expression>::FirstOrderHold(breaks, symbolic_samples);
EXPECT_TRUE(foh_w_symbolic_coeffs.value(0.25)(0).Expand().EqualTo(0.5 * x0 +
0.5 * x1));
}
// Verifies that the derivatives obtained by evaluating a
// `PiecewisePolynomial<AutoDiffXd>` and extracting the gradient of the result
// match those obtained by taking the derivative of the whole trajectory and
// evaluating it at the same point.
GTEST_TEST(PiecewiseTrajectoryTest, AutoDiffDerivativesTest) {
VectorX<AutoDiffXd> breaks(3);
breaks << 0, .5, 1.;
MatrixX<AutoDiffXd> samples(2, 3);
samples << 1, 1, 2, 2, 0, 3;
const PiecewisePolynomial<AutoDiffXd> trajectory =
PiecewisePolynomial<AutoDiffXd>::CubicWithContinuousSecondDerivatives(
breaks, samples);
std::unique_ptr<Trajectory<AutoDiffXd>> derivative_trajectory =
trajectory.MakeDerivative();
const int num_times = 100;
VectorX<double> t = VectorX<double>::LinSpaced(
num_times, ExtractDoubleOrThrow(trajectory.start_time()),
ExtractDoubleOrThrow(trajectory.end_time()));
const double tolerance = 20 * std::numeric_limits<double>::epsilon();
for (int k = 0; k < num_times; ++k) {
AutoDiffXd t_k = math::InitializeAutoDiff(Vector1d{t(k)})[0];
MatrixX<double> derivative_value = ExtractGradient(trajectory.value(t_k));
MatrixX<double> expected_derivative_value =
DiscardGradient(derivative_trajectory->value(t(k)));
EXPECT_TRUE(CompareMatrices(derivative_value, expected_derivative_value,
tolerance));
}
}
// Check roundtrip serialization to YAML of an empty trajectory, including a
// golden answer for the serialized form.
GTEST_TEST(PiecesewisePolynomialTest, YamlIoEmpty) {
const PiecewisePolynomial<double> empty;
const std::string yaml = R"""(
breaks: []
polynomials: []
)""";
EXPECT_EQ("\n" + SaveYamlString(empty), yaml);
auto readback = yaml::LoadYamlString<PiecewisePolynomial<double>>(yaml);
EXPECT_TRUE(readback.empty());
}
// Check roundtrip serialization to YAML of a ZOH, including a golden answer for
// the serialized form.
GTEST_TEST(PiecesewisePolynomialTest, YamlIoZoh) {
// clang-format off
std::vector<double> breaks{0, 0.5, 1.0};
std::vector<Eigen::MatrixXd> samples(3);
samples[0].resize(2, 3);
samples[0] << 1, 1, 2,
2, 0, 3;
samples[1].resize(2, 3);
samples[1] << 3, 4, 5,
6, 7, 8;
samples[2].setZero(2, 3);
// clang-format on
const PiecewisePolynomial<double> zoh =
PiecewisePolynomial<double>::ZeroOrderHold(breaks, samples);
const std::string yaml = R"""(
breaks: [0.0, 0.5, 1.0]
polynomials:
-
-
- [1.0]
- [1.0]
- [2.0]
-
- [2.0]
- [0.0]
- [3.0]
-
-
- [3.0]
- [4.0]
- [5.0]
-
- [6.0]
- [7.0]
- [8.0]
)""";
EXPECT_EQ("\n" + SaveYamlString(zoh), yaml);
auto readback = yaml::LoadYamlString<PiecewisePolynomial<double>>(yaml);
const double tolerance = 0.0;
EXPECT_TRUE(readback.isApprox(zoh, tolerance));
}
// Check roundtrip serialization to YAML for a more complicated trajectory.
// Here we don't check the YAML string, just that it goes through unchanged.
GTEST_TEST(PiecesewisePolynomialTest, YamlIoComplicated) {
// clang-format off
Eigen::VectorXd breaks(5);
breaks << 0, 1, 2, 3, 4;
Eigen::MatrixXd samples(3, 5);
samples << 1, 1, 1,
2, 2, 2,
0, 3, 3,
-2, 2, 2,
1, 1, 1;
// clang-format on
const auto dut =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
breaks, samples);
const std::string yaml = SaveYamlString(dut);
const auto readback = yaml::LoadYamlString<PiecewisePolynomial<double>>(yaml);
const double tolerance = 0.0;
EXPECT_TRUE(readback.isApprox(dut, tolerance)) << fmt::format(
"=== original ===\n{}\n"
"=== readback ===\n{}",
yaml, SaveYamlString(readback));
}
// Check that mixed-degree polynomials get padded out to the max degree.
GTEST_TEST(PiecesewisePolynomialTest, YamlIoRagged) {
Polynomial<double> poly0(Eigen::Vector2d(1.0, 2.0));
Polynomial<double> poly1(Eigen::Vector3d(3.0, 4.0, 5.0));
const PiecewisePolynomial<double> dut({poly0, poly1}, {0.0, 1.0, 2.0});
const std::string yaml = R"""(
breaks: [0.0, 1.0, 2.0]
polynomials:
-
-
- [1.0, 2.0, 0.0]
-
-
- [3.0, 4.0, 5.0]
)""";
EXPECT_EQ("\n" + SaveYamlString(dut), yaml);
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/bspline_trajectory_test.cc | #include "drake/common/trajectories/bspline_trajectory.h"
#include <algorithm>
#include <functional>
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include "drake/common/default_scalars.h"
#include "drake/common/proto/call_python.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/trajectories/trajectory.h"
#include "drake/common/yaml/yaml_io.h"
#include "drake/math/autodiff_gradient.h"
#include "drake/math/bspline_basis.h"
#include "drake/math/compute_numerical_gradient.h"
#include "drake/math/knot_vector_type.h"
DEFINE_bool(visualize, false,
"If true, emit Python plotting commands using CallPython(). "
"You must build and run //common/proto:call_python_client_cli "
"first in order to see the resulting plots (you will also need to "
"set up an rpc file - see the --help for call_python_client_cli "
"for more information). This option does not work with "
"`bazel run`. Run the binary from bazel-bin instead.");
namespace drake {
namespace trajectories {
using common::CallPython;
using math::BsplineBasis;
using math::ComputeNumericalGradient;
using math::ExtractGradient;
using math::KnotVectorType;
using math::NumericalGradientMethod;
using math::NumericalGradientOption;
using symbolic::Expression;
using yaml::LoadYamlString;
namespace {
template <typename T = double>
BsplineTrajectory<T> MakeCircleTrajectory() {
using std::cos;
using std::sin;
const int order = 4;
const int num_control_points = 11;
std::vector<MatrixX<T>> control_points{};
const auto t_dummy = VectorX<T>::LinSpaced(num_control_points, 0, 2 * M_PI);
for (int i = 0; i < num_control_points; ++i) {
control_points.push_back(
(MatrixX<T>(2, 1) << sin(t_dummy(i)), cos(t_dummy(i))).finished());
}
return {BsplineBasis<T>{order, num_control_points}, control_points};
}
} // namespace
template <typename T>
class BsplineTrajectoryTests : public ::testing::Test {};
using DefaultScalars = ::testing::Types<double, AutoDiffXd, Expression>;
TYPED_TEST_SUITE(BsplineTrajectoryTests, DefaultScalars);
// Verifies that the constructors work as expected.
TYPED_TEST(BsplineTrajectoryTests, ConstructorTest) {
using T = TypeParam;
const int expected_order = 4;
const int expected_num_control_points = 11;
const std::vector<T> expected_knots{
0, 0, 0, 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1, 1, 1, 1};
const int expected_rows = 2;
const int expected_cols = 1;
const T expected_start_time = 0;
const T expected_end_time = 1;
std::vector<MatrixX<T>> expected_control_points{};
for (int i = 0; i < expected_num_control_points; ++i) {
expected_control_points.push_back(
i * MatrixX<T>::Ones(expected_rows, expected_cols));
}
BsplineBasis<T> bspline_basis_1{expected_order, expected_knots};
BsplineTrajectory<T> trajectory{bspline_basis_1, expected_control_points};
// Verify method return values.
EXPECT_EQ(trajectory.rows(), expected_rows);
EXPECT_EQ(trajectory.cols(), expected_cols);
EXPECT_EQ(trajectory.start_time(), expected_start_time);
EXPECT_EQ(trajectory.end_time(), expected_end_time);
// Use std::equal (not EXPECT_EQ) to deal with symbolic::Formula.
const auto& traj_control_points = trajectory.control_points();
EXPECT_TRUE(
std::equal(traj_control_points.begin(), traj_control_points.end(),
expected_control_points.begin(), expected_control_points.end(),
[](const auto& traj_matrix, const auto& expected_matrix) {
return (traj_matrix - expected_matrix).norm() == 0.0;
}));
// Verify that construction from BsplineBasis<double> works.
std::vector<double> knots_double{};
for (const auto& knot : expected_knots) {
knots_double.push_back(ExtractDoubleOrThrow(knot));
}
BsplineBasis<double> bspline_basis_2{expected_order, knots_double};
BsplineTrajectory<T> trajectory_from_double{bspline_basis_2,
expected_control_points};
EXPECT_EQ(trajectory_from_double, trajectory);
}
// Verifies that value() works as expected (i.e. as a thin wrapper on
// basis().EvaluateCurve() with clamping).
TYPED_TEST(BsplineTrajectoryTests, ValueTest) {
using T = TypeParam;
BsplineTrajectory<T> trajectory = MakeCircleTrajectory<T>();
// Verify that value() returns the expected results.
const int num_times = 100;
VectorX<T> t = VectorX<T>::LinSpaced(num_times, trajectory.start_time() - 0.1,
trajectory.end_time() + 0.1);
for (int k = 0; k < num_times; ++k) {
MatrixX<T> value = trajectory.value(t(k));
using std::clamp;
const T t_clamped =
clamp(t(k), trajectory.start_time(), trajectory.end_time());
MatrixX<T> expected_value = trajectory.basis().EvaluateCurve(
trajectory.control_points(), t_clamped);
EXPECT_TRUE(CompareMatrices(value, expected_value,
std::numeric_limits<T>::epsilon()));
}
}
// Verifies that MakeDerivative() works as expected.
TYPED_TEST(BsplineTrajectoryTests, MakeDerivativeTest) {
using T = TypeParam;
BsplineTrajectory<T> trajectory = MakeCircleTrajectory<T>();
// Verify that MakeDerivative() returns the expected results.
std::unique_ptr<Trajectory<T>> derivative_trajectory =
trajectory.MakeDerivative();
std::function<void(const Vector1<T>&, VectorX<T>*)> calc_value =
[&trajectory](const Vector1<T>& t, VectorX<T>* value) {
*value = trajectory.value(t(0));
};
const int num_times = 100;
VectorX<T> t = VectorX<T>::LinSpaced(num_times, trajectory.start_time(),
trajectory.end_time());
for (int k = 0; k < num_times; ++k) {
MatrixX<T> derivative = derivative_trajectory->value(t(k));
// To avoid evaluating the B-spline trajectory outside of its domain, we
// use forward/backward finite differences at the start/end points.
NumericalGradientMethod method = NumericalGradientMethod::kCentral;
double tolerance = 1e-7;
if (k == 0) {
method = NumericalGradientMethod::kForward;
tolerance = 1e-5;
} else if (k == num_times - 1) {
method = NumericalGradientMethod::kBackward;
tolerance = 1e-5;
}
MatrixX<T> expected_derivative = ComputeNumericalGradient(
calc_value, Vector1<T>{t(k)}, NumericalGradientOption{method});
EXPECT_TRUE(CompareMatrices(derivative, expected_derivative, tolerance));
}
// Verify that MakeDerivative() returns 0 matrix for derivative of order
// higher than basis degree
derivative_trajectory = trajectory.MakeDerivative(trajectory.basis().order());
MatrixX<T> expected_derivative =
MatrixX<T>::Zero(trajectory.rows(), trajectory.cols());
for (int k = 0; k < num_times; ++k) {
MatrixX<T> derivative = derivative_trajectory->value(t(k));
EXPECT_TRUE(CompareMatrices(derivative, expected_derivative, 0.0));
}
}
// Verifies that EvalDerivative() works as expected.
TYPED_TEST(BsplineTrajectoryTests, EvalDerivativeTest) {
using T = TypeParam;
BsplineTrajectory<T> trajectory = MakeCircleTrajectory<T>();
// Verify that EvalDerivative() returns the consistent results.
const int num_times = 20;
VectorX<T> t = VectorX<T>::LinSpaced(num_times, trajectory.start_time(),
trajectory.end_time());
for (int o = 0; o < trajectory.basis().order(); ++o) {
std::unique_ptr<Trajectory<T>> derivative_trajectory =
trajectory.MakeDerivative(o);
for (int k = 0; k < num_times; ++k) {
MatrixX<T> derivative = trajectory.EvalDerivative(t(k), o);
MatrixX<T> expected_derivative = derivative_trajectory->value(t(k));
double tolerance = 1e-14;
EXPECT_TRUE(CompareMatrices(derivative, expected_derivative, tolerance));
}
}
// Verify that evaluating outside the time interval gets clamped.
for (int o = 0; o < trajectory.basis().order(); ++o) {
EXPECT_TRUE(CompareMatrices(
trajectory.EvalDerivative(trajectory.start_time() - 1, o),
trajectory.EvalDerivative(trajectory.start_time(), o)));
EXPECT_TRUE(
CompareMatrices(trajectory.EvalDerivative(trajectory.end_time() + 1, o),
trajectory.EvalDerivative(trajectory.end_time(), o)));
}
}
// Verifies that CopyBlock() works as expected.
TYPED_TEST(BsplineTrajectoryTests, CopyBlockTest) {
using T = TypeParam;
using std::cos;
using std::sin;
const int order = 4;
const int num_control_points = 11;
const int rows = 3;
const int cols = 3;
std::vector<MatrixX<T>> control_points{};
std::vector<MatrixX<T>> expected_control_points{};
const auto t_dummy = VectorX<T>::LinSpaced(num_control_points, 0, 2 * M_PI);
for (int i = 0; i < num_control_points; ++i) {
T s = sin(t_dummy(i));
T c = cos(t_dummy(i));
// clang-format off
control_points.push_back(
(MatrixX<T>(rows, cols) <<
s, c, s,
s, s, c,
c, s, s).finished());
// clang-format on
expected_control_points.push_back(control_points.back().block(0, 0, 2, 3));
}
for (const auto& knot_vector_type :
{KnotVectorType::kUniform, KnotVectorType::kClampedUniform}) {
BsplineTrajectory<T> trajectory =
BsplineTrajectory<T>{
BsplineBasis<T>{order, num_control_points, knot_vector_type},
control_points}
.CopyBlock(0, 0, 2, 3);
BsplineTrajectory<T> expected_trajectory = BsplineTrajectory<T>{
BsplineBasis<T>{order, num_control_points, knot_vector_type},
expected_control_points};
EXPECT_EQ(trajectory, expected_trajectory);
}
}
// Verifies that InsertKnots() works as expected.
TYPED_TEST(BsplineTrajectoryTests, InsertKnotsTest) {
using T = TypeParam;
BsplineTrajectory<T> original_trajectory = MakeCircleTrajectory<T>();
// Create a vector of new knots to add. Note that it contains a knot with a
// multiplicity of 2.
std::vector<T> new_knots{original_trajectory.start_time(), M_PI_4, 0.25, 0.25,
original_trajectory.end_time()};
// Add the new knots.
BsplineTrajectory<T> trajectory_with_new_knots = original_trajectory;
trajectory_with_new_knots.InsertKnots({new_knots});
// Verify that the number of control points after insertion is equal to the
// original number of control points plus the number of added knots.
EXPECT_EQ(trajectory_with_new_knots.num_control_points(),
original_trajectory.num_control_points() + new_knots.size());
// Add the new knots again to verify that nothing goes wrong if the
// trajectory into which knots are inserted has interior knots with
// multiplicity greater than 1.
trajectory_with_new_knots.InsertKnots({new_knots});
// Verify that the number of control points after insertion is equal to the
// original number of control points plus the number of added knots.
EXPECT_EQ(trajectory_with_new_knots.num_control_points(),
original_trajectory.num_control_points() + 2 * new_knots.size());
// Verify that start_time() and end_time() return the same results for the
// original trajectory and the one with additional knots.
EXPECT_EQ(trajectory_with_new_knots.start_time(),
original_trajectory.start_time());
EXPECT_EQ(trajectory_with_new_knots.end_time(),
original_trajectory.end_time());
// Verify that value() returns the same result for the original trajectory
// and the trajectory with additional knots for `num_times` sampled values
// of `t` between start_time() and end_time().
const int num_times = 100;
VectorX<T> t =
VectorX<T>::LinSpaced(num_times, original_trajectory.start_time(),
original_trajectory.end_time());
const double tolerance = 2 * std::numeric_limits<double>::epsilon();
if constexpr (std::is_same_v<T, double>) {
if (FLAGS_visualize) {
CallPython("figure");
}
}
for (int k = 0; k < num_times; ++k) {
MatrixX<T> value = trajectory_with_new_knots.value(t(k));
MatrixX<T> expected_value = original_trajectory.value(t(k));
EXPECT_TRUE(CompareMatrices(value, expected_value, tolerance));
if constexpr (std::is_same_v<T, double>) {
if (FLAGS_visualize) {
CallPython(
"plot", t(k), value.transpose(),
CompareMatrices(value, expected_value, tolerance) ? "gs" : "rs");
CallPython("plot", t(k), expected_value.transpose(), "ko");
}
}
}
if constexpr (std::is_same_v<T, double>) {
if (FLAGS_visualize) {
CallPython("grid", true);
}
}
}
// Verifies that the derivatives obtained by evaluating a
// `BsplineTrajectory<AutoDiffXd>` and extracting the gradient of the result
// match those obtained by taking the derivative of the whole trajectory and
// evaluating it at the same point.
GTEST_TEST(BsplineTrajectoryDerivativeTests, AutoDiffTest) {
BsplineTrajectory<AutoDiffXd> trajectory = MakeCircleTrajectory<AutoDiffXd>();
std::unique_ptr<Trajectory<double>> derivative_trajectory =
MakeCircleTrajectory<double>().MakeDerivative();
const int num_times = 100;
VectorX<double> t = VectorX<double>::LinSpaced(
num_times, ExtractDoubleOrThrow(trajectory.start_time()),
ExtractDoubleOrThrow(trajectory.end_time()));
const double kTolerance = 20 * std::numeric_limits<double>::epsilon();
for (int k = 0; k < num_times; ++k) {
AutoDiffXd t_k = math::InitializeAutoDiff(Vector1d{t(k)})[0];
MatrixX<double> derivative_value = ExtractGradient(trajectory.value(t_k));
MatrixX<double> expected_derivative_value =
derivative_trajectory->value(t(k));
EXPECT_TRUE(CompareMatrices(derivative_value, expected_derivative_value,
kTolerance));
}
}
const char* const good = R"""(
basis: !BsplineBasis
order: 2
knots: [0., 1., 1.5, 1.6, 2.]
control_points:
-
- [0.0, 0.1, 0.2]
- [0.3, 0.4, 0.5]
-
- [1.0, 1.1, 1.2]
- [1.3, 1.4, 1.5]
-
- [2.0, 2.1, 2.2]
- [2.3, 2.4, 2.5]
)""";
GTEST_TEST(BsplineTrajectorySerializeTests, GoodTest) {
const int kOrder{2};
const std::vector<double> knots{0., 1., 1.5, 1.6, 2.};
// clang-format off
const std::vector<MatrixX<double>> control_points{
(MatrixX<double>(2, 3) << 0.0, 0.1, 0.2,
0.3, 0.4, 0.5).finished(),
(MatrixX<double>(2, 3) << 1.0, 1.1, 1.2,
1.3, 1.4, 1.5).finished(),
(MatrixX<double>(2, 3) << 2.0, 2.1, 2.2,
2.3, 2.4, 2.5).finished(),
};
// clang-format on
const auto dut = LoadYamlString<BsplineTrajectory<double>>(good);
EXPECT_EQ(dut, BsplineTrajectory<double>(BsplineBasis<double>(kOrder, knots),
control_points));
}
const char* const not_enough_control_points = R"""(
basis: !BsplineBasis
order: 2
knots: [0., 1., 1.5, 1.6, 2.]
control_points:
-
- [0.0, 0.1, 0.2]
- [0.3, 0.4, 0.5]
-
- [1.0, 1.1, 1.2]
- [1.3, 1.4, 1.5]
)""";
GTEST_TEST(BsplineTrajectorySerializeTests, NotEnoughControlPointsTest) {
DRAKE_EXPECT_THROWS_MESSAGE(
LoadYamlString<BsplineTrajectory<double>>(not_enough_control_points),
".*num_basis_functions.*");
}
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/discrete_time_trajectory_test.cc | #include "drake/common/trajectories/discrete_time_trajectory.h"
#include <gtest/gtest.h>
#include "drake/common/drake_assert.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
namespace drake {
namespace trajectories {
namespace {
GTEST_TEST(DiscreteTimeTrajectoryTest, EigenConstructorTest) {
const Eigen::Vector3d times{0., 0.31, .52};
Eigen::Matrix3d values;
values << 2, 5, 67, 5, -4, 1, 34, 16, -23;
DiscreteTimeTrajectory<double> traj(times, values);
EXPECT_EQ(traj.num_times(), 3);
EXPECT_EQ(traj.get_times()[1], times[1]);
EXPECT_EQ(traj.value(times[1]), values.col(1));
EXPECT_EQ(traj.rows(), 3);
EXPECT_EQ(traj.cols(), 1);
EXPECT_EQ(traj.start_time(), times[0]);
EXPECT_EQ(traj.end_time(), times[2]);
}
GTEST_TEST(DiscreteTimeTrajectoryTest, StdVectorConstructorTest) {
const std::vector<double> times{0., 0.31, .52};
std::vector<Eigen::MatrixXd> values(3, Eigen::Vector3d::Zero());
values[0] << 2, 5, 67;
values[1] << 5, -4, 1;
values[2] << 34, 16, -23;
DiscreteTimeTrajectory<double> traj(times, values);
EXPECT_EQ(traj.num_times(), 3);
EXPECT_EQ(traj.get_times()[1], times[1]);
EXPECT_EQ(traj.value(times[1]), values[1]);
EXPECT_EQ(traj.rows(), 3);
EXPECT_EQ(traj.cols(), 1);
EXPECT_EQ(traj.start_time(), times[0]);
EXPECT_EQ(traj.end_time(), times[2]);
}
GTEST_TEST(DiscreteTimeTrajectoryTest, ValueThrowsTest) {
const Eigen::Vector3d times{0., 0.31, .52};
Eigen::Matrix3d values;
values << 2, 5, 67, 5, -4, 1, 34, 16, -23;
DiscreteTimeTrajectory<double> traj(times, values);
DRAKE_EXPECT_THROWS_MESSAGE(
traj.value(-1), "Value requested at time -1(\\.0)? does not match .*");
DRAKE_EXPECT_THROWS_MESSAGE(traj.value(0.4),
"Value requested at time 0.4 does not match .*");
DRAKE_EXPECT_THROWS_MESSAGE(
traj.value(1), "Value requested at time 1(\\.0)? does not match .*");
const double kLooseTolerance = 0.1;
DiscreteTimeTrajectory<double> traj_w_loose_tol(times, values,
kLooseTolerance);
EXPECT_EQ(traj_w_loose_tol.time_comparison_tolerance(), kLooseTolerance);
EXPECT_EQ(traj_w_loose_tol.value(0.4), values.col(1));
}
GTEST_TEST(DiscreteTimeTrajectoryTest, CloneTest) {
const Eigen::Vector3d times{0.24, 0.331, .526};
Eigen::Matrix3d values;
values << 6, 5, 67, 5, -4, 1, 34, 16, -23;
const double kTimeComparisonTol = 0.01;
DiscreteTimeTrajectory<double> traj(times, values, kTimeComparisonTol);
auto clone = traj.Clone();
EXPECT_EQ(clone->start_time(), traj.start_time());
EXPECT_EQ(clone->end_time(), traj.end_time());
EXPECT_EQ(clone->value(times[1]), values.col(1));
EXPECT_EQ(clone->value(times[1] + kTimeComparisonTol / 2.0), values.col(1));
}
template <typename T>
void ScalarTypeTest() {
const Vector3<T> times{0.24, 0.331, .526};
Matrix3<T> values;
values << 6, 5, 67, 5, -4, 1, 34, 16, -23;
DiscreteTimeTrajectory<T> traj(times, values);
EXPECT_EQ(traj.value(times[1]), values.col(1));
}
GTEST_TEST(DiscreteTimeTrajectoryTest, ScalarTypeTest) {
ScalarTypeTest<double>();
ScalarTypeTest<AutoDiffXd>();
ScalarTypeTest<symbolic::Expression>();
}
// Confirm that Expression fails fast if times are not constants.
GTEST_TEST(DicreteTimeTrajectoryTest, SymbolicTimes) {
using symbolic::Expression;
symbolic::Variable t{"t"};
Vector3<Expression> times{0.24, t, .526};
Matrix3<Expression> values;
values << 6, 5, 67, 5, -4, 1, 34, 16, -23;
DRAKE_EXPECT_THROWS_MESSAGE(
DiscreteTimeTrajectory<Expression>(times, values),
".*environment does not have an entry for the variable t.*\n*");
times[1] = 0.4;
DiscreteTimeTrajectory<Expression> traj(times, values);
DRAKE_EXPECT_THROWS_MESSAGE(
traj.value(t),
".*environment does not have an entry for the variable t.*\n*");
}
// Confirm that autodiff gradients on the time parameters have no impact on the
// trajectory values.
GTEST_TEST(DiscreteTimeTrajectoryTest, AutodiffTimes) {
Vector3<AutoDiffXd> times{0.24, 0.34, .526};
Matrix3<AutoDiffXd> values;
values << 6, 5, 67, 5, -4, 1, 34, 16, -23;
// Case 1: No gradients on the trajectory member variables, but gradients on
// the sampled time.
DiscreteTimeTrajectory<AutoDiffXd> traj(times, values);
AutoDiffXd t{times[1]};
t.derivatives() = Eigen::Vector2d(-2, 3);
Vector3<AutoDiffXd> y = traj.value(t);
for (int i = 0; i < 3; ++i) {
EXPECT_EQ(y[i].derivatives().size(), 0);
}
// Case 2: Gradients on the time member variables.
times[1].derivatives() = Eigen::Vector2d(24, 1.2);
DiscreteTimeTrajectory<AutoDiffXd> traj2(times, values);
y = traj2.value(t);
for (int i = 0; i < 3; ++i) {
EXPECT_EQ(y[i].derivatives().size(), 0);
}
// Case 3: Gradients on the value member variables DO persist.
values(2, 0).derivatives() = Eigen::Vector3d(3, 4, 6);
DiscreteTimeTrajectory<AutoDiffXd> traj3(times, values);
y = traj3.value(times[0]);
EXPECT_EQ(y[2].derivatives(), Eigen::Vector3d(3, 4, 6));
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/derivative_trajectory_test.cc | #include "drake/common/trajectories/derivative_trajectory.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/trajectories/discrete_time_trajectory.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/common/trajectories/piecewise_quaternion.h"
namespace drake {
namespace trajectories {
namespace {
using Eigen::Vector2d;
using Vector1d = Vector1<double>;
// Create an arbitrary piecewise polynomial trajectory.
template <typename T>
PiecewisePolynomial<T> MakePP() {
return PiecewisePolynomial<T>::CubicShapePreserving(
{0.2, 0.3, 0.7, 0.8}, {Vector2d(10, -100), Vector2d(20, 0),
Vector2d(90, 10), Vector2d(100, 200)});
}
GTEST_TEST(DerivativeTrajectoryTest, BasicTest) {
const PiecewisePolynomial<double> nominal = MakePP<double>();
for (int derivative_order = 0; derivative_order < 3; ++derivative_order) {
const DerivativeTrajectory<double> dut(nominal, derivative_order);
EXPECT_EQ(dut.rows(), nominal.rows());
EXPECT_EQ(dut.cols(), nominal.cols());
EXPECT_TRUE(dut.has_derivative());
EXPECT_EQ(dut.start_time(), nominal.start_time());
EXPECT_EQ(dut.end_time(), nominal.end_time());
const double t = 0.45;
EXPECT_TRUE(CompareMatrices(dut.value(t),
nominal.EvalDerivative(t, derivative_order)));
auto clone = dut.Clone();
EXPECT_TRUE(CompareMatrices(clone->value(t),
nominal.EvalDerivative(t, derivative_order)));
for (int i = 0; i < 2; ++i) {
EXPECT_TRUE(
CompareMatrices(dut.EvalDerivative(t, i),
nominal.EvalDerivative(t, derivative_order + i)));
auto deriv = dut.MakeDerivative(i);
EXPECT_TRUE(CompareMatrices(
deriv->value(t), nominal.EvalDerivative(t, derivative_order + i)));
}
}
}
GTEST_TEST(DerivativeTrajectoryTest, ThrowsIfNoDerivative) {
DiscreteTimeTrajectory<double> nominal({0.1, 0.4},
{Vector1d{0.3}, Vector1d{0.5}});
DRAKE_EXPECT_THROWS_MESSAGE(DerivativeTrajectory(nominal),
".*has_derivative.*failed.*");
}
GTEST_TEST(DerivativeTrajectoryTest, ThrowsIfNegativeOrder) {
const PiecewisePolynomial<double> nominal = MakePP<double>();
DRAKE_EXPECT_THROWS_MESSAGE(DerivativeTrajectory(nominal, -1),
".*derivative_order.*failed.*");
}
// PiecewiseQuaternion has the feature that the number of rows of the
// derivative is different than the rows of the nominal.
GTEST_TEST(DerivativeTrajectoryTest, PiecewiseQuaternion) {
const std::vector<double> time = {0, 1.6, 2.32};
const std::vector<double> ang = {1, 2.4 - 2 * M_PI, 5.3};
const Vector3<double> axis = Vector3<double>(1, 2, 3).normalized();
std::vector<Quaternion<double>> quat(ang.size());
for (size_t i = 0; i < ang.size(); ++i) {
quat[i] = Quaternion<double>(AngleAxis<double>(ang[i], axis));
}
const PiecewiseQuaternionSlerp<double> nominal(time, quat);
for (int derivative_order = 0; derivative_order < 3; ++derivative_order) {
DerivativeTrajectory dut(nominal, derivative_order);
EXPECT_EQ(dut.rows(), derivative_order == 0 ? 4 : 3);
const double t = 0.45;
EXPECT_TRUE(CompareMatrices(dut.value(t),
nominal.EvalDerivative(t, derivative_order)));
}
}
template <typename T>
void TestScalar() {
const PiecewisePolynomial<T> nominal = MakePP<T>();
const int derivative_order = 1;
const DerivativeTrajectory<T> dut(nominal, derivative_order);
const T time{0.62};
EXPECT_EQ(dut.value(time), nominal.EvalDerivative(time));
}
GTEST_TEST(DerivativeTrajectoryTest, DefaultScalars) {
TestScalar<double>();
TestScalar<AutoDiffXd>();
TestScalar<symbolic::Expression>();
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/piecewise_polynomial_generation_test.cc | #include "drake/common/test_utilities/expect_no_throw.h"
/* clang-format off to disable clang-format-includes */
#include "drake/common/trajectories/piecewise_polynomial.h"
/* clang-format on */
#include <random>
#include <vector>
#include <gtest/gtest.h>
#include "drake/common/drake_assert.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
using Eigen::Matrix3d;
using Eigen::MatrixXd;
using Eigen::Vector3d;
using std::default_random_engine;
namespace drake {
namespace trajectories {
namespace {
// Computes the maximum or minimum velocity in interval [0, t].
// This assumes `vel` is a second order polynomial.
template <typename T>
T ComputeExtremeVel(const Polynomial<T>& vel, double t, bool max_vel) {
DRAKE_DEMAND(vel.GetDegree() == 2);
Polynomial<T> acc = vel.Derivative();
VectorX<T> acc_coeffs = acc.GetCoefficients();
T vel0 = vel.EvaluateUnivariate(0);
T vel1 = vel.EvaluateUnivariate(t);
T vel_extrema = vel0;
// Not constant acceleration, vel extrema is when acc = 0.
if (std::abs(acc_coeffs[1]) > 1e-12) {
T t_extrema = -acc_coeffs[0] / acc_coeffs[1];
// If t_extrema is in [0, t], vel_extrema needs to be evaluated.
// Otherwise, it's at one of the end points.
if (t_extrema >= 0 && t_extrema <= t) {
vel_extrema = vel.EvaluateUnivariate(t_extrema);
}
}
if (max_vel) {
return std::max(std::max(vel0, vel1), vel_extrema);
} else {
return std::min(std::min(vel0, vel1), vel_extrema);
}
}
// Check continuity for up to d degree, where d is the minimum of \p degree and
// the highest degree of the trajectory.
template <typename T>
bool CheckContinuity(const PiecewisePolynomial<T>& traj, T tol, int degree) {
if (degree < 0) return false;
typedef Polynomial<T> PolynomialType;
int rows = traj.rows();
int cols = traj.cols();
T val0, val1;
for (int n = 0; n < traj.get_number_of_segments() - 1; ++n) {
double dt = traj.duration(n);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
PolynomialType poly = traj.getPolynomial(n, i, j);
PolynomialType next_poly = traj.getPolynomial(n + 1, i, j);
int max_degree =
std::min(degree, traj.getSegmentPolynomialDegree(n, i, j));
for (int d = 0; d < max_degree + 1; d++) {
// Values evaluated at the end of the current segment.
val0 = poly.EvaluateUnivariate(dt);
// Values evaluated at the beginning of the next segment.
val1 = next_poly.EvaluateUnivariate(0);
if (std::abs(val0 - val1) > tol) {
return false;
}
poly = poly.Derivative();
next_poly = next_poly.Derivative();
}
}
}
}
return true;
}
// Check P(t), P'(t), P''(t), ... match values[i][t], where i is the ith
// derivative, and t is the tth break.
template <typename T>
bool CheckValues(const PiecewisePolynomial<T>& traj,
const std::vector<std::vector<MatrixX<T>>>& values, T tol,
bool check_last_time_step = true) {
if (values.empty()) return false;
typedef Polynomial<T> PolynomialType;
int rows = traj.rows();
int cols = traj.cols();
T val0, val1;
for (int n = 0; n < traj.get_number_of_segments(); ++n) {
double dt = traj.duration(n);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
PolynomialType poly = traj.getPolynomial(n, i, j);
for (const auto& value : values) {
// Values evaluated at the beginning of the current segment.
val0 = poly.EvaluateUnivariate(0);
if (std::abs(val0 - value.at(n)(i, j)) > tol) {
return false;
}
// Checks the last time step's values.
if (check_last_time_step && n == traj.get_number_of_segments() - 1) {
// Values evaluated at the end.
val1 = poly.EvaluateUnivariate(dt);
if (std::abs(val1 - value.at(n + 1)(i, j)) > tol) {
return false;
}
}
poly = poly.Derivative();
}
}
}
}
return true;
}
template <typename T>
bool CheckInterpolatedValuesAtBreakTime(const PiecewisePolynomial<T>& traj,
const std::vector<double>& breaks,
const std::vector<MatrixX<T>>& values,
T tol,
bool check_last_time_step = true) {
int N = static_cast<int>(breaks.size());
for (int i = 0; i < N; ++i) {
if (i == N - 1 && !check_last_time_step) continue;
if (!CompareMatrices(traj.value(breaks[i]), values[i], tol,
MatrixCompareType::absolute)) {
return false;
}
}
return true;
}
// This function does the following checks for each dimension of Y:
// traj(T) = Y
// for each segment Pi:
// Pi(end_time_i) = Pi+1(0)
// Pi'(end_time_i) = Pi+1'(0)
// if (Y[i+1] - Y[i] > 0)
// min(Pi') >= 0
// else if (Y[i+1] - Y[i] < 0)
// max(Pi') <= 0
//
// The last two conditions are the monotonic conditions ("shape preserving").
template <typename T>
void PchipTest(const std::vector<double>& breaks,
const std::vector<MatrixX<T>>& samples,
const PiecewisePolynomial<T>& traj, T tol) {
typedef Polynomial<T> PolynomialType;
const std::vector<MatrixX<T>>& Y = samples;
int rows = Y.front().rows();
int cols = Y.front().cols();
EXPECT_TRUE(CheckContinuity(traj, tol, 1));
EXPECT_TRUE(CheckValues(traj, {Y}, tol));
EXPECT_TRUE(CheckInterpolatedValuesAtBreakTime(traj, breaks, Y, tol));
// Check monotonic.
for (int n = 0; n < traj.get_number_of_segments(); ++n) {
double dt = traj.duration(n);
EXPECT_NEAR(breaks[n], traj.start_time(n), tol);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
const PolynomialType& poly = traj.getPolynomial(n, i, j);
PolynomialType poly_deriv = poly.Derivative();
T y0 = poly.EvaluateUnivariate(0);
T y1 = poly.EvaluateUnivariate(dt);
double vv;
// If Y is increasing in this segment, all velocity in this segment >=
// 0.
if (y1 > y0) {
vv = ComputeExtremeVel(poly_deriv, dt, false);
EXPECT_TRUE(vv >= -tol);
} else if (y1 < y0) {
// If Y is increasing in this segment, all velocity in this segment >=
// 0.
vv = ComputeExtremeVel(poly_deriv, dt, true);
EXPECT_TRUE(vv <= tol);
} else {
vv = ComputeExtremeVel(poly_deriv, dt, true);
EXPECT_NEAR(vv, 0, tol);
}
}
}
}
}
GTEST_TEST(SplineTests, PchipAndCubicSplineCompareWithMatlabTest) {
// Matlab example (matlab's coefs has the opposite order):
// x = -3:3;
// y = [-1 -1 -1 0 1 1 1];
// pp = pchip(x,y);
// pp.coefs
//
// ans =
//
// 0 0 0 -1
// 0 0 0 -1
// -1 2 0 -1
// -1 1 1 0
// 0 0 0 1
// 0 0 0 1
std::vector<double> T = {-3, -2, -1, 0, 1, 2, 3};
std::vector<MatrixX<double>> Y(T.size(), MatrixX<double>::Zero(1, 1));
Y[0](0, 0) = -1;
Y[1](0, 0) = -1;
Y[2](0, 0) = -1;
Y[3](0, 0) = 0;
Y[4](0, 0) = 1;
Y[5](0, 0) = 1;
Y[6](0, 0) = 1;
std::vector<Vector4<double>> coeffs(T.size());
coeffs[0] << -1, 0, 0, 0;
coeffs[1] << -1, 0, 0, 0;
coeffs[2] << -1, 0, 2, -1;
coeffs[3] << 0, 1, 1, -1;
coeffs[4] << 1, 0, 0, 0;
coeffs[5] << 1, 0, 0, 0;
PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::CubicShapePreserving(T, Y);
EXPECT_EQ(spline.get_number_of_segments(), static_cast<int>(T.size()) - 1);
for (int t = 0; t < spline.get_number_of_segments(); ++t) {
const PiecewisePolynomial<double>::PolynomialMatrix& poly_matrix =
spline.getPolynomialMatrix(t);
EXPECT_TRUE(CompareMatrices(poly_matrix(0, 0).GetCoefficients(), coeffs[t],
1e-12, MatrixCompareType::absolute));
}
PchipTest(T, Y, spline, 1e-12);
// pp = spline(x, y)
// pp.coefs
//
// ans =
//
// 0.2500 -0.7500 0.5000 -1.0000
// 0.2500 0 -0.2500 -1.0000
// -0.2500 0.7500 0.5000 -1.0000
// -0.2500 0 1.2500 0
// 0.2500 -0.7500 0.5000 1.0000
// 0.2500 0.0000 -0.2500 1.0000
coeffs[0] << -1, 0.5, -0.75, 0.25;
coeffs[1] << -1, -0.25, 0, 0.25;
coeffs[2] << -1, 0.5, 0.75, -0.25;
coeffs[3] << 0, 1.25, 0, -0.25;
coeffs[4] << 1, 0.5, -0.75, 0.25;
coeffs[5] << 1, -0.25, 0, 0.25;
spline =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(T, Y);
EXPECT_EQ(spline.get_number_of_segments(), static_cast<int>(T.size()) - 1);
for (int t = 0; t < spline.get_number_of_segments(); ++t) {
const PiecewisePolynomial<double>::PolynomialMatrix& poly_matrix =
spline.getPolynomialMatrix(t);
EXPECT_TRUE(CompareMatrices(poly_matrix(0, 0).GetCoefficients(), coeffs[t],
1e-12, MatrixCompareType::absolute));
}
EXPECT_TRUE(CheckContinuity(spline, 1e-12, 2));
EXPECT_TRUE(CheckValues(spline, {Y}, 1e-12));
EXPECT_TRUE(CheckInterpolatedValuesAtBreakTime(spline, T, Y, 1e-12));
// Add special case for pchip to test for the last two samples being the same.
// There was a sign comparison bug in ComputePchipEndSlope when the end
// slope = 0. See issue #4450.
T = {0, 1, 2};
Y.resize(T.size(), MatrixX<double>::Zero(1, 1));
Y[0](0, 0) = 1;
Y[1](0, 0) = 3;
Y[2](0, 0) = 3;
spline = PiecewisePolynomial<double>::CubicShapePreserving(T, Y);
EXPECT_TRUE(CompareMatrices(
spline.getPolynomialMatrix(0)(0, 0).GetCoefficients(),
Vector4<double>(1, 3, 0, -1), 1e-12, MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(
spline.getPolynomialMatrix(1)(0, 0).GetCoefficients(),
Vector4<double>(3, 0, 0, 0), 1e-12, MatrixCompareType::absolute));
}
GTEST_TEST(SplineTests, RandomizedLinearSplineTest) {
default_random_engine generator(123);
int N = 11;
int num_tests = 1000;
int rows = 3;
int cols = 6;
for (int ctr = 0; ctr < num_tests; ++ctr) {
std::vector<double> T =
PiecewiseTrajectory<double>::RandomSegmentTimes(N - 1, generator);
std::vector<MatrixX<double>> Y(N);
for (int i = 0; i < N; ++i) Y[i] = MatrixX<double>::Random(rows, cols);
PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::FirstOrderHold(T, Y);
EXPECT_TRUE(CheckContinuity(spline, 1e-12, 0));
EXPECT_TRUE(CheckValues(spline, {Y}, 1e-12));
EXPECT_TRUE(CheckInterpolatedValuesAtBreakTime(spline, T, Y, 1e-12));
// Now test that we could have constructed the same trajectory
// incrementally.
PiecewisePolynomial<double> incremental =
PiecewisePolynomial<double>::FirstOrderHold({T[0], T[1]}, {Y[0], Y[1]});
for (int i = 2; i < N; i++) {
incremental.AppendFirstOrderSegment(T[i], Y[i]);
}
EXPECT_TRUE(spline.isApprox(incremental, 1e-10));
}
}
GTEST_TEST(SplineTests, RandomizedConstantSplineTest) {
default_random_engine generator(123);
int N = 2;
int num_tests = 1;
int rows = 3;
int cols = 6;
for (int ctr = 0; ctr < num_tests; ++ctr) {
std::vector<double> T =
PiecewiseTrajectory<double>::RandomSegmentTimes(N - 1, generator);
std::vector<MatrixX<double>> Y(N);
for (int i = 0; i < N; ++i) Y[i] = MatrixX<double>::Random(rows, cols);
PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::ZeroOrderHold(T, Y);
// Don't check the last time step, because constant spline ignores the last
// sample.
EXPECT_TRUE(CheckValues(spline, {Y}, 1e-12, false));
EXPECT_TRUE(CheckInterpolatedValuesAtBreakTime(spline, T, Y, 1e-12, false));
}
}
GTEST_TEST(SplineTests, RandomizedPchipSplineTest) {
default_random_engine generator(123);
int N = 10;
int num_tests = 1000;
int rows = 3;
int cols = 4;
for (int ctr = 0; ctr < num_tests; ++ctr) {
std::vector<double> T =
PiecewiseTrajectory<double>::RandomSegmentTimes(N - 1, generator);
std::vector<MatrixX<double>> Y(N);
for (int i = 0; i < N; ++i) Y[i] = MatrixX<double>::Random(rows, cols);
PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::CubicShapePreserving(T, Y);
PchipTest(T, Y, spline, 1e-8);
spline = PiecewisePolynomial<double>::CubicShapePreserving(
T, Y, true /* Uses zero end point derivative. */);
PchipTest(T, Y, spline, 1e-8);
// Derivatives at end points should be zero.
PiecewisePolynomial<double> spline_dot = spline.derivative();
EXPECT_NEAR(spline_dot.value(spline_dot.start_time()).norm(), 0, 1e-10);
EXPECT_NEAR(spline_dot.value(spline_dot.end_time()).norm(), 0, 1e-10);
}
}
GTEST_TEST(SplineTests, PchipLength2Test) {
std::vector<double> T = {0, 1};
std::vector<MatrixX<double>> Y(2, MatrixX<double>::Zero(1, 1));
Y[0] << 1;
Y[1] << 3;
PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::CubicShapePreserving(T, Y, true);
PiecewisePolynomial<double> spline_dot = spline.derivative();
EXPECT_NEAR(spline_dot.value(spline_dot.start_time()).norm(), 0, 1e-10);
EXPECT_NEAR(spline_dot.value(spline_dot.end_time()).norm(), 0, 1e-10);
// Computes the minimal velocity from T = 0 to T = 1. Since this segment is
// increasing, the minimal velocity needs to be greater than 0.
double v_min =
ComputeExtremeVel(spline_dot.getPolynomial(0), T.back(), false);
EXPECT_GE(v_min, 0);
Y[0] << 5;
Y[1] << -2;
spline = PiecewisePolynomial<double>::CubicShapePreserving(T, Y, true);
spline_dot = spline.derivative();
EXPECT_NEAR(spline_dot.value(spline_dot.start_time()).norm(), 0, 1e-10);
EXPECT_NEAR(spline_dot.value(spline_dot.end_time()).norm(), 0, 1e-10);
// Max velocity should be non positive.
double v_max = ComputeExtremeVel(spline_dot.getPolynomial(0), T.back(), true);
EXPECT_LE(v_max, 0);
}
GTEST_TEST(SplineTests, RandomizedCubicSplineTest) {
default_random_engine generator(123);
int N = 30;
int num_tests = 40;
int rows = 3;
int cols = 4;
// Test CubicWithContinuousSecondDerivatives(T, Y)
for (int ctr = 0; ctr < num_tests; ++ctr) {
std::vector<double> T =
PiecewiseTrajectory<double>::RandomSegmentTimes(N - 1, generator);
std::vector<MatrixX<double>> Y(N);
for (int i = 0; i < N; ++i) Y[i] = MatrixX<double>::Random(rows, cols);
PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(T, Y);
EXPECT_TRUE(CheckContinuity(spline, 1e-8, 2));
EXPECT_TRUE(CheckValues(spline, {Y}, 1e-8));
EXPECT_TRUE(CheckInterpolatedValuesAtBreakTime(spline, T, Y, 1e-8));
}
// Test CubicWithContinuousSecondDerivatives(T, Y, Ydot0, Ydot1)
for (int ctr = 0; ctr < num_tests; ++ctr) {
std::vector<double> T =
PiecewiseTrajectory<double>::RandomSegmentTimes(N - 1, generator);
std::vector<MatrixX<double>> Y(N);
for (int i = 0; i < N; ++i) Y[i] = MatrixX<double>::Random(rows, cols);
MatrixX<double> Ydot0 = MatrixX<double>::Random(rows, cols);
MatrixX<double> Ydot1 = MatrixX<double>::Random(rows, cols);
PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
T, Y, Ydot0, Ydot1);
EXPECT_TRUE(CheckContinuity(spline, 1e-8, 2));
EXPECT_TRUE(CheckValues(spline, {Y}, 1e-8));
EXPECT_TRUE(CheckInterpolatedValuesAtBreakTime(spline, T, Y, 1e-8));
// Check the first and last first derivatives.
MatrixX<double> Ydot0_test = spline.derivative().value(T.front());
MatrixX<double> Ydot1_test = spline.derivative().value(T.back());
EXPECT_TRUE(
CompareMatrices(Ydot0, Ydot0_test, 1e-8, MatrixCompareType::absolute));
EXPECT_TRUE(
CompareMatrices(Ydot1, Ydot1_test, 1e-8, MatrixCompareType::absolute));
}
// Test CubicHermite(T, Y, Ydots)
for (int ctr = 0; ctr < num_tests; ++ctr) {
std::vector<double> T(N);
std::iota(T.begin(), T.end(), 0);
std::vector<MatrixX<double>> Y(N);
std::vector<MatrixX<double>> Ydot(N);
for (int i = 0; i < N; ++i) {
Y[i] = MatrixX<double>::Random(rows, cols);
Ydot[i] = MatrixX<double>::Random(rows, cols);
}
const PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::CubicHermite(T, Y, Ydot);
EXPECT_TRUE(CheckContinuity(spline, 1e-8, 1));
EXPECT_TRUE(CheckValues(spline, {Y, Ydot}, 1e-8));
EXPECT_TRUE(CheckInterpolatedValuesAtBreakTime(spline, T, Y, 1e-8));
// Now test that we could have constructed the same trajectory
// incrementally.
PiecewisePolynomial<double> incremental =
PiecewisePolynomial<double>::CubicHermite({T[0], T[1]}, {Y[0], Y[1]},
{Ydot[0], Ydot[1]});
for (int i = 2; i < N; i++) {
incremental.AppendCubicHermiteSegment(T[i], Y[i], Ydot[i]);
}
EXPECT_TRUE(spline.isApprox(incremental, 1e-10));
}
}
GTEST_TEST(SplineTests, CubicSplineSize2) {
std::vector<double> T = {1, 2};
std::vector<MatrixX<double>> Y(2, MatrixX<double>::Zero(1, 1));
MatrixX<double> Ydot0 = MatrixX<double>::Zero(1, 1);
MatrixX<double> Ydot1 = MatrixX<double>::Zero(1, 1);
Y[0] << 1;
Y[1] << 3;
Ydot0 << 2;
Ydot1 << -1;
PiecewisePolynomial<double> spline =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
T, Y, Ydot0, Ydot1);
EXPECT_TRUE(CheckValues(spline, {Y, {Ydot0, Ydot1}}, 1e-8));
spline = PiecewisePolynomial<double>::CubicHermite(T, Y, {Ydot0, Ydot1});
EXPECT_TRUE(CheckValues(spline, {Y, {Ydot0, Ydot1}}, 1e-8));
// Calling CubicWithContinuousSecondDerivatives(times, Y) with only 2 samples
// should not be allowed.
EXPECT_THROW(
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(T, Y),
std::runtime_error);
}
// Test that the Eigen API methods return the same results as the std::vector
// versions.
GTEST_TEST(SplineTests, EigenTest) {
const double tol = 1e-12;
Vector3d breaks_mat{0., 1., 2.};
std::vector<double> breaks_vec{0., 1., 2.};
Matrix3d samples_mat = Matrix3d::Identity();
std::vector<MatrixXd> samples_vec = {
Vector3d{1., 0., 0.}, Vector3d{0., 1., 0.}, Vector3d{0., 0., 1.}};
// Keep the code cleaner below.
using PP = PiecewisePolynomial<double>;
EXPECT_TRUE(PP::ZeroOrderHold(breaks_mat, samples_mat)
.isApprox(PP::ZeroOrderHold(breaks_vec, samples_vec), tol));
EXPECT_TRUE(PP::FirstOrderHold(breaks_mat, samples_mat)
.isApprox(PP::FirstOrderHold(breaks_vec, samples_vec), tol));
EXPECT_TRUE(
PP::CubicShapePreserving(breaks_mat, samples_mat, false)
.isApprox(PP::CubicShapePreserving(breaks_vec, samples_vec, false),
tol));
EXPECT_TRUE(
PP::CubicShapePreserving(breaks_mat, samples_mat, true)
.isApprox(PP::CubicShapePreserving(breaks_vec, samples_vec, true),
tol));
EXPECT_TRUE(PP::CubicWithContinuousSecondDerivatives(breaks_mat, samples_mat)
.isApprox(PP::CubicWithContinuousSecondDerivatives(
breaks_vec, samples_vec),
tol));
Matrix3d samples_dot_mat = 2. * Matrix3d::Identity();
std::vector<MatrixXd> samples_dot_vec = {
Vector3d{2., 0., 0.}, Vector3d{0., 2., 0.}, Vector3d{0., 0., 2.}};
EXPECT_TRUE(
PP::CubicHermite(breaks_mat, samples_mat, samples_dot_mat)
.isApprox(PP::CubicHermite(breaks_vec, samples_vec, samples_dot_vec),
tol));
EXPECT_TRUE(PP::CubicWithContinuousSecondDerivatives(breaks_mat, samples_mat,
samples_dot_vec[0],
samples_dot_vec[2])
.isApprox(PP::CubicWithContinuousSecondDerivatives(
breaks_vec, samples_vec, samples_dot_vec[0],
samples_dot_vec[2]),
tol));
}
template <typename T>
void TestThrows(const std::vector<double>& breaks,
const std::vector<MatrixX<T>>& samples) {
EXPECT_THROW(PiecewisePolynomial<double>::ZeroOrderHold(breaks, samples),
std::runtime_error);
EXPECT_THROW(PiecewisePolynomial<double>::FirstOrderHold(breaks, samples),
std::runtime_error);
EXPECT_THROW(
PiecewisePolynomial<double>::CubicShapePreserving(breaks, samples),
std::runtime_error);
EXPECT_THROW(
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
breaks, samples),
std::runtime_error);
}
template <typename T>
void TestNoThrows(const std::vector<double>& breaks,
const std::vector<MatrixX<T>>& samples) {
DRAKE_EXPECT_NO_THROW(
PiecewisePolynomial<double>::ZeroOrderHold(breaks, samples));
DRAKE_EXPECT_NO_THROW(
PiecewisePolynomial<double>::FirstOrderHold(breaks, samples));
DRAKE_EXPECT_NO_THROW(
PiecewisePolynomial<double>::CubicShapePreserving(breaks, samples));
DRAKE_EXPECT_NO_THROW(
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
breaks, samples));
}
GTEST_TEST(SplineTests, TestException) {
// Doesn't throw.
int rows = 3;
int cols = 4;
std::vector<double> T = {1, 2, 3, 4};
std::vector<MatrixX<double>> Y(T.size(), MatrixX<double>::Zero(rows, cols));
TestNoThrows(T, Y);
// Non increasing T
T = {1, 0, 3, 4};
TestThrows(T, Y);
T = {0, 0, 3, 4};
TestThrows(T, Y);
// Inconsistent Y dimension.
Y.front().resize(Y.front().rows() + 1, Y.front().cols() + 1);
TestThrows(T, Y);
// T size doesn't match Y size
Y = std::vector<MatrixX<double>>(T.size() + 1,
MatrixX<double>::Zero(rows, cols));
TestThrows(T, Y);
// Min length
T = {1, 2};
Y = std::vector<MatrixX<double>>(T.size(), MatrixX<double>::Zero(rows, cols));
DRAKE_EXPECT_NO_THROW(PiecewisePolynomial<double>::FirstOrderHold(T, Y));
DRAKE_EXPECT_NO_THROW(PiecewisePolynomial<double>::ZeroOrderHold(T, Y));
EXPECT_THROW(PiecewisePolynomial<double>::CubicShapePreserving(T, Y),
std::runtime_error);
EXPECT_THROW(
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(T, Y),
std::runtime_error);
T = {2};
Y = std::vector<MatrixX<double>>(T.size(), MatrixX<double>::Zero(rows, cols));
EXPECT_THROW(PiecewisePolynomial<double>::ZeroOrderHold(T, Y),
std::runtime_error);
EXPECT_THROW(PiecewisePolynomial<double>::FirstOrderHold(T, Y),
std::runtime_error);
// Test Ydot0 / Ydot1 mismatch.
T = {1, 2, 3};
Y = std::vector<MatrixX<double>>(T.size(), MatrixX<double>::Zero(rows, cols));
MatrixX<double> Ydot0(rows, cols);
MatrixX<double> Ydot1(rows, cols);
Ydot0.setZero();
Ydot1.setZero();
DRAKE_EXPECT_NO_THROW(
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
T, Y, Ydot0, Ydot1));
Ydot0.resize(rows, cols);
Ydot1.resize(rows, cols + 1);
EXPECT_THROW(
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
T, Y, Ydot0, Ydot1),
std::runtime_error);
Ydot0.resize(rows + 1, cols);
Ydot1.resize(rows, cols);
EXPECT_THROW(
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
T, Y, Ydot0, Ydot1),
std::runtime_error);
// Test Ydot mismatch.
T = {1, 2, 3};
Y = std::vector<MatrixX<double>>(T.size(), MatrixX<double>::Zero(rows, cols));
std::vector<MatrixX<double>> Ydot =
std::vector<MatrixX<double>>(T.size(), MatrixX<double>::Zero(rows, cols));
DRAKE_EXPECT_NO_THROW(PiecewisePolynomial<double>::CubicHermite(T, Y, Ydot));
Ydot = std::vector<MatrixX<double>>(T.size() + 1,
MatrixX<double>::Zero(rows, cols));
EXPECT_THROW(PiecewisePolynomial<double>::CubicHermite(T, Y, Ydot),
std::runtime_error);
Ydot =
std::vector<MatrixX<double>>(T.size(), MatrixX<double>::Zero(rows, cols));
Ydot.front().resize(rows + 2, cols + 1);
EXPECT_THROW(PiecewisePolynomial<double>::CubicHermite(T, Y, Ydot),
std::runtime_error);
}
GTEST_TEST(SplineTests, LagrangeInterpolatingPolynomialTest) {
Eigen::Vector4d times(0.1, 0.5, 0.8, 1.34);
Eigen::RowVector4d samples(4.1, -1.3, 0.5, -3.4);
PiecewisePolynomial<double> scalar_trajectory =
PiecewisePolynomial<double>::LagrangeInterpolatingPolynomial(times,
samples);
EXPECT_EQ(scalar_trajectory.start_time(), times[0]);
EXPECT_EQ(scalar_trajectory.end_time(), times[times.size() - 1]);
EXPECT_EQ(scalar_trajectory.get_number_of_segments(), 1);
EXPECT_EQ(scalar_trajectory.getPolynomial(0, 0, 0).GetDegree(),
times.size() - 1);
EXPECT_TRUE(CompareMatrices(
scalar_trajectory.vector_values({times[0], times[1], times[2], times[3]}),
samples, 1e-12));
std::vector<double> mtimes = {-3.2, 0.4, 6.7};
std::vector<Eigen::MatrixXd> msamples(3);
const int rows = 3;
const int cols = 2;
for (size_t i = 0; i < mtimes.size(); ++i) {
msamples[i] = Eigen::MatrixXd::Random(rows, cols);
}
PiecewisePolynomial<double> matrix_trajectory =
PiecewisePolynomial<double>::LagrangeInterpolatingPolynomial(mtimes,
msamples);
EXPECT_EQ(matrix_trajectory.start_time(), mtimes[0]);
EXPECT_EQ(matrix_trajectory.end_time(), mtimes[mtimes.size() - 1]);
EXPECT_EQ(matrix_trajectory.get_number_of_segments(), 1);
for (size_t i = 0; i < mtimes.size(); ++i) {
EXPECT_TRUE(CompareMatrices(matrix_trajectory.value(mtimes[i]), msamples[i],
1e-12));
}
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/trajectory_test.cc | #include "drake/common/trajectories/trajectory.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/expect_throws_message.h"
namespace drake {
namespace trajectories {
namespace {
// Dummy implementation of Trajectory to test the basic functions.
template <typename T = double>
class TrajectoryTester : public Trajectory<T> {
public:
explicit TrajectoryTester(bool has_derivative)
: has_derivative_(has_derivative) {}
MatrixX<T> value(const T& t) const override { return MatrixX<T>(0, 0); }
std::unique_ptr<Trajectory<T>> Clone() const override { return nullptr; }
Eigen::Index rows() const override { return 0; }
Eigen::Index cols() const override { return 0; }
T start_time() const override { return 0; }
T end_time() const override { return 1; }
private:
bool do_has_derivative() const override { return has_derivative_; }
bool has_derivative_;
};
GTEST_TEST(TrajectoryTest, EvalDerivativesTest) {
TrajectoryTester traj_yes_deriv(true);
EXPECT_TRUE(traj_yes_deriv.has_derivative());
DRAKE_EXPECT_THROWS_MESSAGE(
traj_yes_deriv.EvalDerivative(traj_yes_deriv.start_time()),
".* must implement .*");
DRAKE_EXPECT_THROWS_MESSAGE(
traj_yes_deriv.EvalDerivative(traj_yes_deriv.start_time(), -1),
".*derivative_order >= 0.*");
TrajectoryTester traj_no_deriv(false);
EXPECT_FALSE(traj_no_deriv.has_derivative());
DRAKE_EXPECT_THROWS_MESSAGE(
traj_no_deriv.EvalDerivative(traj_no_deriv.start_time()),
".* does not support .*");
}
GTEST_TEST(TrajectoryTest, MakeDerivativesTest) {
TrajectoryTester traj_yes_deriv(true);
EXPECT_TRUE(traj_yes_deriv.has_derivative());
DRAKE_EXPECT_THROWS_MESSAGE(traj_yes_deriv.MakeDerivative(),
".* must implement .*");
TrajectoryTester traj_no_deriv(false);
EXPECT_FALSE(traj_no_deriv.has_derivative());
DRAKE_EXPECT_THROWS_MESSAGE(traj_no_deriv.MakeDerivative(),
".* does not support .*");
}
template <typename T>
void TestScalarType() {
TrajectoryTester<T> traj(true);
const MatrixX<T> value = traj.value(traj.start_time());
EXPECT_EQ(value.rows(), 0);
EXPECT_EQ(value.cols(), 0);
}
GTEST_TEST(PiecewiseTrajectoryTest, ScalarTypes) {
TestScalarType<AutoDiffXd>();
TestScalarType<symbolic::Expression>();
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/piecewise_trajectory_test.cc | #include "drake/common/trajectories/piecewise_trajectory.h"
#include <random>
#include <gtest/gtest.h>
#include "drake/common/drake_assert.h"
namespace drake {
namespace trajectories {
namespace {
// Dummy implementation of PiecewiseTrajectory to test the basic indexing
// functions.
template <typename T = double>
class PiecewiseTrajectoryTester : public PiecewiseTrajectory<T> {
public:
explicit PiecewiseTrajectoryTester(const std::vector<T>& times)
: PiecewiseTrajectory<T>(times) {}
Eigen::Index rows() const override { return 0; }
Eigen::Index cols() const override { return 0; }
MatrixX<T> value(const T& t) const override { return MatrixX<T>(0, 0); }
std::unique_ptr<Trajectory<T>> Clone() const override { return nullptr; }
};
void TestPiecewiseTrajectoryTimeRelatedGetters(
const PiecewiseTrajectoryTester<double>& traj,
const std::vector<double>& time) {
EXPECT_EQ(traj.get_number_of_segments(), static_cast<int>(time.size()) - 1);
EXPECT_EQ(traj.start_time(), time.front());
EXPECT_EQ(traj.end_time(), time.back());
// Check start / end / duration for each segment.
for (int i = 0; i < static_cast<int>(time.size()) - 1; i++) {
EXPECT_EQ(traj.start_time(i), time[i]);
EXPECT_EQ(traj.end_time(i), time[i + 1]);
EXPECT_EQ(traj.duration(i), time[i + 1] - time[i]);
}
// Check returned segment times == given.
const std::vector<double>& ret_seg_times = traj.get_segment_times();
EXPECT_EQ(ret_seg_times.size(), time.size());
for (int i = 0; i < static_cast<int>(time.size()); i++) {
EXPECT_EQ(time[i], ret_seg_times[i]);
}
// Check get_segment_index works at the breaks, also epsilon from the
// breaks.
for (int i = 0; i < static_cast<int>(time.size()); i++) {
int idx = traj.get_segment_index(time[i]);
if (i == static_cast<int>(time.size()) - 1) {
EXPECT_EQ(idx, i - 1);
} else {
EXPECT_EQ(idx, i);
}
if (i != 0) {
const double t_minus_eps = time[i] - 1e-10;
idx = traj.get_segment_index(t_minus_eps);
EXPECT_EQ(idx, i - 1);
EXPECT_TRUE(traj.start_time(idx) < t_minus_eps);
}
}
// Dense sample the time, and make sure the returned index is valid.
for (double t = time.front() - 0.1; t < time.back() + 0.1; t += 0.01) {
const int idx = traj.get_segment_index(t);
EXPECT_GE(idx, 0);
EXPECT_LT(idx, traj.get_number_of_segments());
if (t >= traj.start_time() && t <= traj.end_time()) {
EXPECT_TRUE(t >= traj.start_time(idx));
EXPECT_TRUE(t <= traj.end_time(idx));
}
}
}
GTEST_TEST(PiecewiseTrajectoryTest, RandomizedGetIndexTest) {
int N = 100000;
std::default_random_engine generator(123);
std::vector<double> time =
PiecewiseTrajectory<double>::RandomSegmentTimes(N - 1, generator);
PiecewiseTrajectoryTester traj(time);
TestPiecewiseTrajectoryTimeRelatedGetters(traj, time);
}
GTEST_TEST(PiecewiseTrajectoryTest, GetIndexTest) {
std::vector<double> time = {0, 1, 2, 3.5};
PiecewiseTrajectoryTester traj(time);
TestPiecewiseTrajectoryTimeRelatedGetters(traj, time);
}
template <typename T>
void TestScalarType() {
std::default_random_engine generator(123);
std::vector<T> time =
PiecewiseTrajectory<T>::RandomSegmentTimes(5, generator);
PiecewiseTrajectoryTester<T> traj(time);
const MatrixX<T> value = traj.value(traj.start_time());
EXPECT_EQ(value.rows(), 0);
EXPECT_EQ(value.cols(), 0);
EXPECT_TRUE(static_cast<bool>(
traj.is_time_in_range((traj.start_time() + traj.end_time()) / 2.0)));
}
GTEST_TEST(PiecewiseTrajectoryTest, ScalarTypes) {
TestScalarType<AutoDiffXd>();
TestScalarType<symbolic::Expression>();
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/composite_trajectory_test.cc | #include "drake/common/trajectories/composite_trajectory.h"
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/trajectories/bezier_curve.h"
namespace drake {
namespace trajectories {
namespace {
GTEST_TEST(CompositeTrajectoryTest, Basic) {
Eigen::Matrix2d points;
// clang-format off
points << 1, 2,
3, 7;
// clang-format on
std::vector<copyable_unique_ptr<Trajectory<double>>> segments(2);
segments[0] = std::make_unique<BezierCurve<double>>(2, 3, points);
points.col(0) = points.col(1);
points.col(1) << 3, 10;
segments[1] = std::make_unique<BezierCurve<double>>(3, 4, points);
CompositeTrajectory<double> traj(segments);
EXPECT_EQ(traj.start_time(), 2.0);
EXPECT_EQ(traj.end_time(), 4.0);
EXPECT_EQ(traj.rows(), 2);
EXPECT_EQ(traj.cols(), 1);
EXPECT_EQ(traj.get_number_of_segments(), 2);
EXPECT_EQ(traj.segment(0).start_time(), 2.0);
EXPECT_EQ(traj.segment(1).start_time(), 3.0);
EXPECT_EQ(traj.segment(1).end_time(), 4.0);
EXPECT_TRUE(CompareMatrices(traj.value(2.5), Eigen::Vector2d(1.5, 5), 1e-14));
EXPECT_TRUE(
CompareMatrices(traj.value(3.5), Eigen::Vector2d(2.5, 8.5), 1e-14));
EXPECT_TRUE(traj.has_derivative());
auto deriv = traj.MakeDerivative();
EXPECT_EQ(deriv->start_time(), 2.0);
EXPECT_EQ(deriv->end_time(), 4.0);
EXPECT_TRUE(CompareMatrices(deriv->value(2.5), Eigen::Vector2d(1, 4), 1e-14));
EXPECT_TRUE(CompareMatrices(deriv->value(3.5), Eigen::Vector2d(1, 3), 1e-14));
EXPECT_TRUE(
CompareMatrices(traj.EvalDerivative(2.5), Eigen::Vector2d(1, 4), 1e-14));
EXPECT_TRUE(
CompareMatrices(traj.EvalDerivative(3.5), Eigen::Vector2d(1, 3), 1e-14));
auto clone = traj.Clone();
EXPECT_EQ(clone->start_time(), 2.0);
EXPECT_EQ(clone->end_time(), 4.0);
EXPECT_TRUE(
CompareMatrices(clone->value(2.5), Eigen::Vector2d(1.5, 5), 1e-14));
EXPECT_TRUE(
CompareMatrices(clone->value(3.5), Eigen::Vector2d(2.5, 8.5), 1e-14));
auto clone2 = traj.MakeDerivative(0);
EXPECT_EQ(clone->start_time(), 2.0);
EXPECT_EQ(clone->end_time(), 4.0);
EXPECT_TRUE(
CompareMatrices(clone->value(2.5), Eigen::Vector2d(1.5, 5), 1e-14));
EXPECT_TRUE(
CompareMatrices(clone->value(3.5), Eigen::Vector2d(2.5, 8.5), 1e-14));
}
template <typename T>
void CheckScalarType() {
Eigen::Matrix<T, 2, 3> points;
// clang-format off
points << 1, 0, 0,
0, 0, 1;
// clang-format on
std::vector<copyable_unique_ptr<Trajectory<T>>> segments(1);
segments[0] = std::make_unique<BezierCurve<T>>(0, 1, points);
CompositeTrajectory<T> traj(segments);
EXPECT_TRUE(
CompareMatrices(traj.value(0.5), Eigen::Vector2d(0.25, 0.25), 1e-14));
}
GTEST_TEST(CompositeTrajectoryTest, ScalarTypes) {
CheckScalarType<double>();
CheckScalarType<AutoDiffXd>();
CheckScalarType<symbolic::Expression>();
}
GTEST_TEST(CompositeTrajectoryTest, Empty) {
CompositeTrajectory<double> traj({});
DRAKE_EXPECT_THROWS_MESSAGE(traj.rows(), ".*no segments.*");
DRAKE_EXPECT_THROWS_MESSAGE(traj.cols(), ".*no segments.*");
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/stacked_trajectory_test.cc | #include "drake/common/trajectories/stacked_trajectory.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/trajectories/discrete_time_trajectory.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
namespace drake {
namespace trajectories {
namespace {
using Eigen::MatrixXd;
using Eigen::RowVector2d;
using Eigen::RowVector4d;
using Eigen::Vector2d;
using Eigen::Vector4d;
using Vector1d = Vector1<double>;
DiscreteTimeTrajectory<double> MakeDiscrete(double t0, const MatrixXd& value0,
double t1, const MatrixXd& value1) {
std::vector<double> times{t0, t1};
std::vector<MatrixXd> values{value0, value1};
return DiscreteTimeTrajectory<double>(times, values);
}
GTEST_TEST(StackedTrajectoryTest, Empty) {
const StackedTrajectory<double> dut;
EXPECT_EQ(dut.rows(), 0);
EXPECT_EQ(dut.cols(), 0);
EXPECT_EQ(dut.start_time(), 0.0);
EXPECT_EQ(dut.end_time(), 0.0);
EXPECT_NO_THROW(dut.Clone());
EXPECT_TRUE(CompareMatrices(dut.value(0), MatrixXd::Zero(0, 0)));
EXPECT_TRUE(dut.has_derivative());
EXPECT_TRUE(CompareMatrices(dut.EvalDerivative(0), MatrixXd::Zero(0, 0)));
EXPECT_TRUE(dut.MakeDerivative() != nullptr);
}
GTEST_TEST(StackedTrajectoryTest, CopyCtor) {
const auto x = Vector1d(22);
StackedTrajectory<double> dut;
dut.Append(MakeDiscrete(0, x, 1, -x));
EXPECT_EQ(dut.rows(), 1);
EXPECT_EQ(dut.cols(), 1);
EXPECT_TRUE(CompareMatrices(dut.value(0), x));
// The 'other' copies the data from 'dut'.
StackedTrajectory<double> other(dut);
EXPECT_EQ(other.rows(), 1);
EXPECT_EQ(other.cols(), 1);
EXPECT_TRUE(CompareMatrices(other.value(0), x));
EXPECT_NO_THROW(other.Clone());
// The 'dut' is unchanged.
EXPECT_EQ(dut.rows(), 1);
EXPECT_EQ(dut.cols(), 1);
EXPECT_TRUE(CompareMatrices(dut.value(0), x));
EXPECT_NO_THROW(dut.Clone());
// Changing 'dut' does not affect 'other'.
dut.Append(MakeDiscrete(0, x, 1, -x));
EXPECT_EQ(dut.rows(), 1 + 1);
EXPECT_EQ(dut.cols(), 1);
EXPECT_EQ(other.rows(), 1);
EXPECT_EQ(other.cols(), 1);
}
GTEST_TEST(StackedTrajectoryTest, MoveCtor) {
const auto x = Vector1d(22);
StackedTrajectory<double> dut;
dut.Append(MakeDiscrete(0, x, 1, -x));
EXPECT_EQ(dut.rows(), 1);
EXPECT_EQ(dut.cols(), 1);
EXPECT_TRUE(CompareMatrices(dut.value(0), x));
// The 'other' takes over the data from 'dut'.
StackedTrajectory<double> other(std::move(dut));
EXPECT_EQ(other.rows(), 1);
EXPECT_EQ(other.cols(), 1);
EXPECT_TRUE(CompareMatrices(other.value(0), x));
EXPECT_NO_THROW(other.Clone());
// The 'dut' is empty now.
EXPECT_EQ(dut.rows(), 0);
EXPECT_EQ(dut.cols(), 0);
EXPECT_TRUE(CompareMatrices(dut.value(0), MatrixXd::Zero(0, 0)));
EXPECT_NO_THROW(dut.Clone());
}
GTEST_TEST(StackedTrajectoryTest, AppendMismatchedTimes) {
StackedTrajectory<double> dut;
const auto x = Vector1d(22);
auto time_zero_two = MakeDiscrete(0, x, 2, -x);
auto time_zero_one = MakeDiscrete(0, x, 1, -x);
auto time_one_two = MakeDiscrete(1, x, 2, -x);
dut.Append(time_zero_two);
DRAKE_EXPECT_THROWS_MESSAGE(dut.Append(time_one_two), ".*start_time.*");
DRAKE_EXPECT_THROWS_MESSAGE(dut.Append(time_zero_one), ".*end_time.*");
}
GTEST_TEST(StackedTrajectoryTest, AppendMismatchedSizesRowwise) {
const auto x = Vector2d(11, 22);
const auto y = RowVector2d(33, 44);
StackedTrajectory<double> dut;
dut.Append(MakeDiscrete(0, x, 1, -x));
DRAKE_EXPECT_THROWS_MESSAGE(dut.Append(MakeDiscrete(0, y, 1, -y)),
".*cols.*");
}
GTEST_TEST(StackedTrajectoryTest, AppendMismatchedSizesColwise) {
const auto x = Vector2d(11, 22);
const auto y = RowVector2d(33, 44);
StackedTrajectory<double> dut(/* rowwise = */ false);
dut.Append(MakeDiscrete(0, y, 1, -y));
DRAKE_EXPECT_THROWS_MESSAGE(dut.Append(MakeDiscrete(0, x, 1, -x)),
".*rows.*");
}
GTEST_TEST(StackedTrajectoryTest, StackTwoDiscreteColumnVectors) {
const double t0 = 0.2;
const double tf = 0.8;
StackedTrajectory<double> dut;
dut.Append(MakeDiscrete(t0, Vector2d(1, 2), tf, Vector2d(11, 12)));
dut.Append(MakeDiscrete(t0, Vector2d(3, 4), tf, Vector2d(13, 14)));
EXPECT_EQ(dut.rows(), 4);
EXPECT_EQ(dut.cols(), 1);
EXPECT_EQ(dut.start_time(), t0);
EXPECT_EQ(dut.end_time(), tf);
EXPECT_NO_THROW(dut.Clone());
EXPECT_TRUE(CompareMatrices(dut.value(t0), Vector4d(1, 2, 3, 4)));
EXPECT_TRUE(CompareMatrices(dut.value(tf), Vector4d(11, 12, 13, 14)));
EXPECT_FALSE(dut.has_derivative());
}
GTEST_TEST(StackedTrajectoryTest, StackTwoDiscreteRowVectors) {
const double t0 = 0.2;
const double tf = 0.8;
StackedTrajectory<double> dut(/* rowwise = */ false);
dut.Append(MakeDiscrete(t0, RowVector2d(1, 2), tf, RowVector2d(11, 12)));
dut.Append(MakeDiscrete(t0, RowVector2d(3, 4), tf, RowVector2d(13, 14)));
EXPECT_EQ(dut.rows(), 1);
EXPECT_EQ(dut.cols(), 4);
EXPECT_EQ(dut.start_time(), t0);
EXPECT_EQ(dut.end_time(), tf);
EXPECT_NO_THROW(dut.Clone());
EXPECT_TRUE(CompareMatrices(dut.value(t0), RowVector4d(1, 2, 3, 4)));
EXPECT_TRUE(CompareMatrices(dut.value(tf), RowVector4d(11, 12, 13, 14)));
EXPECT_FALSE(dut.has_derivative());
}
GTEST_TEST(StackedTrajectoryTest, Clone) {
const auto x = Vector1d(22);
StackedTrajectory<double> original;
original.Append(MakeDiscrete(0, x, 1, -x));
original.Append(MakeDiscrete(0, -x, 1, x));
Trajectory<double>& upcast = original;
auto clone = upcast.Clone();
// The original and the clone are the same.
for (const auto* item : {&upcast, clone.get()}) {
EXPECT_EQ(item->rows(), 2);
EXPECT_EQ(item->cols(), 1);
EXPECT_EQ(item->start_time(), 0);
EXPECT_EQ(item->end_time(), 1);
EXPECT_TRUE(CompareMatrices(item->value(0), Vector2d(22, -22)));
EXPECT_TRUE(CompareMatrices(item->value(1), Vector2d(-22, 22)));
}
}
GTEST_TEST(StackedTrajectoryTest, HasDerivative) {
const double t0 = 0.2;
const double tf = 0.8;
const auto x = Vector1d(22);
StackedTrajectory<double> dut;
EXPECT_EQ(dut.has_derivative(), true);
// When we append a polynomial, we still have derivatives.
auto zoh = PiecewisePolynomial<double>::ZeroOrderHold({t0, tf}, {x, x});
dut.Append(zoh);
EXPECT_EQ(dut.has_derivative(), true);
// When we append a discrete, we no longer have derivatives.
dut.Append(MakeDiscrete(t0, x, tf, -x));
EXPECT_EQ(dut.has_derivative(), false);
}
GTEST_TEST(StackedTrajectoryTest, MakeDerivative) {
const double t0 = 0.2;
const double tf = 0.8;
const auto x = RowVector2d(22, -22);
auto zoh = PiecewisePolynomial<double>::ZeroOrderHold({t0, tf}, {x, x});
// Create a stack of zoh.
// Do it colwise to make sure the non-default option is propagated.
StackedTrajectory<double> dut(/* rowwise = */ false);
dut.Append(zoh);
dut.Append(zoh);
dut.Append(zoh);
// Relying on glass-box testing, we'll presume that when the result has the
// correct shape and doesn't crash we don't need to check the derivative
// for mathematical correctness.
Trajectory<double>& upcast = dut;
auto deriv = dut.MakeDerivative();
for (const auto* item : {&upcast, deriv.get()}) {
EXPECT_EQ(item->rows(), 1);
EXPECT_EQ(item->cols(), 6);
EXPECT_NO_THROW(item->value(t0));
}
}
GTEST_TEST(StackedTrajectoryTest, EvalDerivative) {
for (bool rowwise : {true, false}) {
SCOPED_TRACE(fmt::format("Using rowwise = {}", rowwise));
const double t0 = 0.2;
const double t1 = 0.3;
const double t2 = 0.7;
const double tf = 0.8;
// Create a stack of arbitrary polynomials.
// clang-format off
auto make_poly = [&](const std::vector<MatrixXd>& samples) {
return PiecewisePolynomial<double>::CubicShapePreserving(
{t0, t1, t2, tf}, samples);
};
StackedTrajectory<double> dut(rowwise);
dut.Append(make_poly({
Vector2d(10, -100),
Vector2d(20, 0),
Vector2d(90, 10),
Vector2d(100, 200)}));
dut.Append(make_poly({
Vector2d(0, -1),
Vector2d(50, -2),
Vector2d(100, -4),
Vector2d(200, -8)}));
// clang-format on
// We'll assume that MakeDerivative is correct and use its values as the
// gold standard.
auto deriv = dut.MakeDerivative(2);
for (int i = 0; i < 100; ++i) {
const double t = (i / 99.0) * (tf - t0);
MatrixXd actual = dut.EvalDerivative(t, 2);
MatrixXd expected = deriv->value(t);
ASSERT_TRUE(CompareMatrices(actual, expected));
}
}
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/path_parameterized_trajectory_test.cc | #include "drake/common/trajectories/path_parameterized_trajectory.h"
#include <algorithm>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
namespace drake {
namespace trajectories {
namespace {
class PathParameterizedTrajectoryTest : public ::testing::Test {
protected:
void SetUp() override {
VectorX<double> times(3);
RowVectorX<double> s_samples(3);
MatrixX<double> x_samples(3, 2);
times << 1, 1.5, 2;
s_samples << 3, 4.5, 5;
x_samples.leftCols(1) << 0.3, 0, -0.5;
x_samples.rightCols(1) << 1, -1, 3;
time_scaling_ = PiecewisePolynomial<double>::CubicShapePreserving(
times, s_samples, true);
path_ = PiecewisePolynomial<double>::CubicShapePreserving(
Vector2<double>(s_samples(0), s_samples(2)), x_samples, true);
dut_ = std::make_unique<PathParameterizedTrajectory<double>>(path_,
time_scaling_);
}
PiecewisePolynomial<double> path_;
PiecewisePolynomial<double> time_scaling_;
std::unique_ptr<PathParameterizedTrajectory<double>> dut_;
};
TEST_F(PathParameterizedTrajectoryTest, TestConstructor) {
EXPECT_EQ(dut_->start_time(), 1.0);
EXPECT_EQ(dut_->end_time(), 2.0);
}
TEST_F(PathParameterizedTrajectoryTest, TestValue) {
for (double t = 0.88; t < 2.2; t += 0.12) {
const double time =
std::clamp(t, time_scaling_.start_time(), time_scaling_.end_time());
EXPECT_TRUE(CompareMatrices(
dut_->value(t), path_.value(time_scaling_.scalarValue(time)), 1e-14));
}
}
TEST_F(PathParameterizedTrajectoryTest, TestDerivatives) {
for (double t = 0.88; t < 2.2; t += 0.12) {
const double time =
std::clamp(t, time_scaling_.start_time(), time_scaling_.end_time());
EXPECT_TRUE(
CompareMatrices(dut_->EvalDerivative(t, 0), dut_->value(t), 1e-14));
double s = time_scaling_.scalarValue(time);
double s_dot = time_scaling_.EvalDerivative(time, 1)(0, 0);
VectorX<double> x_dot = path_.EvalDerivative(s, 1) * s_dot;
EXPECT_TRUE(CompareMatrices(dut_->EvalDerivative(t, 1), x_dot, 1e-14));
auto deriv = dut_->MakeDerivative(1);
EXPECT_TRUE(CompareMatrices(deriv->value(t), x_dot, 1e-14));
double s_ddot = time_scaling_.EvalDerivative(time, 2)(0, 0);
VectorX<double> x_ddot = path_.EvalDerivative(s, 1) * s_ddot +
path_.EvalDerivative(s, 2) * s_dot * s_dot;
EXPECT_TRUE(CompareMatrices(dut_->EvalDerivative(t, 2), x_ddot, 1e-14));
auto deriv2 = dut_->MakeDerivative(2);
EXPECT_TRUE(CompareMatrices(deriv2->value(t), x_ddot, 1e-14));
double s_3dot = time_scaling_.EvalDerivative(time, 3)(0, 0);
VectorX<double> x_3dot = path_.EvalDerivative(s, 1) * s_3dot +
3 * path_.EvalDerivative(s, 2) * s_ddot * s_dot +
path_.EvalDerivative(s, 3) * std::pow(s_dot, 3);
EXPECT_TRUE(CompareMatrices(dut_->EvalDerivative(t, 3), x_3dot, 1e-12));
auto deriv3 = dut_->MakeDerivative(3);
EXPECT_TRUE(CompareMatrices(deriv3->value(t), x_3dot, 1e-12));
}
}
// Tests getters.
TEST_F(PathParameterizedTrajectoryTest, TestGetTrajectory) {
EXPECT_TRUE(dynamic_cast<const PiecewisePolynomial<double>&>(dut_->path())
.isApprox(path_, 0));
EXPECT_TRUE(
dynamic_cast<const PiecewisePolynomial<double>&>(dut_->time_scaling())
.isApprox(time_scaling_, 0));
}
template <typename T>
void TestScalarType() {
VectorX<T> times(2);
VectorX<T> s_samples(2);
MatrixX<T> x_samples(3, 2);
times << 1, 2;
s_samples << 3, 5;
x_samples.leftCols(1) << 0.3, 0, -0.5;
x_samples.rightCols(1) << 1, -1, 3;
PiecewisePolynomial<T> time_scaling =
PiecewisePolynomial<T>::FirstOrderHold(times, s_samples.transpose());
PiecewisePolynomial<T> path =
PiecewisePolynomial<T>::FirstOrderHold(s_samples, x_samples);
PathParameterizedTrajectory<T> trajectory(path, time_scaling);
}
GTEST_TEST(PathParameterizedTrajectoryScalarTest, ScalarTypes) {
TestScalarType<double>();
TestScalarType<AutoDiffXd>();
TestScalarType<symbolic::Expression>();
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/exponential_plus_piecewise_polynomial_test.cc | #include "drake/common/trajectories/exponential_plus_piecewise_polynomial.h"
#include <cmath>
#include <random>
#include <Eigen/Core>
#include <gtest/gtest.h>
#include "drake/common/trajectories/test/random_piecewise_polynomial.h"
using std::default_random_engine;
using std::uniform_real_distribution;
namespace drake {
namespace trajectories {
namespace {
template <typename T>
void testSimpleCase() {
int num_coefficients = 5;
MatrixX<T> K = MatrixX<T>::Random(1, 1);
MatrixX<T> A = MatrixX<T>::Random(1, 1);
MatrixX<T> alpha = MatrixX<T>::Random(1, 1);
std::vector<double> breaks = {1.2, 3.4};
default_random_engine generator;
auto polynomial_part =
test::MakeRandomPiecewisePolynomial<T>(1, 1, num_coefficients, breaks);
ExponentialPlusPiecewisePolynomial<T> expPlusPp(K, A, alpha, polynomial_part);
EXPECT_EQ(expPlusPp.rows(), 1);
EXPECT_EQ(expPlusPp.cols(), 1);
EXPECT_EQ(expPlusPp.get_number_of_segments(), 1);
EXPECT_EQ(expPlusPp.start_time(), breaks[0]);
EXPECT_EQ(expPlusPp.end_time(), breaks[1]);
ExponentialPlusPiecewisePolynomial<T> derivative = expPlusPp.derivative();
uniform_real_distribution<T> uniform(expPlusPp.start_time(),
expPlusPp.end_time());
double t = uniform(generator);
auto check = K(0) * std::exp(A(0) * (t - expPlusPp.start_time())) * alpha(0) +
polynomial_part.scalarValue(t);
auto derivative_check =
K(0) * A(0) * std::exp(A(0) * (t - expPlusPp.start_time())) * alpha(0) +
polynomial_part.derivative().scalarValue(t);
EXPECT_NEAR(check, expPlusPp.value(t)(0), 1e-8);
EXPECT_NEAR(derivative_check, derivative.value(t)(0), 1e-8);
const double kShift = 5.6;
expPlusPp.shiftRight(kShift);
EXPECT_EQ(expPlusPp.start_time(), breaks[0] + kShift);
EXPECT_EQ(expPlusPp.end_time(), breaks[1] + kShift);
}
GTEST_TEST(testExponentialPlusPiecewisePolynomial, BasicTest) {
testSimpleCase<double>();
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/random_piecewise_polynomial.h | #pragma once
#include <vector>
#include <Eigen/Core>
#include "drake/common/test_utilities/random_polynomial_matrix.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
namespace drake {
namespace trajectories {
namespace test {
/**
* Obtains a random PiecewisePolynomial with the given @p segment_times. Each
* segment will have a matrix of random Polynomials of the specified size.
*/
template <typename T = double>
PiecewisePolynomial<T> MakeRandomPiecewisePolynomial(
Eigen::Index rows, Eigen::Index cols,
Eigen::Index num_coefficients_per_polynomial,
const std::vector<double>& segment_times) {
Eigen::Index num_segments =
static_cast<Eigen::Index>(segment_times.size() - 1);
typedef Polynomial<T> PolynomialType;
typedef Eigen::Matrix<PolynomialType, Eigen::Dynamic, Eigen::Dynamic>
PolynomialMatrix;
std::vector<PolynomialMatrix> polynomials;
for (Eigen::Index segment_index = 0; segment_index < num_segments;
++segment_index) {
polynomials.push_back(drake::test::RandomPolynomialMatrix<T>(
num_coefficients_per_polynomial, rows, cols));
}
return PiecewisePolynomial<T>(polynomials, segment_times);
}
} // namespace test
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/bezier_curve_test.cc | #include "drake/common/trajectories/bezier_curve.h"
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include "drake/common/symbolic/polynomial.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/geometry/optimization/vpolytope.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace trajectories {
namespace {
using Eigen::Map;
using Eigen::Matrix2d;
using Eigen::MatrixXd;
using Eigen::SparseMatrix;
using Eigen::Vector2d;
using Eigen::VectorXd;
// Tests the default constructor.
GTEST_TEST(BezierCurveTest, DefaultConstructor) {
BezierCurve<double> curve;
EXPECT_EQ(curve.order(), -1);
EXPECT_EQ(curve.start_time(), 0);
EXPECT_EQ(curve.end_time(), 1);
EXPECT_EQ(curve.rows(), 0);
EXPECT_EQ(curve.cols(), 1);
EXPECT_EQ(curve.BernsteinBasis(0, 0), 0);
EXPECT_EQ(curve.control_points().size(), 0);
EXPECT_EQ(curve.Clone()->rows(), 0);
EXPECT_EQ(curve.value(0).size(), 0);
EXPECT_EQ(curve.GetExpression().size(), 0);
curve.ElevateOrder();
EXPECT_EQ(curve.order(), 0);
EXPECT_EQ(curve.control_points().size(), 0);
}
GTEST_TEST(BezierCurveTest, Constant) {
const Eigen::Vector2d kValue(1, 2);
BezierCurve<double> curve(0, 1, kValue);
EXPECT_EQ(curve.order(), 0);
EXPECT_EQ(curve.start_time(), 0);
EXPECT_EQ(curve.end_time(), 1);
EXPECT_EQ(curve.rows(), 2);
EXPECT_EQ(curve.cols(), 1);
EXPECT_TRUE(CompareMatrices(curve.value(0.5), kValue));
auto M = curve.AsLinearInControlPoints(1);
EXPECT_EQ(M.rows(), 1);
EXPECT_EQ(M.cols(), 0);
curve.ElevateOrder();
EXPECT_EQ(curve.order(), 1);
EXPECT_TRUE(CompareMatrices(curve.value(0.5), kValue));
}
using drake::geometry::optimization::VPolytope;
void CheckConvexHullProperty(const BezierCurve<double>& curve,
int num_samples) {
VPolytope control_polytope{curve.control_points()};
const double tol_sol = 1e-8;
Eigen::VectorXd samples = Eigen::VectorXd::LinSpaced(
num_samples, curve.start_time(), curve.end_time());
for (int i = 0; i < num_samples; ++i) {
EXPECT_TRUE(control_polytope.PointInSet(curve.value(samples(i)), tol_sol));
}
}
// An empty curve.
GTEST_TEST(BezierCurveTest, Default) {
BezierCurve<double> curve;
EXPECT_EQ(curve.order(), -1);
EXPECT_EQ(curve.control_points().rows(), 0);
EXPECT_EQ(curve.control_points().cols(), 0);
EXPECT_NO_THROW(curve.Clone());
}
// A moved-from curve.
GTEST_TEST(BezierCurveTest, MoveConstructor) {
Eigen::Matrix2d points;
// clang-format off
points << 1, 2,
3, 7;
// clang-format on
BezierCurve<double> orig(2, 3, points);
EXPECT_EQ(orig.order(), 1);
EXPECT_EQ(orig.start_time(), 2.0);
EXPECT_EQ(orig.end_time(), 3.0);
// A moved-into trajectory retains the original information.
BezierCurve<double> dest(std::move(orig));
EXPECT_EQ(dest.order(), 1);
EXPECT_EQ(dest.start_time(), 2.0);
EXPECT_EQ(dest.end_time(), 3.0);
// The moved-from trajectory must still be in a valid state.
EXPECT_EQ(orig.order(), orig.control_points().cols() - 1);
EXPECT_GE(orig.end_time(), orig.start_time());
}
// Line segment from (1,3) to (2,7).
GTEST_TEST(BezierCurveTest, Linear) {
Eigen::Matrix2d points;
// clang-format off
points << 1, 2,
3, 7;
// clang-format on
BezierCurve<double> curve(2, 3, points);
EXPECT_EQ(curve.order(), 1);
EXPECT_EQ(curve.start_time(), 2.0);
EXPECT_EQ(curve.end_time(), 3.0);
EXPECT_TRUE(
CompareMatrices(curve.value(2.5), Eigen::Vector2d(1.5, 5), 1e-14));
EXPECT_TRUE(CompareMatrices(curve.value(0), Eigen::Vector2d(1, 3), 1e-14));
auto deriv = curve.MakeDerivative();
BezierCurve<double>& deriv_bezier =
dynamic_cast<BezierCurve<double>&>(*deriv);
EXPECT_EQ(deriv_bezier.order(), 0);
EXPECT_EQ(deriv->start_time(), 2.0);
EXPECT_EQ(deriv->end_time(), 3.0);
EXPECT_TRUE(CompareMatrices(deriv->value(2.5), Eigen::Vector2d(1, 4), 1e-14));
EXPECT_TRUE(
CompareMatrices(curve.EvalDerivative(2.5), Eigen::Vector2d(1, 4), 1e-14));
const int num_samples{100};
CheckConvexHullProperty(curve, num_samples);
CheckConvexHullProperty(deriv_bezier, num_samples);
auto M = curve.AsLinearInControlPoints(1);
EXPECT_EQ(M.rows(), 2);
EXPECT_EQ(M.cols(), 1);
EXPECT_TRUE(CompareMatrices(deriv_bezier.control_points(),
curve.control_points() * M, 1e-14));
M = curve.AsLinearInControlPoints(0);
EXPECT_TRUE(CompareMatrices(M.toDense(), Matrix2d::Identity()));
M = curve.AsLinearInControlPoints(2);
EXPECT_EQ(M.rows(), 2);
EXPECT_EQ(M.cols(), 0);
curve.ElevateOrder();
EXPECT_EQ(curve.order(), 2);
EXPECT_TRUE(
CompareMatrices(curve.value(2.5), Eigen::Vector2d(1.5, 5), 1e-14));
EXPECT_TRUE(CompareMatrices(curve.value(0), Eigen::Vector2d(1, 3), 1e-14));
EXPECT_TRUE(CompareMatrices(curve.value(3.0), Eigen::Vector2d(2, 7), 1e-14));
}
// Quadratic curve: [ (1-t)Β²; t^2 ]
GTEST_TEST(BezierCurveTest, Quadratic) {
Eigen::Matrix<double, 2, 3> points;
// clang-format off
points << 1, 0, 0,
0, 0, 1;
// clang-format on
BezierCurve<double> curve(0, 1, points);
EXPECT_EQ(curve.order(), 2);
EXPECT_EQ(curve.start_time(), 0);
EXPECT_EQ(curve.end_time(), 1.0);
// derivative is [ -2(1-t); 2t ]
auto deriv = curve.MakeDerivative();
BezierCurve<double>& deriv_bezier =
dynamic_cast<BezierCurve<double>&>(*deriv);
EXPECT_EQ(deriv_bezier.order(), 1);
EXPECT_EQ(deriv->start_time(), 0.0);
EXPECT_EQ(deriv->end_time(), 1.0);
auto M = curve.AsLinearInControlPoints(1);
EXPECT_EQ(M.rows(), 3);
EXPECT_EQ(M.cols(), 2);
EXPECT_TRUE(CompareMatrices(deriv_bezier.control_points(),
curve.control_points() * M, 1e-14));
// second derivative is [ 2; 2 ]
auto second_deriv = curve.MakeDerivative(2);
BezierCurve<double>& second_deriv_bezier =
dynamic_cast<BezierCurve<double>&>(*second_deriv);
EXPECT_EQ(second_deriv_bezier.order(), 0);
EXPECT_EQ(second_deriv->start_time(), 0.0);
EXPECT_EQ(second_deriv->end_time(), 1.0);
auto second_deriv_via_deriv = deriv->MakeDerivative();
BezierCurve<double>& second_deriv_via_deriv_bezier =
dynamic_cast<BezierCurve<double>&>(*second_deriv_via_deriv);
// second derivative matches, if obtained by differentiating twice.
EXPECT_TRUE(CompareMatrices(second_deriv_bezier.control_points(),
second_deriv_via_deriv_bezier.control_points()));
// Note: includes evaluations outside the start and end times of the curve.
for (double sample_time = -0.2; sample_time <= 1.2; sample_time += 0.1) {
const double t = std::clamp(sample_time, 0.0, 1.0);
EXPECT_TRUE(CompareMatrices(curve.value(sample_time),
Eigen::Vector2d((1 - t) * (1 - t), t * t),
1e-14));
EXPECT_TRUE(CompareMatrices(deriv->value(sample_time),
Eigen::Vector2d(-2 * (1 - t), 2 * t), 1e-14));
EXPECT_TRUE(CompareMatrices(curve.EvalDerivative(sample_time),
Eigen::Vector2d(-2 * (1 - t), 2 * t), 1e-14));
EXPECT_TRUE(CompareMatrices(second_deriv->value(sample_time),
Eigen::Vector2d(2, 2), 1e-14));
EXPECT_TRUE(CompareMatrices(curve.EvalDerivative(sample_time, 2),
Eigen::Vector2d(2, 2), 1e-14));
}
M = curve.AsLinearInControlPoints(2);
EXPECT_EQ(M.rows(), 3);
EXPECT_EQ(M.cols(), 1);
EXPECT_TRUE(CompareMatrices(second_deriv_bezier.control_points(),
curve.control_points() * M, 1e-14));
// Extract the symbolic expression for the bezier curve.
VectorX<symbolic::Expression> curve_expression{
curve.GetExpression(symbolic::Variable("t"))};
for (int i = 0; i < curve_expression.rows(); i++) {
EXPECT_TRUE(curve_expression(i).is_polynomial());
EXPECT_EQ(symbolic::Polynomial(curve_expression(i)).TotalDegree(), 2);
}
const int num_samples{100};
CheckConvexHullProperty(curve, num_samples);
CheckConvexHullProperty(deriv_bezier, num_samples);
curve.ElevateOrder();
EXPECT_EQ(curve.order(), 3);
for (double sample_time = -0.2; sample_time <= 1.2; sample_time += 0.1) {
const double t = std::clamp(sample_time, 0.0, 1.0);
EXPECT_TRUE(CompareMatrices(curve.value(sample_time),
Eigen::Vector2d((1 - t) * (1 - t), t * t),
1e-14));
}
}
// Test the example from the AsLinearInControlPoints doc string.
GTEST_TEST(BezierCurve, ConstraintDerivativeControlPoint) {
Eigen::Matrix<double, 2, 3> points;
// clang-format off
points << 1, 0, 0,
0, 0, 1;
// clang-format on
BezierCurve<double> curve(0, 1, points);
auto deriv = curve.MakeDerivative();
BezierCurve<double>& deriv_bezier =
dynamic_cast<BezierCurve<double>&>(*deriv);
solvers::MathematicalProgram prog;
auto p = prog.NewContinuousVariables<2, 3>("p");
prog.SetInitialGuess(p, points);
SparseMatrix<double> M = curve.AsLinearInControlPoints(1);
const Vector2d lb(-0.1, -0.2);
const Vector2d ub(0.1, 0.2);
const int k = 1;
// Test the code sample.
for (int i = 0; i < curve.rows(); ++i) {
auto constraint = std::make_shared<solvers::LinearConstraint>(
M.col(k).transpose(), Vector1d(lb(i)), Vector1d(ub(i)));
auto b = prog.AddConstraint(constraint, p.row(i).transpose());
EXPECT_NEAR(prog.EvalBindingAtInitialGuess(b)[0],
deriv_bezier.control_points()(i, k), 1e-12);
}
// TODO(russt): Implement blkdiag for SparseMatrix and switch this example to
// use it instead of converting to dense matrices.
/* Test the block matrix documentation:
vec(derivative.control_points().T) = blockMT * vec(this.control_points().T),
blockMT = [ M.T, 0, .... 0 ]
[ 0, M.T, 0, ... ]
[ ... ]
[ ... , 0, M.T ].
*/
const int m = M.rows();
const int n = M.cols();
MatrixXd blockMT = MatrixXd::Zero(n * curve.rows(), m * curve.rows());
for (int i = 0; i < curve.rows(); ++i) {
blockMT.block(i * n, i * m, n, m) = M.transpose().toDense();
}
Map<const VectorXd> vec_curve_points(
curve.control_points().transpose().data(),
curve.rows() * (curve.order() + 1));
Map<const VectorXd> vec_deriv_points(
deriv_bezier.control_points().transpose().data(),
curve.rows() * (deriv_bezier.order() + 1));
EXPECT_TRUE(
CompareMatrices(vec_deriv_points, blockMT * vec_curve_points, 1e-12));
}
GTEST_TEST(BezierCurve, Clone) {
Eigen::Matrix<double, 2, 3> points;
// clang-format off
points << 1, 0, 0,
0, 0, 1;
// clang-format on
BezierCurve<double> curve(0, 1, points);
auto clone = curve.Clone();
BezierCurve<double>& clone_bezier =
dynamic_cast<BezierCurve<double>&>(*clone);
EXPECT_EQ(clone->start_time(), curve.start_time());
EXPECT_EQ(clone->end_time(), curve.end_time());
EXPECT_EQ(clone_bezier.control_points(), curve.control_points());
}
GTEST_TEST(BezierCurve, ScalarTypes) {
Eigen::Matrix<double, 2, 3> points;
// clang-format off
points << 1, 0, 0,
0, 0, 1;
// clang-format on
BezierCurve<double> curve(0, 1, points);
BezierCurve<AutoDiffXd> curve_ad(0, 1, points.cast<AutoDiffXd>());
BezierCurve<symbolic::Expression> curve_sym(
0, 1, points.cast<symbolic::Expression>());
EXPECT_TRUE(CompareMatrices(curve.value(0.5), curve_ad.value(0.5), 1e-14));
EXPECT_TRUE(CompareMatrices(curve.value(0.5), curve_sym.value(0.5), 1e-14));
}
GTEST_TEST(BezierCurve, GetExpressionLinear) {
symbolic::Variable t{"t"};
// Tests that the call to GetExpression returns a polynomial of appropriate
// degree and that all scalar types return the same expression when the
// underlying control points are the same. Whether the underlying expression
// is correct must be done separately.
auto test_expression_from_points =
[&t](double start_time, double end_time,
const Eigen::Ref<const Eigen::MatrixXd>& points) {
BezierCurve<double> curve_double(start_time, end_time, points);
BezierCurve<AutoDiffXd> curve_ad(start_time, end_time,
points.cast<AutoDiffXd>());
BezierCurve<symbolic::Expression> curve_sym(
start_time, end_time, points.cast<symbolic::Expression>());
const VectorX<symbolic::Expression> curve_expression{
curve_sym.GetExpression(t)};
const VectorX<symbolic::Expression> curve_expression_double{
curve_double.GetExpression(t)};
const VectorX<symbolic::Expression> curve_expression_ad{
curve_ad.GetExpression(t)};
for (int i = 0; i < curve_expression.rows(); i++) {
EXPECT_TRUE(curve_expression(i).is_polynomial());
EXPECT_EQ(symbolic::Polynomial(curve_expression(i)).TotalDegree(),
points.cols() - 1);
EXPECT_TRUE(curve_expression(i).EqualTo(curve_expression_double(i)));
EXPECT_TRUE(curve_expression(i).EqualTo(curve_expression_ad(i)));
}
return curve_expression;
};
// Line segment from (1,3) to (2,7).
Eigen::Matrix2d points_linear;
// clang-format off
points_linear << 1, 2,
3, 7;
// clang-format on
const double start_time_linear{2};
const double end_time_linear{3};
const VectorX<symbolic::Expression> linear_curve_expression =
test_expression_from_points(start_time_linear, end_time_linear,
points_linear);
for (int i = 0; i < linear_curve_expression.rows(); i++) {
symbolic::Expression expr_expected =
(end_time_linear - t) * points_linear(i, 0) +
(t - start_time_linear) * points_linear(i, 1);
EXPECT_TRUE(linear_curve_expression(i).EqualTo(expr_expected.Expand()));
}
// Quadratic curve: [ (1-t)Β²; t^2 ]
Eigen::Matrix<double, 2, 3> points_quadratic;
// clang-format off
points_quadratic << 1, 0, 0,
0, 0, 1;
// clang-format on
const VectorX<symbolic::Expression> quadratic_curve_expression =
test_expression_from_points(0, 1, points_quadratic);
EXPECT_TRUE(quadratic_curve_expression(0).EqualTo(pow(t, 2) - 2 * t + 1));
EXPECT_TRUE(quadratic_curve_expression(1).EqualTo(pow(t, 2)));
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/piecewise_quaternion_test.cc | #include "drake/common/trajectories/piecewise_quaternion.h"
#include <random>
#include <gtest/gtest.h>
#include "drake/common/drake_assert.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/math/wrap_to.h"
namespace drake {
namespace trajectories {
namespace {
// Returns q1 = quat(omega * dt) * q0
template <typename Scalar>
Quaternion<double> EulerIntegrateQuaternion(const Quaternion<Scalar>& q0,
const Vector3<Scalar>& omega,
double dt) {
Vector3<Scalar> delta = omega * dt;
Quaternion<Scalar> q1;
if (delta.norm() < Eigen::NumTraits<Scalar>::epsilon()) {
q1 = q0;
} else {
Quaternion<Scalar> q_delta =
Quaternion<Scalar>(AngleAxis<Scalar>(delta.norm(), delta.normalized()));
q1 = q_delta * q0;
}
q1.normalize();
return q1;
}
// Checks q[n].dot(q[n-1]) >= 0
template <typename Scalar>
bool CheckClosest(const std::vector<Quaternion<Scalar>>& quaternions) {
if (quaternions.size() <= 1) return true;
for (size_t i = 1; i < quaternions.size(); ++i) {
if (quaternions[i].dot(quaternions[i - 1]) < 0) return false;
}
return true;
}
// Let i be the head of the segment where t falls in.
// Checks spline.orientation(t) = quat(omega_i * (t - t_i)) * q_i
template <typename Scalar>
bool CheckSlerpInterpolation(const PiecewiseQuaternionSlerp<Scalar>& spline,
double t) {
t = std::min(t, spline.end_time());
t = std::max(t, spline.start_time());
int i = spline.get_segment_index(t);
double t0 = spline.start_time(i);
double t1 = spline.end_time(i);
t = std::min(t, t1);
t = std::max(t, t0);
double dt = t - t0;
DRAKE_DEMAND(dt <= spline.duration(i));
Quaternion<Scalar> q_spline = spline.orientation(t);
Quaternion<Scalar> q0 = spline.orientation(t0);
Vector3<Scalar> w0 = spline.angular_velocity(t0);
Quaternion<Scalar> q1 = EulerIntegrateQuaternion(q0, w0, dt);
if (q_spline.isApprox(q1, 1e-10))
return true;
else
return false;
}
// Generates a vector of random orientation using randomized axis angles.
template <typename Scalar>
std::vector<Quaternion<Scalar>> GenerateRandomQuaternions(
int size, std::default_random_engine* generator) {
DRAKE_DEMAND(size >= 0);
std::vector<Quaternion<Scalar>> ret(size);
std::uniform_real_distribution<double> uniform(-10, 10);
for (int i = 0; i < size; ++i) {
ret[i] = Quaternion<Scalar>(AngleAxis<Scalar>(
uniform(*generator),
Vector3<Scalar>(uniform(*generator), uniform(*generator),
uniform(*generator))));
}
return ret;
}
// Tests CheckSlerpInterpolation and "closestness" for PiecewiseQuaternionSlerp
// generated from random breaks and samples.
GTEST_TEST(TestPiecewiseQuaternionSlerp,
TestRandomizedPiecewiseQuaternionSlerp) {
std::default_random_engine generator(123);
int N = 10000;
std::vector<double> time =
PiecewiseTrajectory<double>::RandomSegmentTimes(N - 1, generator);
std::vector<Quaternion<double>> quat =
GenerateRandomQuaternions<double>(N, &generator);
PiecewiseQuaternionSlerp<double> rot_spline(time, quat);
const auto rot_spline_deriv = rot_spline.MakeDerivative(1);
// Check dense interpolated quaternions.
for (double t = time.front(); t < time.back(); t += 0.01) {
EXPECT_TRUE(CheckSlerpInterpolation(rot_spline, t));
}
EXPECT_TRUE(CheckClosest(rot_spline.get_quaternion_samples()));
// Test that I can build the equivalent spline incrementally.
PiecewiseQuaternionSlerp<double> incremental;
for (int i = 0; i < N; i++) {
incremental.Append(time[i], quat[i]);
}
incremental.is_approx(rot_spline, 0.0);
for (double t = time.front(); t < time.back(); t += 0.1) {
EXPECT_EQ(incremental.EvalDerivative(t), rot_spline.EvalDerivative(t));
}
// And again with the other types.
PiecewiseQuaternionSlerp<double> incremental_rotation_matrices,
incremental_angle_axes;
for (int i = 0; i < N; i++) {
incremental_rotation_matrices.Append(time[i],
math::RotationMatrix<double>(quat[i]));
incremental_angle_axes.Append(time[i], AngleAxis<double>(quat[i]));
}
incremental_rotation_matrices.is_approx(rot_spline, 1e-14);
incremental_angle_axes.is_approx(rot_spline, 1e-14);
for (double t = time.front(); t < time.back(); t += 0.1) {
EXPECT_TRUE(CompareMatrices(incremental_rotation_matrices.EvalDerivative(t),
rot_spline.EvalDerivative(t), 1e-12));
EXPECT_TRUE(CompareMatrices(incremental_angle_axes.EvalDerivative(t),
rot_spline.EvalDerivative(t), 1e-12));
}
}
// Tests when the given quaternions are not "closest" to the previous one.
// Also tests the returned angular velocity against known values.
GTEST_TEST(TestPiecewiseQuaternionSlerp,
TestShortestQuaternionPiecewiseQuaternionSlerp) {
std::vector<double> time = {0, 1.6, 2.32};
std::vector<double> ang = {1, 2.4 - 2 * M_PI, 5.3};
Vector3<double> axis = Vector3<double>(1, 2, 3).normalized();
std::vector<Quaternion<double>> quat(ang.size());
for (size_t i = 0; i < ang.size(); ++i) {
quat[i] = Quaternion<double>(AngleAxis<double>(ang[i], axis));
}
PiecewiseQuaternionSlerp<double> rot_spline(time, quat);
const std::vector<Quaternion<double>>& internal_quat =
rot_spline.get_quaternion_samples();
EXPECT_TRUE(CheckClosest(internal_quat));
EXPECT_FALSE(CheckClosest(quat));
for (size_t i = 0; i < time.size() - 1; ++i) {
EXPECT_TRUE(CompareMatrices(rot_spline.orientation(time[i]).coeffs(),
internal_quat[i].coeffs(), 1e-10,
MatrixCompareType::absolute));
double ang_diff = ang[i + 1] - ang[i];
double time_diff = time[i + 1] - time[i];
double omega = math::wrap_to(ang_diff, -M_PI, M_PI) / time_diff;
EXPECT_TRUE(CompareMatrices(rot_spline.angular_velocity(time[i]),
omega * axis, 1e-10,
MatrixCompareType::absolute));
}
// Check dense interpolated quaternions.
for (double t = time.front(); t < time.back(); t += 0.01) {
EXPECT_TRUE(CheckSlerpInterpolation(rot_spline, t));
}
}
GTEST_TEST(TestPiecewiseQuaternionSlerp,
TestIdenticalPiecewiseQuaternionSlerp) {
std::vector<double> time = {0, 1.6};
std::vector<double> ang = {-1.3, -1.3 + 2 * M_PI};
Vector3<double> axis = Vector3<double>(1, 2, 3).normalized();
std::vector<Quaternion<double>> quat(ang.size());
for (size_t i = 0; i < ang.size(); ++i) {
quat[i] = Quaternion<double>(AngleAxis<double>(ang[i], axis));
}
PiecewiseQuaternionSlerp<double> rot_spline(time, quat);
double t = 0.3 * time[0] + 0.7 * time[1];
const std::vector<Quaternion<double>>& internal_quats =
rot_spline.get_quaternion_samples();
EXPECT_TRUE(CompareMatrices(rot_spline.orientation(t).coeffs(),
internal_quats[0].coeffs(), 1e-10,
MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(rot_spline.orientation(t).coeffs(),
internal_quats[1].coeffs(), 1e-10,
MatrixCompareType::absolute));
}
GTEST_TEST(TestPiecewiseQuaternionSlerp, TestIsApprox) {
std::vector<double> time = {0, 1.6};
std::vector<double> ang = {-1.3, 1};
Vector3<double> axis = Vector3<double>(1, 2, 3).normalized();
std::vector<Quaternion<double>> quat(ang.size());
for (size_t i = 0; i < ang.size(); ++i) {
quat[i] = Quaternion<double>(AngleAxis<double>(ang[i], axis));
}
PiecewiseQuaternionSlerp<double> traj0(time, quat);
// -q represents the same orientation, so it should result in equality.
std::vector<Quaternion<double>> quat_neg = quat;
for (size_t i = 0; i < ang.size(); ++i) {
quat_neg[i].coeffs() *= -1;
}
PiecewiseQuaternionSlerp<double> traj1(time, quat_neg);
EXPECT_TRUE(traj0.is_approx(traj1, 1e-12));
// Mutates a bit, should not be equal anymore.
quat[0] = Quaternion<double>(AngleAxis<double>(ang[0] + 1e-6, axis));
PiecewiseQuaternionSlerp<double> traj2(time, quat);
EXPECT_FALSE(traj0.is_approx(traj2, 1e-7));
EXPECT_TRUE(traj0.is_approx(traj2, 1e-5));
}
GTEST_TEST(TestPiecewiseQuaternionSlerp, TestDerivatives) {
std::vector<double> time = {0, 1.6, 2.32};
std::vector<double> ang = {1, 2.4 - 2 * M_PI, 5.3};
Vector3<double> axis = Vector3<double>(1, 2, 3).normalized();
std::vector<Quaternion<double>> quat(ang.size());
for (size_t i = 0; i < ang.size(); ++i) {
quat[i] = Quaternion<double>(AngleAxis<double>(ang[i], axis));
}
PiecewiseQuaternionSlerp<double> rot_spline(time, quat);
const auto zeroth_derivative = rot_spline.MakeDerivative(0);
const auto first_derivative = rot_spline.MakeDerivative(1);
const auto second_derivative = rot_spline.MakeDerivative(2);
for (double t = -1.0; t < 4.0; t += 0.234) {
// Test that value() and rows() and cols() are compatible.
EXPECT_EQ(rot_spline.value(t).rows(), rot_spline.rows());
EXPECT_EQ(rot_spline.value(t).cols(), rot_spline.cols());
// Test zeroth derivative.
EXPECT_TRUE(CompareMatrices(rot_spline.value(t),
zeroth_derivative->value(t), 1e-14));
EXPECT_TRUE(CompareMatrices(rot_spline.value(t),
rot_spline.EvalDerivative(t, 0), 1e-14));
// Test first derivative.
EXPECT_TRUE(CompareMatrices(rot_spline.angular_velocity(t),
first_derivative->value(t), 1e-14));
EXPECT_TRUE(CompareMatrices(rot_spline.angular_velocity(t),
rot_spline.EvalDerivative(t, 1), 1e-14));
// Test second derivative.
EXPECT_TRUE(CompareMatrices(rot_spline.angular_acceleration(t),
second_derivative->value(t), 1e-14));
EXPECT_TRUE(CompareMatrices(rot_spline.angular_acceleration(t),
rot_spline.EvalDerivative(t, 2), 1e-14));
}
}
template <typename T>
void TestScalarType() {
std::vector<T> times = {1, 2};
std::vector<AngleAxis<T>> rot_samples(times.size());
rot_samples[0] = AngleAxis<T>(0.3, Vector3<T>::UnitX());
rot_samples[1] = AngleAxis<T>(-1, Vector3<T>::UnitY());
PiecewiseQuaternionSlerp<T> quat_traj(times, rot_samples);
}
GTEST_TEST(TestPiecewiseQuaternionSlerp, ScalarTypes) {
TestScalarType<double>();
TestScalarType<AutoDiffXd>();
TestScalarType<symbolic::Expression>();
}
} // namespace
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/trajectories | /home/johnshepherd/drake/common/trajectories/test/piecewise_pose_test.cc | #include "drake/common/trajectories/piecewise_pose.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/math/rigid_transform.h"
#include "drake/math/rotation_matrix.h"
namespace drake {
namespace trajectories {
using Eigen::Vector3d;
using math::RigidTransform;
using math::RigidTransformd;
using math::RotationMatrixd;
using trajectories::PiecewisePolynomial;
using trajectories::PiecewiseQuaternionSlerp;
class PiecewisePoseTest : public ::testing::Test {
protected:
void SetUp() override {
std::vector<double> times = {1, 2};
std::vector<AngleAxis<double>> rot_samples(times.size());
std::vector<MatrixX<double>> pos_samples(times.size(),
MatrixX<double>(3, 1));
rot_samples[0] = AngleAxis<double>(0.3, Vector3<double>::UnitX());
rot_samples[1] = AngleAxis<double>(-1, Vector3<double>::UnitY());
pos_samples[0] << 0.3, 0, -0.5;
pos_samples[1] << 1, -1, 3;
std::vector<RigidTransform<double>> samples(times.size());
for (size_t i = 0; i < times.size(); ++i) {
samples[i] = RigidTransform<double>(rot_samples[i], pos_samples[i]);
}
Vector3<double> start_vel(Vector3<double>::Zero());
Vector3<double> end_vel(Vector3<double>::Zero());
dut_ = PiecewisePose<double>::MakeCubicLinearWithEndLinearVelocity(
times, samples, start_vel, end_vel);
test_times_ = {times.front() - 0.2, times.front(),
(times.front() + times.back()) / 2., times.back(),
times.back() + 0.3};
position_ =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
times, pos_samples, start_vel, end_vel);
orientation_ = PiecewiseQuaternionSlerp<double>(times, rot_samples);
}
PiecewisePose<double> dut_;
std::vector<double> test_times_;
PiecewisePolynomial<double> position_;
PiecewiseQuaternionSlerp<double> orientation_;
};
TEST_F(PiecewisePoseTest, TestConstructor) {
EXPECT_EQ(dut_.get_number_of_segments(), 1);
EXPECT_EQ(dut_.get_segment_times()[1], 2);
}
// Tests linear velocity starts and ends at zero.
TEST_F(PiecewisePoseTest, TestEndLinearVelocity) {
double t0 = dut_.get_position_trajectory().start_time();
double t1 = dut_.get_position_trajectory().end_time();
EXPECT_TRUE(drake::CompareMatrices(dut_.GetVelocity(t0).tail<3>(),
Vector3<double>::Zero(), 1e-12,
drake::MatrixCompareType::absolute));
EXPECT_TRUE(drake::CompareMatrices(dut_.GetVelocity(t1).tail<3>(),
Vector3<double>::Zero(), 1e-12,
drake::MatrixCompareType::absolute));
}
// Tests pose matches that directly interpolated from PiecewiseQuaternionSlerp
// and PiecewisePolynomial.
TEST_F(PiecewisePoseTest, TestPose) {
for (double time : test_times_) {
math::RigidTransform<double> expected(orientation_.orientation(time),
position_.value(time));
EXPECT_TRUE(drake::CompareMatrices(dut_.GetPose(time).GetAsMatrix4(),
expected.GetAsMatrix4(), 1e-12,
drake::MatrixCompareType::absolute));
EXPECT_TRUE(drake::CompareMatrices(dut_.value(time),
expected.GetAsMatrix4(), 1e-12,
drake::MatrixCompareType::absolute));
}
}
// Tests velocity matches that directly interpolated from
// PiecewiseQuaternionSlerp and PiecewisePolynomial.
TEST_F(PiecewisePoseTest, TestVelocity) {
for (double time : test_times_) {
Vector6<double> expected;
expected.head<3>() = orientation_.angular_velocity(time);
expected.tail<3>() = position_.derivative().value(time);
if (!orientation_.is_time_in_range(time)) expected.head<3>().setZero();
if (!position_.is_time_in_range(time)) expected.tail<3>().setZero();
EXPECT_TRUE(drake::CompareMatrices(dut_.GetVelocity(time), expected, 1e-12,
drake::MatrixCompareType::absolute));
}
}
// Tests angular acceleration is always zero because of linear interpolation,
// and linear acceleration matches that interpolated from
// PiecewisePolynomial.
TEST_F(PiecewisePoseTest, TestAcceleration) {
for (double time : test_times_) {
Vector6<double> expected;
expected.head<3>() = Vector3<double>::Zero();
expected.tail<3>() = position_.derivative(2).value(time);
if (!position_.is_time_in_range(time)) expected.tail<3>().setZero();
EXPECT_TRUE(drake::CompareMatrices(dut_.GetAcceleration(time), expected,
1e-12,
drake::MatrixCompareType::absolute));
}
}
// Tests getters.
TEST_F(PiecewisePoseTest, TestGetTrajectory) {
EXPECT_TRUE(dut_.get_position_trajectory().isApprox(position_, 1e-12));
EXPECT_TRUE(dut_.get_orientation_trajectory().is_approx(orientation_, 1e-12));
}
// Tests is_approx().
TEST_F(PiecewisePoseTest, TestIsApprox) {
std::vector<double> times = {1, 2};
std::vector<AngleAxis<double>> rot_samples(times.size());
std::vector<MatrixX<double>> pos_samples(times.size(), MatrixX<double>(3, 1));
pos_samples[0] << -3, 1, 0;
pos_samples[1] << -2, -1, 5;
rot_samples[0] = AngleAxis<double>(0.3, Vector3<double>::UnitX());
rot_samples[1] = AngleAxis<double>(-1.2, Vector3<double>::UnitY());
Vector3<double> start_vel(Vector3<double>::Zero());
Vector3<double> end_vel(Vector3<double>::Zero());
PiecewisePolynomial<double> new_pos_traj =
PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives(
times, pos_samples, start_vel, end_vel);
PiecewiseQuaternionSlerp<double> new_rot_traj(times, rot_samples);
PiecewisePose<double> diff_position(new_pos_traj, orientation_);
EXPECT_TRUE(!diff_position.IsApprox(dut_, 1e-12));
PiecewisePose<double> diff_orientation(position_, new_rot_traj);
EXPECT_TRUE(!diff_orientation.IsApprox(dut_, 1e-12));
}
// Tests getters.
TEST_F(PiecewisePoseTest, TestTrajectoryOverrides) {
EXPECT_EQ(dut_.rows(), 4);
EXPECT_EQ(dut_.cols(), 4);
EXPECT_TRUE(dut_.has_derivative());
std::vector<double> truncated_test_times_ =
std::vector<double>(test_times_.begin() + 1, test_times_.end() - 1);
const auto zeroth_derivative = dut_.MakeDerivative(0);
const auto first_derivative = dut_.MakeDerivative(1);
const auto second_derivative = dut_.MakeDerivative(2);
for (double time : truncated_test_times_) {
EXPECT_TRUE(drake::CompareMatrices(dut_.value(time),
zeroth_derivative->value(time), 1e-12,
drake::MatrixCompareType::absolute));
EXPECT_TRUE(drake::CompareMatrices(dut_.value(time),
dut_.EvalDerivative(time, 0), 1e-12,
drake::MatrixCompareType::absolute));
EXPECT_TRUE(drake::CompareMatrices(dut_.GetVelocity(time),
first_derivative->value(time), 1e-12,
drake::MatrixCompareType::absolute));
EXPECT_TRUE(drake::CompareMatrices(dut_.GetVelocity(time),
dut_.EvalDerivative(time, 1), 1e-12,
drake::MatrixCompareType::absolute));
EXPECT_TRUE(drake::CompareMatrices(dut_.GetAcceleration(time),
second_derivative->value(time), 1e-12,
drake::MatrixCompareType::absolute));
EXPECT_TRUE(drake::CompareMatrices(dut_.GetAcceleration(time),
dut_.EvalDerivative(time, 2), 1e-12,
drake::MatrixCompareType::absolute));
}
}
GTEST_TEST(PiecewisePoseMakeTest, MakeLinear) {
const std::vector<double> times = {1., 2., 3.};
const std::vector<RigidTransformd> poses{
RigidTransformd(),
RigidTransformd(RotationMatrixd::MakeXRotation(M_PI / 2),
Vector3d{.1, .2, .3}),
RigidTransformd(Vector3d{.4, .5, .6})};
PiecewisePose<double> pose_traj =
PiecewisePose<double>::MakeLinear(times, poses);
EXPECT_EQ(pose_traj.start_time(), 1.);
EXPECT_EQ(pose_traj.end_time(), 3.);
EXPECT_EQ(pose_traj.get_number_of_segments(), 2);
const auto& position = pose_traj.get_position_trajectory();
EXPECT_EQ(position.start_time(), 1.);
EXPECT_EQ(position.end_time(), 3.);
EXPECT_EQ(position.get_number_of_segments(), 2);
EXPECT_EQ(position.getSegmentPolynomialDegree(0), 1);
EXPECT_EQ(position.getSegmentPolynomialDegree(1), 1);
const auto& orientation = pose_traj.get_orientation_trajectory();
EXPECT_EQ(orientation.start_time(), 1.);
EXPECT_EQ(orientation.end_time(), 3.);
EXPECT_EQ(orientation.get_number_of_segments(), 2);
EXPECT_TRUE(pose_traj.GetPose(1.5).IsNearlyEqualTo(
RigidTransformd(RotationMatrixd::MakeXRotation(M_PI / 4),
Vector3d{.05, .1, .15}),
1e-14));
EXPECT_TRUE(pose_traj.GetPose(2.5).IsNearlyEqualTo(
RigidTransformd(RotationMatrixd::MakeXRotation(M_PI / 4),
Vector3d{.25, .35, .45}),
1e-14));
}
template <typename T>
void TestScalarType() {
std::vector<T> times = {1, 2};
std::vector<AngleAxis<T>> rot_samples(times.size());
std::vector<MatrixX<T>> pos_samples(times.size(), MatrixX<T>(3, 1));
rot_samples[0] = AngleAxis<T>(0.3, Vector3<T>::UnitX());
rot_samples[1] = AngleAxis<T>(-1, Vector3<T>::UnitY());
pos_samples[0] << 0.3, 0, -0.5;
pos_samples[1] << 1, -1, 3;
Vector3<T> start_vel(Vector3<T>::Zero());
Vector3<T> end_vel(Vector3<T>::Zero());
PiecewisePolynomial<T> position_traj =
PiecewisePolynomial<T>::CubicWithContinuousSecondDerivatives(
times, pos_samples, start_vel, end_vel);
PiecewiseQuaternionSlerp<T> orientation_traj(times, rot_samples);
PiecewisePose<T> pose_traj(position_traj, orientation_traj);
}
GTEST_TEST(PiecewisePoseScalarTest, ScalarTypes) {
TestScalarType<double>();
TestScalarType<AutoDiffXd>();
TestScalarType<symbolic::Expression>();
}
} // namespace trajectories
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test/find_loaded_library_test.cc | #include "drake/common/find_loaded_library.h"
#include <string>
#include <gtest/gtest.h>
using std::string;
// @note gcc requires us to consume something from `lib_is_real` to link the
// library.
void lib_is_real_dummy_function();
namespace drake {
namespace {
GTEST_TEST(FindLibraryTest, Library) {
// See above.
lib_is_real_dummy_function();
// Test whether or not `LoadedLibraryPath()` can find the path to a library
// loaded by the process.
std::optional<string> library_path = LoadedLibraryPath("lib_is_real.so");
ASSERT_TRUE(library_path);
EXPECT_EQ(library_path.value()[0], '/');
library_path = LoadedLibraryPath("lib_not_real.so");
EXPECT_FALSE(library_path);
}
} // namespace
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test/scope_exit_test.cc | #include "drake/common/scope_exit.h"
#include <gtest/gtest.h>
namespace drake {
namespace {
// Reproduce the header file example as a test case. There are no GTEST
// predicates here; if the memory is not freed, we'll rely on our memory
// checkers to complain.
GTEST_TEST(ScopeExitTest, Example) {
void* foo = ::malloc(10);
ScopeExit guard([foo]() {
::free(foo);
});
}
// Test that the func() is invoked.
GTEST_TEST(ScopeExitTest, CountTest) {
int count = 0;
{
ScopeExit guard([&count]() { ++count; });
}
EXPECT_EQ(count, 1);
}
// Test that the guard can be disarmed.
GTEST_TEST(ScopeExitTest, DisarmTest) {
int count = 0;
{
ScopeExit guard([&count]() { ++count; });
guard.Disarm();
}
EXPECT_EQ(count, 0);
}
} // namespace
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test/autodiffxd_subtraction_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, Subtraction) {
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/drake_cc_googletest_main_test_device.cc | /// @file
/// This is a sample unit test whose purpose is to provide a binary for
/// test/drake_cc_googletest_main_test.py to run, in order to assess the
/// correctness of command-line flag handling. That python file contains the
/// majority of the meaningful unit test logic.
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include "drake/common/text_logging.h"
// We expect the invoking shell to set this to 1.0 via the command-line.
// (If it doesn't, the unit test will fail.)
DEFINE_double(magic_number, 0.0, "Magic number");
namespace drake {
namespace {
GTEST_TEST(GtestMainTest, BasicTest) {
drake::log()->debug("Cross your fingers for the magic_number {}", 1.0);
EXPECT_EQ(FLAGS_magic_number, 1.0);
}
} // namespace
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/test/fmt_ostream_test.cc | #include "drake/common/fmt_ostream.h"
#include <gtest/gtest.h>
// Sample code that shows how to shim Drake code that defines an operator<< to
// interface with fmt >= 9 semantics. The ostream_formatter is intended to be a
// porting shim for #17742 and will probably be deleted eventually, once all
// of Drake is using fmt pervasively.
namespace sample {
class UnportedStreamable {
public:
friend std::ostream& operator<<(std::ostream& os, const UnportedStreamable&) {
return os << "US";
}
};
} // namespace sample
namespace fmt {
template <>
struct formatter<sample::UnportedStreamable> : drake::ostream_formatter {};
} // namespace fmt
// Sample code that shows how to print a third-party type that only supports
// operator<< and not fmt::formatter. We plan to keep this sugar indefinitely,
// since many third-party types will never know about fmt::formatter.
namespace sample {
class ThirdPartyStreamable {
public:
ThirdPartyStreamable() = default;
// Non-copyable.
ThirdPartyStreamable(const ThirdPartyStreamable&) = delete;
friend std::ostream& operator<<(std::ostream& os,
const ThirdPartyStreamable&) {
return os << "TPS";
}
};
} // namespace sample
namespace drake {
namespace {
GTEST_TEST(FmtOstreamTest, UnportedOstreamShim) {
const sample::UnportedStreamable value;
EXPECT_EQ(fmt::format("{}", value), "US");
EXPECT_EQ(fmt::format("{:4}", value), "US ");
EXPECT_EQ(fmt::format("{:>4}", value), " US");
}
GTEST_TEST(FmtOstreamTest, ThirdPartyOstreamShim) {
const sample::ThirdPartyStreamable value;
EXPECT_EQ(fmt::format("{}", fmt_streamed(value)), "TPS");
EXPECT_EQ(fmt::format("{:4}", fmt_streamed(value)), "TPS ");
EXPECT_EQ(fmt::format("{:>4}", fmt_streamed(value)), " TPS");
}
} // namespace
} // namespace drake
| 0 |
Subsets and Splits