repo_id
stringclasses
205 values
file_path
stringlengths
33
141
content
stringlengths
1
307k
__index_level_0__
int64
0
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/schema/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 = "schema", visibility = ["//visibility:public"], deps = [ ":rotation", ":stochastic", ":transform", ], ) drake_cc_library( name = "rotation", srcs = ["rotation.cc"], hdrs = ["rotation.h"], deps = [ ":stochastic", "//common:name_value", "//common:overloaded", "//math:geometric_transform", ], ) drake_cc_library( name = "stochastic", srcs = ["stochastic.cc"], hdrs = ["stochastic.h"], deps = [ "//common:essential", "//common:name_value", "//common:nice_type_name", "//common:overloaded", "//common:random", "//common:unused", "//common/symbolic:expression", ], ) drake_cc_library( name = "transform", srcs = ["transform.cc"], hdrs = ["transform.h"], deps = [ ":rotation", ":stochastic", "//common:name_value", "//math:geometric_transform", ], ) # === test/ === drake_cc_googletest( name = "rotation_test", deps = [ ":rotation", "//common/test_utilities:eigen_matrix_compare", "//common/yaml", ], ) drake_cc_googletest( name = "stochastic_test", deps = [ ":stochastic", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", "//common/yaml", ], ) drake_cc_googletest( name = "transform_test", deps = [ ":transform", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", "//common/yaml", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/schema/stochastic.cc
#include "drake/common/schema/stochastic.h" #include <stdexcept> #include <utility> #include <fmt/format.h> #include "drake/common/nice_type_name.h" #include "drake/common/overloaded.h" #include "drake/common/unused.h" using drake::symbolic::Expression; using std::unique_ptr; namespace drake { namespace schema { Distribution::Distribution() {} Distribution::~Distribution() {} Deterministic::Deterministic() {} Deterministic::Deterministic(double value_in) : value(value_in) {} Deterministic::~Deterministic() {} double Deterministic::Sample(drake::RandomGenerator* generator) const { unused(generator); return value; } double Deterministic::Mean() const { return value; } Expression Deterministic::ToSymbolic() const { return value; } Gaussian::Gaussian() {} Gaussian::Gaussian(double mean_in, double stddev_in) : mean(mean_in), stddev(stddev_in) {} Gaussian::~Gaussian() {} double Gaussian::Sample(drake::RandomGenerator* generator) const { std::normal_distribution<double> distribution(mean, stddev); return distribution(*generator); } double Gaussian::Mean() const { return mean; } Expression Gaussian::ToSymbolic() const { std::normal_distribution<Expression> distribution(mean, stddev); return distribution(); } Uniform::Uniform() {} Uniform::Uniform(double min_in, double max_in) : min(min_in), max(max_in) {} // NOLINT(build/include_what_you_use) Uniform::~Uniform() {} double Uniform::Sample(drake::RandomGenerator* generator) const { std::uniform_real_distribution<double> distribution(min, max); return distribution(*generator); } double Uniform::Mean() const { return (min + max) / 2.0; } Expression Uniform::ToSymbolic() const { std::uniform_real_distribution<Expression> distribution( min, max); return distribution(); } UniformDiscrete::UniformDiscrete() {} UniformDiscrete::UniformDiscrete(std::vector<double> values_in) : values(std::move(values_in)) {} UniformDiscrete::~UniformDiscrete() {} double UniformDiscrete::Sample(drake::RandomGenerator* generator) const { if (values.empty()) { throw std::logic_error( "Cannot Sample() empty UniformDiscrete distribution."); } const std::vector<double> weights(values.size(), 1.); const int index = std::discrete_distribution<int>(weights.begin(), weights.end())( *generator); return values.at(index); } double UniformDiscrete::Mean() const { if (values.empty()) { throw std::logic_error( "Cannot Mean() empty UniformDiscrete distribution."); } double sum = 0; for (double value : values) { sum += value; } return sum / values.size(); } Expression UniformDiscrete::ToSymbolic() const { if (values.empty()) { throw std::logic_error( "Cannot ToSymbolic() empty UniformDiscrete distribution."); } // Sample a real number distribution over [0, num_values). const int num_values = values.size(); std::uniform_real_distribution<Expression> distribution(0, num_values); const Expression real_index = distribution(); // Loop to compute the result as if we were doing: // result = (real_index < 1.0) ? values[0] : // (real_index < 2.0) ? values[1] : // ... // values.back(); Expression result = values.back(); for (int i = num_values - 2; i >= 0; --i) { result = if_then_else(real_index < (i + 1), values[i], result); } return result; } unique_ptr<Distribution> ToDistribution(const DistributionVariant& var) { return std::visit([](auto&& arg) -> unique_ptr<Distribution> { using ContainedType = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<ContainedType, double>) { return std::make_unique<Deterministic>(arg); } else { return std::make_unique<ContainedType>(arg); } }, var); } double Sample(const DistributionVariant& var, drake::RandomGenerator* generator) { return ToDistribution(var)->Sample(generator); } double Mean(const DistributionVariant& var) { return ToDistribution(var)->Mean(); } Expression ToSymbolic(const DistributionVariant& var) { return ToDistribution(var)->ToSymbolic(); } Eigen::VectorXd Sample(const std::vector<DistributionVariant>& vec, drake::RandomGenerator* generator) { Eigen::VectorXd result(vec.size()); for (size_t i = 0; i < vec.size(); ++i) { result(i) = Sample(vec[i], generator); } return result; } Eigen::VectorXd Mean(const std::vector<DistributionVariant>& vec) { Eigen::VectorXd result(vec.size()); for (size_t i = 0; i < vec.size(); ++i) { result(i) = Mean(vec[i]); } return result; } drake::VectorX<Expression> ToSymbolic( const std::vector<DistributionVariant>& vec) { drake::VectorX<Expression> result(vec.size()); for (size_t i = 0; i < vec.size(); ++i) { result(i) = ToSymbolic(vec[i]); } return result; } bool IsDeterministic(const DistributionVariant& var) { return std::visit<bool>(overloaded{ [](const double&) { return true; }, [](const Deterministic&) { return true; }, [](const Gaussian& arg) { return arg.stddev == 0.0; }, [](const Uniform& arg) { return arg.min == arg.max; }, [](const UniformDiscrete& arg) { return arg.values.size() == 1; }, }, var); } double GetDeterministicValue(const DistributionVariant& var) { if (!IsDeterministic(var)) { std::visit([](auto&& arg) { using ContainedType = std::decay_t<decltype(arg)>; throw std::logic_error(fmt::format( "Attempt to GetDeterministicValue() on a variant that contains a {}", drake::NiceTypeName::Get<ContainedType>())); }, var); } return ToDistribution(var)->Mean(); } DistributionVector::DistributionVector() {} DistributionVector::~DistributionVector() {} template <int Size> DeterministicVector<Size>::DeterministicVector() {} template <int Size> DeterministicVector<Size>::DeterministicVector( const drake::Vector<double, Size>& value_in) : value(value_in) {} template <int Size> DeterministicVector<Size>::~DeterministicVector() {} template <int Size> Eigen::VectorXd DeterministicVector<Size>::Sample( drake::RandomGenerator* generator) const { unused(generator); return value; } template <int Size> Eigen::VectorXd DeterministicVector<Size>::Mean() const { return value; } template <int Size> drake::VectorX<Expression> DeterministicVector<Size>::ToSymbolic() const { return value.template cast<Expression>(); } template <int Size> GaussianVector<Size>::GaussianVector() {} template <int Size> GaussianVector<Size>::GaussianVector( const drake::Vector<double, Size>& mean_in, const drake::VectorX<double>& stddev_in) : mean(mean_in), stddev(stddev_in) {} template <int Size> GaussianVector<Size>::~GaussianVector() {} template <int Size> Eigen::VectorXd GaussianVector<Size>::Sample( drake::RandomGenerator* generator) const { if (!(stddev.size() == mean.size() || stddev.size() == 1)) { throw std::logic_error(fmt::format( "Cannot Sample() a GaussianVector distribution with " "size {} mean but size {} dev", mean.size(), stddev.size())); } Eigen::VectorXd result(mean.size()); for (int i = 0; i < mean.size(); ++i) { const double stddev_i = (stddev.size() == 1) ? stddev(0) : stddev(i); result(i) = Gaussian(mean(i), stddev_i).Sample(generator); } return result; } template <int Size> Eigen::VectorXd GaussianVector<Size>::Mean() const { return mean; } template <int Size> drake::VectorX<Expression> GaussianVector<Size>::ToSymbolic() const { if (!(stddev.size() == mean.size() || stddev.size() == 1)) { throw std::logic_error(fmt::format( "Cannot ToSymbolic() a GaussianVector distribution with " "size {} mean but size {} dev", mean.size(), stddev.size())); } drake::VectorX<Expression> result(mean.size()); for (int i = 0; i < mean.size(); ++i) { const double stddev_i = (stddev.size() == 1) ? stddev(0) : stddev(i); result(i) = Gaussian(mean(i), stddev_i).ToSymbolic(); } return result; } template <int Size> UniformVector<Size>::UniformVector() {} template <int Size> UniformVector<Size>::UniformVector( const drake::Vector<double, Size>& min_in, const drake::Vector<double, Size>& max_in) : min(min_in), max(max_in) {} // NOLINT(build/include_what_you_use) template <int Size> UniformVector<Size>::~UniformVector() {} template <int Size> Eigen::VectorXd UniformVector<Size>::Sample( drake::RandomGenerator* generator) const { if (min.size() != max.size()) { throw std::logic_error(fmt::format( "Cannot Sample() a UniformVector distribution with " "size {} min but size {} max", min.size(), max.size())); } Eigen::VectorXd result(max.size()); for (int i = 0; i < max.size(); ++i) { result(i) = Uniform(min(i), max(i)).Sample(generator); } return result; } template <int Size> Eigen::VectorXd UniformVector<Size>::Mean() const { if (min.size() != max.size()) { throw std::logic_error(fmt::format( "Cannot Mean() a UniformVector distribution with " "size {} min but size {} max", min.size(), max.size())); } return (min + max) / 2.0; } template <int Size> drake::VectorX<Expression> UniformVector<Size>::ToSymbolic() const { if (min.size() != max.size()) { throw std::logic_error(fmt::format( "Cannot ToSymbolic() a UniformVector distribution with " "size {} min but size {} max", min.size(), max.size())); } drake::VectorX<Expression> result(max.size()); for (int i = 0; i < max.size(); ++i) { // NOLINTNEXTLINE(build/include_what_you_use) result(i) = Uniform(min(i), max(i)).ToSymbolic(); } return result; } template <int Size> unique_ptr<DistributionVector> ToDistributionVector( const DistributionVectorVariant<Size>& vec) { return std::visit<unique_ptr<DistributionVector>>(overloaded{ // NOLINTNEXTLINE(whitespace/line_length) [](const drake::Vector<double, Size>& arg) { return std::make_unique<DeterministicVector<Size>>(arg); }, [](const DeterministicVector<Size>& arg) { return std::make_unique<DeterministicVector<Size>>(arg); }, [](const GaussianVector<Size>& arg) { return std::make_unique<GaussianVector<Size>>(arg); }, [](const UniformVector<Size>& arg) { return std::make_unique<UniformVector<Size>>(arg); }, [](const Deterministic& arg) { return std::make_unique<DeterministicVector<Size>>( Eigen::VectorXd::Constant(1, arg.value)); }, [](const Gaussian& arg) { return std::make_unique<GaussianVector<Size>>( Eigen::VectorXd::Constant(1, arg.mean), Eigen::VectorXd::Constant(1, arg.stddev)); }, [](const Uniform& arg) { return std::make_unique<UniformVector<Size>>( Eigen::VectorXd::Constant(1, arg.min), Eigen::VectorXd::Constant(1, arg.max)); }, []<typename T>(const internal::InvalidVariantSelection<T>&) -> std::nullptr_t { DRAKE_UNREACHABLE(); }, }, vec); } template <int Size> bool IsDeterministic(const DistributionVectorVariant<Size>& vec) { return std::visit<bool>(overloaded{ [](const drake::Vector<double, Size>&) { return true; }, [](const DeterministicVector<Size>&) { return true; }, [](const GaussianVector<Size>& arg) { return arg.stddev.isZero(0.0); }, [](const UniformVector<Size>& arg) { return arg.min == arg.max; }, [](const Deterministic&) { return true; }, [](const Gaussian& arg) { return arg.stddev == 0.0; }, [](const Uniform& arg) { return arg.min == arg.max; }, []<typename T>(const internal::InvalidVariantSelection<T>&) -> std::false_type { DRAKE_UNREACHABLE(); }, }, vec); } template <int Size> Eigen::VectorXd GetDeterministicValue( const DistributionVectorVariant<Size>& vec) { if (!IsDeterministic(vec)) { std::visit([](auto&& arg) { using ContainedType = std::decay_t<decltype(arg)>; throw std::logic_error(fmt::format( "Attempt to GetDeterministicValue() on a variant that contains a {}", drake::NiceTypeName::Get<ContainedType>())); }, vec); } return ToDistributionVector(vec)->Mean(); } #define DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES(Clazz) \ template class Clazz<Eigen::Dynamic>; \ template class Clazz<1>; \ template class Clazz<2>; \ template class Clazz<3>; \ template class Clazz<4>; \ template class Clazz<5>; \ template class Clazz<6>; DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES(DeterministicVector) DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES(GaussianVector) DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES(UniformVector) #undef DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES #define DRAKE_DEFINE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES(Func) \ template Func(const DistributionVectorVariantX&); \ template Func(const DistributionVectorVariant<1>&); \ template Func(const DistributionVectorVariant<2>&); \ template Func(const DistributionVectorVariant<3>&); \ template Func(const DistributionVectorVariant<4>&); \ template Func(const DistributionVectorVariant<5>&); \ template Func(const DistributionVectorVariant<6>&); DRAKE_DEFINE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES( unique_ptr<DistributionVector> ToDistributionVector) DRAKE_DEFINE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES( bool IsDeterministic) DRAKE_DEFINE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES( Eigen::VectorXd GetDeterministicValue) #undef DRAKE_DEFINE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES } // namespace schema } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/schema/transform.cc
#include "drake/common/schema/transform.h" #include <stdexcept> #include <fmt/format.h> #include "drake/common/drake_assert.h" #include "drake/common/drake_throw.h" #include "drake/math/rotation_matrix.h" namespace drake { namespace schema { using symbolic::Expression; namespace { math::RigidTransformd SampleInternal(const Transform& stochastic_transform, RandomGenerator* generator) { // It is somewhat yak-shavey to get an actual materialized transform here. // We convert to symbolic, convert the symbolic to a vector and matrix of // symbolic, `Evaluate` those, convert the result back to a // `RigidTransform<double>`, and build the resulting values into a new // fully deterministic `Transform`. // // This is *much* prettier written with `auto` but please do not be // tempted to use it here: I have left the long type names in because it // is impossible to debug Eigen `enable_if` error messages without them. const math::RigidTransform<Expression> symbolic_transform = stochastic_transform.ToSymbolic(); const Vector3<Expression> symbolic_translation = symbolic_transform.translation(); const Eigen::Vector3d concrete_translation = symbolic::Evaluate(symbolic_translation, {}, generator); const math::RotationMatrix<Expression> symbolic_rotation = symbolic_transform.rotation(); const math::RotationMatrixd concrete_rotation( symbolic::Evaluate(symbolic_rotation.matrix(), {}, generator)); return math::RigidTransformd{concrete_rotation, concrete_translation}; } } // namespace Transform::Transform(const math::RigidTransformd& x) { translation = x.translation(); rotation = schema::Rotation{x.rotation()}; } bool Transform::IsDeterministic() const { return schema::IsDeterministic(translation) && rotation.IsDeterministic(); } math::RigidTransformd Transform::GetDeterministicValue() const { DRAKE_THROW_UNLESS(this->IsDeterministic()); return { rotation.GetDeterministicValue(), schema::GetDeterministicValue(translation), }; } math::RigidTransform<Expression> Transform::ToSymbolic() const { auto sym_translate = schema::ToDistributionVector(translation)->ToSymbolic(); auto sym_rotate = rotation.ToSymbolic(); return math::RigidTransform<Expression>(sym_rotate, sym_translate); } math::RigidTransformd Transform::Mean() const { using symbolic::Environment; using symbolic::Variables; using VariableType = symbolic::Variable::Type; // Obtain the symbolic form of this Transform; this is an easy way to // collapse the variants into simple arithmetic expressions. const math::RigidTransform<Expression> symbolic = ToSymbolic(); // The symbolic representation of the transform uses uniform random // variables (or else has no variables). Set them all to the mean. Environment env; for (const auto& var : GetDistinctVariables(symbolic.GetAsMatrix34())) { DRAKE_DEMAND(var.get_type() == VariableType::RANDOM_UNIFORM); env.insert(var, 0.5); } // Extract the underlying matrix of the transform, substitute the env so // that the expressions are now all constants, and then re-create the // RigidTransform wrapper around the matrix. const auto to_double = [&env](const auto& x) { return x.Evaluate(env); }; return math::RigidTransformd( symbolic.GetAsMatrix34().unaryExpr(to_double)); } Transform Transform::SampleAsTransform(RandomGenerator* generator) const { Transform result(SampleInternal(*this, generator)); result.base_frame = base_frame; return result; } math::RigidTransformd Transform::Sample(RandomGenerator* generator) const { if (base_frame.has_value() && (*base_frame != "world")) { throw std::logic_error( fmt::format( "Transform::Sample() would discard non-trivial base frame \"{}\"; " "use Transform::SampleAsTransform() instead.", *base_frame)); } return SampleInternal(*this, generator); } } // namespace schema } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/schema/stochastic.h
#pragma once #include <memory> #include <type_traits> #include <variant> #include <vector> #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/common/name_value.h" #include "drake/common/random.h" #include "drake/common/symbolic/expression.h" namespace drake { namespace schema { /** @defgroup schema_stochastic Configuring distributions @ingroup stochastic_systems @{ This page describes how to use classes such as schema::Distribution to denote stochastic quantities, as a bridge between loading a scenario specification and populating the corresponding symbolic::Expression quantities into a systems::System. # Stochastic variables We'll explain uses of schema::Distribution and related types using the matching YAML syntax as parsed by yaml::LoadYamlFile. Given this C++ data structure: ``` struct MyStuff { schema::DistributionVariant value; }; MyStuff stuff; ``` You might load a YAML file such as this: ``` stuff: value: 1.0 ``` The `stuff.value` is set to a constant (not stochastic) value 1.0. Alternatively, you might load a YAML file such as this: ``` stuff: value: !Gaussian mean: 1.0 stddev: 0.5 ``` Now, `stuff.value` is set to gaussian variable with the given mean and standard deviation. The exclamation point syntax is a YAML type tag, which we use to specify the type choice within an `std::variant`. The schema::DistributionVariant is a typedef for a specific `std::variant`. There are a few other choices for the type. Here, you might specify a real-valued uniform range: ``` stuff: value: !Uniform min: 1.0 max: 5.0 ``` Or, you might choose from a set of equally-likely options: ``` stuff: value: !UniformDiscrete values: [1.0, 1.5, 2.0] ``` You may also use YAML's flow style to fit everything onto a single line. These one-line spellings are the equivalent to those above. ``` stuff: value: !Gaussian { mean: 1.0, stddev: 0.5 } ``` ``` stuff: value: !Uniform { min: 1.0, max: 5.0 } ``` ``` stuff: value: !UniformDiscrete { values: [1.0, 1.5, 2.0] } ``` # Vectors of stochastic variables For convenience, we also provide the option to specify a vector of independent stochastic variables with the same type. We'll explain uses of schema::DistributionVector and related types using the matching YAML syntax as parsed by yaml::LoadYamlFile. Given this C++ data structure: ``` struct MyThing { schema::DistributionVectorVariantX value; }; MyThing thing; ``` You might load a YAML file such as this: ``` thing: value: [1.0, 2.0, 3.0] ``` The `thing.value` is set to a constant (not stochastic) vector with three elements. You might also choose to constrain the vector to be a fixed size: ``` struct MyThing3 { schema::DistributionVectorVariant3 value; }; MyThing3 thing3; ``` Whether fixed or dynamic size, you might specify stochastic variables: ``` thing: value: !GaussianVector mean: [2.1, 2.2, 2.3] stddev: [1.0] # Same stddev each. ``` Or: ``` thing: value: !GaussianVector mean: [2.1, 2.2, 2.3] stddev: [1.0, 0.5, 0.2] # Different stddev each. ``` Or: ``` thing: value: !UniformVector min: [10.0, 20.0] max: [11.0, 22.0] ``` @note You cannot mix, e.g., %Gaussian and %Uniform within the same vector; all elements must be a homogeneous type. All distributions still support constants for some elements and stochastic for others by specifying a zero-sized range for the constant elements: ``` thing: value: !UniformVector # The first element is a constant 2.0, not stochastic. min: [2.0, -1.0] max: [2.0, 1.0] ``` Or: ``` thing: value: !GaussianVector # The first element is a constant 2.0, not stochastic. mean: [2.0, 3.0] stddev: [0.0, 1.0] ``` # See also See @ref schema_transform for one practical application, of specifying rotations, translations, and transforms using stochastic schemas. @} */ /// Base class for a single distribution, to be used with YAML archives. /// (See class DistributionVector for vector-valued distributions.) /// /// See @ref implementing_serialize "Implementing Serialize" for implementation /// details, especially the unusually public member fields of our subclasses. class Distribution { public: virtual ~Distribution(); virtual double Sample(drake::RandomGenerator* generator) const = 0; virtual double Mean() const = 0; virtual drake::symbolic::Expression ToSymbolic() const = 0; protected: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Distribution) Distribution(); }; /// A single deterministic `value`. class Deterministic final : public Distribution { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Deterministic) Deterministic(); explicit Deterministic(double value); ~Deterministic() final; double Sample(drake::RandomGenerator*) const final; double Mean() const final; drake::symbolic::Expression ToSymbolic() const final; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } double value{}; }; /// A gaussian distribution with `mean` and `stddev`. class Gaussian final : public Distribution { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Gaussian) Gaussian(); Gaussian(double mean, double stddev); ~Gaussian() final; double Sample(drake::RandomGenerator*) const final; double Mean() const final; drake::symbolic::Expression ToSymbolic() const final; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(mean)); a->Visit(DRAKE_NVP(stddev)); } double mean{}; double stddev{}; }; /// A uniform distribution with `min` inclusive and `max` exclusive. class Uniform final : public Distribution { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Uniform) Uniform(); Uniform(double min, double max); ~Uniform() final; double Sample(drake::RandomGenerator*) const final; double Mean() const final; drake::symbolic::Expression ToSymbolic() const final; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(min)); a->Visit(DRAKE_NVP(max)); } double min{}; double max{}; }; /// Chooses from among discrete `values` with equal probability. class UniformDiscrete final : public Distribution { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(UniformDiscrete) UniformDiscrete(); explicit UniformDiscrete(std::vector<double> values); ~UniformDiscrete() final; double Sample(drake::RandomGenerator*) const final; double Mean() const final; drake::symbolic::Expression ToSymbolic() const final; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(values)); } std::vector<double> values; }; /// Variant over all kinds of distributions. using DistributionVariant = std::variant< double, Deterministic, Gaussian, Uniform, UniformDiscrete>; /// Copies the given variant into a Distribution base class. std::unique_ptr<Distribution> ToDistribution( const DistributionVariant& var); /// Like Distribution::Sample, but on a DistributionVariant instead. double Sample(const DistributionVariant& var, drake::RandomGenerator* generator); /// Like Distribution::Mean, but on a DistributionVariant instead. double Mean(const DistributionVariant& var); /// Like Distribution::ToSymbolic, but on a DistributionVariant instead. drake::symbolic::Expression ToSymbolic(const DistributionVariant& var); /// Like Distribution::Sample, but elementwise over a collection of /// possibly-heterogenous DistributionVariant instead. Eigen::VectorXd Sample(const std::vector<DistributionVariant>& vec, drake::RandomGenerator* generator); /// Like Distribution::Mean, but elementwise over a collection of /// possibly-heterogenous DistributionVariant instead. Eigen::VectorXd Mean(const std::vector<DistributionVariant>& vec); /// Like Distribution::ToSymbolic, but elementwise over a collection of /// possibly-heterogenous DistributionVariant instead. drake::VectorX<drake::symbolic::Expression> ToSymbolic( const std::vector<DistributionVariant>& vec); /// Returns true iff `var` is set to a deterministic value. bool IsDeterministic(const DistributionVariant& var); /// If `var` is deterministic, retrieves its value. /// @throws std::exception if `var` is not deterministic. double GetDeterministicValue(const DistributionVariant& var); // --------------------------------------------------------------------------- /// Base class for a vector of distributions, to be used with YAML archives. /// (See class Distribution for scalar-valued distributions.) /// /// See @ref implementing_serialize for implementation details, especially the /// unusually public member fields in our subclasses. class DistributionVector { public: virtual ~DistributionVector(); virtual Eigen::VectorXd Sample(drake::RandomGenerator* generator) const = 0; virtual Eigen::VectorXd Mean() const = 0; virtual drake::VectorX<drake::symbolic::Expression> ToSymbolic() const = 0; protected: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(DistributionVector) DistributionVector(); }; /// A single deterministic vector `value`. /// @tparam Size rows at compile time (max 6) or else Eigen::Dynamic. template <int Size> class DeterministicVector final : public DistributionVector { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(DeterministicVector) DeterministicVector(); explicit DeterministicVector(const drake::Vector<double, Size>& value); ~DeterministicVector() final; Eigen::VectorXd Sample(drake::RandomGenerator* generator) const final; Eigen::VectorXd Mean() const final; drake::VectorX<drake::symbolic::Expression> ToSymbolic() const final; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } drake::Vector<double, Size> value; }; /// A gaussian distribution with vector `mean` and vector or scalar `stddev`. /// /// When `mean` and `stddev` both have the same number of elements, that /// denotes an elementwise pairing of the 0th mean with 0th stddev, 1st mean /// with 1st stddev, etc. /// /// Alternatively, `stddev` can be a vector with a single element, no matter /// the size of `mean`; that denotes the same `stddev` value applied to every /// element of `mean`. /// /// @tparam Size rows at compile time (max 6) or else Eigen::Dynamic. template <int Size> class GaussianVector final : public DistributionVector { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(GaussianVector) GaussianVector(); GaussianVector(const drake::Vector<double, Size>& mean, const drake::VectorX<double>& stddev); ~GaussianVector() final; Eigen::VectorXd Sample(drake::RandomGenerator*) const final; Eigen::VectorXd Mean() const final; drake::VectorX<drake::symbolic::Expression> ToSymbolic() const final; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(mean)); a->Visit(DRAKE_NVP(stddev)); } drake::Vector<double, Size> mean; drake::VectorX<double> stddev; }; /// A uniform distribution with vector `min` inclusive and vector `max` /// exclusive. /// @tparam Size rows at compile time (max 6) or else Eigen::Dynamic. template <int Size> class UniformVector final : public DistributionVector { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(UniformVector) UniformVector(); UniformVector(const drake::Vector<double, Size>& min, const drake::Vector<double, Size>& max); ~UniformVector() final; Eigen::VectorXd Sample(drake::RandomGenerator* generator) const final; Eigen::VectorXd Mean() const final; drake::VectorX<drake::symbolic::Expression> ToSymbolic() const final; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(min)); a->Visit(DRAKE_NVP(max)); } drake::Vector<double, Size> min; drake::Vector<double, Size> max; }; namespace internal { // This struct is used below in DistributionVectorVariant to help reject the // single-valued family of stochastic classes (e.g., schema::Deterministic) // when the compile time Size does not permit single values (i.e., Size >= 2). // // @tparam Singular the disallowed single-valued class (e.g., Deterministic). template <typename Singular> struct InvalidVariantSelection { template <typename Archive> void Serialize(Archive*) { DRAKE_UNREACHABLE(); } }; } // namespace internal /// Variant over all kinds of vector distributions. /// /// If the Size parameter allows for 1-element vectors (i.e, is either 1 or /// Eigen::Dynamic), then this variant also offers the single distribution /// types (Deterministic, Gaussian, Uniform). If the Size parameter is 2 or /// greater, the single distribution types are not allowed. /// /// @tparam Size rows at compile time (max 6) or else Eigen::Dynamic. template <int Size> using DistributionVectorVariant = std::variant< drake::Vector<double, Size>, DeterministicVector<Size>, GaussianVector<Size>, UniformVector<Size>, std::conditional_t<(Size == Eigen::Dynamic || Size == 1), Deterministic, internal::InvalidVariantSelection<Deterministic>>, std::conditional_t<(Size == Eigen::Dynamic || Size == 1), Gaussian, internal::InvalidVariantSelection<Gaussian>>, std::conditional_t<(Size == Eigen::Dynamic || Size == 1), Uniform, internal::InvalidVariantSelection<Uniform>>>; /// DistributionVectorVariant that permits any vector size dynamically. using DistributionVectorVariantX = DistributionVectorVariant<Eigen::Dynamic>; /// Copies the given variant into a DistributionVector base class. /// @tparam Size rows at compile time (max 6) or else Eigen::Dynamic. template <int Size> std::unique_ptr<DistributionVector> ToDistributionVector( const DistributionVectorVariant<Size>& vec); /// Returns true iff all of `vec`'s elements are set to a deterministic value. /// @tparam Size rows at compile time (max 6) or else Eigen::Dynamic. template <int Size> bool IsDeterministic(const DistributionVectorVariant<Size>& vec); /// If `vec` is deterministic, retrieves its value. /// @throws std::exception if `vec` is not deterministic. /// @tparam Size rows at compile time (max 6) or else Eigen::Dynamic. template <int Size> Eigen::VectorXd GetDeterministicValue( const DistributionVectorVariant<Size>& vec); #define DRAKE_DECLARE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES(Func) \ extern template Func(const DistributionVectorVariantX&); \ extern template Func(const DistributionVectorVariant<1>&); \ extern template Func(const DistributionVectorVariant<2>&); \ extern template Func(const DistributionVectorVariant<3>&); \ extern template Func(const DistributionVectorVariant<4>&); \ extern template Func(const DistributionVectorVariant<5>&); \ extern template Func(const DistributionVectorVariant<6>&); DRAKE_DECLARE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES( std::unique_ptr<DistributionVector> ToDistributionVector) DRAKE_DECLARE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES( bool IsDeterministic) DRAKE_DECLARE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES( Eigen::VectorXd GetDeterministicValue) #undef DRAKE_DECLARE_TEMPLATE_INSTANTIATIONS_ON_ALL_SIZES } // namespace schema } // namespace drake
0
/home/johnshepherd/drake/common/schema
/home/johnshepherd/drake/common/schema/test/transform_test.cc
#include "drake/common/schema/transform.h" #include <limits> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/common/yaml/yaml_io.h" #include "drake/math/rigid_transform.h" using drake::yaml::LoadYamlString; namespace drake { namespace schema { namespace { const char* deterministic = R"""( base_frame: foo translation: [1., 2., 3.] rotation: !Rpy { deg: [10, 20, 30] } )"""; GTEST_TEST(DeterministicTest, TransformTest) { const auto transform = LoadYamlString<Transform>(deterministic); EXPECT_EQ(*transform.base_frame, "foo"); drake::math::RigidTransformd expected( drake::math::RollPitchYawd( Eigen::Vector3d(10., 20., 30.) * (M_PI / 180.0)), Eigen::Vector3d(1., 2., 3.)); constexpr double kTol = std::numeric_limits<double>::epsilon(); EXPECT_TRUE(drake::CompareMatrices( transform.GetDeterministicValue().GetAsMatrix34(), expected.GetAsMatrix34(), kTol)); EXPECT_TRUE(drake::CompareMatrices( transform.Mean().GetAsMatrix34(), expected.GetAsMatrix34(), kTol)); } const char* random = R"""( base_frame: bar translation: !UniformVector { min: [1., 2., 3.], max: [4., 5., 6.] } rotation: !Uniform {} )"""; GTEST_TEST(StochasticTest, TransformTest) { const auto transform = LoadYamlString<Transform>(random); EXPECT_EQ(*transform.base_frame, "bar"); EXPECT_FALSE(IsDeterministic(transform.translation)); EXPECT_TRUE(std::holds_alternative<Rotation::Uniform>( transform.rotation.value)); EXPECT_TRUE(drake::CompareMatrices( transform.Mean().translation(), Eigen::Vector3d(2.5, 3.5, 4.5))); } const char* random_bounded = R"""( translation: !UniformVector { min: [1., 2., 3.], max: [4., 5., 6.] } rotation: !Rpy deg: !UniformVector min: [380, -0.25, -1.] max: [400, 0.25, 1.] )"""; GTEST_TEST(StochasticSampleTest, TransformTest) { const auto transform = LoadYamlString<Transform>(random_bounded); drake::RandomGenerator generator(0); drake::math::RigidTransformd sampled_transform = transform.Sample(&generator); // The sampled transforms must lie within the randomization domain. // TODO(jwnimmer-tri) The correctness checks below traceable to rotation.cc's // implementation would be better placed in rotation_test.cc. const auto& translation_domain = std::get<schema::UniformVector<3>>(transform.translation); for (int i = 0; i < 3; i++) { EXPECT_GT(sampled_transform.translation()[i], translation_domain.min[i]); EXPECT_LT(sampled_transform.translation()[i], translation_domain.max[i]); } const auto& rotation_domain = std::get<schema::UniformVector<3>>( std::get<schema::Rotation::Rpy>( transform.rotation.value).deg); const Eigen::Vector3d rpy = drake::math::RollPitchYawd(sampled_transform.rotation()) .vector() * (180 / M_PI); EXPECT_LT(rpy[0], rotation_domain.max[0] - 360); EXPECT_GT(rpy[0], rotation_domain.min[0] - 360); EXPECT_LT(rpy[1], rotation_domain.max[1]); EXPECT_GT(rpy[1], rotation_domain.min[1]); EXPECT_LT(rpy[2], rotation_domain.max[2]); EXPECT_GT(rpy[2], rotation_domain.min[2]); // A second sample will (almost certainly) differ from the first sample. const drake::math::RigidTransformd sampled_transform_2 = transform.Sample(&generator); EXPECT_FALSE(sampled_transform.IsExactlyEqualTo(sampled_transform_2)); // Check the mean. drake::math::RigidTransformd expected_mean( drake::math::RollPitchYawd( Eigen::Vector3d(390., 0., 0.) * (M_PI / 180.0)), Eigen::Vector3d(2.5, 3.5, 4.5)); EXPECT_TRUE(transform.Mean().IsExactlyEqualTo(expected_mean)); } GTEST_TEST(StochasticSampleTest, TransformTestWithBaseFrame) { const Transform transform = LoadYamlString<Transform>(random_bounded); drake::RandomGenerator generator(0); const math::RigidTransformd sampled_rigidtransformd = transform.Sample(&generator); Transform transform_with_base_frame = transform; transform_with_base_frame.base_frame = "baz"; DRAKE_EXPECT_THROWS_MESSAGE(transform_with_base_frame.Sample(&generator), ".*frame.*use.*SampleAsTransform.*instead.*"); generator = drake::RandomGenerator(0); const Transform sampled_transform = transform_with_base_frame.SampleAsTransform(&generator); EXPECT_EQ(sampled_transform.GetDeterministicValue().translation(), sampled_rigidtransformd.translation()); EXPECT_TRUE( sampled_transform.GetDeterministicValue().rotation().IsNearlyEqualTo( sampled_rigidtransformd.rotation(), 1e-14)); } } // namespace } // namespace schema } // namespace drake
0
/home/johnshepherd/drake/common/schema
/home/johnshepherd/drake/common/schema/test/stochastic_test.cc
#include "drake/common/schema/stochastic.h" #include <algorithm> #include <cmath> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/common/yaml/yaml_io.h" using drake::symbolic::Expression; using drake::symbolic::test::ExprEqual; using drake::symbolic::Variable; using drake::symbolic::Variables; using drake::yaml::LoadYamlString; using drake::yaml::SaveYamlString; namespace drake { namespace schema { namespace { struct DistributionStruct { std::vector<DistributionVariant> vec; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(vec)); } }; const char* all_variants = R"""( vec: [ !Deterministic { value: 5.0 }, !Gaussian { mean: 2.0, stddev: 4.0 }, !Uniform { min: 1.0, max: 5.0 }, !UniformDiscrete { values: [1, 1.5, 2] }, 3.2 ] )"""; const char* floats = "vec: [5.0, 6.1, 7.2]"; void CheckGaussianSymbolic(const Expression& e, double mean, double stddev) { const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 1); const Variable& v{*(vars.begin())}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_GAUSSIAN); EXPECT_PRED2(ExprEqual, e, mean + stddev * v); } void CheckUniformSymbolic(const Expression& e, double min, double max) { const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 1); const Variable& v{*(vars.begin())}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_UNIFORM); EXPECT_PRED2(ExprEqual, e, min + (max - min) * v); } void CheckUniformDiscreteSymbolic( const Expression& e, std::vector<double> values) { const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 1); const Variable& v{*(vars.begin())}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_UNIFORM); // We don't check the structure here; it can be checked more readably by the // caller via string comparison. } GTEST_TEST(StochasticTest, ScalarTest) { const auto variants = LoadYamlString<DistributionStruct>(all_variants); RandomGenerator generator; const Deterministic& d = std::get<Deterministic>(variants.vec[0]); EXPECT_EQ(d.Sample(&generator), 5.0); EXPECT_EQ(d.Mean(), 5.0); EXPECT_PRED2(ExprEqual, d.ToSymbolic(), 5.0); EXPECT_TRUE(IsDeterministic(variants.vec[0])); EXPECT_EQ(GetDeterministicValue(variants.vec[0]), 5.0); const Gaussian& g = std::get<Gaussian>(variants.vec[1]); EXPECT_EQ(g.mean, 2.); EXPECT_EQ(g.stddev, 4.); EXPECT_TRUE(std::isfinite(d.Sample(&generator))); EXPECT_EQ(g.Mean(), 2.); CheckGaussianSymbolic(g.ToSymbolic(), g.mean, g.stddev); EXPECT_FALSE(IsDeterministic(variants.vec[1])); EXPECT_THROW(GetDeterministicValue(variants.vec[1]), std::logic_error); const Uniform& u = std::get<Uniform>(variants.vec[2]); EXPECT_EQ(u.min, 1.); EXPECT_EQ(u.max, 5.); double uniform_sample = u.Sample(&generator); EXPECT_LE(u.min, uniform_sample); EXPECT_GE(u.max, uniform_sample); EXPECT_EQ(u.Mean(), 3.); CheckUniformSymbolic(u.ToSymbolic(), u.min, u.max); EXPECT_FALSE(IsDeterministic(variants.vec[2])); EXPECT_THROW(GetDeterministicValue(variants.vec[2]), std::logic_error); const UniformDiscrete& ub = std::get<UniformDiscrete>(variants.vec[3]); EXPECT_NE(std::find(ub.values.begin(), ub.values.end(), ub.Sample(&generator)), ub.values.end()); EXPECT_EQ(ub.Mean(), 1.5); CheckUniformDiscreteSymbolic(ub.ToSymbolic(), ub.values); EXPECT_EQ(ub.ToSymbolic().to_string(), "(if ((3 * random_uniform_0) < 1) then 1 else " "(if ((3 * random_uniform_0) < 2) then 1.5 else " "2))"); EXPECT_FALSE(IsDeterministic(variants.vec[3])); EXPECT_THROW(GetDeterministicValue(variants.vec[3]), std::logic_error); EXPECT_EQ(std::get<double>(variants.vec[4]), 3.2); EXPECT_EQ(Sample(variants.vec[4], &generator), 3.2); EXPECT_EQ(Mean(variants.vec[4]), 3.2); EXPECT_TRUE(IsDeterministic(variants.vec[4])); EXPECT_EQ(GetDeterministicValue(variants.vec[4]), 3.2); Eigen::VectorXd vec = Sample(variants.vec, &generator); ASSERT_EQ(vec.size(), 5); EXPECT_EQ(vec(0), 5.0); EXPECT_TRUE(std::isfinite(vec(1))); EXPECT_LE(u.min, vec(2)); EXPECT_GE(u.max, vec(2)); EXPECT_NE(std::find(ub.values.begin(), ub.values.end(), vec(3)), ub.values.end()); EXPECT_EQ(vec(4), 3.2); vec = Mean(variants.vec); ASSERT_EQ(vec.size(), 5); EXPECT_EQ(vec(0), 5.0); EXPECT_EQ(vec(1), 2.0); EXPECT_EQ(vec(2), 3.0); EXPECT_EQ(vec(3), 1.5); EXPECT_EQ(vec(4), 3.2); VectorX<Expression> symbolic_vec = ToSymbolic(variants.vec); ASSERT_EQ(symbolic_vec.size(), 5); EXPECT_PRED2(ExprEqual, symbolic_vec(0), 5.0); CheckGaussianSymbolic(symbolic_vec(1), g.mean, g.stddev); CheckUniformSymbolic(symbolic_vec(2), u.min, u.max); CheckUniformDiscreteSymbolic(symbolic_vec(3), ub.values); EXPECT_PRED2(ExprEqual, symbolic_vec(4), 3.2); // Confirm that writeback works for every possible type. EXPECT_EQ(SaveYamlString(variants, "root"), R"""(root: vec: - !Deterministic value: 5.0 - !Gaussian mean: 2.0 stddev: 4.0 - !Uniform min: 1.0 max: 5.0 - !UniformDiscrete values: [1.0, 1.5, 2.0] - 3.2 )"""); // Try loading a value which looks like an ordinary vector. const auto parsed_floats = LoadYamlString<DistributionStruct>(floats); vec = Sample(parsed_floats.vec, &generator); ASSERT_EQ(vec.size(), 3); EXPECT_TRUE(CompareMatrices(vec, Eigen::Vector3d(5.0, 6.1, 7.2))); } struct DistributionVectorStruct { DistributionVectorVariantX vector; DistributionVectorVariantX deterministic; DistributionVectorVariantX gaussian1; DistributionVectorVariant<4> gaussian2; DistributionVectorVariantX uniform; DistributionVectorVariantX deterministic_scalar; DistributionVectorVariantX gaussian_scalar; DistributionVectorVariantX uniform_scalar; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(vector)); a->Visit(DRAKE_NVP(deterministic)); a->Visit(DRAKE_NVP(gaussian1)); a->Visit(DRAKE_NVP(gaussian2)); a->Visit(DRAKE_NVP(uniform)); a->Visit(DRAKE_NVP(deterministic_scalar)); a->Visit(DRAKE_NVP(gaussian_scalar)); a->Visit(DRAKE_NVP(uniform_scalar)); } }; const char* vector_variants = R"""( vector: [1., 2., 3.] deterministic: !DeterministicVector { value: [3., 4., 5.] } gaussian1: !GaussianVector { mean: [1.1, 1.2, 1.3], stddev: [0.1, 0.2, 0.3] } gaussian2: !GaussianVector { mean: [2.1, 2.2, 2.3, 2.4], stddev: [1.0] } uniform: !UniformVector { min: [10, 20], max: [11, 22] } deterministic_scalar: !Deterministic { value: 19.5 } gaussian_scalar: !Gaussian { mean: 5, stddev: 1 } uniform_scalar: !Uniform { min: 1, max: 2 } )"""; GTEST_TEST(StochasticTest, VectorTest) { const auto variants = LoadYamlString<DistributionVectorStruct>(vector_variants); RandomGenerator generator; EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.vector)->Sample(&generator), Eigen::Vector3d(1., 2., 3.))); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.vector)->Mean(), Eigen::Vector3d(1., 2., 3.))); auto symbolic_vector = ToDistributionVector(variants.vector)->ToSymbolic(); ASSERT_EQ(symbolic_vector.size(), 3); EXPECT_PRED2(ExprEqual, symbolic_vector(0), 1.); EXPECT_PRED2(ExprEqual, symbolic_vector(1), 2.); EXPECT_PRED2(ExprEqual, symbolic_vector(2), 3.); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.deterministic)->Sample(&generator), Eigen::Vector3d(3., 4., 5.))); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.deterministic)->Mean(), Eigen::Vector3d(3., 4., 5.))); symbolic_vector = ToDistributionVector(variants.deterministic)->ToSymbolic(); ASSERT_EQ(symbolic_vector.size(), 3); EXPECT_PRED2(ExprEqual, symbolic_vector(0), 3.); EXPECT_PRED2(ExprEqual, symbolic_vector(1), 4.); EXPECT_PRED2(ExprEqual, symbolic_vector(2), 5.); EXPECT_EQ( ToDistributionVector(variants.gaussian1)->Sample(&generator).size(), 3); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.gaussian1)->Mean(), Eigen::Vector3d(1.1, 1.2, 1.3))); symbolic_vector = ToDistributionVector(variants.gaussian1)->ToSymbolic(); ASSERT_EQ(symbolic_vector.size(), 3); CheckGaussianSymbolic(symbolic_vector(0), 1.1, 0.1); CheckGaussianSymbolic(symbolic_vector(1), 1.2, 0.2); CheckGaussianSymbolic(symbolic_vector(2), 1.3, 0.3); EXPECT_EQ( ToDistributionVector(variants.gaussian2)->Sample(&generator).size(), 4); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.gaussian2)->Mean(), Eigen::Vector4d(2.1, 2.2, 2.3, 2.4))); symbolic_vector = ToDistributionVector(variants.gaussian2)->ToSymbolic(); ASSERT_EQ(symbolic_vector.size(), 4); CheckGaussianSymbolic(symbolic_vector(0), 2.1, 1.0); CheckGaussianSymbolic(symbolic_vector(1), 2.2, 1.0); CheckGaussianSymbolic(symbolic_vector(2), 2.3, 1.0); CheckGaussianSymbolic(symbolic_vector(3), 2.4, 1.0); EXPECT_TRUE(IsDeterministic(variants.vector)); EXPECT_TRUE(CompareMatrices( GetDeterministicValue(variants.vector), Eigen::Vector3d(1., 2., 3.))); EXPECT_TRUE(IsDeterministic(variants.deterministic)); EXPECT_TRUE(CompareMatrices( GetDeterministicValue(variants.deterministic), Eigen::Vector3d(3., 4., 5.))); EXPECT_FALSE(IsDeterministic(variants.gaussian1)); EXPECT_THROW(GetDeterministicValue(variants.gaussian1), std::logic_error); EXPECT_FALSE(IsDeterministic(variants.gaussian2)); EXPECT_THROW(GetDeterministicValue(variants.gaussian2), std::logic_error); EXPECT_FALSE(IsDeterministic(variants.uniform)); EXPECT_THROW(GetDeterministicValue(variants.uniform), std::logic_error); EXPECT_TRUE(IsDeterministic(variants.deterministic_scalar)); EXPECT_TRUE(CompareMatrices( GetDeterministicValue(variants.deterministic_scalar), Vector1d(19.5))); EXPECT_FALSE(IsDeterministic(variants.gaussian_scalar)); EXPECT_THROW(GetDeterministicValue(variants.gaussian_scalar), std::logic_error); EXPECT_FALSE(IsDeterministic(variants.uniform_scalar)); EXPECT_THROW(GetDeterministicValue(variants.uniform_scalar), std::logic_error); Eigen::VectorXd uniform = ToDistributionVector(variants.uniform)->Sample(&generator); ASSERT_EQ(uniform.size(), 2); EXPECT_LE(10, uniform(0)); EXPECT_GE(11, uniform(0)); EXPECT_LE(20, uniform(1)); EXPECT_GE(22, uniform(1)); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.uniform)->Mean(), Eigen::Vector2d(10.5, 21.0))); symbolic_vector = ToDistributionVector(variants.uniform)->ToSymbolic(); ASSERT_EQ(symbolic_vector.size(), 2); CheckUniformSymbolic(symbolic_vector(0), 10, 11); CheckUniformSymbolic(symbolic_vector(1), 20, 22); Eigen::VectorXd deterministic_scalar = ToDistributionVector(variants.deterministic_scalar)->Sample(&generator); ASSERT_EQ(deterministic_scalar.size(), 1); EXPECT_EQ(deterministic_scalar(0), 19.5); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.deterministic_scalar)->Mean(), Vector1d(19.5))); Eigen::VectorXd gaussian_scalar = ToDistributionVector(variants.gaussian_scalar)->Sample(&generator); ASSERT_EQ(gaussian_scalar.size(), 1); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.gaussian_scalar)->Mean(), Vector1d(5.0))); Eigen::VectorXd uniform_scalar = ToDistributionVector(variants.uniform_scalar)->Sample(&generator); ASSERT_EQ(uniform_scalar.size(), 1); EXPECT_LE(1, uniform_scalar(0)); EXPECT_GE(2, uniform_scalar(0)); EXPECT_TRUE(CompareMatrices( ToDistributionVector(variants.uniform_scalar)->Mean(), Vector1d(1.5))); // Confirm that writeback works for every possible type. EXPECT_EQ(SaveYamlString(variants, "root"), R"""(root: vector: [1.0, 2.0, 3.0] deterministic: !DeterministicVector value: [3.0, 4.0, 5.0] gaussian1: !GaussianVector mean: [1.1, 1.2, 1.3] stddev: [0.1, 0.2, 0.3] gaussian2: !GaussianVector mean: [2.1, 2.2, 2.3, 2.4] stddev: [1.0] uniform: !UniformVector min: [10.0, 20.0] max: [11.0, 22.0] deterministic_scalar: !Deterministic value: 19.5 gaussian_scalar: !Gaussian mean: 5.0 stddev: 1.0 uniform_scalar: !Uniform min: 1.0 max: 2.0 )"""); } // Check the special cases of IsDeterministic for zero-size ranges. GTEST_TEST(StochasticTest, ZeroSizeRandomRanges) { DistributionVectorVariantX gaussian = GaussianVector<Eigen::Dynamic>( Eigen::VectorXd::Constant(3, 4.5), Eigen::VectorXd::Constant(3, 0.0)); DistributionVectorVariantX uniform = UniformVector<Eigen::Dynamic>( Eigen::VectorXd::Constant(2, 1.5), Eigen::VectorXd::Constant(2, 1.5)); DistributionVectorVariantX gaussian_scalar = Gaussian(4.5, 0.0); DistributionVectorVariantX uniform_scalar = Uniform(1.5, 1.5); EXPECT_TRUE(IsDeterministic(gaussian)); EXPECT_TRUE(CompareMatrices( GetDeterministicValue(gaussian), Eigen::VectorXd::Constant(3, 4.5))); EXPECT_TRUE(IsDeterministic(uniform)); EXPECT_TRUE(CompareMatrices( GetDeterministicValue(uniform), Eigen::VectorXd::Constant(2, 1.5))); EXPECT_TRUE(IsDeterministic(gaussian_scalar)); EXPECT_TRUE(CompareMatrices( GetDeterministicValue(gaussian_scalar), Eigen::VectorXd::Constant(1, 4.5))); EXPECT_TRUE(IsDeterministic(uniform_scalar)); EXPECT_TRUE(CompareMatrices( GetDeterministicValue(uniform_scalar), Eigen::VectorXd::Constant(1, 1.5))); } struct FixedSize2 { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } DistributionVectorVariant<2> value; }; GTEST_TEST(StochasticTest, IncorrectVectorTest) { const char* const input = R"""( value: !Deterministic { value: 2.0 } )"""; DRAKE_EXPECT_THROWS_MESSAGE( LoadYamlString<FixedSize2>(input), ".*unsupported type tag !Deterministic while selecting a variant<> entry" " for std::variant<.*> value.*"); } } // namespace } // namespace schema } // namespace drake
0
/home/johnshepherd/drake/common/schema
/home/johnshepherd/drake/common/schema/test/rotation_test.cc
#include "drake/common/schema/rotation.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/yaml/yaml_io.h" namespace drake { namespace schema { namespace { using Eigen::Vector3d; using drake::math::RollPitchYawd; using drake::yaml::LoadYamlString; using drake::yaml::SaveYamlString; GTEST_TEST(RotationTest, ConstructorDefault) { Rotation rotation; EXPECT_TRUE(std::holds_alternative<Rotation::Identity>(rotation.value)); } GTEST_TEST(RotationTest, ConstructorRotMat) { const Vector3d rpy_rad(0.1, 0.2, 0.3); const Rotation rotation{RollPitchYawd(rpy_rad).ToRotationMatrix()}; ASSERT_TRUE(std::holds_alternative<Rotation::Rpy>(rotation.value)); const Vector3d actual_deg = schema::GetDeterministicValue( std::get<Rotation::Rpy>(rotation.value).deg); const Vector3d expected_deg = rpy_rad * 180 / M_PI; EXPECT_TRUE(drake::CompareMatrices(actual_deg, expected_deg, 1e-10)); } GTEST_TEST(RotationTest, ConstructorRpy) { const Vector3d rpy_rad(0.1, 0.2, 0.3); const Rotation rotation{RollPitchYawd(rpy_rad)}; ASSERT_TRUE(std::holds_alternative<Rotation::Rpy>(rotation.value)); const Vector3d actual_deg = schema::GetDeterministicValue( std::get<Rotation::Rpy>(rotation.value).deg); const Vector3d expected_deg = rpy_rad * 180 / M_PI; EXPECT_TRUE(drake::CompareMatrices(actual_deg, expected_deg, 1e-10)); } GTEST_TEST(RotationTest, Rpy) { constexpr const char* const yaml_data = R"""( value: !Rpy { deg: [10., 20., 30.] } )"""; const auto rotation = LoadYamlString<Rotation>(yaml_data); ASSERT_TRUE(rotation.IsDeterministic()); const RollPitchYawd rpy(rotation.GetDeterministicValue()); const Vector3d actual = rpy.vector() * 180 / M_PI; const Vector3d expected(10.0, 20.0, 30.0); EXPECT_TRUE(drake::CompareMatrices(actual, expected, 1e-10)); } GTEST_TEST(RotationTest, AngleAxis) { constexpr const char* const yaml_data = R"""( value: !AngleAxis { angle_deg: 10.0, axis: [0, 1, 0] } )"""; const auto rotation = LoadYamlString<Rotation>(yaml_data); ASSERT_TRUE(rotation.IsDeterministic()); const Eigen::AngleAxis<double> actual = rotation.GetDeterministicValue().ToAngleAxis(); EXPECT_EQ(actual.angle() * 180 / M_PI, 10.0); const Vector3d expected_axis(0.0, 1.0, 0.0); EXPECT_TRUE(drake::CompareMatrices(actual.axis(), expected_axis, 1e-10)); } GTEST_TEST(RotationTest, Uniform) { constexpr const char* const yaml_data = R"""( value: !Uniform {} )"""; const auto rotation = LoadYamlString<Rotation>(yaml_data); EXPECT_FALSE(rotation.IsDeterministic()); EXPECT_NO_THROW(rotation.ToSymbolic()); } GTEST_TEST(RotationTest, RpyUniform) { constexpr const char* const yaml_data = R"""( value: !Rpy { deg: !UniformVector { min: [0, 10, 20], max: [30, 40, 50] } } )"""; const auto rotation = LoadYamlString<Rotation>(yaml_data); EXPECT_FALSE(rotation.IsDeterministic()); // We trust stochastic_test.cc to check that stochastic.h parsed the ranges // correctly, and so do not verify them further here. } // Ensure that we can write out YAML for Identity. GTEST_TEST(RotationTest, IdentityToYaml) { Rotation rotation; EXPECT_EQ(SaveYamlString(rotation, "root"), "root:\n value: {}\n"); } // Ensure that we can write out YAML for Rpy. GTEST_TEST(RotationTest, RpyToYaml) { Rotation rotation; rotation.set_rpy_deg(Vector3d(1.0, 2.0, 3.0)); EXPECT_EQ(SaveYamlString(rotation, "root"), "root:\n value: !Rpy\n deg: [1.0, 2.0, 3.0]\n"); } } // namespace } // namespace schema } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_io.h
#pragma once #include <optional> #include <string> #include <string_view> #include <utility> #include "drake/common/yaml/yaml_io_options.h" #include "drake/common/yaml/yaml_read_archive.h" #include "drake/common/yaml/yaml_write_archive.h" namespace drake { namespace yaml { /** Loads data from a YAML-formatted file. Refer to @ref yaml_serialization "YAML Serialization" for background and examples. @param filename Filename to be read from. @param child_name (optional) If provided, loads data from given-named child of the document's root instead of the root itself. @param defaults (optional) If provided, then the structure being read into will be initialized using this value instead of the default constructor, and also (unless the `options` argument is provided and specifies otherwise) any member fields that are not mentioned in the YAML will retain their default values. @param options (optional, advanced) If provided, overrides the nominal parsing options. Most users should not specify this; the default is usually correct. @returns the loaded user data. @tparam Serializable must implement a @ref implementing_serialize "Serialize" function and be default constructible. */ template <typename Serializable> static Serializable LoadYamlFile( const std::string& filename, const std::optional<std::string>& child_name = std::nullopt, const std::optional<Serializable>& defaults = std::nullopt, const std::optional<LoadYamlOptions>& options = std::nullopt); /** Loads data from a YAML-formatted string. Refer to @ref yaml_serialization "YAML Serialization" for background and examples. @param data the YAML document as a string. @param child_name (optional) If provided, loads data from given-named child of the document's root instead of the root itself. @param defaults (optional) If provided, then the structure being read into will be initialized using this value instead of the default constructor, and also (unless the `options` argument is provided and specifies otherwise) any member fields that are not mentioned in the YAML will retain their default values. @param options (optional, advanced) If provided, overrides the nominal parsing options. Most users should not specify this; the default is usually correct. @returns the loaded user data. @tparam Serializable must implement a @ref implementing_serialize "Serialize" function and be default constructible. */ template <typename Serializable> static Serializable LoadYamlString( const std::string& data, const std::optional<std::string>& child_name = std::nullopt, const std::optional<Serializable>& defaults = std::nullopt, const std::optional<LoadYamlOptions>& options = std::nullopt); /** Saves data as a YAML-formatted file. Refer to @ref yaml_serialization "YAML Serialization" for background. The YAML will consist of a single document with a mapping node at the root. If a `child_name` is **not** provided (the default), then the serialized data will appear directly within that top-level mapping node. If a `child_name` **is** provided, then the top-level mapping node will contain only one entry, whose key is `child_name` and value is the serialized `data`. @param filename Filename to be written to. @param data User data to be serialized. @param child_name (optional) If provided, the YAML document will be `{child_name: { data }}` rather than just `{ data }`. @param defaults (optional) If provided, then only data that differs from the given defaults will be serialized. @tparam Serializable must implement a @ref implementing_serialize "Serialize" function. */ template <typename Serializable> void SaveYamlFile(const std::string& filename, const Serializable& data, const std::optional<std::string>& child_name = std::nullopt, const std::optional<Serializable>& defaults = std::nullopt); /** Saves data as a YAML-formatted string. Refer to @ref yaml_serialization "YAML Serialization" for background. The YAML will consist of a single document with a mapping node at the root. If a `child_name` is **not** provided (the default), then the serialized data will appear directly within that top-level mapping node. If a `child_name` **is** provided, then the top-level mapping node will contain only one entry, whose key is `child_name` and value is the serialized `data`. @param data User data to be serialized. @param child_name (optional) If provided, the YAML document will be `{child_name: { data }}` rather than just `{ data }`. @param defaults (optional) If provided, then only data that differs from the given defaults will be serialized. @returns the YAML document as a string. @tparam Serializable must implement a @ref implementing_serialize "Serialize" function. */ template <typename Serializable> std::string SaveYamlString( const Serializable& data, const std::optional<std::string>& child_name = std::nullopt, const std::optional<Serializable>& defaults = std::nullopt); /** Saves data as a JSON-formatted file. Refer to @ref yaml_serialization "YAML Serialization" for background. Note that there is no matching `LoadJsonFile` function, because we haven't found any specific need for it yet in C++. @param data User data to be serialized. @returns the JSON data as a string. @tparam Serializable must implement a @ref implementing_serialize "Serialize" function. */ template <typename Serializable> void SaveJsonFile(const std::string& filename, const Serializable& data); /** Saves data as a JSON-formatted string. Refer to @ref yaml_serialization "YAML Serialization" for background. Note that there is no matching `LoadJsonString` function, because we haven't found any specific need for it yet in C++. @param data User data to be serialized. @returns the JSON data as a string. @tparam Serializable must implement a @ref implementing_serialize "Serialize" function. */ template <typename Serializable> std::string SaveJsonString(const Serializable& data); namespace internal { void WriteFile(std::string_view function_name, const std::string& filename, const std::string& data); template <typename Serializable> static Serializable LoadNode(internal::Node node, const std::optional<Serializable>& defaults, const std::optional<LoadYamlOptions>& options) { // Reify our optional arguments. Serializable result = defaults.value_or(Serializable{}); LoadYamlOptions new_options = options.value_or(LoadYamlOptions{}); if (defaults.has_value() && !options.has_value()) { // Do not overwrite existing values. new_options.allow_cpp_with_no_yaml = true; new_options.retain_map_defaults = true; } // Parse and return. internal::YamlReadArchive(std::move(node), new_options).Accept(&result); return result; } } // namespace internal // (Implementation of a function declared above. This cannot be defined // inline because we need internal::LoadNode to be declared.) template <typename Serializable> static Serializable LoadYamlFile( const std::string& filename, const std::optional<std::string>& child_name, const std::optional<Serializable>& defaults, const std::optional<LoadYamlOptions>& options) { internal::Node node = internal::YamlReadArchive::LoadFileAsNode(filename, child_name); return internal::LoadNode(std::move(node), defaults, options); } // (Implementation of a function declared above. This cannot be defined // inline because we need internal::LoadNode to be declared.) template <typename Serializable> static Serializable LoadYamlString( const std::string& data, const std::optional<std::string>& child_name, const std::optional<Serializable>& defaults, const std::optional<LoadYamlOptions>& options) { internal::Node node = internal::YamlReadArchive::LoadStringAsNode(data, child_name); return internal::LoadNode(std::move(node), defaults, options); } // (Implementation of a function declared above. This cannot be defined // inline because we need SaveYamlString to be declared.) template <typename Serializable> void SaveYamlFile(const std::string& filename, const Serializable& data, const std::optional<std::string>& child_name, const std::optional<Serializable>& defaults) { internal::WriteFile("SaveYamlFile", filename, SaveYamlString(data, child_name, defaults)); } // (Implementation of a function declared above. This could be defined // inline, but we keep it with the others for consistency.) template <typename Serializable> std::string SaveYamlString(const Serializable& data, const std::optional<std::string>& child_name, const std::optional<Serializable>& defaults) { internal::YamlWriteArchive archive; archive.Accept(data); if (defaults.has_value()) { internal::YamlWriteArchive defaults_archive; defaults_archive.Accept(defaults.value()); archive.EraseMatchingMaps(defaults_archive); } return archive.EmitString(child_name.value_or(std::string())); } // (Implementation of a function declared above. This could be defined // inline, but we keep it with the others for consistency.) template <typename Serializable> void SaveJsonFile(const std::string& filename, const Serializable& data) { internal::WriteFile("SaveJsonFile", filename, SaveJsonString(data)); } // (Implementation of a function declared above. This could be defined // inline, but we keep it with the others for consistency.) template <typename Serializable> std::string SaveJsonString(const Serializable& data) { internal::YamlWriteArchive archive; archive.Accept(data); return archive.ToJson(); } } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/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 = "yaml", visibility = ["//visibility:public"], deps = [ ":yaml_io", ":yaml_io_options", ":yaml_node", ":yaml_read_archive", ":yaml_write_archive", ], ) drake_cc_library( name = "yaml_io_options", srcs = ["yaml_io_options.cc"], hdrs = ["yaml_io_options.h"], deps = [ "//common:essential", ], ) drake_cc_library( name = "yaml_node", srcs = ["yaml_node.cc"], hdrs = ["yaml_node.h"], deps = [ "//common:essential", "//common:overloaded", "//common:string_container", ], ) drake_cc_library( name = "yaml_read_archive", srcs = ["yaml_read_archive.cc"], hdrs = ["yaml_read_archive.h"], deps = [ ":yaml_io_options", ":yaml_node", "//common:essential", "//common:name_value", "//common:nice_type_name", "//common:unused", "@yaml_cpp_internal//:yaml_cpp", ], ) drake_cc_library( name = "yaml_write_archive", srcs = ["yaml_write_archive.cc"], hdrs = ["yaml_write_archive.h"], deps = [ ":yaml_node", "//common:essential", "//common:name_value", "//common:nice_type_name", "//common:overloaded", "//common:unused", "@yaml_cpp_internal//:yaml_cpp", ], ) drake_cc_library( name = "yaml_io", srcs = ["yaml_io.cc"], hdrs = ["yaml_io.h"], deps = [ ":yaml_io_options", ":yaml_read_archive", ":yaml_write_archive", ], ) # === test/ === drake_cc_library( name = "example_structs", testonly = True, hdrs = ["test/example_structs.h"], visibility = ["//visibility:private"], deps = [ "//common:name_value", ], ) drake_cc_googletest( name = "json_test", deps = [ ":example_structs", ":yaml_io", "//common:temp_directory", "//common/test_utilities:expect_throws_message", ], ) drake_cc_googletest( name = "yaml_doxygen_test", deps = [ ":yaml_io", "//common:find_resource", "//common:temp_directory", ], ) drake_cc_googletest( name = "yaml_io_test", data = [ "test/yaml_io_test_input_1.yaml", "test/yaml_io_test_input_2.yaml", ], deps = [ ":example_structs", ":yaml_io", "//common:find_resource", "//common:temp_directory", "//common/test_utilities:expect_throws_message", ], ) drake_cc_googletest( name = "yaml_node_test", deps = [ ":yaml_node", "//common/test_utilities:expect_throws_message", "//common/test_utilities:limit_malloc", ], ) drake_cc_googletest( name = "yaml_performance_test", deps = [ ":yaml_io", ":yaml_read_archive", "//common:autodiff", "//common:name_value", "//common/test_utilities:limit_malloc", ], ) drake_cc_googletest( name = "yaml_read_archive_test", deps = [ ":example_structs", ":yaml_read_archive", "//common:name_value", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", ], ) drake_cc_googletest( name = "yaml_write_archive_test", deps = [ ":example_structs", ":yaml_write_archive", "//common:name_value", "//common/test_utilities:expect_throws_message", ], ) drake_cc_googletest( name = "yaml_write_archive_defaults_test", deps = [ ":example_structs", ":yaml_write_archive", ], ) add_lint_tests()
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_node.h
#pragma once #include <map> #include <optional> #include <ostream> #include <string> #include <string_view> #include <utility> #include <variant> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/common/string_map.h" // Note that even though this file contains "class Node", the file is named // "yaml_node.h" not "node.h" to avoid conflict with "yaml-cpp/node/node.h". namespace drake { namespace yaml { namespace internal { /* The three possible kinds of YAML nodes. See https://yaml.org/spec/1.2.2/#nodes for the definition of a node. Note that even though our links to the YAML specification point to YAML version 1.2.2, we don't actually care about the version number in particular; this class is not tied to a specific version. <!-- As an implementation note for all of the below: the Node API for accessors, modifiers, etc., is very spare compared to what we might imagine. At, the moment, because this is an internal class, the functions only provide the minimal API that we need. We can add more functions if and when we need them. --> */ enum class NodeType { // See https://yaml.org/spec/1.2.2/#scalar for the definition. // See https://yaml.org/spec/1.2.2/#scalars for examples. // // Note that even though Drake most often uses "scalar" to refer to a // mathematical scalar type such as `double`, here we use "scalar" in the // sense of YAML. kScalar, // See https://yaml.org/spec/1.2.2/#sequence for the definition. // See https://yaml.org/spec/1.2.2/#collections for Example 2.1. kSequence, // See https://yaml.org/spec/1.2.2/#mapping for the definition. // See https://yaml.org/spec/1.2.2/#collections for Example 2.2. // // Note that even though YAML in general allows the keys of a mapping to be // any type of node, in our implementation we limit keys to be only strings, // for better compatibility with other serialization formats such as JSON. kMapping, }; /* Denotes one of the "JSON Schema" tags. Note that this schema incorporates the "failsafe schema" by reference. See https://yaml.org/spec/1.2.2/#json-schema. */ enum class JsonSchemaTag { // https://yaml.org/spec/1.2.2/#null kNull, // https://yaml.org/spec/1.2.2/#boolean kBool, // https://yaml.org/spec/1.2.2/#integer kInt, // https://yaml.org/spec/1.2.2/#floating-point kFloat, // https://yaml.org/spec/1.2.2/#generic-string kStr, }; /* Data type that represents a YAML node. A Node can hold one of three possible kinds of value at runtime: - Scalar - Sequence[Node] - Mapping[string, Node] Refer to https://yaml.org/spec/1.2.2/#nodes for details. This class implements the https://yaml.org/spec/1.2.2/#321-representation-graph concept, with two caveats for better compatibility with JSON serialization: - graph cycles are not allowed; - mapping keys must only be scalar strings. Each node may also have a tag. By default (i.e., at construction time), the tag will be empty. Use GetTag() and SetTag() to query and adjust it. Refer to https://yaml.org/spec/1.2.2/#tags for details. */ class Node final { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Node) /* Returns a Scalar node with the given value. Note that even though Drake most often uses "scalar" to refer to a mathematical scalar type such as `double`, here we use "scalar" in the sense of YAML. */ static Node MakeScalar(std::string value = {}); /* Returns an empty Sequence node. */ static Node MakeSequence(); /* Returns an empty Mapping node. */ static Node MakeMapping(); /* Returns a null Scalar node. The returned node's tag is kTagNull and value is "null". Refer to https://yaml.org/spec/1.2.2/#null for details. */ static Node MakeNull(); /* Returns type of stored value. */ NodeType GetType() const; /* Returns a description of the type of stored value, suitable for use in error messages, e.g., "Mapping". */ std::string_view GetTypeString() const; /* Returns a description of the given type, suitable for use in error messages, e.g., "Mapping". */ static std::string_view GetTypeString(NodeType); /* Returns true iff this Node's type is Scalar. */ bool IsScalar() const; /* Returns true iff this Node's type is Sequence. */ bool IsSequence() const; /* Returns true iff this Node's type is Mapping. */ bool IsMapping() const; /* Compares two nodes for equality. */ friend bool operator==(const Node&, const Node&); /* Gets this node's YAML tag. See https://yaml.org/spec/1.2.2/#tags. By default (i.e., at construction time), the tag will be empty. */ std::string_view GetTag() const; /* Returns whether or not `important = true` was used during SetTag(). */ bool IsTagImportant() const; /* Sets this node's YAML tag to one of the "JSON Schema" tags. Optionally allows marking the tag as "important", which means that when emitting the YAML document it will always appear in the output, even if it would have been implied by default. See https://yaml.org/spec/1.2.2/#json-schema. */ void SetTag(JsonSchemaTag, bool important = false); /* Sets this node's YAML tag. See https://yaml.org/spec/1.2.2/#tags. The tag is not checked for well-formedness nor consistency with the node's type nor value. The caller is responsible for providing a valid tag. */ void SetTag(std::string); // https://yaml.org/spec/1.2.2/#null static constexpr std::string_view kTagNull{"tag:yaml.org,2002:null"}; // https://yaml.org/spec/1.2.2/#boolean static constexpr std::string_view kTagBool{"tag:yaml.org,2002:bool"}; // https://yaml.org/spec/1.2.2/#integer static constexpr std::string_view kTagInt{"tag:yaml.org,2002:int"}; // https://yaml.org/spec/1.2.2/#floating-point static constexpr std::string_view kTagFloat{"tag:yaml.org,2002:float"}; // https://yaml.org/spec/1.2.2/#generic-string static constexpr std::string_view kTagStr{"tag:yaml.org,2002:str"}; /* Sets the filename where this Node was read from. A nullopt indicates that the filename is not known. */ void SetFilename(std::optional<std::string> filename); /* Gets the filename where this Node was read from. A nullopt indicates that the filename is not known. */ const std::optional<std::string>& GetFilename() const; /* An indication of where in a file or string this Node was read from. The indexing is 1-based (the first character is line 1 column 1). */ struct Mark { int line{}; int column{}; friend bool operator==(const Mark&, const Mark&); }; /* Sets the line:column offset in the file or string where this Node was read from. A nullopt indicates that the Node's position is unknown. */ void SetMark(std::optional<Mark> mark); /* Gets the line:column offset in the file or string where this Node was read from. A nullopt indicates that the Node's position is unknown. */ const std::optional<Mark>& GetMark() const; // @name Scalar-only Functions // These functions may only be called when IsScalar() is true; // otherwise, they will throw an exception. // // Note that there is no SetScalar function provided; users should call // the Node::operator= function, instead. //@{ /* Gets this node's Scalar data. */ const std::string& GetScalar() const; //@} // @name Sequence-only Functions // These functions may only be called when IsSequence() is true; // otherwise, they will throw an exception. // // Note that there is no SetSequence function provided to bulk-overwrite the // sequence; users should call the Node::operator= function, instead. //@{ /* Gets this node's Sequence data. */ const std::vector<Node>& GetSequence() const; /* Appends a new node to the back of this Sequence. Any iterators based on GetSequence() are invalidated. */ void Add(Node); //@} // @name Mapping-only Functions // These functions may only be called when IsMapping() is true; // otherwise, they will throw an exception. // // Note that there is no SetMapping function provided to bulk-overwrite the // mapping; users should call the Node::operator= function, instead. //@{ /* Gets this node's Mapping data. */ const string_map<Node>& GetMapping() const; /* Add a new node to this Mapping. Any iterators based on GetMapping() remain valid. @throws std::exception the given key was already in this mapping. */ void Add(std::string key, Node value); /* Gets an existing node from this Mapping. Any iterators based on GetMapping() remain valid. @throws std::exception the given key does not exist. */ Node& At(std::string_view key); /* Removes an existing node from this Mapping. Any iterators based on GetMapping() that referred to this key are invalidated. @throws std::exception the given key does not exist. */ void Remove(std::string_view key); //@} /* Calls back into the given Visitor using operator(), with an argument type (see below) based on this Node's type. */ template <class Visitor> void Visit(Visitor&& visitor) const { return std::visit(std::forward<Visitor>(visitor), data_); } /* The argument type for Visit on a Scalar node .*/ struct ScalarData final { std::string scalar; friend bool operator==(const ScalarData&, const ScalarData&); }; /* The argument type for Visit on a Sequence node .*/ struct SequenceData final { std::vector<Node> sequence; friend bool operator==(const SequenceData&, const SequenceData&); }; /* The argument type for Visit on a Mapping node .*/ struct MappingData final { // Even though YAML mappings are notionally unordered, we use an ordered // map here to ensure program determinism. string_map<Node> mapping; friend bool operator==(const MappingData&, const MappingData&); }; /* Displays the given node using flow style. Intended only for debugging, not serialization. */ friend std::ostream& operator<<(std::ostream&, const Node&); private: /* No-op for use only by the public "Make..." functions. */ Node(); using Variant = std::variant<ScalarData, SequenceData, MappingData>; Variant data_; // When our tag is one of the well-known JSON schema enum values, we also need // to store whether the tag is "important". Refer to SetTag() for details. struct JsonSchemaTagInfo { JsonSchemaTag value{JsonSchemaTag::kNull}; bool important{false}; }; // A YAML tag is not required (our default value is the empty string), but can // be set to either a well-known enum or a bespoke string. The representation // here isn't canonical: it's possible to set a string value that's equivalent // to an enum's implied string. std::variant<std::string, JsonSchemaTagInfo> tag_; std::optional<Mark> mark_; std::optional<std::string> filename_; }; } // namespace internal } // namespace yaml } // namespace drake #ifndef DRAKE_DOXYGEN_CXX // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::yaml::internal::Node> : drake::ostream_formatter {}; } // namespace fmt #endif
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_io_options.cc
#include "drake/common/yaml/yaml_io_options.h" namespace drake { namespace yaml { std::ostream& operator<<(std::ostream& os, const LoadYamlOptions& x) { return os << "{.allow_yaml_with_no_cpp = " << x.allow_yaml_with_no_cpp << ", .allow_cpp_with_no_yaml = " << x.allow_cpp_with_no_yaml << ", .retain_map_defaults = " << x.retain_map_defaults << "}"; } } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_io.cc
#include "drake/common/yaml/yaml_io.h" #include <fstream> namespace drake { namespace yaml { namespace internal { void WriteFile(std::string_view function_name, const std::string& filename, const std::string& data) { std::ofstream out(filename, std::ios::binary); if (out.fail()) { throw std::runtime_error(fmt::format("{}() could not open '{}' for writing", function_name, filename)); } out << data; if (out.fail()) { throw std::runtime_error( fmt::format("{}() could not write to '{}'", function_name, filename)); } } } // namespace internal } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_doxygen.h
/** @defgroup yaml_serialization YAML Serialization @ingroup technical_notes <h2>Overview</h2> Drake provides infrastructure for reading YAML files into C++ structs, and writing C++ structs into YAML files. These functions are often used to read or write configuration data, but may also be used to serialize runtime data such as Diagram connections or OutputPort traces. Any C++ struct to be serialized must provide a @ref implementing_serialize "Serialize()" function to enumerate its fields. <h2>Examples</h2> Given a struct definition: @code{cpp} struct MyData { ... double foo{0.0}; std::vector<double> bar; }; @endcode <h3>Loading</h3> Given a YAML data file: @code{yaml} foo: 1.0 bar: [2.0, 3.0] @endcode We can use LoadYamlFile() to load the file: @code{cpp} int main() { const MyData data = LoadYamlFile<MyData>("filename.yaml"); std::cout << fmt::format("foo = {:.1f}\n", data.foo); std::cout << fmt::format("bar = {:.1f}\n", fmt::join(data.bar, ", ")); } @endcode Output: @code{txt} foo = 1.0 bar = 2.0, 3.0 @endcode <h3>Saving</h3> We can use SaveYamlFile() to save to a file: @code{cpp} int main() { MyData data{4.0, {5.0, 6.0}}; SaveYamlFile("filename.yaml", data); } @endcode Output file: @code{yaml} foo: 4.0 bar: [5.0, 6.0] @endcode The following sections explain each of these steps in more detail, along with the customization options that are available for each one. @anchor implementing_serialize <h2>Implementing Serialize</h2> Any C++ struct to be serialized must provide a templated `Serialize()` function that enumerates the fields. Typically, `Serialize()` will be implemented via a member function on the struct, but if necessary it can also be a free function obtained via argument-dependent lookup. Here is an example of implementing a Serialize member function: @code{cpp} struct MyData { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(foo)); a->Visit(DRAKE_NVP(bar)); } double foo{0.0}; std::vector<double> bar; }; @endcode Structures can be arbitrarily nested, as long as each `struct` has a `Serialize()` function: @code{cpp} struct MoreData { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(baz)); a->Visit(DRAKE_NVP(quux)); } std::string baz; std::map<std::string, MyData> quux; }; @endcode For background information about visitor-based serialization, see also the <a href="https://www.boost.org/doc/libs/release/libs/serialization/doc/tutorial.html"> Boost.Serialization Tutorial</a>, which served as the inspiration for Drake's design. <h3>Style guide for Serialize</h3> By convention, we place the Serialize function prior to the data members per <a href="https://drake.mit.edu/styleguide/cppguide.html#Declaration_Order">the styleguide rule</a>. Each data member has a matching `Visit` line in the Serialize function, in the same order as the member fields appear. By convention, we declare all of the member fields as public, since they are effectively so anyway (because anything that calls the Serialize function receives a mutable pointer to them). The typical way to do this is to declare the data as a `struct`, instead of a `class`. However, if <a href="https://drake.mit.edu/styleguide/cppguide.html#Structs_vs._Classes">the styleguide rule</a> for struct vs class points towards using a `class` instead, then we follow that advice and make it a `class`, but we explicitly label the member fields as `public`. We also omit the trailing underscore from the field names, so that the Serialize API presented to the caller of the class is indifferent to whether it is phrased as a `struct` or a `class`. See drake::schema::Gaussian for an example of this situation. If the member fields have invariants that must be immediately enforced during de-serialization, then we add invariant checks to the end of the `Serialize()` function to enforce that, and we mark the class fields private (adding back the usual trailing underscore). See drake::math::BsplineBasis for an example of this situation. <h3>Built-in types</h3> Drake's YAML I/O functions provide built-in support for many common types: - bool - double - float - int32_t - int64_t - uint32_t - uint64_t - std::array - std::map - std::optional - std::string - std::unordered_map - std::variant - std::vector - Eigen::Matrix (including 1-dimensional matrices, i.e., vectors) <h3>YAML correspondence</h3> The simple types (`std::string`, `bool`, floating-point number, integers) all serialize to a <a href="https://yaml.org/spec/1.2.2/#scalars">Scalar</a> node in YAML. The array-like types (`std::array`, `std::vector`, `Eigen::Matrix`) all serialize to a <a href="https://yaml.org/spec/1.2.2/#collections">Sequence</a> node in YAML. User-defined structs and the native maps (`std::map`, `std::unordered_map`) all serialize to a <a href="https://yaml.org/spec/1.2.2/#collections">Mapping</a> node in YAML. For the treatment of `std::optional`, refer to @ref serialize_nullable "Nullable types", below. For the treatment of `std::variant`, refer to @ref serialize_variant "Sum types", below. <h2>Reading YAML files</h2> Use LoadYamlFile() or LoadYamlString() to de-serialize YAML-formatted string data into C++ structure. It's often useful to write a helper function to load using a specific schema, in this case the `MyData` schema: @code{cpp} MyData LoadMyData(const std::string& filename) { return LoadYamlFile<MyData>(filename); } int main() { const MyData data = LoadMyData("filename.yaml"); std::cout << fmt::format("foo = {:.1f}\n", data.foo); std::cout << fmt::format("bar = {:.1f}\n", fmt::join(data.bar, ", ")); } @endcode Sample data in `filename.yaml`: @code{yaml} foo: 1.0 bar: [2.0, 3.0] @endcode Sample output: @code{txt} foo = 1.0 bar = 2.0, 3.0 @endcode There is also an option to load from a top-level child in the document: @code{yaml} data_1: foo: 1.0 bar: [2.0, 3.0] data_2: foo: 4.0 bar: [5.0, 6.0] @endcode @code{cpp} MyData LoadMyData2(const std::string& filename) { return LoadYamlFile<MyData>(filename, "data_2"); } @endcode Sample output: @code{txt} foo = 4.0 bar = 5.0, 6.0 @endcode <h3>Defaults</h3> The LoadYamlFile() function offers a `defaults = ...` argument. When provided, the yaml file's contents will overwrite the provided defaults, but any fields that are not mentioned in the yaml file will remain intact at their default values. When merging file data atop any defaults, any `std::map` or `std::unordered_map` collections will merge the contents of the file alongside the existing map values, keeping anything in the default that is unchanged. Any other collections such as `std::vector` are entirely reset, even if they already had some values in place (in particular, they are not merely appended to). <h3>Merge keys</h3> YAML's "merge keys" (https://yaml.org/type/merge.html) are supported during loading. (However, the graph-aliasing relationship implied by nominal YAML semantics is not implemented; the merge keys are fully deep-copied.) Example: @code{yaml} _template: &common_foo foo: 1.0 data_1: << : *common_foo bar: [2.0, 3.0] data_2: << : *common_foo bar: [5.0, 6.0] @endcode <h2>Writing YAML files</h2> Use SaveYamlFile() or SaveYamlString() to output a YAML-formatted serialization of a C++ structure. The serialized output is always deterministic, even for unordered datatypes such as `std::unordered_map`. @code{cpp} struct MyData { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(foo)); a->Visit(DRAKE_NVP(bar)); } double foo{0.0}; std::vector<double> bar; }; int main() { MyData data{1.0, {2.0, 3.0}}; std::cout << SaveYamlString(data, "root"); return 0; } @endcode Output: @code{yaml} root: foo: 1.0 bar: [2.0, 3.0] @endcode <h2>Document root</h2> Usually, YAML reading or writing requires a serializable struct that matches the top-level YAML document. However, sometimes it's convenient to parse the document in the special case of a C++ `std::map` at the top level, without the need to define an enclosing struct. @code{yaml} data_1: foo: 1.0 bar: [2.0, 3.0] data_2: foo: 4.0 bar: [5.0, 6.0] @endcode @code{cpp} std::map<std::string, MyData> LoadAllMyData(const std::string& filename) { return LoadYamlFile<std::map<std::string, MyData>>(filename); } @endcode @anchor serialize_nullable <h2>Nullable types (std::optional)</h2> When a C++ field of type `std::optional` is present, then: - when saving its enclosing struct as YAML data, if the optional is nullopt, then no mapping entry will be emitted. - when load its enclosing struct from YAML data, if no mapping entry is present in the YAML, then it is not an error. @anchor serialize_variant <h2>Sum types (std::variant)</h2> When reading into a std::variant<>, we match its <a href="https://yaml.org/spec/1.2.2/#tags">YAML tag</a> to the shortened C++ class name of the variant selection. For example, to read into this sample struct: @code{cpp} struct Foo { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(data)); } std::string data; }; struct Bar { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } std::variant<std::string, double, Foo> value; }; @endcode Some valid YAML examples are: @code{yaml} # For the first type declared in the variant<>, the tag is optional. bar: value: hello # YAML has built-in tags for string, float, int. bar2: value: !!str hello # For any other type within the variant<>, the tag is required. bar3: value: !!float 1.0 # User-defined types use a single exclamation point. bar4: value: !Foo data: hello @endcode */
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_read_archive.cc
#include "drake/common/yaml/yaml_read_archive.h" #include <algorithm> #include <cstring> #include <fmt/format.h> #include <fmt/ostream.h> #include <yaml-cpp/yaml.h> #include "drake/common/nice_type_name.h" namespace drake { namespace yaml { namespace internal { namespace { // The source and destination are both of type Map. Copy the key-value pairs // from source into destination, but don't overwrite any existing keys. void CopyWithMergeKeySemantics(const YAML::Node& source, YAML::Node* destination) { for (const auto& key_value : source) { const YAML::Node& key = key_value.first; const YAML::Node& value = key_value.second; YAML::Node entry = (*destination)[key.Scalar()]; if (!entry) { // N.B. This assignment indirectly mutates the `destination`! With the // yaml-cpp API, a YAML::Node returned from a mapping lookup (operator[]) // is a back-pointer into the mapping -- something akin to an iterator. entry = value; } } } // If the given `node` (of type Map) has a YAML merge key defined, then mutates // the `node` in place to replace the merge key entry with the merged values. // // See https://yaml.org/type/merge.html for details on syntax and semantics. // // If the YAML merge key syntax is violated, then this function throws an // exception. In the future, it might be nice to use the ReportError helper // instead of throwing, but that is currently too awkward. // // The `parent` is only used to provide context during error reporting. // // If yaml-cpp adds native support for merge keys during its own parsing, then // we should be able to remove this helper. void RewriteMergeKeys(const YAML::Node& parent, YAML::Node* node) { DRAKE_DEMAND(node != nullptr); DRAKE_DEMAND(node->Type() == YAML::NodeType::Map); const YAML::Node& merge_key = (*node)["<<"]; if (!merge_key) { return; } (*node).remove("<<"); const char* error_message = nullptr; YAML::Node error_locus; switch (merge_key.Type()) { case YAML::NodeType::Map: { // Merge `merge_key` Map into `node` Map. CopyWithMergeKeySemantics(merge_key, node); return; } case YAML::NodeType::Sequence: { // Merge each Map in `merge_key` Sequence-of-Maps into the `node` Map. for (const YAML::Node& merge_key_item : merge_key) { if (merge_key_item.Type() != YAML::NodeType::Map) { error_message = "has invalid merge key type (Sequence-of-non-Mapping)."; error_locus = *node; break; } CopyWithMergeKeySemantics(merge_key_item, node); } if (error_message != nullptr) { break; } return; } case YAML::NodeType::Scalar: { error_message = "has invalid merge key type (Scalar)."; error_locus = parent; break; } case YAML::NodeType::Null: { error_message = "has invalid merge key type (Null)."; error_locus = parent; break; } case YAML::NodeType::Undefined: { // We should never reach here due to the "if (!merge_key)" guard above. DRAKE_UNREACHABLE(); } } DRAKE_DEMAND(error_message != nullptr); DRAKE_DEMAND(error_locus.IsDefined()); // Sort the keys so that our error message is deterministic. std::vector<std::string> keys; for (const auto& map_pair : error_locus) { keys.push_back(map_pair.first.as<std::string>()); } std::sort(keys.begin(), keys.end()); throw std::runtime_error( fmt::format("YAML node of type Mapping (with size {} and keys {{{}}}) {}", keys.size(), fmt::join(keys, ", "), error_message)); } // Convert a jbeder/yaml-cpp YAML::Node `node` to a Drake yaml::internal::Node. // See https://github.com/jbeder/yaml-cpp/wiki/Tutorial for a jbeder reference. // The `parent` is only used to provide context during error reporting. internal::Node ConvertJbederYamlNodeToDrakeYamlNode(const YAML::Node& parent, const YAML::Node& node) { std::optional<Node::Mark> mark; if (node.Mark().line >= 0 && node.Mark().column >= 0) { // The jbeder convention is 0-based numbering; we want 1-based. mark = Node::Mark{.line = node.Mark().line + 1, .column = node.Mark().column + 1}; } switch (node.Type()) { case YAML::NodeType::Undefined: { throw std::runtime_error("A yaml-cpp node was unexpectedly Undefined"); } case YAML::NodeType::Null: { return internal::Node::MakeNull(); } case YAML::NodeType::Scalar: { auto result = internal::Node::MakeScalar(node.Scalar()); result.SetTag(node.Tag()); result.SetMark(mark); return result; } case YAML::NodeType::Sequence: { auto result = internal::Node::MakeSequence(); result.SetTag(node.Tag()); result.SetMark(mark); for (size_t i = 0; i < node.size(); ++i) { result.Add(ConvertJbederYamlNodeToDrakeYamlNode(node, node[i])); } return result; } case YAML::NodeType::Map: { YAML::Node merged_node(node); RewriteMergeKeys(parent, &merged_node); auto result = internal::Node::MakeMapping(); result.SetTag(merged_node.Tag()); result.SetMark(mark); for (const auto& key_value : merged_node) { const YAML::Node& key = key_value.first; const YAML::Node& value = key_value.second; result.Add(key.Scalar(), ConvertJbederYamlNodeToDrakeYamlNode(node, value)); } return result; } } DRAKE_UNREACHABLE(); } } // namespace YamlReadArchive::YamlReadArchive(internal::Node root, const LoadYamlOptions& options) : owned_root_(std::move(root)), root_(&owned_root_.value()), mapish_item_key_(nullptr), mapish_item_value_(nullptr), options_(options), parent_(nullptr) { if (!root_->IsMapping()) { throw std::runtime_error(fmt::format( "{}: invalid document: the top level element should be a Mapping " "(not a {})", root_->GetFilename().value_or("<string>"), root_->GetTypeString())); } } // N.B. This is unit tested via yaml_io_test with calls to LoadYamlFile (and // not as part of yaml_read_archive_test as would be typical). In the future, // it might be better to refactor document parsing and merge key handling into // a separate file with more specific testing, but for the moment our use of // yaml-cpp in our public API makes that difficult. internal::Node YamlReadArchive::LoadFileAsNode( const std::string& filename, const std::optional<std::string>& child_name) { internal::Node result = internal::Node::MakeNull(); YAML::Node root = YAML::LoadFile(filename); if (child_name.has_value()) { YAML::Node child_node = root[*child_name]; if (!child_node) { throw std::runtime_error(fmt::format( "When loading '{}', there was no such top-level map entry '{}'", filename, *child_name)); } result = ConvertJbederYamlNodeToDrakeYamlNode({}, child_node); } else { result = ConvertJbederYamlNodeToDrakeYamlNode({}, root); } result.SetFilename(filename); return result; } // N.B. This is unit tested via yaml_io_test with calls to LoadYamlString (and // not as part of yaml_read_archive_test as would be typical). In the future, // it might be better to refactor document parsing and merge key handling into // a separate file with more specific testing, but for the moment our use of // yaml-cpp in our public API makes that difficult. internal::Node YamlReadArchive::LoadStringAsNode( const std::string& data, const std::optional<std::string>& child_name) { YAML::Node root = YAML::Load(data); if (child_name.has_value()) { YAML::Node child_node = root[*child_name]; if (!child_node) { throw std::runtime_error(fmt::format( "When loading YAML, there was no such top-level map entry '{}'", *child_name)); } return ConvertJbederYamlNodeToDrakeYamlNode({}, child_node); } else { return ConvertJbederYamlNodeToDrakeYamlNode({}, root); } } template <typename T> void YamlReadArchive::ParseScalarImpl(const std::string& value, T* result) { DRAKE_DEMAND(result != nullptr); // For the decode-able types, see /usr/include/yaml-cpp/node/convert.h. // Generally, all of the POD types are supported. bool success = YAML::convert<T>::decode(YAML::Node(value), *result); if (!success) { ReportError( fmt::format("could not parse {} value", drake::NiceTypeName::Get<T>())); } } void YamlReadArchive::ParseScalar(const std::string& value, bool* result) { ParseScalarImpl<bool>(value, result); } void YamlReadArchive::ParseScalar(const std::string& value, float* result) { ParseScalarImpl<float>(value, result); } void YamlReadArchive::ParseScalar(const std::string& value, double* result) { ParseScalarImpl<double>(value, result); } void YamlReadArchive::ParseScalar(const std::string& value, int32_t* result) { ParseScalarImpl<int32_t>(value, result); } void YamlReadArchive::ParseScalar(const std::string& value, uint32_t* result) { ParseScalarImpl<uint32_t>(value, result); } void YamlReadArchive::ParseScalar(const std::string& value, int64_t* result) { ParseScalarImpl<int64_t>(value, result); } void YamlReadArchive::ParseScalar(const std::string& value, uint64_t* result) { ParseScalarImpl<uint64_t>(value, result); } void YamlReadArchive::ParseScalar(const std::string& value, std::string* result) { DRAKE_DEMAND(result != nullptr); *result = value; } const internal::Node* YamlReadArchive::MaybeGetSubNode(const char* name) const { DRAKE_DEMAND(name != nullptr); if (mapish_item_key_ != nullptr) { DRAKE_DEMAND(mapish_item_value_ != nullptr); if (std::strcmp(mapish_item_key_, name) == 0) { return mapish_item_value_; } return nullptr; } DRAKE_DEMAND(root_ != nullptr); DRAKE_DEMAND(root_->IsMapping()); const auto& map = root_->GetMapping(); auto iter = map.find(name); if (iter == map.end()) { return nullptr; } return &(iter->second); } const internal::Node* YamlReadArchive::GetSubNodeScalar( const char* name) const { const internal::Node* result = GetSubNodeAny(name, internal::NodeType::kScalar); if ((result != nullptr) && (result->GetTag() == internal::Node::kTagNull)) { ReportError("has non-Scalar (Null)"); result = nullptr; } return result; } const internal::Node* YamlReadArchive::GetSubNodeSequence( const char* name) const { return GetSubNodeAny(name, internal::NodeType::kSequence); } const internal::Node* YamlReadArchive::GetSubNodeMapping( const char* name) const { return GetSubNodeAny(name, internal::NodeType::kMapping); } const internal::Node* YamlReadArchive::GetSubNodeAny( const char* name, internal::NodeType expected_type) const { const internal::Node* result = MaybeGetSubNode(name); if (result == nullptr) { if (!options_.allow_cpp_with_no_yaml) { ReportError("is missing"); } return result; } internal::NodeType actual_type = result->GetType(); if (actual_type != expected_type) { std::string_view expected_type_string = internal::Node::GetTypeString(expected_type); std::string_view actual_type_string = result->GetTypeString(); if (result->GetTag() == internal::Node::kTagNull) { actual_type_string = "Null"; } ReportError(fmt::format("has non-{} ({})", expected_type_string, actual_type_string)); result = nullptr; } return result; } void YamlReadArchive::CheckAllAccepted() const { // This function is only ever called on Serializeable nodes (i.e., where we // have a real Mapping node). Calling it with a map-ish key (i.e., while // parsing a sequence) would mean that YamlReadArchive went off the rails. DRAKE_DEMAND(mapish_item_key_ == nullptr); DRAKE_DEMAND(root_->IsMapping()); if (options_.allow_yaml_with_no_cpp) { return; } for (const auto& [key, value] : root_->GetMapping()) { unused(value); if (!visited_names_.contains(key)) { ReportError(fmt::format("key '{}' did not match any visited value", key)); } } } void YamlReadArchive::ReportError(const std::string& note) const { std::ostringstream e; // A buffer for the error message text. // Output the filename. bool found_filename = false; for (auto* archive = this; archive != nullptr; archive = archive->parent_) { if ((archive->root_ != nullptr) && (archive->root_->GetFilename().has_value())) { const std::string& filename = archive->root_->GetFilename().value(); fmt::print(e, "{}:", filename); found_filename = true; break; } } if (!found_filename) { e << "<string>:"; } // Output the nearby line and column number. It's usually the mark for `this` // but for a "mapish item" can a nearby ancestor. for (auto* archive = this; archive != nullptr; archive = archive->parent_) { if (archive->root_ != nullptr) { if (archive->root_->GetMark().has_value()) { const Node::Mark& mark = archive->root_->GetMark().value(); fmt::print(e, "{}:{}:", mark.line, mark.column); } break; } } e << " "; // Describe this node. this->PrintNodeSummary(e); fmt::print(e, " {} entry for ", note); PrintVisitNameType(e); // Describe its parents. for (auto* archive = parent_; archive; archive = archive->parent_) { fmt::print(e, " while accepting "); archive->PrintNodeSummary(e); if (archive->debug_visit_name_ != nullptr) { fmt::print(e, " while visiting "); archive->PrintVisitNameType(e); } } fmt::print(e, "."); throw std::runtime_error(e.str()); } void YamlReadArchive::PrintNodeSummary(std::ostream& s) const { if (mapish_item_key_ != nullptr) { fmt::print(s, " (with size 1 and keys {{{}}})", mapish_item_key_); return; } DRAKE_DEMAND(root_ != nullptr); fmt::print(s, "YAML node of type {}", root_->GetTypeString()); // Grab the mapping's keys. (It's a std::map, so the ordering here is // fully deterministic.) DRAKE_DEMAND(root_->IsMapping()); std::vector<std::string_view> keys; for (const auto& [key, value] : root_->GetMapping()) { unused(value); keys.push_back(key); } // Output the details of the keys. fmt::print(s, " (with size {} and keys {{{}}})", keys.size(), fmt::join(keys, ", ")); } void YamlReadArchive::PrintVisitNameType(std::ostream& s) const { if (debug_visit_name_ == nullptr) { s << "<root>"; return; } DRAKE_DEMAND(debug_visit_name_ != nullptr); DRAKE_DEMAND(debug_visit_type_ != nullptr); fmt::print(s, "{} {}", drake::NiceTypeName::Get(*debug_visit_type_), debug_visit_name_); } } // namespace internal } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_write_archive.cc
#include "drake/common/yaml/yaml_write_archive.h" #include <algorithm> #include <sstream> #include <utility> #include <vector> #include <yaml-cpp/emitfromevents.h> #include <yaml-cpp/yaml.h> #include "drake/common/drake_assert.h" #include "drake/common/overloaded.h" #include "drake/common/unused.h" namespace drake { namespace yaml { namespace internal { namespace { constexpr const char* const kKeyOrder = "__key_order"; // This function uses the same approach as YAML::NodeEvents::Emit. // https://github.com/jbeder/yaml-cpp/blob/release-0.5.2/src/nodeevents.cpp#L55 // // The `sink` object keeps track of document state. Our job is to feed it with // an event stream (e.g., start mapping, "foo", start sequence, "1", "2", // end sequence, end mapping) and then its job is to spit out the equivalent // YAML syntax for that stream (e.g., "foo: [1, 2]") with appropriately matched // delimiters (i.e., `:` or `{}` or `[]`) and horizontal indentation levels. void RecursiveEmit(const internal::Node& node, YAML::EmitFromEvents* sink) { const YAML::Mark no_mark; const YAML::anchor_t no_anchor = YAML::NullAnchor; std::string tag{node.GetTag()}; if ((tag == internal::Node::kTagNull) || (tag == internal::Node::kTagBool) || (tag == internal::Node::kTagInt) || (tag == internal::Node::kTagFloat) || (tag == internal::Node::kTagStr)) { // In most cases we don't need to emit the "JSON Schema" tags for YAML data, // because they are implied by default. However, YamlWriteArchive on variant // types sometimes marks the tag as important. if (node.IsTagImportant()) { DRAKE_DEMAND(tag.size() > 0); // The `internal::Node::kTagFoo` all look like "tag:yaml.org,2002:foo". // We only want the "foo" part (after the second colon). tag = "!!" + tag.substr(18); } else { tag.clear(); } } node.Visit(overloaded{ [&](const internal::Node::ScalarData& data) { sink->OnScalar(no_mark, tag, no_anchor, data.scalar); }, [&](const internal::Node::SequenceData& data) { // If all children are scalars, then format this sequence onto a // single line; otherwise, format as a bulleted list. auto style = YAML::EmitterStyle::Flow; for (const auto& child : data.sequence) { if (!child.IsScalar()) { style = YAML::EmitterStyle::Block; } } sink->OnSequenceStart(no_mark, tag, no_anchor, style); for (const auto& child : data.sequence) { RecursiveEmit(child, sink); } sink->OnSequenceEnd(); }, [&](const internal::Node::MappingData& data) { // If there are no children, then format this map onto a single line; // otherwise, format over multiple "key: value\n" lines. auto style = YAML::EmitterStyle::Block; if (data.mapping.empty()) { style = YAML::EmitterStyle::Flow; } sink->OnMapStart(no_mark, tag, no_anchor, style); // If there is a __key_order node inserted (as part of the Accept() // member function in our header file), use it to specify output order; // otherwise, use alphabetical order. std::vector<std::string> key_order; if (data.mapping.contains(kKeyOrder)) { const internal::Node& key_order_node = data.mapping.at(kKeyOrder); // Use Accept()'s ordering. (If EraseMatchingMaps has been called, // some of the keys may have disappeared.) for (const auto& item : key_order_node.GetSequence()) { const std::string& key = item.GetScalar(); if (data.mapping.contains(key)) { key_order.push_back(key); } } } else { // Use alphabetical ordering. for (const auto& [key, value] : data.mapping) { unused(value); key_order.push_back(key); } } for (const auto& string_key : key_order) { RecursiveEmit(internal::Node::MakeScalar(string_key), sink); RecursiveEmit(data.mapping.at(string_key), sink); } sink->OnMapEnd(); }, }); } } // namespace const char* const YamlWriteArchive::kKeyOrderName = kKeyOrder; // Convert the given document to a string ala YAML::Dump, but emit Map nodes // using a specific key ordering (the visit order in case of structs, or else // alphabetical key order for any other kind of Map node). std::string YamlWriteArchive::YamlDumpWithSortedMaps( const internal::Node& document) { YAML::Emitter emitter; YAML::EmitFromEvents sink(emitter); RecursiveEmit(document, &sink); return emitter.c_str(); } std::string YamlWriteArchive::EmitString(const std::string& root_name) const { std::string result; if (root_.GetMapping().empty()) { if (root_name.empty()) { result = "{}\n"; } else { result = root_name + ":\n"; } } else { if (root_name.empty()) { result = YamlDumpWithSortedMaps(root_) + "\n"; } else { auto document = internal::Node::MakeMapping(); document.Add(root_name, root_); result = YamlDumpWithSortedMaps(document) + "\n"; } } return result; } namespace { /* Returns a quoted and escaped JSON string literal per https://www.json.org/json-en.html. */ std::string QuotedJsonString(std::string_view x) { std::string result; result.reserve(x.size() + 2); result.push_back('"'); for (const char ch : x) { if ((ch == '"') || (ch == '\\') || (ch < ' ')) { // This character needs escaping. result.append(fmt::format("\\u00{:02x}", static_cast<uint8_t>(ch))); } else { // No escaping required. result.push_back(ch); } } result.push_back('"'); return result; } /* Outputs the given `node` to `os`. This is the recursive implementation of YamlWriteArchive::ToJson. */ void WriteJson(std::ostream& os, const internal::Node& node) { const std::string_view tag = node.GetTag(); switch (node.GetType()) { case internal::NodeType::kScalar: { const std::string& scalar = node.GetScalar(); if ((tag == internal::Node::kTagNull) || (tag == internal::Node::kTagBool) || (tag == internal::Node::kTagInt)) { // These values are spelled the same in YAML and JSON (without quotes). os << scalar; return; } if (tag == internal::Node::kTagFloat) { // Floats are the same in YAML and JSON except for non-finite values. if (scalar == ".nan") { os << "NaN"; return; } if (scalar == ".inf") { os << "Infinity"; return; } if (scalar == "-.inf") { os << "-Infinity"; return; } os << scalar; return; } if (tag.empty() || (tag == internal::Node::kTagStr)) { // JSON strings are quoted and escaped. os << QuotedJsonString(scalar); return; } throw std::logic_error(fmt::format( "SaveJsonString: Cannot save a YAML scalar '{}' with tag '{}' " "to JSON", scalar, tag)); } case internal::NodeType::kSequence: { if (!tag.empty()) { // N.B. As currently written, yaml_write_archive can never add a tag to // a sequence. We'll still fail-fast in case it ever does. throw std::logic_error(fmt::format( "SaveJsonString: Cannot save a YAML sequence with tag '{}' to JSON", tag)); } os << "["; const auto& node_vector = node.GetSequence(); bool first = true; for (const auto& sub_node : node_vector) { if (first) { first = false; } else { os << ","; } WriteJson(os, sub_node); } os << "]"; return; } case internal::NodeType::kMapping: { if (!tag.empty()) { throw std::logic_error(fmt::format( "SaveJsonString: Cannot save a YAML mapping with tag '{}' to JSON", tag)); } os << "{"; bool first = true; for (const auto& [name, sub_node] : node.GetMapping()) { if (name == kKeyOrder) { // For YAML output, we use a __key_order node to improve readability // of the output (i.e., to follow the schema declaration order). For // JSON, we don't expect the output to be readable in the first place // so we'll simply ignore the declaration order and use the default // (alphabetical) ordering instead. continue; } if (first) { first = false; } else { os << ","; } os << QuotedJsonString(name); os << ":"; WriteJson(os, sub_node); } os << "}"; return; } } DRAKE_UNREACHABLE(); } } // namespace std::string YamlWriteArchive::ToJson() const { std::stringstream result; WriteJson(result, root_); return result.str(); } namespace { // Implements YamlWriteArchive::EraseMatchingMaps recursively. void DoEraseMatchingMaps(internal::Node* x, const internal::Node* y) { DRAKE_DEMAND((x != nullptr) && (y != nullptr)); // If x and y are different types, then no subtraction can be done. // If their type is non-map, then we do not subtract them. The reader's // retain_map_defaults mode only merges default maps; it does not, e.g., // concatenate sequences. if (!(x->IsMapping())) { return; } if (!(y->IsMapping())) { return; } const string_map<internal::Node>& y_map = y->GetMapping(); // Both x are y are maps. Remove from x any key-value pair that is identical // within both x and y. std::vector<std::string> keys_to_prune; for (const auto& [x_key, x_value] : x->GetMapping()) { if (x_key == kKeyOrder) { // Subtraction should always leave the special kKeyOrder node alone when // considering which keys to prune. If any keys are unpruned, we still // want to know in what order they should appear. The only way to remove // a kKeyOrder node is when its enclosing Map is removed wholesale. continue; } auto iter = y_map.find(x_key); if (iter == y_map.end()) { // The key only appears in x, so we should neither prune nor recurse. continue; } const internal::Node& y_value = iter->second; if (x_value == y_value) { // The values match, so we should prune. (We can't call Remove here, // because it would invalidate the range-for iterator.) keys_to_prune.push_back(x_key); continue; } // The maps are tagged differently, so we should not subtract their // children, since they may have different semantics. if (x_value.GetTag() != y_value.GetTag()) { continue; } // Recurse into any children of x and y with the same key name. internal::Node& x_value_mutable = x->At(x_key); DoEraseMatchingMaps(&x_value_mutable, &y_value); } for (const auto& key : keys_to_prune) { x->Remove(key); } } } // namespace void YamlWriteArchive::EraseMatchingMaps(const YamlWriteArchive& other) { DoEraseMatchingMaps(&(this->root_), &(other.root_)); } } // namespace internal } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_node.cc
#include "drake/common/yaml/yaml_node.h" #include <stdexcept> #include <type_traits> #include <fmt/format.h> #include "drake/common/drake_assert.h" #include "drake/common/overloaded.h" namespace drake { namespace yaml { namespace internal { namespace { // Converts a type T from our variant<> into a string name for errors. template <typename T> std::string_view GetNiceVariantName(const T&) { if constexpr (std::is_same_v<T, Node::ScalarData>) { return "Scalar"; } else if constexpr (std::is_same_v<T, Node::SequenceData>) { return "Sequence"; } else if constexpr (std::is_same_v<T, Node::MappingData>) { return "Mapping"; } } } // namespace Node::Node() = default; Node Node::MakeScalar(std::string value) { Node result; result.data_ = ScalarData{std::move(value)}; return result; } Node Node::MakeSequence() { Node result; result.data_ = SequenceData{}; return result; } Node Node::MakeMapping() { Node result; result.data_ = MappingData{}; return result; } Node Node::MakeNull() { Node result; result.data_ = ScalarData{"null"}; result.tag_ = JsonSchemaTagInfo{.value = JsonSchemaTag::kNull}; return result; } NodeType Node::GetType() const { return std::visit<NodeType>( // BR overloaded{ [](const ScalarData&) { return NodeType::kScalar; }, [](const SequenceData&) { return NodeType::kSequence; }, [](const MappingData&) { return NodeType::kMapping; }, }, data_); } std::string_view Node::GetTypeString() const { return std::visit( [](auto&& data) { return GetNiceVariantName(data); }, data_); } std::string_view Node::GetTypeString(NodeType type) { switch (type) { case NodeType::kScalar: { return GetNiceVariantName(ScalarData{}); } case NodeType::kSequence: { return GetNiceVariantName(SequenceData{}); } case NodeType::kMapping: { return GetNiceVariantName(MappingData{}); } } DRAKE_UNREACHABLE(); } bool Node::IsScalar() const { return std::holds_alternative<ScalarData>(data_); } bool Node::IsSequence() const { return std::holds_alternative<SequenceData>(data_); } bool Node::IsMapping() const { return std::holds_alternative<MappingData>(data_); } bool operator==(const Node& a, const Node& b) { // We need to compare the canonical form of a tag (i.e., its string). auto a_tag = a.GetTag(); auto b_tag = b.GetTag(); return std::tie(a_tag, a.data_, a.filename_, a.mark_) == std::tie(b_tag, b.data_, b.filename_, b.mark_); } bool operator==(const Node::Mark& a, const Node::Mark& b) { return std::tie(a.line, a.column) == std::tie(b.line, b.column); } bool operator==(const Node::ScalarData& a, const Node::ScalarData& b) { return a.scalar == b.scalar; } bool operator==(const Node::SequenceData& a, const Node::SequenceData& b) { return a.sequence == b.sequence; } bool operator==(const Node::MappingData& a, const Node::MappingData& b) { return a.mapping == b.mapping; } std::string_view Node::GetTag() const { return std::visit<std::string_view>( // BR overloaded{ [](const std::string& tag) { return std::string_view{tag}; }, [](const JsonSchemaTagInfo& info) { switch (info.value) { case JsonSchemaTag::kNull: return kTagNull; case JsonSchemaTag::kBool: return kTagBool; case JsonSchemaTag::kInt: return kTagInt; case JsonSchemaTag::kFloat: return kTagFloat; case JsonSchemaTag::kStr: return kTagStr; } DRAKE_UNREACHABLE(); }, }, tag_); } bool Node::IsTagImportant() const { return std::visit<bool>( // BR overloaded{ [](const std::string&) { return false; }, [](const JsonSchemaTagInfo& info) { return info.important; }, }, tag_); } void Node::SetTag(JsonSchemaTag tag, bool important) { tag_ = JsonSchemaTagInfo{.value = tag, .important = important}; } void Node::SetTag(std::string tag) { if (tag.empty()) { tag_ = {}; } else { tag_ = std::move(tag); } } void Node::SetFilename(std::optional<std::string> filename) { filename_ = std::move(filename); } const std::optional<std::string>& Node::GetFilename() const { return filename_; } void Node::SetMark(std::optional<Mark> mark) { mark_ = mark; } const std::optional<Node::Mark>& Node::GetMark() const { return mark_; } const std::string& Node::GetScalar() const { return *std::visit<const std::string*>( overloaded{ [](const ScalarData& data) { return &data.scalar; }, [](auto&& data) -> std::nullptr_t { throw std::logic_error(fmt::format("Cannot Node::GetScalar on a {}", GetNiceVariantName(data))); }, }, data_); } const std::vector<Node>& Node::GetSequence() const { return *std::visit<const std::vector<Node>*>( overloaded{ [](const SequenceData& data) { return &data.sequence; }, [](auto&& data) -> std::nullptr_t { throw std::logic_error(fmt::format( "Cannot Node::GetSequence on a {}", GetNiceVariantName(data))); }, }, data_); } void Node::Add(Node value) { return std::visit<void>( overloaded{ [&value](SequenceData& data) { data.sequence.push_back(std::move(value)); }, [](auto&& data) { throw std::logic_error(fmt::format( "Cannot Node::Add(value) on a {}", GetNiceVariantName(data))); }, }, data_); } const string_map<Node>& Node::GetMapping() const { return *visit<const string_map<Node>*>( overloaded{ [](const MappingData& data) { return &data.mapping; }, [](auto&& data) -> std::nullptr_t { throw std::logic_error(fmt::format( "Cannot Node::GetMapping on a {}", GetNiceVariantName(data))); }, }, data_); } void Node::Add(std::string key, Node value) { return std::visit<void>( overloaded{ [&key, &value](MappingData& data) { const auto result = data.mapping.insert({std::move(key), std::move(value)}); const bool inserted = result.second; if (!inserted) { // Our 'key' argument is now empty (because it has been // moved-from), so for the error message we need to dig the // existing key out of the map. const std::string& old_key = result.first->first; throw std::logic_error(fmt::format( "Cannot Node::Add(key, value) using duplicate key '{}'", old_key)); } }, [](auto&& data) { throw std::logic_error( fmt::format("Cannot Node::Add(key, value) on a {}", GetNiceVariantName(data))); }, }, data_); } Node& Node::At(std::string_view key) { return *std::visit<Node*>( overloaded{ [key](MappingData& data) { return &data.mapping.at(std::string{key}); }, [](auto&& data) -> std::nullptr_t { throw std::logic_error(fmt::format("Cannot Node::At(key) on a {}", GetNiceVariantName(data))); }, }, data_); } void Node::Remove(std::string_view key) { return std::visit<void>( overloaded{ [key](MappingData& data) { auto erased = data.mapping.erase(std::string{key}); if (!erased) { throw std::logic_error(fmt::format( "No such key '{}' during Node::Remove(key)", key)); } }, [](auto&& data) { throw std::logic_error(fmt::format( "Cannot Node::Remove(key) on a {}", GetNiceVariantName(data))); }, }, data_); } std::ostream& operator<<(std::ostream& os, const Node& node) { if (!node.GetTag().empty()) { os << "!<" << node.GetTag() << "> "; } node.Visit(overloaded{ [&](const Node::ScalarData& data) { os << '"' << data.scalar << '"'; }, [&](const Node::SequenceData& data) { os << "["; bool first = true; for (const auto& child : data.sequence) { if (!first) { os << ", "; } first = false; os << child; } os << "]"; }, [&](const Node::MappingData& data) { os << "{"; bool first = true; for (const auto& [key, child] : data.mapping) { if (!first) { os << ", "; } first = false; os << '"' << key << '"' << ": " << child; } os << "}"; }, }); return os; } } // namespace internal } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_read_archive.h
#pragma once #include <algorithm> #include <array> #include <cstdint> #include <map> #include <optional> #include <ostream> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <variant> #include <vector> #include <Eigen/Core> #include <fmt/format.h> #include "drake/common/drake_copyable.h" #include "drake/common/drake_throw.h" #include "drake/common/name_value.h" #include "drake/common/nice_type_name.h" #include "drake/common/string_unordered_set.h" #include "drake/common/unused.h" #include "drake/common/yaml/yaml_io_options.h" #include "drake/common/yaml/yaml_node.h" namespace drake { namespace yaml { namespace internal { // A helper class for @ref yaml_serialization "YAML Serialization" that loads // data from a YAML file into a C++ structure. class YamlReadArchive final { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(YamlReadArchive) YamlReadArchive(internal::Node root, const LoadYamlOptions& options); static internal::Node LoadFileAsNode( const std::string& filename, const std::optional<std::string>& child_name); static internal::Node LoadStringAsNode( const std::string& data, const std::optional<std::string>& child_name); // Sets the contents `serializable` based on the YAML file associated this // archive. template <typename Serializable> void Accept(Serializable* serializable) { DRAKE_THROW_UNLESS(serializable != nullptr); this->DoAccept(serializable, static_cast<int32_t>(0)); CheckAllAccepted(); } // Sets the value pointed to by `nvp.value()` based on the YAML file // associated with this archive. Most users should call Accept, not Visit. template <typename NameValuePair> void Visit(const NameValuePair& nvp) { this->Visit(nvp, VisitShouldMemorizeType::kYes); } private: // N.B. In the private details below, we use "NVP" to abbreviate the // "NameValuePair" template concept. // Internal-use constructor during recursion. This constructor aliases all // of its arguments, so all must outlive this object. // @pre root is a Mapping node YamlReadArchive(const internal::Node* root, const YamlReadArchive* parent) : owned_root_(), root_(root), mapish_item_key_(nullptr), mapish_item_value_(nullptr), options_(parent->options_), parent_(parent) { DRAKE_DEMAND(root != nullptr); DRAKE_DEMAND(root->IsMapping()); DRAKE_DEMAND(parent != nullptr); } // Internal-use constructor during recursion. This constructor aliases all // of its arguments, so all must outlive this object. The effect is as-if // we have a root of type NodeType::Mapping with a single (key, value) entry. YamlReadArchive(const char* mapish_item_key, const internal::Node* mapish_item_value, const YamlReadArchive* parent) : owned_root_(), root_(nullptr), mapish_item_key_(mapish_item_key), mapish_item_value_(mapish_item_value), options_(parent->options_), parent_(parent) { DRAKE_DEMAND(mapish_item_key != nullptr); DRAKE_DEMAND(mapish_item_value != nullptr); DRAKE_DEMAND(parent != nullptr); } enum class VisitShouldMemorizeType { kNo, kYes }; // Like the 1-arg Visit, except that the (private) caller can opt-out of this // visit frame appearing in error reports. template <typename NameValuePair> void Visit(const NameValuePair& nvp, VisitShouldMemorizeType trace) { if (trace == VisitShouldMemorizeType::kYes) { debug_visit_name_ = nvp.name(); debug_visit_type_ = &typeid(*nvp.value()); visited_names_.insert(nvp.name()); } // Use int32_t for the final argument to prefer the specialized overload. this->DoVisit(nvp, *nvp.value(), static_cast<int32_t>(0)); if (trace == VisitShouldMemorizeType::kYes) { debug_visit_name_ = nullptr; debug_visit_type_ = nullptr; } } // -------------------------------------------------------------------------- // @name Overloads for the Accept() implementation // This version applies when Serialize is member method. template <typename Serializable> auto DoAccept(Serializable* serializable, int32_t) -> decltype(serializable->Serialize(this)) { serializable->Serialize(this); } // This version applies when `value` is a std::map from std::string to // Serializable. The map's values must be serializable, but there is no // Serialize function required for the map itself. template <typename Serializable, typename Compare, typename Allocator> void DoAccept(std::map<std::string, Serializable, Compare, Allocator>* value, int32_t) { VisitMapDirectly<Serializable>(*root_, value); for (const auto& [name, ignored] : *value) { unused(ignored); visited_names_.insert(name); } } // This version applies when Serialize is an ADL free function. template <typename Serializable> void DoAccept(Serializable* serializable, int64_t) { Serialize(this, serializable); } // -------------------------------------------------------------------------- // @name Overloads for the Visit() implementation // This version applies when the type has a Serialize member function. template <typename NVP, typename T> auto DoVisit(const NVP& nvp, const T&, int32_t) -> decltype(nvp.value()->Serialize( static_cast<YamlReadArchive*>(nullptr))) { this->VisitSerializable(nvp); } // This version applies when the type has an ADL Serialize function. template <typename NVP, typename T> auto DoVisit(const NVP& nvp, const T&, int32_t) -> decltype(Serialize(static_cast<YamlReadArchive*>(nullptr), nvp.value())) { this->VisitSerializable(nvp); } // For std::vector. template <typename NVP, typename T> void DoVisit(const NVP& nvp, const std::vector<T>&, int32_t) { this->VisitVector(nvp); } // For std::array. template <typename NVP, typename T, std::size_t N> void DoVisit(const NVP& nvp, const std::array<T, N>&, int32_t) { this->VisitArray(nvp.name(), N, nvp.value()->data()); } // For std::map. template <typename NVP, typename K, typename V, typename C> void DoVisit(const NVP& nvp, const std::map<K, V, C>&, int32_t) { this->VisitMap<K, V>(nvp); } // For std::unordered_map. template <typename NVP, typename K, typename V, typename H, typename E> void DoVisit(const NVP& nvp, const std::unordered_map<K, V, H, E>&, int32_t) { this->VisitMap<K, V>(nvp); } // For std::optional. template <typename NVP, typename T> void DoVisit(const NVP& nvp, const std::optional<T>&, int32_t) { this->VisitOptional(nvp); } // For std::variant. template <typename NVP, typename... Types> void DoVisit(const NVP& nvp, const std::variant<Types...>&, int32_t) { this->VisitVariant(nvp); } // For Eigen::Matrix or Eigen::Vector. template <typename NVP, typename T, int Rows, int Cols, int Options = 0, int MaxRows = Rows, int MaxCols = Cols> void DoVisit(const NVP& nvp, const Eigen::Matrix<T, Rows, Cols, Options, MaxRows, MaxCols>&, int32_t) { if constexpr (Cols == 1) { if constexpr (Rows >= 0) { this->VisitArray(nvp.name(), Rows, nvp.value()->data()); } else if constexpr (MaxRows >= 0) { this->VisitVector(nvp, MaxRows); } else { this->VisitVector(nvp); } } else { this->VisitMatrix(nvp.name(), nvp.value()); } } // If no other DoVisit matched, we'll treat the value as a scalar. template <typename NVP, typename T> void DoVisit(const NVP& nvp, const T&, int64_t) { this->VisitScalar(nvp); } // -------------------------------------------------------------------------- // @name Implementations of Visit() once the shape is known template <typename NVP> void VisitSerializable(const NVP& nvp) { const internal::Node* sub_node = GetSubNodeMapping(nvp.name()); if (sub_node == nullptr) { return; } YamlReadArchive sub_archive(sub_node, this); auto&& value = *nvp.value(); sub_archive.Accept(&value); } template <typename NVP> void VisitScalar(const NVP& nvp) { const internal::Node* sub_node = GetSubNodeScalar(nvp.name()); if (sub_node == nullptr) { return; } ParseScalar(sub_node->GetScalar(), nvp.value()); } template <typename NVP> void VisitOptional(const NVP& nvp) { // When visiting an optional, we want to match up the null-ness of the YAML // node with the nullopt-ness of the C++ data. Refer to the unit tests for // Optional for a full explanation. const internal::Node* sub_node = MaybeGetSubNode(nvp.name()); if (sub_node == nullptr) { if (!options_.allow_cpp_with_no_yaml) { *nvp.value() = std::nullopt; } return; } if (sub_node->GetTag() == internal::Node::kTagNull) { *nvp.value() = std::nullopt; return; } // Visit the unpacked optional as if it weren't wrapped in optional<>. using T = typename NVP::value_type::value_type; std::optional<T>& storage = *nvp.value(); if (!storage) { storage = T{}; } this->Visit(drake::MakeNameValue(nvp.name(), &storage.value()), VisitShouldMemorizeType::kNo); } template <typename NVP> void VisitVariant(const NVP& nvp) { const internal::Node* sub_node = MaybeGetSubNode(nvp.name()); if (sub_node == nullptr) { if (!options_.allow_cpp_with_no_yaml) { ReportError("is missing"); } return; } // Figure out which variant<...> type we have based on the node's tag. const std::string_view tag = sub_node->GetTag(); VariantHelper(tag, nvp.name(), nvp.value()); } // Steps through Types to extract 'size_t I' and 'typename T' for the Impl. template <template <typename...> class Variant, typename... Types> void VariantHelper(std::string_view tag, const char* name, Variant<Types...>* storage) { if (tag == internal::Node::kTagNull) { // Our variant parsing does not yet support nulls. When the tag indicates // null, don't try to match it to a variant type; instead, just parse into // the first variant type in order to generate a useful error message. // TODO(jwnimmer-tri) Allow for std::monostate as one of the Types..., // in case the user wants to permit nullable variants. using T = std::variant_alternative_t<0, Variant<Types...>>; T& typed_storage = storage->template emplace<0>(); this->Visit(drake::MakeNameValue(name, &typed_storage)); return; } VariantHelperImpl<0, Variant<Types...>, Types...>(tag, name, storage); } // Recursive case -- checks if `tag` matches `T` (which was the I'th type in // the template parameter pack), or else keeps looking. template <size_t I, typename Variant, typename T, typename... Remaining> void VariantHelperImpl(std::string_view tag, const char* name, Variant* storage) { // For the first type declared in the variant<> (I == 0), the tag can be // absent; otherwise, the tag must match one of the variant's types. if (((I == 0) && (tag.empty() || (tag == "?") || (tag == "!"))) || IsTagMatch<T>(tag)) { T& typed_storage = storage->index() == I ? std::get<I>(*storage) : storage->template emplace<I>(); this->Visit(drake::MakeNameValue(name, &typed_storage)); return; } VariantHelperImpl<I + 1, Variant, Remaining...>(tag, name, storage); } // Base case -- no match. template <size_t, typename Variant> void VariantHelperImpl(std::string_view tag, const char*, Variant*) { ReportError(fmt::format( "has unsupported type tag {} while selecting a variant<>", tag)); } // Checks if the given yaml type `tag` matches the C++ type `T`. template <typename T> static bool IsTagMatch(std::string_view tag) { // Check against the JSON schema tags. if constexpr (std::is_same_v<T, bool>) { return tag == internal::Node::kTagBool; } else if constexpr (std::is_integral_v<T>) { return tag == internal::Node::kTagInt; } else if constexpr (std::is_floating_point_v<T>) { return tag == internal::Node::kTagFloat; } else if constexpr (std::is_same_v<T, std::string>) { return tag == internal::Node::kTagStr; } else { // Not a JSON schema. Check the drake-specific tag. return IsTagMatch(drake::NiceTypeName::GetFromStorage<T>(), tag); } } // Checks if a NiceTypeName matches the yaml type tag. static bool IsTagMatch(std::string_view name, std::string_view tag) { // Check for an "application specific" tag such as "!MyClass", which we // will match to our variant item's name such as "my_namespace::MyClass" // ignoring the namespace and any template parameters. const auto start_offset = name.rfind(':'); const auto start = name.begin() + (start_offset == std::string::npos ? 0 : start_offset + 1); const auto end = std::find(start, name.end(), '<'); return (tag[0] == '!') && std::equal( // The `tag` without the leading '!'. tag.begin() + 1, tag.end(), // The `name` without any namespaces or templates. start, end); } template <typename T> void VisitArray(const char* name, size_t size, T* data) { const internal::Node* sub_node = GetSubNodeSequence(name); if (sub_node == nullptr) { return; } const std::vector<internal::Node>& elements = sub_node->GetSequence(); if (elements.size() != size) { ReportError(fmt::format("has {}-size entry (wanted {}-size)", elements.size(), size)); } for (size_t i = 0; i < size; ++i) { const std::string key = fmt::format("{}[{}]", name, i); const internal::Node& value = elements[i]; YamlReadArchive item_archive(key.c_str(), &value, this); item_archive.Visit(drake::MakeNameValue(key.c_str(), &data[i])); } } // @param max_size an upper bound on how big we can resize() the vector template <typename NVP> void VisitVector(const NVP& nvp, std::optional<size_t> max_size = {}) { const internal::Node* sub_node = GetSubNodeSequence(nvp.name()); if (sub_node == nullptr) { return; } const std::vector<internal::Node>& elements = sub_node->GetSequence(); const size_t size = elements.size(); if (max_size.has_value() && size > *max_size) { // This error message snippet looks odd in the source code, but turns // out okay once ReportError tacks on some extra text. ReportError(fmt::format( "has too many array elements ({}); the maximum size is {} in the", size, *max_size)); return; } auto&& storage = *nvp.value(); storage.resize(size); if (size > 0) { this->VisitArray(nvp.name(), size, &storage[0]); } } template <typename T, int Rows, int Cols, int Options = 0, int MaxRows = Rows, int MaxCols = Cols> void VisitMatrix( const char* name, Eigen::Matrix<T, Rows, Cols, Options, MaxRows, MaxCols>* matrix) { const internal::Node* sub_node = GetSubNodeSequence(name); if (sub_node == nullptr) { return; } const std::vector<internal::Node>& elements = sub_node->GetSequence(); // Measure the YAML Sequence-of-Sequence dimensions. // Take a guess at what rows & cols will be (we might adjust later). size_t pending_rows = elements.size(); std::optional<size_t> pending_cols; for (size_t i = 0; i < pending_rows; ++i) { const internal::Node& one_row = elements[i]; if (!one_row.IsSequence()) { ReportError(fmt::format("is Sequence-of-{} (not Sequence-of-Sequence)", one_row.GetTypeString())); return; } const size_t one_row_size = one_row.GetSequence().size(); if (pending_cols && one_row_size != *pending_cols) { ReportError("has inconsistent cols dimensions"); return; } pending_cols = one_row_size; } // Never return an Nx0 matrix; demote it to 0x0 instead. if (pending_cols.value_or(0) == 0) { pending_rows = 0; pending_cols = 0; } const size_t rows = pending_rows; const size_t cols = *pending_cols; // Check the YAML dimensions vs Eigen dimensions, then resize (if dynamic). if (((Rows != Eigen::Dynamic) && (static_cast<int>(rows) != Rows)) || ((Cols != Eigen::Dynamic) && (static_cast<int>(cols) != Cols))) { ReportError(fmt::format("has dimension {}x{} (wanted {}x{})", rows, cols, Rows, Cols)); return; } auto&& storage = *matrix; storage.resize(rows, cols); // Parse. for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < cols; ++j) { const std::string key = fmt::format("{}[{}][{}]", name, i, j); const internal::Node& value = elements[i].GetSequence()[j]; YamlReadArchive item_archive(key.c_str(), &value, this); item_archive.Visit(drake::MakeNameValue(key.c_str(), &storage(i, j))); } } } template <typename Key, typename Value, typename NVP> void VisitMap(const NVP& nvp) { // For now, we only allow std::string as the keys of a serialized std::map. // In the future, we could imagine handling any other kind of scalar value // that was convertible to a string (int, double, string_view, etc.) if we // found that useful. However, to remain compatible with JSON semantics, // we should never allow a YAML Sequence or Mapping to be a used as a key. static_assert(std::is_same_v<Key, std::string>, "std::map keys must be strings"); const internal::Node* sub_node = GetSubNodeMapping(nvp.name()); if (sub_node == nullptr) { return; } auto& result = *nvp.value(); this->VisitMapDirectly<Value>(*sub_node, &result); } template <typename Value, typename Map> void VisitMapDirectly(const internal::Node& node, Map* result) { if (!options_.retain_map_defaults) { result->clear(); } for (const auto& [key, value] : node.GetMapping()) { unused(value); auto newiter_inserted = result->emplace(key, Value{}); auto& newiter = newiter_inserted.first; const bool inserted = newiter_inserted.second; if (!options_.retain_map_defaults) { DRAKE_DEMAND(inserted == true); } Value& newvalue = newiter->second; YamlReadArchive item_archive(&node, this); item_archive.Visit(drake::MakeNameValue(key.c_str(), &newvalue)); } } // -------------------------------------------------------------------------- // @name Scalar parsers // These are the only scalar types that Drake supports. // Users cannot add de-string-ification functions for custom scalars. void ParseScalar(const std::string& value, bool* result); void ParseScalar(const std::string& value, float* result); void ParseScalar(const std::string& value, double* result); void ParseScalar(const std::string& value, int32_t* result); void ParseScalar(const std::string& value, uint32_t* result); void ParseScalar(const std::string& value, int64_t* result); void ParseScalar(const std::string& value, uint64_t* result); void ParseScalar(const std::string& value, std::string* result); template <typename T> void ParseScalarImpl(const std::string& value, T* result); // -------------------------------------------------------------------------- // @name Helpers, utilities, and member variables. // If our root has a child with the given name and type, returns the child. // Otherwise, reports an error and returns nullptr. // // Currently, errors are always reported via an exception, which means that // the nullptr return is irrelevant in practice. However, in the future we // imagine logging multiple errors during parsing (not using exceptions). // Therefore, calling code should be written to handle the nullptr case. const internal::Node* GetSubNodeScalar(const char* name) const; const internal::Node* GetSubNodeSequence(const char* name) const; const internal::Node* GetSubNodeMapping(const char* name) const; // Helper for the prior three functions. const internal::Node* GetSubNodeAny(const char*, internal::NodeType) const; // If our root has child with the given name, returns the child. Otherwise, // returns nullptr. const internal::Node* MaybeGetSubNode(const char*) const; // To be called after Accept-ing a Serializable to cross-check that all keys // in the YAML root's Mapping matched a Visit call from the Serializable. // This relates to the Options.allow_yaml_with_no_cpp setting. void CheckAllAccepted() const; void ReportError(const std::string&) const; void PrintNodeSummary(std::ostream& s) const; void PrintVisitNameType(std::ostream& s) const; // These jointly denote the Node root that our Accept() will read from. // For performance reasons, we'll use a few different members all for the // same purpose. Never access these directly from Visit methods -- use // GetSubNodeFoo() instead. // @{ // A copy of the root node provided by the user to our public constructor. // Our recursive calls to private constructors leave this unset. const std::optional<internal::Node> owned_root_; // Typically set to alias the Node that Accept() will read from. If set, // this will alias owned_root_ when using the public constructor, or else a // temporary root when using the private recursion constructor. Only ever // unset during internal recursion when mapish_item_{key,value}_ are being // used instead. When non-nullptr, it is always a Mapping node. const internal::Node* const root_; // During certain cases of internal recursion, instead of creating a Mapping // node with only a single key-value pair as the root_ pointer, instead we'll // pass the key-value pointers directly. This avoids the copying associated // with constructing a new Mapping node. The two representations are // mutually exclusive -- when root_ is null, both the key_ and value_ must // be non-null, and when root_ is non-null, both key_,value_ must be null. const char* const mapish_item_key_; const internal::Node* const mapish_item_value_; // @} // When the C++ structure and YAML structure disagree, these options govern // which mismatches are permitted without an error. const LoadYamlOptions options_; // The set of NameValue::name keys that have been Visited by the current // Serializable's Accept method so far. string_unordered_set visited_names_; // These are only used for error messages. The two `debug_...` members are // non-nullptr only during Visit()'s lifetime. const YamlReadArchive* const parent_; const char* debug_visit_name_{}; const std::type_info* debug_visit_type_{}; }; } // namespace internal } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_write_archive.h
#pragma once #include <array> #include <cmath> #include <map> #include <optional> #include <stdexcept> #include <string> #include <type_traits> #include <unordered_map> #include <utility> #include <variant> #include <vector> #include <Eigen/Core> #include <fmt/format.h> #include "drake/common/drake_copyable.h" #include "drake/common/name_value.h" #include "drake/common/nice_type_name.h" #include "drake/common/yaml/yaml_node.h" namespace drake { namespace yaml { namespace internal { // A helper class for @ref yaml_serialization "YAML Serialization" that saves // data from a C++ structure into a YAML file. class YamlWriteArchive final { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(YamlWriteArchive) // Creates an archive. YamlWriteArchive() {} // Copies the contents of `serializable` into the YAML object associated with // this archive. template <typename Serializable> void Accept(const Serializable& serializable) { auto* serializable_mutable = const_cast<Serializable*>(&serializable); root_ = internal::Node::MakeMapping(); visit_order_.clear(); this->DoAccept(serializable_mutable, static_cast<int32_t>(0)); if (!visit_order_.empty()) { auto key_order = internal::Node::MakeSequence(); for (const std::string& key : visit_order_) { key_order.Add(internal::Node::MakeScalar(key)); } root_.Add(kKeyOrderName, std::move(key_order)); } } // Returns the YAML string for whatever Serializable was most recently passed // into Accept. // // If the `root_name` is empty, the returned document will be the // Serializable's visited content (which itself is already a Map node) // directly. If the visited serializable content is null (in cases // `Accpet()` has not been called or the entries are erased after calling // `EraseMatchingMaps()`), then an empty map `{}` will be emitted. // // If the `root_name` is not empty, the returned document will be a single // Map node named using `root_name` with the Serializable's visited content // as key-value entries within it. The visited content could be null and the // nullness is defined as above. std::string EmitString(const std::string& root_name = "root") const; // Returns the JSON string for whatever Serializable was most recently passed // into Accept. A std::optional<T> value that is set to std::nullopt will be // entirely omitted from the result, not serialized as "null". std::string ToJson() const; // Removes from this archive any map entries that are identical to an entry // in `other`, iff they reside at the same location within the node tree // hierarchy, and iff their parent nodes (and grandparent, etc., all the way // up to the root) are also all maps. This enables emitting a minimal YAML // representation when the output will be later loaded using YamlReadArchive's // option to retain_map_defaults; the "all parents are maps" condition is the // complement to what retain_map_defaults admits. void EraseMatchingMaps(const YamlWriteArchive& other); // Copies the value pointed to by `nvp.value()` into the YAML object. Most // users should call Accept, not Visit. template <typename NameValuePair> void Visit(const NameValuePair& nvp) { // Use int32_t for the final argument to prefer the specialized overload. this->visit_order_.push_back(nvp.name()); this->DoVisit(nvp, *nvp.value(), static_cast<int32_t>(0)); } private: static const char* const kKeyOrderName; // Helper for EmitString. static std::string YamlDumpWithSortedMaps(const internal::Node&); // N.B. In the private details below, we use "NVP" to abbreviate the // "NameValuePair<T>" template concept. // -------------------------------------------------------------------------- // @name Overloads for the Accept() implementation // This version applies when Serialize is member function. template <typename Serializable> auto DoAccept(Serializable* serializable, int32_t) -> decltype(serializable->Serialize(this)) { return serializable->Serialize(this); } // This version applies when `value` is a std::map from std::string to // Serializable. The map's values must be serializable, but there is no // Serialize function required for the map itself. template <typename Serializable, typename Compare, typename Allocator> void DoAccept(std::map<std::string, Serializable, Compare, Allocator>* value, int32_t) { root_ = VisitMapDirectly(value); } // This version applies when Serialize is an ADL free function. template <typename Serializable> void DoAccept(Serializable* serializable, int64_t) { Serialize(this, serializable); } // -------------------------------------------------------------------------- // @name Overloads for the Visit() implementation // This version applies when the type has a Serialize member function. template <typename NVP, typename T> auto DoVisit(const NVP& nvp, const T&, int32_t) -> decltype(nvp.value()->Serialize( static_cast<YamlWriteArchive*>(nullptr))) { return this->VisitSerializable(nvp); } // This version applies when the type has an ADL Serialize function. template <typename NVP, typename T> auto DoVisit(const NVP& nvp, const T&, int32_t) -> decltype(Serialize(static_cast<YamlWriteArchive*>(nullptr), nvp.value())) { return this->VisitSerializable(nvp); } // For std::vector. template <typename NVP, typename T> void DoVisit(const NVP& nvp, const std::vector<T>&, int32_t) { std::vector<T>& data = *nvp.value(); this->VisitArrayLike<T>(nvp.name(), data.size(), data.empty() ? nullptr : &data.at(0)); } // For std::array. template <typename NVP, typename T, std::size_t N> void DoVisit(const NVP& nvp, const std::array<T, N>&, int32_t) { this->VisitArrayLike<T>(nvp.name(), N, nvp.value()->data()); } // For std::map. template <typename NVP, typename K, typename V, typename C, typename A> void DoVisit(const NVP& nvp, const std::map<K, V, C, A>&, int32_t) { this->VisitMap<K, V>(nvp); } // For std::unordered_map. template <typename NVP, typename K, typename V, typename Hash, typename KeyEqual, typename Allocator> void DoVisit(const NVP& nvp, const std::unordered_map<K, V, Hash, KeyEqual, Allocator>&, int32_t) { this->VisitMap<K, V>(nvp); } // For std::optional. template <typename NVP, typename T> void DoVisit(const NVP& nvp, const std::optional<T>&, int32_t) { this->VisitOptional(nvp); } // For std::variant. template <typename NVP, typename... Types> void DoVisit(const NVP& nvp, const std::variant<Types...>&, int32_t) { this->VisitVariant(nvp); } // For Eigen::Matrix or Eigen::Vector. template <typename NVP, typename T, int Rows, int Cols, int Options = 0, int MaxRows = Rows, int MaxCols = Cols> void DoVisit(const NVP& nvp, const Eigen::Matrix<T, Rows, Cols, Options, MaxRows, MaxCols>&, int32_t) { if constexpr (Cols == 1) { auto& value = *nvp.value(); const bool empty = value.size() == 0; this->VisitArrayLike<T>(nvp.name(), value.size(), empty ? nullptr : &value.coeffRef(0)); } else { this->VisitMatrix<T>(nvp.name(), nvp.value()); } } // If no other DoVisit matched, we'll treat the value as a scalar. template <typename NVP, typename T> void DoVisit(const NVP& nvp, const T&, int64_t) { this->VisitScalar(nvp); } // -------------------------------------------------------------------------- // @name Implementations of Visit() once the shape is known // This is used for structs with a Serialize member or free function. template <typename NVP> void VisitSerializable(const NVP& nvp) { YamlWriteArchive sub_archive; using T = typename NVP::value_type; const T& value = *nvp.value(); sub_archive.Accept(value); root_.Add(nvp.name(), std::move(sub_archive.root_)); } // This is used for simple types that can be converted to a string. template <typename NVP> void VisitScalar(const NVP& nvp) { using T = typename NVP::value_type; const T& value = *nvp.value(); if constexpr (std::is_floating_point_v<T>) { std::string value_str = std::isfinite(value) ? fmt_floating_point(value) : std::isnan(value) ? ".nan" : (value > 0) ? ".inf" : "-.inf"; auto scalar = internal::Node::MakeScalar(std::move(value_str)); scalar.SetTag(internal::JsonSchemaTag::kFloat); root_.Add(nvp.name(), std::move(scalar)); return; } auto scalar = internal::Node::MakeScalar(fmt::format("{}", value)); if constexpr (std::is_same_v<T, bool>) { scalar.SetTag(internal::JsonSchemaTag::kBool); } if constexpr (std::is_integral_v<T>) { scalar.SetTag(internal::JsonSchemaTag::kInt); } root_.Add(nvp.name(), std::move(scalar)); } // This is used for std::optional or similar. template <typename NVP> void VisitOptional(const NVP& nvp) { // Bail out if the optional was unset. if (!nvp.value()->has_value()) { // Since we are not going to add ourselves to root_, we should not list // our name in the visit_order either. This undoes the addition of our // name that was performed by the Visit() call on the optional<T> value. this->visit_order_.pop_back(); return; } // Visit the unpacked optional as if it weren't wrapped in optional<>. using T = typename NVP::value_type::value_type; T& storage = nvp.value()->value(); this->Visit(drake::MakeNameValue(nvp.name(), &storage)); // The above call to Visit() for the *unwrapped* value pushed our name onto // the visit_order a second time, duplicating work performed by the Visit() // for the *wrapped* value. We'll undo that duplication now. this->visit_order_.pop_back(); } // This is used for std::variant or similar. template <typename NVP> void VisitVariant(const NVP& nvp) { // Visit the unpacked variant as if it weren't wrapped in variant<>, // setting a YAML type tag iff required. const char* const name = nvp.name(); auto& variant = *nvp.value(); const bool needs_tag = variant.index() > 0; std::visit( [this, name, needs_tag](auto&& unwrapped) { this->Visit(drake::MakeNameValue(name, &unwrapped)); if (needs_tag) { // TODO(jwnimmer-tri) Spell this as remove_cvref_t in C++20. using T = std::decay_t<decltype(unwrapped)>; Node& node = root_.At(name); if constexpr (std::is_same_v<T, bool>) { node.SetTag(JsonSchemaTag::kBool, /* important = */ true); } else if constexpr (std::is_integral_v<T>) { node.SetTag(JsonSchemaTag::kInt, /* important = */ true); } else if constexpr (std::is_floating_point_v<T>) { node.SetTag(JsonSchemaTag::kFloat, /* important = */ true); } else if constexpr (std::is_same_v<T, std::string>) { node.SetTag(JsonSchemaTag::kStr, /* important = */ true); } else { node.SetTag(YamlWriteArchive::GetVariantTag<T>()); } } }, variant); // The above call to this->Visit() for the *unwrapped* value pushed our // name onto the visit_order a second time, duplicating work performed by // the Visit() for the *wrapped* value. We'll undo that duplication now. this->visit_order_.pop_back(); } template <typename T> static std::string GetVariantTag() { const std::string full_name = NiceTypeName::GetFromStorage<T>(); std::string short_name = NiceTypeName::RemoveNamespaces(full_name); auto angle = short_name.find('<'); if (angle != std::string::npos) { // Remove template arguments. short_name.resize(angle); } return short_name; } // This is used for std::array, std::vector, Eigen::Vector, or similar. // @param size is the number of items pointed to by data // @param data is the base pointer to the array to serialize // @tparam T is the element type of the array template <typename T> void VisitArrayLike(const char* name, size_t size, T* data) { auto sub_node = internal::Node::MakeSequence(); for (size_t i = 0; i < size; ++i) { T& item = data[i]; YamlWriteArchive sub_archive; sub_archive.Visit(drake::MakeNameValue("i", &item)); sub_node.Add(std::move(sub_archive.root_.At("i"))); } root_.Add(name, std::move(sub_node)); } template <typename T, int Rows, int Cols, int Options = 0, int MaxRows = Rows, int MaxCols = Cols> void VisitMatrix( const char* name, const Eigen::Matrix<T, Rows, Cols, Options, MaxRows, MaxCols>* matrix) { auto sub_node = internal::Node::MakeSequence(); for (int i = 0; i < matrix->rows(); ++i) { Eigen::Matrix<T, Cols, 1> row = matrix->row(i); YamlWriteArchive sub_archive; sub_archive.Visit(drake::MakeNameValue("i", &row)); sub_node.Add(std::move(sub_archive.root_.At("i"))); } root_.Add(name, std::move(sub_node)); } // This is used for std::map, std::unordered_map, or similar. // The map key must be a string; the value can be anything that serializes. template <typename Key, typename Value, typename NVP> void VisitMap(const NVP& nvp) { // For now, we only allow std::string as the keys of a serialized std::map. // In the future, we could imagine handling any other kind of scalar value // that was convertible to a string (int, double, string_view, etc.) if we // found that useful. However, to remain compatible with JSON semantics, // we should never allow a YAML Sequence or Mapping to be a used as a key. static_assert(std::is_same_v<Key, std::string>, "Map keys must be strings"); auto sub_node = this->VisitMapDirectly(nvp.value()); root_.Add(nvp.name(), std::move(sub_node)); } template <typename Map> internal::Node VisitMapDirectly(Map* value) { DRAKE_DEMAND(value != nullptr); auto result = internal::Node::MakeMapping(); // N.B. For std::unordered_map, this iteration order is non-deterministic, // but because internal::Node::MapData uses sorted keys anyway, it doesn't // matter what order we insert them here. for (auto&& [key, sub_value] : *value) { YamlWriteArchive sub_archive; sub_archive.Visit(drake::MakeNameValue(key.c_str(), &sub_value)); result.Add(key, std::move(sub_archive.root_.At(key))); } return result; } internal::Node root_ = internal::Node::MakeMapping(); std::vector<std::string> visit_order_; }; } // namespace internal } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/yaml/yaml_io_options.h
#pragma once #include <ostream> #include "drake/common/fmt_ostream.h" namespace drake { namespace yaml { /** Configuration for LoadYamlFile() and LoadYamlString() to govern when certain conditions are errors or not. Refer to the member fields for details. */ struct LoadYamlOptions { friend std::ostream& operator<<(std::ostream&, const LoadYamlOptions&); /** Allows yaml Maps to have extra key-value pairs that are not Visited by the Serializable being parsed into. In other words, the Serializable types provide an incomplete schema for the YAML data. This allows for parsing only a subset of the YAML data. */ bool allow_yaml_with_no_cpp{false}; /** Allows Serializables to provide more key-value pairs than are present in the YAML data. In other words, the structs have default values that are left intact unless the YAML data provides a value. */ bool allow_cpp_with_no_yaml{false}; /** If set to true, when parsing a std::map the Archive will merge the YAML data into the destination, instead of replacing the std::map contents entirely. In other words, a visited std::map can have default values that are left intact unless the YAML data provides a value *for that specific key*. */ bool retain_map_defaults{false}; }; } // namespace yaml } // namespace drake // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::yaml::LoadYamlOptions> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/example_structs.h
#pragma once #include <array> #include <map> #include <optional> #include <ostream> #include <string> #include <unordered_map> #include <variant> #include <vector> #include <Eigen/Core> #include <fmt/ostream.h> #include "drake/common/fmt_eigen.h" #include "drake/common/name_value.h" #include "drake/common/string_map.h" #include "drake/common/string_unordered_map.h" namespace drake { namespace yaml { namespace test { // These data structures are the C++ flavor of the Python test classes at // drake/bindings/pydrake/common/test/yaml_typed_test.py // and should be roughly kept in sync with the code in that file. // A value used in the test data below to include a default (placeholder) value // when initializing struct data members. constexpr double kNominalDouble = 1.2345; // These unit tests use a variety of sample Serializable structs, showing what // a user may write for their own schemas. struct DoubleStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } double value = kNominalDouble; }; // This is used only for EXPECT_EQ, not by any YAML operations. bool operator==(const DoubleStruct& a, const DoubleStruct& b) { return a.value == b.value; } struct StringStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } std::string value = "kNominalDouble"; }; // This is used only for EXPECT_EQ, not by any YAML operations. bool operator==(const StringStruct& a, const StringStruct& b) { return a.value == b.value; } struct AllScalarsStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(some_bool)); a->Visit(DRAKE_NVP(some_float)); a->Visit(DRAKE_NVP(some_double)); a->Visit(DRAKE_NVP(some_int32)); a->Visit(DRAKE_NVP(some_uint32)); a->Visit(DRAKE_NVP(some_int64)); a->Visit(DRAKE_NVP(some_uint64)); a->Visit(DRAKE_NVP(some_string)); } bool some_bool = false; double some_double = kNominalDouble; float some_float = static_cast<float>(kNominalDouble); int32_t some_int32 = 12; uint32_t some_uint32 = 12; int64_t some_int64 = 14; uint64_t some_uint64 = 15; std::string some_string = "kNominalString"; }; struct ArrayStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } ArrayStruct() { value.fill(kNominalDouble); } explicit ArrayStruct(const std::array<double, 3>& value_in) : value(value_in) {} std::array<double, 3> value; }; struct VectorStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } VectorStruct() { value.resize(1, kNominalDouble); } explicit VectorStruct(const std::vector<double>& value_in) : value(value_in) {} std::vector<double> value; }; struct NonPodVectorStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } NonPodVectorStruct() { value.resize(1, {"kNominalDouble"}); } std::vector<StringStruct> value; }; struct MapStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } MapStruct() { value["kNominalDouble"] = kNominalDouble; } explicit MapStruct(const std::map<std::string, double>& value_in) : value(value_in.begin(), value_in.end()) {} string_map<double> value; }; struct UnorderedMapStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } UnorderedMapStruct() { value["kNominalDouble"] = kNominalDouble; } explicit UnorderedMapStruct( const std::unordered_map<std::string, double>& value_in) : value(value_in.begin(), value_in.end()) {} string_unordered_map<double> value; }; struct OptionalStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } OptionalStruct() { value = kNominalDouble; } explicit OptionalStruct(const double value_in) : OptionalStruct(std::optional<double>(value_in)) {} explicit OptionalStruct(const std::optional<double>& value_in) : value(value_in) {} std::optional<double> value; }; struct OptionalStructNoDefault { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } OptionalStructNoDefault() : value(std::nullopt) {} explicit OptionalStructNoDefault(const double value_in) : OptionalStructNoDefault(std::optional<double>(value_in)) {} explicit OptionalStructNoDefault(const std::optional<double>& value_in) : value(value_in) {} std::optional<double> value; }; template <int Rows, int Cols, int MaxRows = Rows, int MaxCols = Cols> struct EigenStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } EigenStruct() { if ((value.size() == 0) && (Rows != 0) && (Cols != 0)) { value.resize(1, 1); } value.setConstant(kNominalDouble); } explicit EigenStruct(const Eigen::Matrix<double, Rows, Cols>& value_in) : value(value_in) {} // We'd like to test a non-default value for Options, but it's awkward to have // to specify one as part of our template arguments. Instead, we'll use our // variation in values of existing template arguments to establish variation // of Options as well. The particular choice of Rows and DontAlign here is // irrelevant -- we just need any kind of variation. static constexpr int Options = (MaxRows != Rows) ? Eigen::DontAlign : 0; Eigen::Matrix<double, Rows, Cols, Options, MaxRows, MaxCols> value; }; // This is used only for EXPECT_EQ, not by any YAML operations. template <int Rows, int Cols> bool operator==(const EigenStruct<Rows, Cols>& a, const EigenStruct<Rows, Cols>& b) { return a.value == b.value; } using EigenVecStruct = EigenStruct<Eigen::Dynamic, 1>; using EigenVec3Struct = EigenStruct<3, 1>; using EigenVecUpTo3Struct = EigenStruct<Eigen::Dynamic, 1, 3, 1>; using EigenMatrixStruct = EigenStruct<Eigen::Dynamic, Eigen::Dynamic>; using EigenMatrix34Struct = EigenStruct<3, 4>; using EigenMatrix00Struct = EigenStruct<0, 0>; using EigenMatrixUpTo6Struct = EigenStruct<Eigen::Dynamic, Eigen::Dynamic, 6, 6>; using Variant4 = std::variant<std::string, double, DoubleStruct, EigenVecStruct>; std::ostream& operator<<(std::ostream& os, const Variant4& value) { if (value.index() == 0) { fmt::print(os, "std::string{{{}}}", std::get<0>(value)); } else if (value.index() == 1) { fmt::print(os, "double{{{}}}", std::get<1>(value)); } else if (value.index() == 2) { fmt::print(os, "DoubleStruct{{{}}}", std::get<2>(value).value); } else { fmt::print(os, "EigenVecStruct{{{}}}", fmt_eigen(std::get<3>(value).value)); } return os; } struct VariantStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } VariantStruct() { value = kNominalDouble; } explicit VariantStruct(const Variant4& value_in) : value(value_in) {} Variant4 value; }; struct VariantWrappingStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(inner)); } VariantStruct inner; }; using PrimitiveVariant = std::variant<std::vector<double>, bool, int, double, std::string>; struct PrimitiveVariantStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } PrimitiveVariant value = kNominalDouble; }; struct OuterStruct { struct InnerStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(inner_value)); } double inner_value = kNominalDouble; }; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(outer_value)); a->Visit(DRAKE_NVP(inner_struct)); } double outer_value = kNominalDouble; InnerStruct inner_struct; }; struct OuterStructOpposite { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(inner_struct)); a->Visit(DRAKE_NVP(outer_value)); } // N.B. The opposite member order of OuterStruct. OuterStruct::InnerStruct inner_struct; double outer_value = kNominalDouble; }; struct OuterWithBlankInner { struct Blank { template <typename Archive> void Serialize(Archive* a) {} }; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(outer_value)); a->Visit(DRAKE_NVP(inner_struct)); } double outer_value = kNominalDouble; Blank inner_struct; }; struct BigMapStruct { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } BigMapStruct() { value["foo"].outer_value = 1.0; value["foo"].inner_struct.inner_value = 2.0; } std::map<std::string, OuterStruct> value; }; } // namespace test } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_write_archive_test.cc
#include "drake/common/yaml/yaml_write_archive.h" #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/name_value.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/yaml/test/example_structs.h" // This test suite is the C++ flavor of the Python test suite at // drake/bindings/pydrake/common/test/yaml_typed_test.py // and should be roughly kept in sync with the test cases in that file. namespace drake { namespace yaml { namespace test { namespace { using internal::YamlWriteArchive; // A test fixture with common helpers. class YamlWriteArchiveTest : public ::testing::Test { public: template <typename Serializable> static std::string Save(const Serializable& data, const std::string& root_name) { YamlWriteArchive archive; archive.Accept(data); return archive.EmitString(root_name); } template <typename Serializable> static std::string Save(const Serializable& data) { return Save(data, "doc"); } static std::string WrapDoc(const std::string& value) { return "doc:\n value: " + value + "\n"; } }; TEST_F(YamlWriteArchiveTest, Double) { const auto test = [](const double value, const std::string& expected) { const DoubleStruct x{value}; EXPECT_EQ(Save(x), WrapDoc(expected)); }; test(0.0, "0.0"); test(1.0, "1.0"); test(-1.0, "-1.0"); test(0.009, "0.009"); test(1.2, "1.2"); test(-1.2, "-1.2"); test(5.6e+16, "5.6e+16"); test(5.6e-12, "5.6e-12"); test(-5.6e+16, "-5.6e+16"); test(-5.6e-12, "-5.6e-12"); // See https://yaml.org/spec/1.2.2/#10214-floating-point for the specs. test(std::numeric_limits<double>::quiet_NaN(), ".nan"); test(std::numeric_limits<double>::infinity(), ".inf"); test(-std::numeric_limits<double>::infinity(), "-.inf"); } TEST_F(YamlWriteArchiveTest, String) { const auto test = [](const std::string& value, const std::string& expected) { const StringStruct x{value}; EXPECT_EQ(Save(x), WrapDoc(expected)); }; test("a", "a"); test("1", "1"); } TEST_F(YamlWriteArchiveTest, StdArray) { const auto test = [](const std::array<double, 3>& value, const std::string& expected) { const ArrayStruct x{value}; EXPECT_EQ(Save(x), expected); }; test({1.0, 2.0, 3.0}, R"""(doc: value: [1.0, 2.0, 3.0] )"""); } TEST_F(YamlWriteArchiveTest, StdVector) { const auto test = [](const std::vector<double>& value, const std::string& expected) { const VectorStruct x{value}; EXPECT_EQ(Save(x), expected); }; // When the vector items are simple YAML scalars, we should use // "flow" style, where they all appear on a single line. test({}, R"""(doc: value: [] )"""); test({1.0, 2.0, 3.0}, R"""(doc: value: [1.0, 2.0, 3.0] )"""); // When the vector items are not simple scalars, we should use // "block" style, where each gets its own line(s). NonPodVectorStruct x; x.value = { {.value = "foo"}, {.value = "bar"}, }; EXPECT_EQ(Save(x), R"""(doc: value: - value: foo - value: bar )"""); } TEST_F(YamlWriteArchiveTest, StdMap) { const auto test = [](const std::map<std::string, double>& value, const std::string& expected) { const MapStruct x{value}; EXPECT_EQ(Save(x), expected); }; test({}, R"""(doc: value: {} )"""); test({{"foo", 0.0}}, R"""(doc: value: foo: 0.0 )"""); test({{"foo", 0.0}, {"bar", 1.0}}, R"""(doc: value: bar: 1.0 foo: 0.0 )"""); } TEST_F(YamlWriteArchiveTest, StdUnorderedMap) { const auto test = [](const std::unordered_map<std::string, double>& value, const std::string& expected) { const UnorderedMapStruct x{value}; EXPECT_EQ(Save(x), expected); }; // The YamlWriteArchive API promises that the output must be deterministic. // Here, we test a stronger condition that it's always sorted. (If in the // future we decide to use a different order, we can update here to match.) const std::unordered_map<std::string, double> value{ // Use many values to increase the chance that we'll detect // implementations that fail to sort. {"gulf", 6.0}, {"fox", 5.0}, {"echo", 4.0}, {"delta", 3.0}, {"charlie", 2.0}, {"bravo", 1.0}, {"alpha", 0.0}, }; test(value, R"""(doc: value: alpha: 0.0 bravo: 1.0 charlie: 2.0 delta: 3.0 echo: 4.0 fox: 5.0 gulf: 6.0 )"""); } TEST_F(YamlWriteArchiveTest, StdMapDirectly) { const auto test = [](const std::map<std::string, double>& value, const std::string& expected) { EXPECT_EQ(Save(value), expected); }; test({}, R"""(doc: )"""); test({{"foo", 0.0}}, R"""(doc: foo: 0.0 )"""); test({{"foo", 0.0}, {"bar", 1.0}}, R"""(doc: bar: 1.0 foo: 0.0 )"""); } TEST_F(YamlWriteArchiveTest, Optional) { const auto test = [](const std::optional<double>& value, const std::string& expected) { const OptionalStruct x{value}; EXPECT_EQ(Save(x), expected); }; test(std::nullopt, "doc:\n"); test(1.0, "doc:\n value: 1.0\n"); } TEST_F(YamlWriteArchiveTest, Variant) { const auto test = [](const Variant4& value, const std::string& expected) { const VariantStruct x{value}; EXPECT_EQ(Save(x), WrapDoc(expected)); }; test(Variant4(std::string()), "\"\""); test(Variant4(std::string("foo")), "foo"); test(Variant4(1.0), "!!float 1.0"); test(Variant4(DoubleStruct{1.0}), "!DoubleStruct\n value: 1.0"); test(Variant4(EigenVecStruct{Eigen::Vector2d(1.0, 2.0)}), "!EigenStruct\n value: [1.0, 2.0]"); } TEST_F(YamlWriteArchiveTest, PrimitiveVariant) { const auto test = [](const PrimitiveVariant& value, const std::string& expected) { const PrimitiveVariantStruct x{value}; EXPECT_EQ(Save(x), WrapDoc(expected)); }; test(std::vector<double>{1.0, 2.0}, "[1.0, 2.0]"); test(true, "!!bool true"); test(10, "!!int 10"); test(1.0, "!!float 1.0"); test(std::string("foo"), "!!str foo"); } TEST_F(YamlWriteArchiveTest, EigenVector) { const auto test = [](const Eigen::VectorXd& value, const std::string& expected) { const EigenVecStruct x{value}; EXPECT_EQ(Save(x), expected); const EigenVec3Struct x3{value}; EXPECT_EQ(Save(x3), expected); }; test(Eigen::Vector3d(1.0, 2.0, 3.0), R"""(doc: value: [1.0, 2.0, 3.0] )"""); } TEST_F(YamlWriteArchiveTest, EigenVectorX) { const auto test = [](const Eigen::VectorXd& value, const std::string& expected) { const EigenVecStruct x{value}; EXPECT_EQ(Save(x), expected); }; test(Eigen::VectorXd(), R"""(doc: value: [] )"""); test(Eigen::Matrix<double, 1, 1>(1.0), R"""(doc: value: [1.0] )"""); } TEST_F(YamlWriteArchiveTest, EigenMatrix) { using Matrix34d = Eigen::Matrix<double, 3, 4>; const auto test = [](const Matrix34d& value, const std::string& expected) { const EigenMatrixStruct x{value}; EXPECT_EQ(Save(x), expected); const EigenMatrix34Struct x3{value}; EXPECT_EQ(Save(x3), expected); }; test((Matrix34d{} << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).finished(), R"""(doc: value: - [0.0, 1.0, 2.0, 3.0] - [4.0, 5.0, 6.0, 7.0] - [8.0, 9.0, 10.0, 11.0] )"""); } TEST_F(YamlWriteArchiveTest, EigenMatrixUpTo6) { using Matrix34d = Eigen::Matrix<double, 3, 4>; const auto test = [](const Matrix34d& value, const std::string& expected) { const EigenMatrixUpTo6Struct x{value}; EXPECT_EQ(Save(x), expected); }; test((Matrix34d{} << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).finished(), R"""(doc: value: - [0.0, 1.0, 2.0, 3.0] - [4.0, 5.0, 6.0, 7.0] - [8.0, 9.0, 10.0, 11.0] )"""); } TEST_F(YamlWriteArchiveTest, EigenMatrix00) { const auto test = [](const std::string& expected) { const Eigen::MatrixXd empty; const EigenMatrixStruct x{empty}; EXPECT_EQ(Save(x), expected); const EigenMatrix00Struct x00; EXPECT_EQ(Save(x00), expected); }; test(R"""(doc: value: [] )"""); } TEST_F(YamlWriteArchiveTest, Nested) { OuterStruct x; x.inner_struct.inner_value = 2.0; x.outer_value = 1.0; const std::string saved = Save(x); const std::string expected = R"""(doc: outer_value: 1.0 inner_struct: inner_value: 2.0 )"""; EXPECT_EQ(saved, expected); } TEST_F(YamlWriteArchiveTest, BlankInner) { OuterWithBlankInner x; x.outer_value = 1.0; const std::string saved = Save(x); const std::string expected = R"""(doc: outer_value: 1.0 inner_struct: {} )"""; EXPECT_EQ(saved, expected); } // Test the Emitter function given different key names and a provided // serializable content. TEST_F(YamlWriteArchiveTest, EmitterWithProvidedSerializable) { const auto test = [](const std::string& root_name, const std::string& expected) { const DoubleStruct x{1.0}; EXPECT_EQ(Save(x, root_name), expected); }; // Test default key name. const std::string expected_default_root_name = R"""(root: value: 1.0 )"""; test("root", expected_default_root_name); // Test empty key name. const std::string expected_empty_root_name = R"""(value: 1.0 )"""; test("", expected_empty_root_name); } // Test the Emitter function given different key names. The serializable // content is empty. TEST_F(YamlWriteArchiveTest, EmitterNoProvidedSerializable) { const auto test = [](const std::string& root_name, const std::string& expected) { YamlWriteArchive archive; EXPECT_EQ(archive.EmitString(root_name), expected); }; // Test non-empty key name will return a node with empty value. const std::string expected_default_root_name = R"""(root: )"""; test("root", expected_default_root_name); // Test empty key name will yield an empty map. const std::string expected_empty_root_name = R"""({} )"""; test("", expected_empty_root_name); } } // namespace } // namespace test } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_io_test.cc
#include "drake/common/yaml/yaml_io.h" #include <fstream> #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/common/temp_directory.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/yaml/test/example_structs.h" // This unit test only covers the basics of the helper functions in yaml_io, // as well as (indirectly) the helper functions on YamlReadArchive related // to file document loading (LoadFileAsNode, LoadStringAsNode). // // The exact details of YAML/C++ parsing, matching, and error messages are // tested in more focused unit tests of the Archive classes. namespace drake { namespace yaml { namespace test { namespace { GTEST_TEST(YamlIoTest, LoadString) { const std::string data = R"""( value: some_value )"""; const auto result = LoadYamlString<StringStruct>(data); EXPECT_EQ(result.value, "some_value"); } GTEST_TEST(YamlIoTest, LoadStringChildName) { const std::string data = R"""( some_child_name: value: some_value )"""; const std::string child_name = "some_child_name"; const auto result = LoadYamlString<StringStruct>(data, child_name); EXPECT_EQ(result.value, "some_value"); // When the requested child_name does not exist, that's an error. DRAKE_EXPECT_THROWS_MESSAGE( LoadYamlString<StringStruct>(data, "wrong_child_name"), ".* no such .* map entry .*wrong_child_name.*"); } GTEST_TEST(YamlIoTest, LoadStringDefaults) { const std::string data = R"""( value: some_key: 1.0 )"""; const std::optional<std::string> no_child_name; const MapStruct defaults; // The defaults contains kNominalDouble already. const auto result = LoadYamlString<MapStruct>(data, no_child_name, defaults); EXPECT_EQ(result.value.at("some_key"), 1.0); EXPECT_EQ(result.value.at("kNominalDouble"), test::kNominalDouble); EXPECT_EQ(result.value.size(), 2); } GTEST_TEST(YamlIoTest, LoadStringOptions) { const std::string data = R"""( value: some_value extra_junk: will_be_ignored )"""; const std::optional<std::string> no_child_name; const std::optional<StringStruct> no_defaults; LoadYamlOptions options; options.allow_yaml_with_no_cpp = true; const auto result = LoadYamlString<StringStruct>(data, no_child_name, no_defaults, options); EXPECT_EQ(result.value, "some_value"); // Cross-check that the options actually were important. DRAKE_EXPECT_THROWS_MESSAGE( LoadYamlString<StringStruct>(data, no_child_name, no_defaults, {/* no options */}), ".*extra_junk.*"); } GTEST_TEST(YamlIoTest, LoadStringDefaultsAndOptions) { const std::string data = R"""( value: some_key: 1.0 extra_junk: will_be_ignored: 2.0 )"""; const std::optional<std::string> no_child_name; const MapStruct defaults; // The defaults contains kNominalDouble already. LoadYamlOptions options; options.allow_yaml_with_no_cpp = true; const auto result = LoadYamlString<MapStruct>(data, no_child_name, defaults, options); // When user options are provided, the implicit options that would otherwise // be used for defaults parsing are not in effect; thus, retain_map_defaults // will be false and kNominalDouble is not present in the result. EXPECT_EQ(result.value.at("some_key"), 1.0); EXPECT_EQ(result.value.size(), 1); } GTEST_TEST(YamlIoTest, LoadFile) { const std::string filename = FindResourceOrThrow("drake/common/yaml/test/yaml_io_test_input_1.yaml"); const auto result = LoadYamlFile<StringStruct>(filename); EXPECT_EQ(result.value, "some_value_1"); } GTEST_TEST(YamlIoTest, LoadFileChildName) { const std::string filename = FindResourceOrThrow("drake/common/yaml/test/yaml_io_test_input_2.yaml"); const std::string child_name = "some_string_struct"; const auto result = LoadYamlFile<StringStruct>(filename, child_name); EXPECT_EQ(result.value, "some_value_2"); } GTEST_TEST(YamlIoTest, LoadFileChildNameBad) { const std::string filename = FindResourceOrThrow("drake/common/yaml/test/yaml_io_test_input_2.yaml"); const std::string child_name = "wrong_child_name"; DRAKE_EXPECT_THROWS_MESSAGE( LoadYamlFile<StringStruct>(filename, child_name), ".*yaml_io_test_input_2.yaml.* no such .*wrong_child_name.*"); } GTEST_TEST(YamlIoTest, LoadFileSchemaBad) { const std::string filename = FindResourceOrThrow("drake/common/yaml/test/yaml_io_test_input_2.yaml"); using WrongSchema = std::map<std::string, DoubleStruct>; DRAKE_EXPECT_THROWS_MESSAGE( LoadYamlFile<WrongSchema>(filename), ".*/test/yaml_io_test_input_2.yaml:2:3:" " YAML node of type Mapping .*" " could not parse double value entry for double value.*"); } // Because we know that the LoadFile and LoadString implementations share a // helper function that implements handling of defaults and options, these // specific variations of File-based test cases are not needed because the // LoadString cases already covered them: // // - LoadFileDefaults // - LoadFileOptions // - LoadFileDefaultsAndOptions GTEST_TEST(YamlIoTest, SaveString) { const StringStruct data{.value = "save_string"}; const auto result = SaveYamlString(data); EXPECT_EQ(result, "value: save_string\n"); } GTEST_TEST(YamlIoTest, SaveStringChild) { const std::string child_name = "some_child"; const StringStruct data{.value = "save_string_child"}; const auto result = SaveYamlString(data, child_name); EXPECT_EQ(result, "some_child:\n value: save_string_child\n"); } GTEST_TEST(YamlIoTest, SaveStringDefaults) { const std::optional<std::string> no_child_name; const MapStruct defaults; MapStruct data; // The data.value contains kNominalDouble already. data.value.insert({"save_string_defaults", 1.0}); ASSERT_EQ(data.value.size(), 2); const auto result = SaveYamlString(data, no_child_name, {defaults}); // Only the non-default map entry is saved. EXPECT_EQ(result, "value:\n save_string_defaults: 1.0\n"); } // The implementation of SaveYamlFile calls SaveYamlString, so we only need // to lightly test it (specifically the file-writing function). We'll do // one test case with minimal arguments (just the filename) and one test // case with all arguments (to confirm that they are all forwarded). GTEST_TEST(YamlIoTest, SaveFile) { const std::string filename = temp_directory() + "/SaveFile1.yaml"; const StringStruct data{.value = "save_file_1"}; SaveYamlFile(filename, data); const auto result = ReadFileOrThrow(filename); EXPECT_EQ(result, "value: save_file_1\n"); } GTEST_TEST(YamlIoTest, SaveFileAllArgs) { const std::string filename = temp_directory() + "/SaveFile4.yaml"; const std::string child_name = "some_child"; const MapStruct defaults; MapStruct data; // The data.value contains kNominalDouble already. data.value.insert({"save_file_4", 1.0}); ASSERT_EQ(data.value.size(), 2); SaveYamlFile(filename, data, child_name, {defaults}); const auto result = ReadFileOrThrow(filename); EXPECT_EQ(result, "some_child:\n value:\n save_file_4: 1.0\n"); } GTEST_TEST(YamlIoTest, SaveFileBad) { const std::string filename = temp_directory() + "/no_such_dir/file.yaml"; DRAKE_EXPECT_THROWS_MESSAGE(SaveYamlFile(filename, StringStruct{}), ".* could not open .*/no_such_dir/.*"); } } // namespace } // namespace test } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_write_archive_defaults_test.cc
// This file tests the yaml_write_archive.h method EraseMatchingMaps(), which // is used to write out YAML details without repeating the default values. #include <cmath> #include <vector> #include <Eigen/Core> #include <gtest/gtest.h> #include "drake/common/yaml/test/example_structs.h" #include "drake/common/yaml/yaml_write_archive.h" // This test suite is the C++ flavor of the Python test suite at // drake/bindings/pydrake/common/test/yaml_typed_test.py // and should be roughly kept in sync with the test cases in that file. namespace drake { namespace yaml { namespace test { namespace { using internal::YamlWriteArchive; // A test fixture with common helpers. class YamlWriteArchiveDefaultsTest : public ::testing::Test { public: template <typename DataSerializable, typename DefaultsSerializable> static std::string SaveDataWithoutDefaults( const DataSerializable& data, const DefaultsSerializable& defaults, const std::string& key_name = "doc") { YamlWriteArchive defaults_archive; defaults_archive.Accept(defaults); YamlWriteArchive archive; archive.Accept(data); archive.EraseMatchingMaps(defaults_archive); return archive.EmitString(key_name); } }; // Shows the typical use -- that only the novel data is output. // The inner_struct is the same for both x and y, so is not output. TEST_F(YamlWriteArchiveDefaultsTest, BasicExample1) { OuterStruct defaults; defaults.outer_value = 1.0; defaults.inner_struct.inner_value = 2.0; OuterStruct data = defaults; data.outer_value = 3.0; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: outer_value: 3.0 )"""); } // Shows the typical use -- that only the novel data is output. // The outer_value is the same for both x and y, so is not output. TEST_F(YamlWriteArchiveDefaultsTest, BasicExample2) { OuterStruct defaults; defaults.outer_value = 1.0; defaults.inner_struct.inner_value = 2.0; OuterStruct data = defaults; data.inner_struct.inner_value = 3.0; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: inner_struct: inner_value: 3.0 )"""); } // Shows the typical use -- emit the content with or without providing a // root_name. TEST_F(YamlWriteArchiveDefaultsTest, BasicExample3) { OuterStruct defaults; defaults.outer_value = 1.0; OuterStruct data; data.outer_value = 3.0; data.inner_struct.inner_value = defaults.inner_struct.inner_value; // Emit using the default "doc" root name. EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: outer_value: 3.0 )"""); // Emit using an empty root name. EXPECT_EQ(SaveDataWithoutDefaults(data, defaults, ""), R"""(outer_value: 3.0 )"""); // Emit with an empty root name without defaults. EXPECT_EQ(SaveDataWithoutDefaults(defaults, defaults, ""), R"""({} )"""); } // Same as the BasicExample1 from above, except that the map order of the // defaults vs data differs. The defaults still take effect. TEST_F(YamlWriteArchiveDefaultsTest, DifferentMapOrder1) { OuterStructOpposite defaults; defaults.inner_struct.inner_value = 1.0; defaults.outer_value = 2.0; OuterStruct data; data.outer_value = 3.0; data.inner_struct.inner_value = defaults.inner_struct.inner_value; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: outer_value: 3.0 )"""); } // Same as the BasicExample2 from above, except that the map order of the // defaults vs data differs. The defaults still take effect. TEST_F(YamlWriteArchiveDefaultsTest, DifferentMapOrder2) { OuterStructOpposite defaults; defaults.inner_struct.inner_value = 1.0; defaults.outer_value = 2.0; OuterStruct data; data.outer_value = defaults.outer_value; data.inner_struct.inner_value = 3.0; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: inner_struct: inner_value: 3.0 )"""); } // YAML nulls are handled reasonably, without throwing. TEST_F(YamlWriteArchiveDefaultsTest, Nulls) { OptionalStruct data; data.value = std::nullopt; OptionalStruct defaults = data; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: )"""); } // Arrays differing in their values are not erased. TEST_F(YamlWriteArchiveDefaultsTest, DifferentArrays) { ArrayStruct data; data.value = {1.0, 2.0, 3.0}; ArrayStruct defaults; defaults.value = {0.0, 0.0, 0.0}; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: value: [1.0, 2.0, 3.0] )"""); } // Vectors differing in size (but sharing a prefix) are not erased. TEST_F(YamlWriteArchiveDefaultsTest, DifferentSizeVectors) { VectorStruct data; data.value = {1.0, 2.0, 3.0}; VectorStruct defaults; defaults.value = {1.0, 2.0}; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: value: [1.0, 2.0, 3.0] )"""); } // Variants differing by tag are not erased. TEST_F(YamlWriteArchiveDefaultsTest, DifferentVariantTag) { VariantStruct data; data.value = DoubleStruct{1.0}; VariantStruct defaults; defaults.value = EigenVecStruct(); EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: value: !DoubleStruct value: 1.0 )"""); } // Maps differing in key only (same value) are not erased. TEST_F(YamlWriteArchiveDefaultsTest, DifferentMapKeys) { MapStruct data; data.value["a"] = 1.0; MapStruct defaults; defaults.value["b"] = 1.0; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: value: a: 1.0 )"""); } // Maps differing in value only (same key) are not erased. TEST_F(YamlWriteArchiveDefaultsTest, DifferentMapValues) { MapStruct data; data.value["a"] = 1.0; MapStruct defaults; defaults.value["a"] = 2.0; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: value: a: 1.0 )"""); } // In the unusual case that the user provided two different schemas to // subtract, we notice the discrepancy without throwing any exceptions. // This test case serves to help achieve code coverage; we do not intend // for users to necessarily depend on this behavior. // Here, we do DoubleStruct - ArrayStruct. TEST_F(YamlWriteArchiveDefaultsTest, DifferentSchemas) { DoubleStruct data; data.value = 1.0; ArrayStruct defaults; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: value: 1.0 )"""); } // In the unusual case that the user provided two different (but similar) // schemas to subtract, we notice the discrepancy without throwing any // exceptions. This test case serves to help achieve code coverage; we do not // intend for users to necessarily depend on this behavior. Here, we do // OuterStruct - OuterWithBlankInner. TEST_F(YamlWriteArchiveDefaultsTest, DifferentInnerSchemas) { OuterStruct data; data.outer_value = 1.0; data.inner_struct.inner_value = 2.0; OuterWithBlankInner defaults; EXPECT_EQ(SaveDataWithoutDefaults(data, defaults), R"""(doc: outer_value: 1.0 inner_struct: inner_value: 2.0 )"""); } } // namespace } // namespace test } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_read_archive_test.cc
#include "drake/common/yaml/yaml_read_archive.h" #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/name_value.h" #include "drake/common/nice_type_name.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/yaml/test/example_structs.h" // This test suite is the C++ flavor of the Python test suite at // drake/bindings/pydrake/common/test/yaml_typed_test.py // and should be roughly kept in sync with the test cases in that file. // TODO(jwnimmer-tri) All of these regexps would be better off using the // std::regex::basic grammar, where () and {} are not special characters. namespace drake { namespace yaml { namespace test { namespace { using internal::YamlReadArchive; // TODO(jwnimmer-tri) Add a test case for reading NonPodVectorStruct. // TODO(jwnimmer-tri) Add a test case for reading OuterWithBlankInner. // TODO(jwnimmer-tri) Add a test case for reading StringStruct. // TODO(jwnimmer-tri) Add a test case for reading UnorderedMapStruct. // A test fixture with common helpers. class YamlReadArchiveTest : public ::testing::TestWithParam<LoadYamlOptions> { public: // Loads a single "doc: { ... }" map from `contents` and returns the nested // map (i.e., just the "{ ... }" part, not the "doc" part). It is an error // for the "{ ... }" part not to be a map node. static internal::Node Load(std::string contents) { while (contents.size() > 0 && contents.at(0) == '\n') { // Strip off leading newlines. contents.erase(0, 1); } const internal::Node loaded = YamlReadArchive::LoadStringAsNode(contents, std::nullopt); if (!loaded.IsMapping()) { throw std::logic_error("Bad contents parse " + contents); } const string_map<internal::Node>& mapping = loaded.GetMapping(); if (!mapping.contains("doc")) { throw std::logic_error("Missing doc parse " + contents); } const internal::Node doc = mapping.at("doc"); if (!doc.IsMapping()) { throw std::logic_error("Bad doc parse " + contents); } return doc; } // Loads a single "{ value: something }" map node. If the argument is the // empty string, the result is a map from "value" to Null (not an empty map, // nor Null itself, etc.) static internal::Node LoadSingleValue(const std::string& value) { return Load("doc:\n value: " + value + "\n"); } // Parses root into a Serializable and returns the result of the parse. // Any exceptions raised are reported as errors. template <typename Serializable> static Serializable AcceptNoThrow(const internal::Node& root) { SCOPED_TRACE("for type " + NiceTypeName::Get<Serializable>()); Serializable result{}; bool raised = false; std::string what; try { YamlReadArchive(root, GetParam()).Accept(&result); } catch (const std::exception& e) { raised = true; what = e.what(); } EXPECT_FALSE(raised); EXPECT_EQ(what, ""); return result; } // Parses root into a Serializable and discards the result. // This is usually used to check that an exception is raised. template <typename Serializable> static void AcceptIntoDummy(const internal::Node& root) { Serializable dummy{}; YamlReadArchive(root, GetParam()).Accept(&dummy); } // Parses root into a Serializable and returns the result of the parse. // If allow_cpp_with_no_yaml is set, then any exceptions are errors. // If allow_cpp_with_no_yaml is not set, then lack of exception is an error. template <typename Serializable> static Serializable AcceptEmptyDoc() { SCOPED_TRACE("for type " + NiceTypeName::Get<Serializable>()); const internal::Node root = Load("doc: {}"); Serializable result{}; bool raised = false; std::string what; try { YamlReadArchive(root, GetParam()).Accept(&result); } catch (const std::exception& e) { raised = true; what = e.what(); } if (GetParam().allow_cpp_with_no_yaml) { EXPECT_FALSE(raised); EXPECT_EQ(what, ""); } else { EXPECT_TRUE(raised); EXPECT_THAT(what, testing::MatchesRegex(".*missing entry for [^ ]* value.*")); } return result; } }; TEST_P(YamlReadArchiveTest, Double) { const auto test = [](const std::string& value, double expected) { const auto& x = AcceptNoThrow<DoubleStruct>(LoadSingleValue(value)); EXPECT_EQ(x.value, expected); }; test("0", 0.0); test("1", 1.0); test("-1", -1.0); test("0.0", 0.0); test("1.2", 1.2); test("-1.2", -1.2); test("3e4", 3e4); test("3e-4", 3e-4); test("5.6e7", 5.6e7); test("5.6e-7", 5.6e-7); test("-5.6e7", -5.6e7); test("-5.6e-7", -5.6e-7); test("3E4", 3e4); test("3E-4", 3e-4); test("5.6E7", 5.6e7); test("5.6E-7", 5.6e-7); test("-5.6E7", -5.6e7); test("-5.6E-7", -5.6e-7); } TEST_P(YamlReadArchiveTest, DoubleMissing) { const auto& x = AcceptEmptyDoc<DoubleStruct>(); EXPECT_EQ(x.value, kNominalDouble); } TEST_P(YamlReadArchiveTest, AllScalars) { const std::string doc = R"""( doc: some_bool: true some_double: 100.0 some_float: 101.0 some_int32: 102 some_uint32: 103 some_int64: 104 some_uint64: 105 some_string: foo )"""; const auto& x = AcceptNoThrow<AllScalarsStruct>(Load(doc)); EXPECT_EQ(x.some_bool, true); EXPECT_EQ(x.some_double, 100.0); EXPECT_EQ(x.some_float, 101.0); EXPECT_EQ(x.some_int32, 102); EXPECT_EQ(x.some_uint32, 103); EXPECT_EQ(x.some_int64, 104); EXPECT_EQ(x.some_uint64, 105); EXPECT_EQ(x.some_string, "foo"); } TEST_P(YamlReadArchiveTest, StdArray) { const auto test = [](const std::string& value, const std::array<double, 3>& expected) { const auto& x = AcceptNoThrow<ArrayStruct>(LoadSingleValue(value)); EXPECT_EQ(x.value, expected); }; test("[1.0, 2.0, 3.0]", {1.0, 2.0, 3.0}); } TEST_P(YamlReadArchiveTest, StdArrayMissing) { const auto& x = AcceptEmptyDoc<ArrayStruct>(); EXPECT_EQ(x.value[0], kNominalDouble); EXPECT_EQ(x.value[1], kNominalDouble); EXPECT_EQ(x.value[2], kNominalDouble); } TEST_P(YamlReadArchiveTest, StdVector) { const auto test = [](const std::string& value, const std::vector<double>& expected) { const auto& x = AcceptNoThrow<VectorStruct>(LoadSingleValue(value)); EXPECT_EQ(x.value, expected); }; test("[1.0, 2.0, 3.0]", {1.0, 2.0, 3.0}); } TEST_P(YamlReadArchiveTest, StdVectorMissing) { const auto& x = AcceptEmptyDoc<VectorStruct>(); ASSERT_EQ(x.value.size(), 1); EXPECT_EQ(x.value[0], kNominalDouble); } TEST_P(YamlReadArchiveTest, StdMap) { const auto test = [](const std::string& doc, const std::map<std::string, double>& expected) { const auto& x = AcceptNoThrow<MapStruct>(Load(doc)); string_map<double> adjusted_expected{expected.begin(), expected.end()}; if (GetParam().retain_map_defaults) { adjusted_expected["kNominalDouble"] = kNominalDouble; } EXPECT_EQ(x.value, adjusted_expected) << doc; }; test("doc:\n value:\n foo: 0.0\n bar: 1.0\n", {{"foo", 0.0}, {"bar", 1.0}}); } TEST_P(YamlReadArchiveTest, BigStdMapAppend) { if (!GetParam().allow_cpp_with_no_yaml) { // The parser would raise an uninteresting exception in this case. return; } std::string doc = R"""( doc: value: bar: outer_value: 3.0 inner_struct: inner_value: 4.0 )"""; const auto& x = AcceptNoThrow<BigMapStruct>(Load(doc)); if (GetParam().retain_map_defaults) { EXPECT_EQ(x.value.size(), 2); EXPECT_EQ(x.value.at("foo").outer_value, 1.0); EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, 2.0); } else { EXPECT_EQ(x.value.size(), 1); } EXPECT_EQ(x.value.at("bar").outer_value, 3.0); EXPECT_EQ(x.value.at("bar").inner_struct.inner_value, 4.0); } TEST_P(YamlReadArchiveTest, BigStdMapMergeNewOuterValue) { if (!GetParam().allow_cpp_with_no_yaml) { // The parser would raise an uninteresting exception in this case. return; } std::string doc = R"""( doc: value: foo: outer_value: 3.0 )"""; const auto& x = AcceptNoThrow<BigMapStruct>(Load(doc)); EXPECT_EQ(x.value.size(), 1); EXPECT_EQ(x.value.at("foo").outer_value, 3.0); if (GetParam().retain_map_defaults) { EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, 2.0); } else { EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, kNominalDouble); } } TEST_P(YamlReadArchiveTest, BigStdMapMergeNewInnerValue) { if (!GetParam().allow_cpp_with_no_yaml) { // The parser would raise an uninteresting exception in this case. return; } std::string doc = R"""( doc: value: foo: inner_struct: inner_value: 4.0 )"""; const auto& x = AcceptNoThrow<BigMapStruct>(Load(doc)); EXPECT_EQ(x.value.size(), 1); if (GetParam().retain_map_defaults) { EXPECT_EQ(x.value.at("foo").outer_value, 1.0); } else { EXPECT_EQ(x.value.at("foo").outer_value, kNominalDouble); } EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, 4.0); } TEST_P(YamlReadArchiveTest, BigStdMapMergeEmpty) { if (!GetParam().allow_cpp_with_no_yaml) { // The parser would raise an uninteresting exception in this case. return; } std::string doc = R"""( doc: value: foo: {} )"""; const auto& x = AcceptNoThrow<BigMapStruct>(Load(doc)); EXPECT_EQ(x.value.size(), 1); if (GetParam().retain_map_defaults) { EXPECT_EQ(x.value.at("foo").outer_value, 1.0); EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, 2.0); } else { EXPECT_EQ(x.value.at("foo").outer_value, kNominalDouble); EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, kNominalDouble); } } TEST_P(YamlReadArchiveTest, StdMapMissing) { const auto& x = AcceptEmptyDoc<MapStruct>(); ASSERT_EQ(x.value.size(), 1); EXPECT_EQ(x.value.at("kNominalDouble"), kNominalDouble); } TEST_P(YamlReadArchiveTest, StdMapWithMergeKeys) { const auto test = [](const std::string& doc, const std::map<std::string, double>& expected) { const auto& x = AcceptNoThrow<MapStruct>(Load(doc)); string_map<double> adjusted_expected{expected.begin(), expected.end()}; if (GetParam().retain_map_defaults) { adjusted_expected["kNominalDouble"] = kNominalDouble; } EXPECT_EQ(x.value, adjusted_expected) << doc; }; // Use merge keys to populate some keys. test(R"""( _template: &template foo: 1.0 doc: value: << : *template bar: 2.0 )""", {{"foo", 1.0}, {"bar", 2.0}}); // A pre-existing value should win, though. test(R"""( _template: &template foo: 3.0 doc: value: << : *template foo: 1.0 bar: 2.0 )""", {{"foo", 1.0}, {"bar", 2.0}}); // A list of merges should also work. test(R"""( _template: &template - foo: 1.0 - baz: 3.0 doc: value: << : *template bar: 2.0 )""", {{"foo", 1.0}, {"bar", 2.0}, {"baz", 3.0}}); } TEST_P(YamlReadArchiveTest, StdMapWithBadMergeKey) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<MapStruct>(Load(R"""( _template: &template 99.0 doc: value: << : *template bar: 2.0 )""")), "YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has invalid merge key type \\(Scalar\\)\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<MapStruct>(Load(R"""( _template: &template doc: value: << : *template bar: 2.0 )""")), "YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has invalid merge key type \\(Null\\)."); } TEST_P(YamlReadArchiveTest, StdMapDirectly) { const std::string doc = R"""( doc: key_1: value: 1.0 key_2: value: 2.0 )"""; const auto& x = AcceptNoThrow<std::map<std::string, DoubleStruct>>(Load(doc)); EXPECT_EQ(x.size(), 2); EXPECT_EQ(x.at("key_1").value, 1.0); EXPECT_EQ(x.at("key_2").value, 2.0); } TEST_P(YamlReadArchiveTest, StdMapDirectlyWithDefaults) { const std::string doc = R"""( doc: key_1: value: 1.0 key_with_defaulted_value: {} )"""; const auto node = Load(doc); if (GetParam().allow_cpp_with_no_yaml) { std::map<std::string, DoubleStruct> result; result.emplace("pre_existing_default", DoubleStruct{.value = 0.0}); YamlReadArchive(node, GetParam()).Accept(&result); if (GetParam().retain_map_defaults) { EXPECT_EQ(result.size(), 3); EXPECT_EQ(result.at("pre_existing_default").value, 0.0); } else { EXPECT_EQ(result.size(), 2); } EXPECT_EQ(result.at("key_1").value, 1.0); EXPECT_EQ(result.at("key_with_defaulted_value").value, kNominalDouble); } else { DRAKE_EXPECT_THROWS_MESSAGE( (AcceptIntoDummy<std::map<std::string, DoubleStruct>>(node)), ".*missing entry for double value.*"); } } TEST_P(YamlReadArchiveTest, Optional) { const auto test_with_default = [](const std::string& doc, const std::optional<double>& expected) { const auto& x = AcceptNoThrow<OptionalStruct>(Load(doc)); if (expected.has_value()) { ASSERT_TRUE(x.value.has_value()) << *expected; EXPECT_EQ(x.value.value(), expected.value()) << *expected; } else { EXPECT_FALSE(x.value.has_value()); } }; const auto test_no_default = [](const std::string& doc, const std::optional<double>& expected) { const auto& x = AcceptNoThrow<OptionalStructNoDefault>(Load(doc)); if (expected.has_value()) { ASSERT_TRUE(x.value.has_value()) << *expected; EXPECT_EQ(x.value.value(), expected.value()) << *expected; } else { EXPECT_FALSE(x.value.has_value()); } }; /* If the YAML data provided a value for the optional key, then we should always take that value (1-4). If the YAML data provided an explicit null for the optional key, then we should always take that null (5-8). If the YAML data did not mention the key (9-12), the situation is more subtle. In the case where allow_cpp_with_no_yaml is false, then every C++ member field must match up with YAML -- with the caveat that optional members can be omitted; in that case, an absent YAML node must interpreted as nullopt so that C++ and YAML remain congruent (9, 11). In the case where allow_cpp_with_no_yaml is true, we should only be changing C++ values when the yaml data mentions the key; unmentioned values should stay undisturbed; in that case, a missing key should have no effect (10, 12); only an explicit null key (7, 8) should evidence a change. # | yaml | store | acwny || want ===+========+=======+=======++======== 1 | Scalar | False | False || Scalar 2 | Scalar | False | True || Scalar 3 | Scalar | True | False || Scalar 4 | Scalar | True | True || Scalar 5 | Null | False | False || False 6 | Null | False | True || False 7 | Null | True | False || False 8 | Null | True | True || False 9 | Absent | False | False || False 10 | Absent | False | True || False 11 | Absent | True | False || False 12 | Absent | True | True || True yaml = node type present in yaml file store = nvp.value().has_value() initial condition acwny = Options.allow_cpp_with_no_yaml want = nvp.value() desired final condition */ test_no_default("doc:\n value: 1.0", 1.0); // # 1, 2 test_with_default("doc:\n value: 1.0", 1.0); // # 3, 4 test_no_default("doc:\n value:", std::nullopt); // # 5, 6 test_with_default("doc:\n value:", std::nullopt); // # 7, 8 test_no_default("doc: {}", std::nullopt); // # 9, 10 if (GetParam().allow_cpp_with_no_yaml) { test_with_default("doc: {}", kNominalDouble); // # 12 } else { test_with_default("doc: {}", std::nullopt); // # 11 } if (GetParam().allow_yaml_with_no_cpp) { test_no_default("doc:\n foo: bar\n value: 1.0", 1.0); // # 1, 2 test_with_default("doc:\n foo: bar\n value: 1.0", 1.0); // # 3, 4 test_no_default("doc:\n foo: bar\n value:", std::nullopt); // # 5, 6 test_with_default("doc:\n foo: bar\n value:", std::nullopt); // # 7, 8 test_no_default("doc:\n foo: bar", std::nullopt); // # 9, 10 if (GetParam().allow_cpp_with_no_yaml) { test_with_default("doc:\n foo: bar", kNominalDouble); // # 12 } else { test_with_default("doc:\n foo: bar", std::nullopt); // # 11 } } } TEST_P(YamlReadArchiveTest, Variant) { const auto test = [](const std::string& doc, const Variant4& expected) { const auto& x = AcceptNoThrow<VariantStruct>(Load(doc)); EXPECT_EQ(x.value, expected) << doc; }; test("doc:\n value: \"\"", ""); test("doc:\n value: foo", "foo"); test("doc:\n value: \"foo\"", "foo"); test("doc:\n value: !!str foo", "foo"); test("doc:\n value: !!float 1.0", 1.0); test("doc:\n value: !DoubleStruct { value: 1.0 }", DoubleStruct{1.0}); } TEST_P(YamlReadArchiveTest, PrimitiveVariant) { const auto test = [](const std::string& doc, const PrimitiveVariant& expected) { const auto& x = AcceptNoThrow<PrimitiveVariantStruct>(Load(doc)); EXPECT_EQ(x.value, expected) << doc; }; test("doc:\n value: [1.0, 2.0]", std::vector<double>{1.0, 2.0}); test("doc:\n value: !!bool true", true); test("doc:\n value: !!bool 'true'", true); test("doc:\n value: !!int 10", 10); test("doc:\n value: !!int '10'", 10); test("doc:\n value: !!float 1.0", 1.0); test("doc:\n value: !!float '1.0'", 1.0); test("doc:\n value: !!str foo", std::string("foo")); test("doc:\n value: !!str 'foo'", std::string("foo")); // It might be sensible for this case to pass, but for now we'll require that // non-0'th variant indices always use a tag even where it could be inferred. DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<PrimitiveVariantStruct>(Load("doc:\n value: 1.0")), ".*vector.*double.*"); } // When loading a variant, the default value should remain intact in cases where // the type tag is unchanged. TEST_P(YamlReadArchiveTest, VariantNestedDefaults) { const LoadYamlOptions param = GetParam(); VariantStruct result{Variant4{DoubleStruct{.value = 22.0}}}; const std::string doc = "doc: { value: !DoubleStruct {} }"; auto parse = [&]() { YamlReadArchive(Load(doc), param).Accept(&result); }; if (param.allow_cpp_with_no_yaml) { EXPECT_NO_THROW(parse()); } else { EXPECT_THROW(parse(), std::exception); } EXPECT_EQ(std::get<DoubleStruct>(result.value).value, 22.0); } TEST_P(YamlReadArchiveTest, VariantMissing) { const auto& x = AcceptEmptyDoc<VariantStruct>(); EXPECT_EQ(std::get<double>(x.value), kNominalDouble); } TEST_P(YamlReadArchiveTest, EigenVector) { const auto test = [](const std::string& value, const Eigen::VectorXd& expected) { const auto& vec = AcceptNoThrow<EigenVecStruct>(LoadSingleValue(value)); const auto& vec3 = AcceptNoThrow<EigenVec3Struct>(LoadSingleValue(value)); const auto& upto3 = AcceptNoThrow<EigenVecUpTo3Struct>(LoadSingleValue(value)); EXPECT_TRUE(drake::CompareMatrices(vec.value, expected)); EXPECT_TRUE(drake::CompareMatrices(vec3.value, expected)); EXPECT_TRUE(drake::CompareMatrices(upto3.value, expected)); }; test("[1.0, 2.0, 3.0]", Eigen::Vector3d(1.0, 2.0, 3.0)); } TEST_P(YamlReadArchiveTest, EigenVectorX) { const auto test = [](const std::string& value, const Eigen::VectorXd& expected) { const auto& x = AcceptNoThrow<EigenVecStruct>(LoadSingleValue(value)); EXPECT_TRUE(drake::CompareMatrices(x.value, expected)); const auto& upto3 = AcceptNoThrow<EigenVecUpTo3Struct>(LoadSingleValue(value)); EXPECT_TRUE(drake::CompareMatrices(upto3.value, expected)); }; test("[]", Eigen::VectorXd()); test("[1.0]", Eigen::Matrix<double, 1, 1>(1.0)); } TEST_P(YamlReadArchiveTest, EigenVectorOverflow) { DRAKE_EXPECT_THROWS_MESSAGE(AcceptIntoDummy<EigenVecUpTo3Struct>(Load(R"""( doc: value: [0, 0, 0, 0] )""")), ".*maximum size is 3.*"); } TEST_P(YamlReadArchiveTest, EigenMatrix) { using Matrix34d = Eigen::Matrix<double, 3, 4>; const auto test = [](const std::string& doc, const Eigen::MatrixXd& expected) { const auto& mat = AcceptNoThrow<EigenMatrixStruct>(Load(doc)); const auto& mat34 = AcceptNoThrow<EigenMatrix34Struct>(Load(doc)); EXPECT_TRUE(drake::CompareMatrices(mat.value, expected)); EXPECT_TRUE(drake::CompareMatrices(mat34.value, expected)); }; test(R"""( doc: value: - [0.0, 1.0, 2.0, 3.0] - [4.0, 5.0, 6.0, 7.0] - [8.0, 9.0, 10.0, 11.0] )""", (Matrix34d{} << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).finished()); } TEST_P(YamlReadArchiveTest, EigenMatrixUpTo6) { using Matrix34d = Eigen::Matrix<double, 3, 4>; const auto test = [](const std::string& doc, const Matrix34d& expected) { const auto& mat = AcceptNoThrow<EigenMatrixUpTo6Struct>(Load(doc)); EXPECT_TRUE(drake::CompareMatrices(mat.value, expected)); }; test(R"""( doc: value: - [0.0, 1.0, 2.0, 3.0] - [4.0, 5.0, 6.0, 7.0] - [8.0, 9.0, 10.0, 11.0] )""", (Matrix34d{} << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).finished()); } TEST_P(YamlReadArchiveTest, EigenMatrix00) { const auto test = [](const std::string& doc) { const auto& mat = AcceptNoThrow<EigenMatrixStruct>(Load(doc)); const auto& mat00 = AcceptNoThrow<EigenMatrix00Struct>(Load(doc)); const Eigen::MatrixXd empty; EXPECT_TRUE(drake::CompareMatrices(mat.value, empty)); EXPECT_TRUE(drake::CompareMatrices(mat00.value, empty)); }; test(R"""( doc: value: [] )"""); test(R"""( doc: value: [[]] )"""); } TEST_P(YamlReadArchiveTest, EigenMissing) { const auto& vx = AcceptEmptyDoc<EigenVecStruct>(); const auto& vn = AcceptEmptyDoc<EigenVec3Struct>(); const auto& mx = AcceptEmptyDoc<EigenMatrixStruct>(); const auto& mn = AcceptEmptyDoc<EigenMatrix34Struct>(); ASSERT_EQ(vx.value.size(), 1); ASSERT_EQ(mx.value.size(), 1); EXPECT_EQ(vx.value(0), kNominalDouble); EXPECT_EQ(vn.value(0), kNominalDouble); EXPECT_EQ(mx.value(0, 0), kNominalDouble); EXPECT_EQ(mn.value(0, 0), kNominalDouble); } TEST_P(YamlReadArchiveTest, Nested) { const auto& x = AcceptNoThrow<OuterStruct>(Load(R"""( doc: outer_value: 1.0 inner_struct: inner_value: 2.0 )""")); EXPECT_EQ(x.outer_value, 1.0); EXPECT_EQ(x.inner_struct.inner_value, 2.0); } TEST_P(YamlReadArchiveTest, NestedWithMergeKeys) { const auto test = [](const std::string& orig_doc) { std::string doc = orig_doc; if (!GetParam().allow_yaml_with_no_cpp) { doc = std::regex_replace(orig_doc, std::regex(" *ignored_key: ignored_value"), ""); } SCOPED_TRACE("With doc = " + doc); const auto& x = AcceptNoThrow<OuterStruct>(Load(doc)); EXPECT_EQ(x.outer_value, 1.0); EXPECT_EQ(x.inner_struct.inner_value, 2.0); }; // Use merge keys to populate InnerStruct. test(R"""( _template: &template inner_value: 2.0 ignored_key: ignored_value doc: inner_struct: << : *template outer_value: 1.0 )"""); // Use merge keys to populate InnerStruct, though to no effect because the // existing value wins. test(R"""( _template: &template inner_value: 3.0 ignored_key: ignored_value doc: inner_struct: << : *template inner_value: 2.0 outer_value: 1.0 )"""); // Use merge keys to populate OuterStruct. test(R"""( _template: &template inner_struct: inner_value: 2.0 ignored_key: ignored_value doc: << : *template outer_value: 1.0 )"""); // Use array of merge keys to populate OuterStruct. // First array with a value wins. test(R"""( _template: &template - inner_struct: inner_value: 2.0 ignored_key: ignored_value - inner_struct: inner_value: 3.0 doc: << : *template outer_value: 1.0 )"""); } TEST_P(YamlReadArchiveTest, NestedWithBadMergeKey) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(Load(R"""( _template: &template 99.0 doc: inner_struct: << : *template outer_value: 1.0 )""")), "YAML node of type Mapping" " \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)" " has invalid merge key type \\(Scalar\\)\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(Load(R"""( _template: &template doc: inner_struct: << : *template outer_value: 1.0 )""")), "YAML node of type Mapping" " \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)" " has invalid merge key type \\(Null\\)\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(Load(R"""( _template: &template - inner_value - 2.0 doc: << : *template outer_value: 1.0 )""")), "YAML node of type Mapping \\(with size 1 and keys \\{outer_value\\}\\)" " has invalid merge key type \\(Sequence-of-non-Mapping\\)\\."); } // This finds nothing when a scalar was wanted, because the name had a typo. TEST_P(YamlReadArchiveTest, VisitScalarFoundNothing) { // This has a "_TYPO" in a field name. const internal::Node node = Load(R"""( doc: outer_value: 1.0 inner_struct: inner_value_TYPO: 2.0 )"""); if (GetParam().allow_cpp_with_no_yaml && GetParam().allow_yaml_with_no_cpp) { const auto& x = AcceptNoThrow<OuterStruct>(node); EXPECT_EQ(x.outer_value, 1.0); EXPECT_EQ(x.inner_struct.inner_value, kNominalDouble); } else if (GetParam().allow_cpp_with_no_yaml) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(node), "<string>:4:5:" " YAML node of type Mapping" " \\(with size 1 and keys \\{inner_value_TYPO\\}\\)" " key 'inner_value_TYPO' did not match any visited value entry for" " <root> while accepting YAML node of type Mapping" " \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)" " while visiting [^ ]*InnerStruct inner_struct\\."); } else { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(node), "<string>:4:5:" " YAML node of type Mapping" " \\(with size 1 and keys \\{inner_value_TYPO\\}\\)" " is missing entry for double inner_value" " while accepting YAML node of type Mapping" " \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)" " while visiting [^ ]*InnerStruct inner_struct\\."); } } // This finds an array when a scalar was wanted. TEST_P(YamlReadArchiveTest, VisitScalarFoundArray) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(Load(R"""( doc: outer_value: 1.0 inner_struct: inner_value: [2.0, 3.0] )""")), "<string>:4:5:" " YAML node of type Mapping \\(with size 1 and keys \\{inner_value\\}\\)" " has non-Scalar \\(Sequence\\) entry for double inner_value" " while accepting YAML node of type Mapping" " \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)" " while visiting [^ ]*InnerStruct inner_struct\\."); } // This finds a struct when a scalar was wanted. TEST_P(YamlReadArchiveTest, VisitScalarFoundStruct) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(Load(R"""( doc: outer_value: 1.0 inner_struct: inner_value: key: 2.0 )""")), "<string>:4:5:" " YAML node of type Mapping \\(with size 1 and keys \\{inner_value\\}\\)" " has non-Scalar \\(Mapping\\) entry for double inner_value" " while accepting YAML node of type Mapping" " \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)" " while visiting [^ ]*InnerStruct inner_struct\\."); } // This finds nothing when a std::array was wanted. TEST_P(YamlReadArchiveTest, VisitArrayFoundNothing) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<ArrayStruct>(LoadSingleValue("")), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Null\\) entry for std::array<.*> value\\."); } // This finds a scalar when a std::array was wanted. TEST_P(YamlReadArchiveTest, VisitArrayFoundScalar) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<ArrayStruct>(LoadSingleValue("1.0")), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Scalar\\) entry for std::array<.*> value\\."); } // This finds a sub-structure when a std::array was wanted. TEST_P(YamlReadArchiveTest, VisitArrayFoundStruct) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<ArrayStruct>(Load(R"""( doc: value: inner_value: 1.0 )""")), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Mapping\\) entry for std::array<.*> value\\."); } // This finds nothing when a std::vector was wanted. TEST_P(YamlReadArchiveTest, VisitVectorFoundNothing) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<VectorStruct>(LoadSingleValue("")), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Null\\) entry for std::vector<.*> value\\."); } // This finds a scalar when a std::vector was wanted. TEST_P(YamlReadArchiveTest, VisitVectorFoundScalar) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<VectorStruct>(LoadSingleValue("1.0")), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Scalar\\) entry for std::vector<.*> value\\."); } // This finds a sub-structure when a std::vector was wanted. TEST_P(YamlReadArchiveTest, VisitVectorFoundStruct) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<VectorStruct>(Load(R"""( doc: value: inner_value: 1.0 )""")), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Mapping\\) entry for std::vector<.*> value\\."); } // This finds a sequence when an optional<double> was wanted. TEST_P(YamlReadArchiveTest, VisitOptionalScalarFoundSequence) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OptionalStruct>(LoadSingleValue("[1.0]")), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Scalar \\(Sequence\\) entry for std::optional<double>" " value\\."); } // This finds various untagged things when a variant was wanted. TEST_P(YamlReadArchiveTest, VisitVariantFoundNoTag) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<VariantWrappingStruct>( Load("doc:\n inner:\n value:")), "<string>:3:5:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Scalar \\(Null\\) entry for std::string value" " while accepting YAML node of type Mapping" " \\(with size 1 and keys \\{inner\\}\\)" " while visiting drake::yaml::test::VariantStruct inner."); // std::string values should load correctly even without a YAML type tag. const auto& str = AcceptNoThrow<VariantWrappingStruct>( Load("doc:\n inner:\n value: foo")); EXPECT_EQ(str.inner.value, Variant4("foo")); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<VariantWrappingStruct>( Load("doc:\n inner:\n value: [foo, bar]")), "<string>:3:5:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Scalar \\(Sequence\\) entry for std::string value" " while accepting YAML node of type Mapping" " \\(with size 1 and keys \\{inner\\}\\)" " while visiting drake::yaml::test::VariantStruct inner."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<VariantWrappingStruct>( Load("doc:\n inner:\n value: {foo: bar}")), "<string>:3:5:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Scalar \\(Mapping\\) entry for std::string value\\" " while accepting YAML node of type Mapping" " \\(with size 1 and keys \\{inner\\}\\)" " while visiting drake::yaml::test::VariantStruct inner."); } // This finds an unknown tag when a variant was wanted. TEST_P(YamlReadArchiveTest, VisitVariantFoundUnknownTag) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<VariantStruct>(Load("doc:\n value: !UnknownTag foo")), "<string>:2:3: " "YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\) " "has unsupported type tag !UnknownTag " "while selecting a variant<> entry for " "std::variant<std::string,double,drake::yaml::test::DoubleStruct," "drake::yaml::test::EigenStruct<-1,1,-1,1>> value."); } // This finds nothing when an Eigen::Vector or Eigen::Matrix was wanted. TEST_P(YamlReadArchiveTest, VisitEigenFoundNothing) { const std::string value; DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenVecStruct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Null\\) entry for Eigen::VectorXd value\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenVec3Struct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Null\\) entry for Eigen::Vector3d value\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenMatrixStruct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Null\\) entry for Eigen::MatrixXd value\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenMatrix34Struct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Null\\) entry for Eigen::Matrix.*3,4.* value\\."); } // This finds a scalar when an Eigen::Vector or Eigen::Matrix was wanted. TEST_P(YamlReadArchiveTest, VisitEigenFoundScalar) { const std::string value{"1.0"}; DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenVecStruct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Scalar\\) entry for Eigen::VectorXd value\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenVec3Struct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Scalar\\) entry for Eigen::Vector3d value\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenMatrixStruct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Scalar\\) entry for Eigen::MatrixXd value\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenMatrix34Struct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has non-Sequence \\(Scalar\\) entry for Eigen::Matrix.* value\\."); } // This finds a one-dimensional Sequence when a 2-d Eigen::Matrix was wanted. TEST_P(YamlReadArchiveTest, VisitEigenMatrixFoundOneDimensional) { const std::string value{"[1.0, 2.0, 3.0, 4.0]"}; DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenMatrixStruct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " is Sequence-of-Scalar \\(not Sequence-of-Sequence\\)" " entry for Eigen::MatrixXd value\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenMatrix34Struct>(LoadSingleValue(value)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " is Sequence-of-Scalar \\(not Sequence-of-Sequence\\)" " entry for Eigen::Matrix.* value\\."); } // This finds a non-square (4+4+3) matrix, when an Eigen::Matrix was wanted. TEST_P(YamlReadArchiveTest, VisitEigenMatrixFoundNonSquare) { const std::string doc(R"""( doc: value: - [0.0, 1.0, 2.0, 3.0] - [4.0, 5.0, 6.0, 7.0] - [8.0, 9.0, 0.0] )"""); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenMatrixStruct>(Load(doc)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has inconsistent cols dimensions entry for Eigen::MatrixXd value\\."); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<EigenMatrix34Struct>(Load(doc)), "<string>:2:3:" " YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)" " has inconsistent cols dimensions entry for Eigen::Matrix.* value\\."); } // This finds nothing when a sub-structure was wanted. TEST_P(YamlReadArchiveTest, VisitStructFoundNothing) { const internal::Node node = Load(R"""( doc: outer_value: 1.0 )"""); if (GetParam().allow_cpp_with_no_yaml) { const auto& x = AcceptNoThrow<OuterStruct>(node); EXPECT_EQ(x.outer_value, 1.0); EXPECT_EQ(x.inner_struct.inner_value, kNominalDouble); } else { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(node), "<string>:2:5:" " YAML node of type Mapping" " \\(with size 1 and keys \\{outer_value\\}\\)" " is missing entry for [^ ]*InnerStruct inner_struct\\."); } } // This finds a scalar when a sub-structure was wanted. TEST_P(YamlReadArchiveTest, VisitStructFoundScalar) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(Load(R"""( doc: outer_value: 1.0 inner_struct: 2.0 )""")), "<string>:2:3:" " YAML node of type Mapping" " \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)" " has non-Mapping \\(Scalar\\) entry for" " [^ ]*InnerStruct inner_struct\\."); } // This finds an array when a sub-structure was wanted. TEST_P(YamlReadArchiveTest, VisitStructFoundArray) { DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(Load(R"""( doc: outer_value: 1.0 inner_struct: [2.0, 3.0] )""")), "<string>:2:3:" " YAML node of type Mapping" " \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)" " has non-Mapping \\(Sequence\\) entry for" " [^ ]*InnerStruct inner_struct\\."); } // The user input a top-level array instead of a mapping. TEST_P(YamlReadArchiveTest, VisitRootStructFoundArray) { const std::string doc = R"""( - foo - bar )"""; const internal::Node root = YamlReadArchive::LoadStringAsNode(doc, std::nullopt); DRAKE_EXPECT_THROWS_MESSAGE( AcceptIntoDummy<OuterStruct>(root), ".*top level element should be a Mapping.*not a Sequence.*"); } std::vector<LoadYamlOptions> MakeAllPossibleOptions() { std::vector<LoadYamlOptions> all; for (const bool i : {false, true}) { for (const bool j : {false, true}) { for (const bool k : {false, true}) { all.push_back(LoadYamlOptions{i, j, k}); } } } return all; } INSTANTIATE_TEST_SUITE_P(AllOptions, YamlReadArchiveTest, ::testing::ValuesIn(MakeAllPossibleOptions())); } // namespace } // namespace test } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_io_test_input_1.yaml
value: some_value_1
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_doxygen_test.cc
#include <fstream> #include <sstream> #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/common/temp_directory.h" #include "drake/common/yaml/yaml_io.h" // This is a unit test that exactly replicates the examples in yaml_doxygen.h, // to ensure that they remain correct. Any changes to this file or the doxygen // file must be mirrored into the other file. namespace drake { namespace yaml { namespace test { namespace { // (This is a test helper, not part of the Doxygen header.) std::string GetTempFilename() { return temp_directory() + "/filename.yaml"; } // Write data to a scratch file and then return the temp's filename. // (This is a test helper, not part of the Doxygen header.) std::string WriteTemp(const std::string& data) { const std::string filename = GetTempFilename(); std::ofstream output(filename); output << data; return filename; } // This is an example from the Doxygen header. struct MyData { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(foo)); a->Visit(DRAKE_NVP(bar)); } double foo{0.0}; std::vector<double> bar; }; GTEST_TEST(YamlDoxygenTest, ExamplesLoading) { // This data is an example from the Doxygen header. const std::string input = R"""( foo: 1.0 bar: [2.0, 3.0] )"""; auto input_filename = WriteTemp(input); std::stringstream std_cout; // This code is an example from the Doxygen header. const MyData data = LoadYamlFile<MyData>(input_filename); std_cout << fmt::format("foo = {:.1f}\n", data.foo); std_cout << fmt::format("bar = {:.1f}\n", fmt::join(data.bar, ", ")); const std::string expected_output = R"""( foo = 1.0 bar = 2.0, 3.0 )"""; EXPECT_EQ(std_cout.str(), expected_output.substr(1)); } GTEST_TEST(YamlDoxygenTest, ExamplesSaving) { const std::string output_filename = GetTempFilename(); // This code is an example from the Doxygen header. MyData data{4.0, {5.0, 6.0}}; SaveYamlFile(output_filename, data); // This data is an example from the Doxygen header. const std::string output = ReadFileOrThrow(output_filename); const std::string expected_output = R"""( foo: 4.0 bar: [5.0, 6.0] )"""; EXPECT_EQ(output, expected_output.substr(1)); } // This is an example from the Doxygen header. struct MoreData { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(baz)); a->Visit(DRAKE_NVP(quux)); } std::string baz; std::map<std::string, MyData> quux; }; // This is an example from the Doxygen header. MyData LoadMyData(const std::string& filename) { return LoadYamlFile<MyData>(filename); } GTEST_TEST(YamlDoxygenTest, ReadingYamlFiles) { // This data is an example from the Doxygen header. const std::string input = R"""( foo: 1.0 bar: [2.0, 3.0] )"""; auto input_filename = WriteTemp(input); std::stringstream std_cout; // This code is an example from the Doxygen header. const MyData data = LoadMyData(input_filename); std_cout << fmt::format("foo = {:.1f}\n", data.foo); std_cout << fmt::format("bar = {:.1f}\n", fmt::join(data.bar, ", ")); // This data is an example from the Doxygen header. const std::string expected_output = R"""( foo = 1.0 bar = 2.0, 3.0 )"""; EXPECT_EQ(std_cout.str(), expected_output.substr(1)); } // This is an example from the Doxygen header. MyData LoadMyData2(const std::string& filename) { return LoadYamlFile<MyData>(filename, "data_2"); } GTEST_TEST(YamlDoxygenTest, TopLevelChild) { // This data is an example from the Doxygen header. const std::string input = R"""( data_1: foo: 1.0 bar: [2.0, 3.0] data_2: foo: 4.0 bar: [5.0, 6.0] )"""; auto input_filename = WriteTemp(input); std::stringstream std_cout; const MyData data = LoadMyData2(input_filename); std_cout << fmt::format("foo = {:.1f}\n", data.foo); std_cout << fmt::format("bar = {:.1f}\n", fmt::join(data.bar, ", ")); // This data is an example from the Doxygen header. const std::string expected_output = R"""( foo = 4.0 bar = 5.0, 6.0 )"""; EXPECT_EQ(std_cout.str(), expected_output.substr(1)); } GTEST_TEST(YamlDoxygenTest, MergeKeys) { // This data is an example from the Doxygen header. const std::string input = R"""( _template: &common_foo foo: 1.0 data_1: << : *common_foo bar: [2.0, 3.0] data_2: << : *common_foo bar: [5.0, 6.0] )"""; auto input_filename = WriteTemp(input); const MyData data = LoadMyData2(input_filename); EXPECT_EQ(data.foo, 1.0); EXPECT_EQ(data.bar, std::vector({5.0, 6.0})); } GTEST_TEST(YamlDoxygenTest, WritingYamlFiles) { std::stringstream std_cout; // This code is an example from the Doxygen header. MyData data{1.0, {2.0, 3.0}}; std_cout << SaveYamlString(data, "root"); // This data is an example from the Doxygen header. const std::string expected_output = R"""( root: foo: 1.0 bar: [2.0, 3.0] )"""; EXPECT_EQ(std_cout.str(), expected_output.substr(1)); } // This is an example from the Doxygen header. std::map<std::string, MyData> LoadAllMyData(const std::string& filename) { return LoadYamlFile<std::map<std::string, MyData>>(filename); } GTEST_TEST(YamlDoxygenTest, DocumentRoot) { // This data is an example from the Doxygen header. const std::string input = R"""( data_1: foo: 1.0 bar: [2.0, 3.0] data_2: foo: 4.0 bar: [5.0, 6.0] )"""; auto input_filename = WriteTemp(input); auto data = LoadAllMyData(input_filename); EXPECT_EQ(data.size(), 2); EXPECT_EQ(data.at("data_2").foo, 4.0); } // This is an example from the Doxygen header. struct Foo { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(data)); } std::string data; }; // This is an example from the Doxygen header. struct Bar { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } std::variant<std::string, double, Foo> value; }; GTEST_TEST(YamlDoxygenTest, NullableTypes) { // This data is an example from the Doxygen header. const std::string input = R"""( bar: value: hello bar2: value: !!str hello bar3: value: !!float 1.0 bar4: value: !Foo data: hello )"""; auto bar = LoadYamlString<Bar>(input, "bar"); ASSERT_EQ(bar.value.index(), 0); EXPECT_EQ(std::get<std::string>(bar.value), "hello"); auto bar2 = LoadYamlString<Bar>(input, "bar2"); ASSERT_EQ(bar2.value.index(), 0); EXPECT_EQ(std::get<std::string>(bar2.value), "hello"); auto bar3 = LoadYamlString<Bar>(input, "bar3"); ASSERT_EQ(bar3.value.index(), 1); EXPECT_EQ(std::get<double>(bar3.value), 1.0); auto bar4 = LoadYamlString<Bar>(input, "bar4"); ASSERT_EQ(bar4.value.index(), 2); EXPECT_EQ(std::get<Foo>(bar4.value).data, "hello"); } } // namespace } // namespace test } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/json_test.cc
#include <limits> #include <gtest/gtest.h> #include "drake/common/temp_directory.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/yaml/test/example_structs.h" #include "drake/common/yaml/yaml_io.h" namespace drake { namespace yaml { namespace test { namespace { GTEST_TEST(YamlJsonTest, WriteScalars) { AllScalarsStruct data; EXPECT_EQ(SaveJsonString(data), R"""({"some_bool":false,)""" R"""("some_double":1.2345,)""" R"""("some_float":1.2345,)""" R"""("some_int32":12,)""" R"""("some_int64":14,)""" R"""("some_string":"kNominalString",)""" R"""("some_uint32":12,)""" R"""("some_uint64":15})"""); } GTEST_TEST(YamlJsonTest, StringEscaping) { StringStruct data; data.value = "foo\n\t\"bar"; EXPECT_EQ(SaveJsonString(data), R"""({"value":"foo\u000a\u0009\u0022bar"})"""); } GTEST_TEST(YamlJsonTest, NonFinite) { DoubleStruct data; data.value = std::numeric_limits<double>::infinity(); EXPECT_EQ(SaveJsonString(data), R"""({"value":Infinity})"""); data.value = -data.value; EXPECT_EQ(SaveJsonString(data), R"""({"value":-Infinity})"""); data.value = std::numeric_limits<double>::quiet_NaN(); EXPECT_EQ(SaveJsonString(data), R"""({"value":NaN})"""); } GTEST_TEST(YamlJsonTest, WriteSequence) { VectorStruct data; data.value = {1.0, 2.0}; EXPECT_EQ(SaveJsonString(data), R"""({"value":[1.0,2.0]})"""); } GTEST_TEST(YamlJsonTest, WriteMapping) { MapStruct data; data.value.clear(); data.value["a"] = 1.0; data.value["b"] = 2.0; EXPECT_EQ(SaveJsonString(data), R"""({"value":{"a":1.0,"b":2.0}})"""); } GTEST_TEST(YamlJsonTest, WriteNested) { OuterStruct data; EXPECT_EQ( SaveJsonString(data), R"""({"inner_struct":{"inner_value":1.2345},"outer_value":1.2345})"""); } GTEST_TEST(YamlJsonTest, WriteOptional) { OptionalStruct data; EXPECT_EQ(SaveJsonString(data), R"""({"value":1.2345})"""); data.value.reset(); EXPECT_EQ(SaveJsonString(data), "{}"); } GTEST_TEST(YamlJsonTest, WriteVariant) { VariantStruct data; data.value = std::string{"foo"}; EXPECT_EQ(SaveJsonString(data), R"""({"value":"foo"})"""); data.value = 0.5; EXPECT_EQ(SaveJsonString(data), R"""({"value":0.5})"""); // It would be plausible here to use the `_tag` convention to annotate // variant tags, matching what we do in our yaml.py conventions. data.value = DoubleStruct{}; DRAKE_EXPECT_THROWS_MESSAGE(SaveJsonString(data), ".*SaveJsonString.*mapping.*tag.*"); } GTEST_TEST(YamlJsonTest, FileRoundTrip) { DoubleStruct data; data.value = 22.25; const std::string filename = temp_directory() + "/file_round_trip.json"; SaveJsonFile(filename, data); const auto readback = LoadYamlFile<DoubleStruct>(filename); EXPECT_EQ(readback.value, 22.25); } } // namespace } // namespace test } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_io_test_input_2.yaml
some_string_struct: value: some_value_2
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_performance_test.cc
#include <vector> #include <Eigen/Core> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <unsupported/Eigen/AutoDiff> #include "drake/common/eigen_types.h" #include "drake/common/name_value.h" #include "drake/common/test_utilities/limit_malloc.h" #include "drake/common/yaml/yaml_io.h" #include "drake/common/yaml/yaml_read_archive.h" namespace drake { namespace yaml { namespace { using drake::yaml::SaveYamlString; using drake::yaml::internal::YamlReadArchive; struct Inner { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(doubles)); } std::vector<double> doubles; }; struct Outer { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(inners)); } std::vector<Inner> inners; }; struct Map { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(items)); } std::map<std::string, Outer> items; }; GTEST_TEST(YamlPerformanceTest, VectorNesting) { // Populate a resonably-sized but non-trival set of data -- 50,000 numbers // arranged into a map with nested vectors. const int kDim = 100; Map data; double dummy = 1.0; const std::vector keys{"a", "b", "c", "d", "e"}; for (const char* const key : keys) { Outer& outer = data.items[key]; outer.inners.resize(kDim); for (Inner& inner : outer.inners) { inner.doubles.resize(kDim, dummy); dummy += 1.0; } } // Convert the `Map data` into yaml string format. const std::string yaml_data = SaveYamlString(data, "doc"); // Parse the yaml string into a node tree while checking that resource // usage is somewhat bounded. internal::Node yaml_root = internal::Node::MakeNull(); { test::LimitMalloc guard({.max_num_allocations = 5'000'000}); yaml_root = YamlReadArchive::LoadStringAsNode(yaml_data, "doc"); } // Transfer the node tree into a C++ structure while checking that resource // usage is sane. Map new_data; { // When the performance of parsing was fixed and this test was added, this // Accept operation used about 51,000 allocations and took about 1 second // of wall clock time (for both release and debug builds). // // The prior implementation with gratuitous copies used over 2.6 billion // allocations and took more than 10 minutes of wall clock time in a // release build. // // We'll set the hard limit ~20x higher than currently observed to allow // some flux as library implementations evolve, etc. test::LimitMalloc guard({.max_num_allocations = 1'000'000}); const LoadYamlOptions default_options; YamlReadArchive archive(std::move(yaml_root), default_options); archive.Accept(&new_data); } // Double-check that we actually did the work. ASSERT_EQ(new_data.items.size(), keys.size()); for (const char* const key : keys) { Outer& outer = new_data.items[key]; ASSERT_EQ(outer.inners.size(), kDim); for (Inner& inner : outer.inners) { ASSERT_EQ(inner.doubles.size(), kDim); } } } } // namespace } // namespace yaml } // namespace drake using ADS1 = Eigen::AutoDiffScalar<drake::VectorX<double>>; using ADS2 = Eigen::AutoDiffScalar<drake::VectorX<ADS1>>; // Add ADL Serialize method to Eigen::AutoDiffScalar. namespace Eigen { template <typename Archive> void Serialize(Archive* a, ADS2* x) { a->Visit(drake::MakeNameValue("value", &(x->value()))); a->Visit(drake::MakeNameValue("derivatives", &(x->derivatives()))); } template <typename Archive> void Serialize(Archive* a, ADS1* x) { a->Visit(drake::MakeNameValue("value", &(x->value()))); a->Visit(drake::MakeNameValue("derivatives", &(x->derivatives()))); } } // namespace Eigen namespace drake { namespace yaml { namespace { struct BigEigen { template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(value)); } MatrixX<ADS2> value; }; GTEST_TEST(YamlPerformanceTest, EigenMatrix) { // Populate a resonably-sized but non-trival set of data, about ~10,000 // numbers stored at various levels of nesting. BigEigen data; const int kDim = 10; data.value.resize(kDim, kDim); double dummy = 1.0; for (int i = 0; i < data.value.rows(); ++i) { for (int j = 0; j < data.value.cols(); ++j) { ADS2& x = data.value(i, j); x.value() = dummy; dummy += 1.0; x.derivatives().resize(kDim); for (int k = 0; k < x.derivatives().size(); ++k) { ADS1& y = x.derivatives()(k); y.value() = dummy; dummy += 1.0; y.derivatives() = Eigen::VectorXd::Zero(kDim); } } } // Convert the `BigEigen data` into yaml string format. const std::string yaml_data = SaveYamlString(data, "doc"); // Parse the yaml string into a node tree while checking that resource // usage is somewhat bounded. internal::Node yaml_root = internal::Node::MakeNull(); { test::LimitMalloc guard({.max_num_allocations = 5'000'000}); yaml_root = YamlReadArchive::LoadStringAsNode(yaml_data, "doc"); } // Transfer the node tree into a C++ structure while checking that resource // usage is sane. BigEigen new_data; { // When the performance of parsing was fixed and this test was added, this // Accept operation used about 12,000 allocations and took less than 1 // second of wall clock time (for both release and debug builds). // // The prior implementation with gratuitous copies used over 1.6 million // allocations. // // We'll set the hard limit ~20x higher than currently observed to allow // some flux as library implementations evolve, etc. test::LimitMalloc guard({.max_num_allocations = 250000}); const LoadYamlOptions default_options; YamlReadArchive archive(std::move(yaml_root), default_options); archive.Accept(&new_data); } // Double-check that we actually did the work. ASSERT_EQ(new_data.value.rows(), kDim); ASSERT_EQ(new_data.value.cols(), kDim); for (int i = 0; i < kDim; ++i) { for (int j = 0; j < kDim; ++j) { ADS2& x = new_data.value(i, j); ASSERT_EQ(x.derivatives().size(), kDim); for (int k = 0; k < kDim; ++k) { ADS1& y = x.derivatives()(k); ASSERT_EQ(y.derivatives().size(), kDim); } } } } } // namespace } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common/yaml
/home/johnshepherd/drake/common/yaml/test/yaml_node_test.cc
#include "drake/common/yaml/yaml_node.h" #include <fmt/format.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/test_utilities/limit_malloc.h" namespace drake { namespace yaml { namespace internal { // Make pretty googletest output. (Per googletest, this cannot be defined in // the anonymous namespace.) static void PrintTo(const NodeType& node_type, std::ostream* os) { *os << "NodeType::k" << Node::GetTypeString(node_type); } namespace { // Check that the tag constants exist. GTEST_TEST(YamlNodeTest, TagConstants) { EXPECT_GT(Node::kTagNull.size(), 0); EXPECT_GT(Node::kTagBool.size(), 0); EXPECT_GT(Node::kTagInt.size(), 0); EXPECT_GT(Node::kTagFloat.size(), 0); EXPECT_GT(Node::kTagStr.size(), 0); } // Check the null-returning factory function. GTEST_TEST(YamlNodeTest, MakeNull) { Node dut = Node::MakeNull(); EXPECT_EQ(dut.GetType(), NodeType::kScalar); EXPECT_EQ(dut.GetScalar(), "null"); EXPECT_EQ(dut.GetTag(), Node::kTagNull); EXPECT_TRUE(Node::MakeNull() == Node::MakeNull()); } // Parameterize the remainder of the tests across the three possible types. using Param = std::tuple<NodeType, std::string_view>; class YamlNodeParamaterizedTest : public testing::TestWithParam<Param> { protected: // Returns the test suite's desired type. NodeType GetExpectedType() { return std::get<0>(GetParam()); } // Returns the test suite's desired type string. std::string_view GetExpectedTypeString() { return std::get<1>(GetParam()); } // Returns a new, empty Node with using the test suite's desired type. Node MakeEmptyDut() { switch (GetExpectedType()) { case NodeType::kScalar: return Node::MakeScalar(); case NodeType::kSequence: return Node::MakeSequence(); case NodeType::kMapping: return Node::MakeMapping(); } DRAKE_UNREACHABLE(); } // Return a new, non-empty Node with using the test suite's desired type. Node MakeNonEmptyDut() { switch (GetExpectedType()) { case NodeType::kScalar: { return Node::MakeScalar("foo"); } case NodeType::kSequence: { Node result = Node::MakeSequence(); result.Add(Node::MakeScalar("item")); return result; } case NodeType::kMapping: { Node result = Node::MakeMapping(); result.Add("key", Node::MakeScalar("value")); return result; } } DRAKE_UNREACHABLE(); } // Given a function name, returns the expected exception message in case the // runtime type of the Node is incorrect. std::string GetExpectedCannot(std::string_view operation) { return fmt::format(".*Cannot.*{}.*on a {}.*", operation, GetExpectedTypeString()); } }; // Check runtime type interrogation. TEST_P(YamlNodeParamaterizedTest, GetType) { Node dut = MakeEmptyDut(); EXPECT_EQ(dut.GetType(), GetExpectedType()); EXPECT_EQ(dut.GetTypeString(), GetExpectedTypeString()); EXPECT_EQ(dut.IsScalar(), GetExpectedType() == NodeType::kScalar); EXPECT_EQ(dut.IsSequence(), GetExpectedType() == NodeType::kSequence); EXPECT_EQ(dut.IsMapping(), GetExpectedType() == NodeType::kMapping); } // Check static type string conversion. TEST_P(YamlNodeParamaterizedTest, StaticTypeString) { EXPECT_EQ(Node::GetTypeString(GetExpectedType()), GetExpectedTypeString()); } // Check generic tag getting and setting. TEST_P(YamlNodeParamaterizedTest, GetSetTag) { Node dut = MakeEmptyDut(); EXPECT_EQ(dut.GetTag(), ""); dut.SetTag("tag"); EXPECT_EQ(dut.GetTag(), "tag"); } // Check JSON Schema tag getting and setting. TEST_P(YamlNodeParamaterizedTest, JsonSchemaTag) { Node dut = MakeEmptyDut(); dut.SetTag(JsonSchemaTag::kNull); EXPECT_EQ(dut.GetTag(), Node::kTagNull); EXPECT_FALSE(dut.IsTagImportant()); dut.SetTag(JsonSchemaTag::kBool); EXPECT_EQ(dut.GetTag(), Node::kTagBool); EXPECT_FALSE(dut.IsTagImportant()); dut.SetTag(JsonSchemaTag::kInt); EXPECT_EQ(dut.GetTag(), Node::kTagInt); EXPECT_FALSE(dut.IsTagImportant()); dut.SetTag(JsonSchemaTag::kFloat); EXPECT_EQ(dut.GetTag(), Node::kTagFloat); EXPECT_FALSE(dut.IsTagImportant()); dut.SetTag(JsonSchemaTag::kStr); EXPECT_EQ(dut.GetTag(), Node::kTagStr); EXPECT_FALSE(dut.IsTagImportant()); // Make sure `important = true` makes it all the way through. dut.SetTag(JsonSchemaTag::kBool, true); EXPECT_EQ(dut.GetTag(), Node::kTagBool); EXPECT_TRUE(dut.IsTagImportant()); } // Check mark getting and setting. TEST_P(YamlNodeParamaterizedTest, GetSetMark) { Node dut = MakeEmptyDut(); EXPECT_FALSE(dut.GetFilename().has_value()); EXPECT_FALSE(dut.GetMark().has_value()); dut.SetFilename("example.yaml"); dut.SetMark(Node::Mark{2, 3}); EXPECT_EQ(dut.GetFilename().value(), "example.yaml"); EXPECT_EQ(dut.GetMark().value().line, 2); EXPECT_EQ(dut.GetMark().value().column, 3); } // It is important for our YAML subsystem performance that the Node's move // operations actually move the stored data, instead of copying it. TEST_P(YamlNodeParamaterizedTest, EfficientMoveConstructor) { Node dut = MakeNonEmptyDut(); auto guard = std::make_unique<test::LimitMalloc>(); Node foo(std::move(dut)); guard.reset(); // The moved-to object must equal the full, original value. EXPECT_EQ(foo, MakeNonEmptyDut()); // The moved-from object must be in some valid (but unspecified) state. EXPECT_FALSE(dut == MakeNonEmptyDut()); } // Ditto per the prior test case. TEST_P(YamlNodeParamaterizedTest, EfficientMoveAssignment) { Node dut = MakeNonEmptyDut(); Node foo = Node::MakeNull(); auto guard = std::make_unique<test::LimitMalloc>(); foo = std::move(dut); guard.reset(); // The moved-to object must equal the full, original value. EXPECT_EQ(foo, MakeNonEmptyDut()); // The moved-from object must be in some valid (but unspecified) state. EXPECT_FALSE(dut == MakeNonEmptyDut()); } // Check (non-)equality as affected by the stored type of empty nodes. TEST_P(YamlNodeParamaterizedTest, EqualityPerType) { Node dut = MakeEmptyDut(); EXPECT_EQ(dut == Node::MakeScalar(), dut.IsScalar()); EXPECT_EQ(dut == Node::MakeSequence(), dut.IsSequence()); EXPECT_EQ(dut == Node::MakeMapping(), dut.IsMapping()); } // Check (non-)equality as affected by the tag. TEST_P(YamlNodeParamaterizedTest, EqualityPerTag) { Node dut = MakeEmptyDut(); Node dut2 = MakeEmptyDut(); EXPECT_TRUE(dut == dut2); // Different tag; not equal. dut2.SetTag("tag"); EXPECT_FALSE(dut == dut2); // Same tag, set via two different overloads; still equal. dut.SetTag(JsonSchemaTag::kInt); dut2.SetTag(std::string{Node::kTagInt}); EXPECT_TRUE(dut == dut2); } // Check (non-)equality as affected by the mark filename. TEST_P(YamlNodeParamaterizedTest, EqualityPerFilename) { Node dut = MakeEmptyDut(); Node dut2 = MakeEmptyDut(); EXPECT_TRUE(dut == dut2); dut2.SetFilename("example.yaml"); EXPECT_FALSE(dut == dut2); } // Check (non-)equality as affected by the mark line. TEST_P(YamlNodeParamaterizedTest, EqualityPerMarkLineCol) { Node dut = MakeEmptyDut(); Node dut2 = MakeEmptyDut(); EXPECT_TRUE(dut == dut2); dut2.SetMark(Node::Mark{1, 2}); EXPECT_FALSE(dut == dut2); dut.SetMark(Node::Mark{3, 4}); EXPECT_FALSE(dut == dut2); dut2.SetMark(Node::Mark{3, 4}); EXPECT_TRUE(dut == dut2); } // Check Scalar-specific operations. TEST_P(YamlNodeParamaterizedTest, ScalarOps) { Node dut = MakeEmptyDut(); if (dut.IsScalar()) { Node dut2 = MakeNonEmptyDut(); EXPECT_FALSE(dut == dut2); EXPECT_EQ(dut2.GetScalar(), "foo"); } else { DRAKE_EXPECT_THROWS_MESSAGE(dut.GetScalar(), GetExpectedCannot("GetScalar")); } } // Check Sequence-specific operations. TEST_P(YamlNodeParamaterizedTest, SequenceOps) { Node dut = MakeEmptyDut(); if (dut.IsSequence()) { EXPECT_TRUE(dut.GetSequence().empty()); Node dut2 = MakeNonEmptyDut(); EXPECT_FALSE(dut == dut2); ASSERT_EQ(dut2.GetSequence().size(), 1); EXPECT_EQ(dut2.GetSequence().front().GetScalar(), "item"); } else { DRAKE_EXPECT_THROWS_MESSAGE(dut.GetSequence(), GetExpectedCannot("GetSequence")); DRAKE_EXPECT_THROWS_MESSAGE(dut.Add(Node::MakeNull()), GetExpectedCannot("Add")); } } // Check Mapping-specific operations. TEST_P(YamlNodeParamaterizedTest, MappingOps) { Node dut = MakeEmptyDut(); if (dut.IsMapping()) { EXPECT_TRUE(dut.GetMapping().empty()); DRAKE_EXPECT_THROWS_MESSAGE(dut.Remove("quux"), ".*No such key.*'quux'.*"); Node dut2 = MakeNonEmptyDut(); EXPECT_FALSE(dut == dut2); ASSERT_EQ(dut2.GetMapping().size(), 1); EXPECT_EQ(dut2.GetMapping().begin()->first, "key"); EXPECT_EQ(dut2.At("key").GetScalar(), "value"); DRAKE_EXPECT_THROWS_MESSAGE(dut2.Add("key", Node::MakeScalar()), "Cannot .*Add.* duplicate key 'key'"); dut2.Remove("key"); EXPECT_TRUE(dut.GetMapping().empty()); } else { DRAKE_EXPECT_THROWS_MESSAGE(dut.GetMapping(), GetExpectedCannot("GetMapping")); DRAKE_EXPECT_THROWS_MESSAGE(dut.Add("key", Node::MakeNull()), GetExpectedCannot("Add")); DRAKE_EXPECT_THROWS_MESSAGE(dut.At("key"), GetExpectedCannot("At")); DRAKE_EXPECT_THROWS_MESSAGE(dut.Remove("key"), GetExpectedCannot("Remove")); } } // Helper to check visiting. struct VisitorThatCopies { void operator()(const Node::ScalarData& data) { scalar = data.scalar; } void operator()(const Node::SequenceData& data) { sequence = data.sequence; } void operator()(const Node::MappingData& data) { mapping = data.mapping; } std::optional<std::string> scalar; std::optional<std::vector<Node>> sequence; std::optional<string_map<Node>> mapping; }; // Check visiting. TEST_P(YamlNodeParamaterizedTest, Visiting) { Node dut = MakeNonEmptyDut(); VisitorThatCopies visitor; dut.Visit(visitor); switch (GetExpectedType()) { case NodeType::kScalar: { const std::string empty; EXPECT_EQ(visitor.scalar.value_or(empty), "foo"); EXPECT_FALSE(visitor.sequence.has_value()); EXPECT_FALSE(visitor.mapping.has_value()); return; } case NodeType::kSequence: { const std::vector<Node> empty; ASSERT_EQ(visitor.sequence.value_or(empty).size(), 1); EXPECT_EQ(visitor.sequence->front().GetScalar(), "item"); EXPECT_FALSE(visitor.scalar.has_value()); EXPECT_FALSE(visitor.mapping.has_value()); return; } case NodeType::kMapping: { const string_map<Node> empty; ASSERT_EQ(visitor.mapping.value_or(empty).size(), 1); EXPECT_EQ(visitor.mapping->begin()->first, "key"); EXPECT_EQ(visitor.mapping->at("key").GetScalar(), "value"); EXPECT_FALSE(visitor.scalar.has_value()); EXPECT_FALSE(visitor.sequence.has_value()); return; } } DRAKE_UNREACHABLE(); } // Check debug printing using operator<<. TEST_P(YamlNodeParamaterizedTest, ToString) { Node dut = MakeNonEmptyDut(); // Confirm that the code is being run by checking for a notable // substring within the printed result. std::string needle; switch (GetExpectedType()) { case NodeType::kScalar: { needle = "foo"; break; } case NodeType::kSequence: { needle = "item"; break; } case NodeType::kMapping: { needle = "key"; break; } } EXPECT_THAT(fmt::format("{}", dut), testing::HasSubstr(needle)); // Confirm that tags are represented somehow. dut.SetTag("MyTag"); EXPECT_THAT(fmt::format("{}", dut), testing::HasSubstr("MyTag")); } INSTANTIATE_TEST_SUITE_P(Suite, YamlNodeParamaterizedTest, testing::Values(Param(NodeType::kScalar, "Scalar"), Param(NodeType::kSequence, "Sequence"), Param(NodeType::kMapping, "Mapping"))); } // namespace } // namespace internal } // namespace yaml } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/chebyshev_basis_element.cc
#include "drake/common/symbolic/chebyshev_basis_element.h" #include <cmath> #include <vector> #define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/expression/expression_cell.h" #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/chebyshev_polynomial.h" namespace drake { namespace symbolic { ChebyshevBasisElement::ChebyshevBasisElement() : PolynomialBasisElement() {} ChebyshevBasisElement::ChebyshevBasisElement( const std::map<Variable, int>& var_to_degree_map) : PolynomialBasisElement(var_to_degree_map) {} ChebyshevBasisElement::ChebyshevBasisElement(const Variable& var) : ChebyshevBasisElement({{var, 1}}) {} ChebyshevBasisElement::ChebyshevBasisElement(const Variable& var, int degree) : ChebyshevBasisElement({{var, degree}}) {} ChebyshevBasisElement::ChebyshevBasisElement(std::nullptr_t) : ChebyshevBasisElement() {} ChebyshevBasisElement::ChebyshevBasisElement( const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& degrees) : PolynomialBasisElement(vars, degrees) {} bool ChebyshevBasisElement::operator<( const ChebyshevBasisElement& other) const { return this->lexicographical_compare(other); } std::map<ChebyshevBasisElement, double> ChebyshevBasisElement::Differentiate( const Variable& var) const { if (!var_to_degree_map().contains(var)) { // Return an empty map (the differentiation result is 0) when @p var is not // a variable in @p this. return {}; } std::map<ChebyshevBasisElement, double> result; std::map<Variable, int> var_to_degree_map = this->var_to_degree_map(); auto it = var_to_degree_map.find(var); const int degree = it->second; const int start_degree = degree % 2 == 0 ? 1 : 2; for (int i = start_degree; i < degree; i += 2) { it->second = i; result.emplace(ChebyshevBasisElement(var_to_degree_map), 2 * degree); } // Lastly, add the term for T0(x) if the degree is odd. The coefficient for // T0(x) is degree instead of 2 * degree. if (degree % 2 == 1) { it->second = 0; result.emplace(ChebyshevBasisElement(var_to_degree_map), degree); } return result; } std::map<ChebyshevBasisElement, double> ChebyshevBasisElement::Integrate( const Variable& var) const { auto var_to_degree_map = this->var_to_degree_map(); auto it = var_to_degree_map.find(var); if (it == var_to_degree_map.end()) { // var is not a variable in this Chebyshev basis element. // Append T1(var) to the var_to_degree_map. var_to_degree_map.emplace_hint(it, var, 1); return {{ChebyshevBasisElement(var_to_degree_map), 1}}; } const int degree = it->second; std::map<ChebyshevBasisElement, double> result; it->second = degree + 1; result.emplace(ChebyshevBasisElement(var_to_degree_map), 1.0 / (2 * degree + 2)); it->second = degree - 1; result.emplace(ChebyshevBasisElement(var_to_degree_map), -1.0 / (2 * degree - 2)); return result; } void ChebyshevBasisElement::MergeBasisElementInPlace( const ChebyshevBasisElement& other) { this->DoMergeBasisElementInPlace(other); } std::pair<double, ChebyshevBasisElement> ChebyshevBasisElement::EvaluatePartial( const Environment& env) const { double coeff; std::map<Variable, int> new_basis_element; DoEvaluatePartial(env, &coeff, &new_basis_element); return std::make_pair(coeff, ChebyshevBasisElement(new_basis_element)); } double ChebyshevBasisElement::DoEvaluate(double variable_val, int degree) const { return EvaluateChebyshevPolynomial(variable_val, degree); } Expression ChebyshevBasisElement::DoToExpression() const { std::map<Expression, Expression> base_to_exponent_map; for (const auto& [var, degree] : var_to_degree_map()) { base_to_exponent_map.emplace( ChebyshevPolynomial(var, degree).ToPolynomial().ToExpression(), 1); } return ExpressionMulFactory{1.0, base_to_exponent_map}.GetExpression(); } namespace { // This function is used in operator*, it appends the pair (var, degree) to each // entry of chebyshev_basis_all. void AppendVariableAndDegree( const Variable& var, int degree, std::vector<std::map<Variable, int>>* chebyshev_basis_all) { for (auto& cheby_basis : *chebyshev_basis_all) { cheby_basis.emplace(var, degree); } } int power_of_2(int degree) { if (degree < 0) { throw std::invalid_argument("power of 2 underflow"); } if (degree > static_cast<int>((sizeof(int) * CHAR_BIT - 2))) { throw std::invalid_argument("power of 2 overflow"); } return 1 << degree; } } // namespace std::map<ChebyshevBasisElement, double> operator*( const ChebyshevBasisElement& a, const ChebyshevBasisElement& b) { // If variable x shows up in both ChebyshevBasisElement a and b, we know that // Tₘ(x) * Tₙ(x) = 0.5 (Tₘ₊ₙ(x) + Tₘ₋ₙ(x)), namely we will expand the product // to the sum of two new Chebyshev polynomials. Hence the number of terms in // the product of a * b is 2 to the power of # common variables showing up in // both a and b. // Number of variables that show up in both ChebyshevBasisElement a and b. // I first count the number of common variables, so as to do memory // allocation for the product result. int num_common_variables = 0; auto it_a = a.var_to_degree_map().begin(); auto it_b = b.var_to_degree_map().begin(); // Since the keys in var_to_degree_map are sorted, we can loop through // a.var_to_degree_map and b.var_to_degree_map jointly to find the common // variables. while (it_a != a.var_to_degree_map().end() && it_b != b.var_to_degree_map().end()) { const Variable& var_a = it_a->first; const Variable& var_b = it_b->first; if (var_a.less(var_b)) { // var_a is less than var_b, and hence var_a less than all variables in b // after var_b. We can increment it_a. it_a++; } else if (var_b.less(var_a)) { it_b++; } else { num_common_variables++; it_a++; it_b++; } } // The number of ChebyshevBasisElement in the product result is // 2^num_common_variables. std::vector<std::map<Variable, int>> chebyshev_basis_all( power_of_2(num_common_variables)); // I will go through the (variable, degree) pair of both a and b. If the // variable shows up in only a or b, then each term in the product a * b // contains that variable and its degree. If a has term Tₘ(x) and b has term // Tₙ(x), where x is the common variable, then half of the basis in a * b // contains term Tₘ₊ₙ(x), and the other half contains Tₘ₋ₙ(x). int common_variables_count = 0; it_a = a.var_to_degree_map().begin(); it_b = b.var_to_degree_map().begin(); // Note that var_to_degree_map() has its keys sorted in an increasing order. while (it_a != a.var_to_degree_map().end() && it_b != b.var_to_degree_map().end()) { const Variable& var_a = it_a->first; const int degree_a = it_a->second; const Variable& var_b = it_b->first; const int degree_b = it_b->second; if (var_a.less(var_b)) { // var_a is not a common variable, add (var_a, degree_a) to each element // in chebyshev_basis_all. AppendVariableAndDegree(var_a, degree_a, &chebyshev_basis_all); it_a++; } else if (var_b.less(var_a)) { // var_b is not a common variable, add (var_b, degree_b) to each element // in chebyshev_basis_all. AppendVariableAndDegree(var_b, degree_b, &chebyshev_basis_all); it_b++; } else { // Add (var_common, degree_a + degree_b) to half of the elements in // chebyshev_basis_all, and (var_common, |degree_a - degree_b| to the // other half of the elements in chebyshev_basis_all. // If we denote 2 ^ common_variables_count = n, then we add (var_common, // degree_a + degree_b) to the chebyshev_basis_all[i], if i is in the // interval of [j * 2n, j * 2n + n) for some j, and we add (var_common, // |degree_a - degree_b|) to chebyshev_basis_all[i] if i is in the // interval [j * 2n + n, (j+1) * 2n). const int degree_sum = degree_a + degree_b; const int degree_diff = std::abs(degree_a - degree_b); const int n = power_of_2(common_variables_count); for (int j = 0; j < power_of_2(num_common_variables - common_variables_count - 1); ++j) { for (int i = j * 2 * n; i < j * 2 * n + n; ++i) { chebyshev_basis_all[i].emplace(var_a, degree_sum); } for (int i = j * 2 * n + n; i < (j + 1) * 2 * n; ++i) { chebyshev_basis_all[i].emplace(var_a, degree_diff); } } it_a++; it_b++; common_variables_count++; } } // Now either or both it_a or it_b is at the end of var_to_degree_map.end(), // if it_a != a.var_to_degree_map().end(), then the remaining variables after // it_a in a.var_to_degree_map cannot be a common variable. Append the rest of // the (variable, degree) to the Chebyshev basis. for (; it_a != a.var_to_degree_map().end(); ++it_a) { AppendVariableAndDegree(it_a->first, it_a->second, &chebyshev_basis_all); } for (; it_b != b.var_to_degree_map().end(); ++it_b) { AppendVariableAndDegree(it_b->first, it_b->second, &chebyshev_basis_all); } const double coeff = 1.0 / power_of_2(num_common_variables); std::map<ChebyshevBasisElement, double> result; for (const auto& var_to_degree_map : chebyshev_basis_all) { result.emplace(ChebyshevBasisElement(var_to_degree_map), coeff); } return result; } std::ostream& operator<<(std::ostream& out, const ChebyshevBasisElement& m) { if (m.var_to_degree_map().empty()) { out << "T0()"; } else { for (const auto& [var, degree] : m.var_to_degree_map()) { out << ChebyshevPolynomial(var, degree); } } return out; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/monomial_util.cc
#include "drake/common/symbolic/monomial_util.h" #include <algorithm> #include <vector> #include "drake/common/drake_assert.h" #include "drake/common/ssize.h" namespace drake { namespace symbolic { Eigen::Matrix<Monomial, Eigen::Dynamic, 1> MonomialBasis(const Variables& vars, const int degree) { return internal::ComputeMonomialBasis<Eigen::Dynamic>( vars, degree, internal::DegreeType::kAny); } VectorX<Monomial> MonomialBasis( const std::unordered_map<Variables, int>& vars_degree) { // Check if the variables overlap. Variables all_vars; for (const auto& [vars, degree] : vars_degree) { for (const auto& var : vars) { if (all_vars.include(var)) { throw std::runtime_error(fmt::format( "MonomialBasis(): {} shows up more than once in vars_degree", var.get_name())); } all_vars.insert(var); } } // First we generate the monomials for each (vars, degree) pair. std::vector<VectorX<Monomial>> monomial_basis_each_vars; for (const auto& [vars, degree] : vars_degree) { monomial_basis_each_vars.push_back(MonomialBasis(vars, degree)); } // Now we collect all the possible combinations of the monomials. Namely for // each i, we take an arbitrary element from monomial_basis_each_vars[i], // and multiply these elements together. We insert the multiplied new // monomial into `basis`. std::vector<Monomial> basis; basis.reserve(std::accumulate( monomial_basis_each_vars.begin(), monomial_basis_each_vars.end(), 1, [](int prod, const VectorX<Monomial>& monomial_vec) { return prod * (monomial_vec.rows()); })); // Insert the 1 monomial. basis.emplace_back(); for (const auto& monomial_vec : monomial_basis_each_vars) { const int monomials_count = ssize(basis); // The last element of monomial_vec should be 1. DRAKE_ASSERT(monomial_vec[monomial_vec.rows() - 1].total_degree() == 0); // Insert the whole monomial_vec besides the 1 monomial which is at the end. basis.insert(basis.end(), monomial_vec.data(), monomial_vec.data() + monomial_vec.rows() - 1); // Start at 1 since basis(0) is the 1 monomial, which we have already // considered in the previous line. for (int i = 1; i < monomials_count; ++i) { // Stop before the 1 monomial at the end of monomial_vec. for (int j = 0; j < monomial_vec.rows() - 1; ++j) { basis.push_back(basis.at(i) * monomial_vec(j)); } } } std::sort(basis.begin(), basis.end(), GradedReverseLexOrder<std::less<Variable>>()); return Eigen::Map<VectorX<Monomial>>(basis.data(), basis.size()); } Eigen::Matrix<Monomial, Eigen::Dynamic, 1> EvenDegreeMonomialBasis( const Variables& vars, int degree) { return internal::ComputeMonomialBasis<Eigen::Dynamic>( vars, degree, internal::DegreeType::kEven); } Eigen::Matrix<Monomial, Eigen::Dynamic, 1> OddDegreeMonomialBasis( const Variables& vars, int degree) { return internal::ComputeMonomialBasis<Eigen::Dynamic>( vars, degree, internal::DegreeType::kOdd); } namespace { // Generates all the monomials with degree up to 1 for each variable, for all // the variables in x[start], x[start+1], ..., x.back(). Append these monomials // to `monomial_basis`. // @param[in/out] monomial_basis We assume that as the input, monomial_basis // doesn't contain x[start] in its variables. As an output, the new monomials // that contain x[start] will be appended to monomial_basis. void CalcMonomialBasisOrderUpToOneHelper( const std::vector<Variable>& x, int start, std::vector<Monomial>* monomial_basis) { DRAKE_DEMAND(start >= 0 && start < static_cast<int>(x.size())); if (start == static_cast<int>(x.size() - 1)) { // Generate the monomial for a single variable, which is 1 and the variable // itself. monomial_basis->emplace_back(); monomial_basis->emplace_back(x[start], 1); return; } else { // First generate the monomials using all the variables x[start + 1] ... // x[x.size() - 1] CalcMonomialBasisOrderUpToOneHelper(x, start + 1, monomial_basis); const int monomial_count = monomial_basis->size(); // Construct the monomial x[start]. const Monomial x_start(x[start], 1); // Multiply x_start to each monomial already in monomial_set, and append the // multiplication result to monomial_set. for (int i = 0; i < monomial_count; ++i) { monomial_basis->push_back(x_start * (*monomial_basis)[i]); } return; } } } // namespace VectorX<Monomial> CalcMonomialBasisOrderUpToOne(const Variables& x, bool sort_monomial) { std::vector<Variable> x_vec; x_vec.reserve(x.size()); for (const auto& var : x) { x_vec.push_back(var); } std::vector<Monomial> monomial_basis; // There will be pow(2, x.size()) monomials in the basis. monomial_basis.reserve(1 << static_cast<int>(x.size())); CalcMonomialBasisOrderUpToOneHelper(x_vec, 0, &monomial_basis); VectorX<Monomial> ret(monomial_basis.size()); if (sort_monomial) { std::sort(monomial_basis.begin(), monomial_basis.end(), GradedReverseLexOrder<std::less<Variable>>()); } for (int i = 0; i < ret.rows(); ++i) { ret(i) = monomial_basis[i]; } return ret; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/polynomial_basis_element.cc
#include "drake/common/symbolic/polynomial_basis_element.h" #include <algorithm> #include <numeric> #include <stdexcept> #include <typeinfo> #include <utility> #include <fmt/format.h> namespace drake { namespace symbolic { namespace { std::map<Variable, int> ToVarToDegreeMap( const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& exponents) { DRAKE_DEMAND(vars.size() == exponents.size()); std::map<Variable, int> powers; for (int i = 0; i < vars.size(); ++i) { if (powers.contains(vars[i])) { throw std::invalid_argument(fmt::format( "PolynomialBasisElement: {} is repeated", vars[i].get_name())); } if (exponents[i] > 0) { powers.emplace(vars[i], exponents[i]); } else if (exponents[i] < 0) { throw std::logic_error("The exponent is negative."); } } return powers; } } // namespace PolynomialBasisElement::PolynomialBasisElement( const std::map<Variable, int>& var_to_degree_map) { total_degree_ = std::accumulate( var_to_degree_map.begin(), var_to_degree_map.end(), 0, [](const int degree, const std::pair<const Variable, int>& p) { return degree + p.second; }); for (const auto& p : var_to_degree_map) { if (p.second > 0) { var_to_degree_map_.insert(p); } else if (p.second < 0) { throw std::logic_error( fmt::format("The degree for {} is negative.", p.first.get_name())); } // Ignore the entry if the degree == 0. } } PolynomialBasisElement::PolynomialBasisElement( const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& degrees) : PolynomialBasisElement(ToVarToDegreeMap(vars, degrees)) {} int PolynomialBasisElement::degree(const Variable& v) const { auto it = var_to_degree_map_.find(v); if (it == var_to_degree_map_.end()) { return 0; } else { return it->second; } } Variables PolynomialBasisElement::GetVariables() const { Variables vars{}; for (const auto& p : var_to_degree_map_) { vars += p.first; } return vars; } double PolynomialBasisElement::Evaluate(const Environment& env) const { return accumulate( var_to_degree_map().begin(), var_to_degree_map().end(), 1.0, [this, &env](const double v, const std::pair<const Variable, int>& p) { const Variable& var{p.first}; const auto it = env.find(var); if (it == env.end()) { throw std::invalid_argument( fmt::format("Evaluate: {} is not in env", var.get_name())); } else { return v * this->DoEvaluate(it->second, p.second); } }); } bool PolynomialBasisElement::operator==( const PolynomialBasisElement& other) const { return typeid(*this) == typeid(other) && EqualTo(other); } bool PolynomialBasisElement::EqualTo( const PolynomialBasisElement& other) const { if (var_to_degree_map_.size() != other.var_to_degree_map_.size()) { return false; } for (auto it1 = var_to_degree_map_.begin(), it2 = other.var_to_degree_map_.begin(); it1 != var_to_degree_map_.end(); ++it1, ++it2) { const Variable& var1{it1->first}; const Variable& var2{it2->first}; const int degree1{it1->second}; const int degree2{it2->second}; if (!var1.equal_to(var2) || degree1 != degree2) { return false; } } return true; } bool PolynomialBasisElement::operator!=( const PolynomialBasisElement& other) const { return !(*this == other); } bool PolynomialBasisElement::lexicographical_compare( const PolynomialBasisElement& other) const { DRAKE_ASSERT(typeid(*this) == typeid(other)); return std::lexicographical_compare( var_to_degree_map_.begin(), var_to_degree_map_.end(), other.var_to_degree_map_.begin(), other.var_to_degree_map_.end(), [](const std::pair<const Variable, int>& p1, const std::pair<const Variable, int>& p2) { const Variable& v1{p1.first}; const int i1{p1.second}; const Variable& v2{p2.first}; const int i2{p2.second}; if (v1.less(v2)) { // m2 does not have the variable v1 explicitly, so we treat it as if // it has (v1)⁰. That is, we need "return i1 < 0", but i1 should be // positive, so this case always returns false. return false; } if (v2.less(v1)) { // m1 does not have the variable v2 explicitly, so we treat it as // if it has (v2)⁰. That is, we need "return 0 < i2", but i2 should // be positive, so it always returns true. return true; } return i1 < i2; }); } symbolic::Expression PolynomialBasisElement::ToExpression() const { return DoToExpression(); } void PolynomialBasisElement::DoEvaluatePartial( const Environment& env, double* coeff, std::map<Variable, int>* new_basis_element) const { DRAKE_ASSERT(coeff != nullptr); DRAKE_ASSERT(new_basis_element != nullptr); DRAKE_ASSERT(new_basis_element->empty()); *coeff = 1; for (const auto& [var, degree] : var_to_degree_map_) { auto it = env.find(var); if (it != env.end()) { *coeff *= DoEvaluate(it->second, degree); } else { new_basis_element->emplace(var, degree); } } } void PolynomialBasisElement::DoMergeBasisElementInPlace( const PolynomialBasisElement& other) { DRAKE_ASSERT(typeid(*this) == typeid(other)); auto it1 = this->var_to_degree_map_.begin(); auto it2 = other.var_to_degree_map_.begin(); while (it1 != this->var_to_degree_map_.end() && it2 != other.var_to_degree_map_.end()) { if (it1->first.equal_to(it2->first)) { it1->second += it2->second; it1++; it2++; } else if (it2->first.less(it1->first)) { this->var_to_degree_map_.insert(it1, std::make_pair(it2->first, it2->second)); it2++; } else { // it1->first < it2->first. it1++; } } while (it2 != other.var_to_degree_map_.end()) { this->var_to_degree_map_.insert(this->var_to_degree_map_.end(), std::make_pair(it2->first, it2->second)); it2++; } total_degree_ += other.total_degree_; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/polynomial_basis.h
#pragma once #include <functional> #include <map> #include <set> #include <Eigen/Core> #include "drake/common/drake_assert.h" #include "drake/common/symbolic/expression.h" #include "drake/common/symbolic/monomial_util.h" #include "drake/common/symbolic/polynomial.h" #include "drake/common/symbolic/polynomial_basis_element.h" namespace drake { namespace symbolic { namespace internal { /* Adds the set {RaisePower(b, m) for m in Basis(vars, degree)} to `bin`. `Basis` is the polynomial basis associated with `BasisElement` and `Basis(vars, degree)` returns all BasisElement objects with variables `vars` and total degree = `degree`. RaisePower(m, b) is the operation that "merges" two `BasisElement`s such that the merged `BasisElement`: - Is a product of all variables present in either m or b. - The power of variable v is the sum of the degree of that variable in m and b. If a variable is missing in a BasisElement, it has degree 0. As a concrete example, assume that BasisElement is actually MonomialBasisElement with vars = {x, y}, degree = 2, and b = x²yz³. MonomialBasis({x, y}, 2) would produce the set of MonomialBasisElements: x², xy, y². And applying RaisePower(b, m) to each m would produce: - RaisePower(x²yz³, x²) --> x⁴yz³ - RaisePower(x²yz³, xy) --> x³y²z³ - RaisePower(x²yz³, y²) --> x²y³z³ @tparam BasisElementOrder a total order of PolynomialBasisElement. An example is BasisElementGradedReverseLexOrder. @tparam BasisElement A derived class of PolynomialBasisElement. @note A non-zero degree has no effect if vars is empty. If vars is empty and degree is zero, then {RaisePower(b, m) for m in Basis(vars, degree)} = {b}. */ template <typename BasisElementOrder, typename BasisElement> void AddPolynomialBasisElementsOfDegreeN( const Variables& vars, int degree, const BasisElement& b, std::set<BasisElement, BasisElementOrder>* const bin) { /* Iterating through Basis(vars, degree) is tricky due to the fact that the number of variables is determined at runtime. For example, assume the MonomialBasisElement with vars = {x, y, z} and degree = 3, then Basis({x, y, z}, 3) would produce the basis elements: x³, x²y, xy², xyz, y³, y²z, yz², z³. Conceptually, this matches well to nested for loops. Each for loop "consumes" a portion of the target degree, leaving the remaining part to the nested loops. for (int p_x = degree; p_x >= 0; --p_x) { for (int p_y = degree - p_x; p_y >= 0; --p_y) { for (int p_z = degree - p_x - p_y; p_z >= 0; --p_z) { Monomial m = x ** p_x * y ** p_y * z ** p_z; // Ok, not real code. bin->insert(RaisePower(m, b)); } } } However, if we add another variable, we have to add another nested for loop. We can't do that dynamically. So, we use recursion to create the *effect* of a dynamically-determined number of nested for loops. Each level of the recursion selects the "first" variable in the set and iteratively consumes some portion of the target degree. The recursive call is made on the remaining variables with the remaining available degree. The consumed portion is preserved by pre-multiplying it with the `b` value and passing on this accumulated b to the recursive call. RaisePower(m, b) is simply m * b. We can refactor the product: RaisePower(m, b) = RaisePower(m/xⁱ, b * xⁱ) and this relationship is the recursive call. */ static_assert( std::is_base_of_v<PolynomialBasisElement, BasisElement> || std::is_same_v<BasisElement, Monomial>, "BasisElement should be a derived class of PolynomialBasisElement"); if (degree == 0) { bin->insert(b); return; } if (vars.empty()) { return; } const Variable& var{*vars.cbegin()}; for (int var_degree = degree; var_degree >= 0; --var_degree) { std::map<Variable, int> new_var_to_degree_map = b.get_powers(); auto it = new_var_to_degree_map.find(var); if (it != new_var_to_degree_map.end()) { it->second += var_degree; } else { new_var_to_degree_map.emplace_hint(it, var, var_degree); } const BasisElement new_b(new_var_to_degree_map); AddPolynomialBasisElementsOfDegreeN(vars - var, degree - var_degree, new_b, bin); } } } // namespace internal /** * Returns all polynomial basis elements up to a given degree under the graded * reverse lexicographic order. * @tparam rows Number of rows or Eigen::Dynamic. * @tparam BasisElement A derived class of PolynomialBasisElement. * @param vars The variables appearing in the polynomial basis. * @param degree The highest total degree of the polynomial basis elements. * @param degree_type If degree_type is kAny, then the polynomial basis * elements' degrees are no larger than @p degree. If degree_type is kEven, then * the elements' degrees are even numbers no larger than @p degree. If * degree_type is kOdd, then the elements' degrees are odd numbers no larger * than @p degree. * TODO(hongkai.dai): this will replace ComputeMonomialBasis in monomial_util.h. */ template <int rows, typename BasisElement> Eigen::Matrix<BasisElement, rows, 1> ComputePolynomialBasisUpToDegree( const Variables& vars, int degree, internal::DegreeType degree_type) { DRAKE_DEMAND(!vars.empty()); DRAKE_DEMAND(degree >= 0); // 1. Collect elements. std::set<BasisElement, BasisElementGradedReverseLexOrder<std::less<Variable>, BasisElement>> basis_elements_set; int start_degree = 0; int degree_stride = 1; switch (degree_type) { case internal::DegreeType::kAny: { start_degree = 0; degree_stride = 1; break; } case internal::DegreeType::kEven: { start_degree = 0; degree_stride = 2; break; } case internal::DegreeType::kOdd: { start_degree = 1; degree_stride = 2; } } for (int i = start_degree; i <= degree; i += degree_stride) { internal::AddPolynomialBasisElementsOfDegreeN(vars, i, BasisElement{}, &basis_elements_set); } // 2. Prepare the return value, basis. DRAKE_DEMAND((rows == Eigen::Dynamic) || (static_cast<size_t>(rows) == basis_elements_set.size())); Eigen::Matrix<BasisElement, rows, 1> basis(basis_elements_set.size()); int i{0}; for (const auto& m : basis_elements_set) { basis[i] = m; i++; } return basis; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/expression.h
#pragma once /// @file /// When using Drake's symbolic expressions library (e.g., the classes /// drake::symbolic::Expression or drake::symbolic::Formula), we provide /// a single include statement to cover all of the required classes: /// `#include <drake/common/symbolic/expression.h>`. // Delegate the internal implementation details to our subdirectory. #include "drake/common/symbolic/expression/all.h"
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/trigonometric_polynomial.cc
#include "drake/common/symbolic/trigonometric_polynomial.h" #include <map> #include <optional> #include <set> #include <stdexcept> #include <string> #include <utility> #define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/expression/expression_cell.h" #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include <fmt/format.h> namespace drake { namespace symbolic { namespace { enum TrigStatus { kNotSinCos, kInsideSin, kInsideCos, }; // Visitor class for sin/cos substitution. class SinCosVisitor { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SinCosVisitor) explicit SinCosVisitor(SinCosSubstitution s) : subs_{std::move(s)} {}; [[nodiscard]] Expression Substitute( const Expression& e, std::optional<bool> needs_substitution = std::nullopt) const { if (!needs_substitution.has_value()) { needs_substitution = false; Variables vars = e.GetVariables(); for (const auto& sc : subs_) { if (vars.find(sc.first) != vars.end()) { needs_substitution = true; } } } if (*needs_substitution) { return VisitExpression<Expression, const SinCosVisitor, TrigStatus>( this, e, kNotSinCos); } else { return e; } } [[nodiscard]] Expression VisitVariable(const Expression& e, TrigStatus status) const { auto iter = subs_.find(get_variable(e)); if (iter == subs_.end()) { return e; } else if (status == kInsideSin) { return iter->second.type == SinCosSubstitutionType::kAngle ? iter->second.s : 2 * iter->second.s * iter->second.c; } else if (status == kInsideCos) { switch (iter->second.type) { case SinCosSubstitutionType::kAngle: return iter->second.c; case SinCosSubstitutionType::kHalfAnglePreferSin: return 1 - 2 * iter->second.s * iter->second.s; case SinCosSubstitutionType::kHalfAnglePreferCos: return 2 * iter->second.c * iter->second.c - 1; } } return e; } [[nodiscard]] Expression VisitConstant(const Expression& e, TrigStatus status) const { if (status == kInsideSin) { return sin(e); } else if (status == kInsideCos) { return cos(e); } return e; } [[nodiscard]] Expression VisitAddition(const Expression& e, TrigStatus status) const { const double c{get_constant_in_addition(e)}; std::map<Expression, double> expr_to_coeff_map{ get_expr_to_coeff_map_in_addition(e)}; if (status == kInsideSin) { if (c != 0.0) { return sin(c) * Substitute(cos(e - c), true) + cos(c) * Substitute(sin(e - c), true); } // Recursively substitute sin(x + y) where x is the first term, and y is // all the rest. auto x = expr_to_coeff_map.extract(expr_to_coeff_map.begin()); Expression y = ExpressionAddFactory(0, expr_to_coeff_map).GetExpression(); return Substitute(sin(x.key() * x.mapped())) * Substitute(cos(y)) + Substitute(cos(x.key() * x.mapped())) * Substitute(sin(y)); } else if (status == kInsideCos) { if (c != 0.0) { return cos(c) * Substitute(cos(e - c), true) - sin(c) * Substitute(sin(e - c), true); } // Recursively substitute cos(x + y) where x is the first term, and y is // all the rest. auto x = expr_to_coeff_map.extract(expr_to_coeff_map.begin()); Expression y = ExpressionAddFactory(0, expr_to_coeff_map).GetExpression(); return Substitute(cos(x.key() * x.mapped())) * Substitute(cos(y)) - Substitute(sin(x.key() * x.mapped())) * Substitute(sin(y)); } Expression v{c}; for (const auto& [term, coeff] : expr_to_coeff_map) { v += coeff * Substitute(term); } return v; } [[nodiscard]] Expression VisitMultiplication(const Expression& e, TrigStatus status) const { const double c{get_constant_in_multiplication(e)}; const std::map<Expression, Expression>& base_to_exponent_map{ get_base_to_exponent_map_in_multiplication(e)}; if (status == kInsideSin) { std::string msg = fmt::format( "Got sin({}), but we only support sin(c*x) where c is an integer (c " "= +/- 0.5 is also supported if performing a half-angle " "substitution), and x is a variable to be substituted.", e.to_string()); if (base_to_exponent_map.size() != 1 || base_to_exponent_map.begin()->second != 1.0) { throw std::runtime_error(msg); } Expression x = base_to_exponent_map.begin()->first; if (!is_variable(x)) { throw std::runtime_error(msg); } auto iter = subs_.find(get_variable(x)); if (iter == subs_.end()) { throw std::runtime_error(msg); } if (iter->second.type != SinCosSubstitutionType::kAngle) { // Handle special case of sin(±0.5*x). if (c == 0.5) { return iter->second.s; } else if (c == -0.5) { return -iter->second.s; } // TODO(russt): Handle the cases where c is an odd multiple of 0.5. } double c_int; if (modf(c, &c_int) != 0.0) { throw std::runtime_error(msg); } if (c_int == 0.0) { return 0.0; // Don't expect to get here, though. } else if (c_int == 1.0) { return Substitute(sin(x), true); } else if (c_int > 1.0) { // TODO(russt): Use // https://mathworld.wolfram.com/Multiple-AngleFormulas.html to avoid // this recursive computation. return Substitute( sin(x) * cos((c_int - 1) * x) + cos(x) * sin((c_int - 1) * x), true); } else if (c_int < 0.0) { return Substitute(-sin(-c_int * x), true); } throw std::runtime_error("Got unexpected 0 < c_int < 1"); } else if (status == kInsideCos) { std::string msg = fmt::format( "Got cos({}), but we only support cos(c*x) where c is an integer (c " "= +/- 0.5 is also supported if performing a half-angle " "substitution), and x is a variable to be substituted.", e.to_string()); if (base_to_exponent_map.size() != 1 || base_to_exponent_map.begin()->second != 1.0) { throw std::runtime_error(msg); } Expression x = base_to_exponent_map.begin()->first; if (!is_variable(x)) { throw std::runtime_error(msg); } auto iter = subs_.find(get_variable(x)); if (iter == subs_.end()) { throw std::runtime_error(msg); } if (iter->second.type != SinCosSubstitutionType::kAngle) { // Handle special case of cos(±0.5*x). if (c == 0.5 || c == -0.5) { return iter->second.c; } // TODO(russt): Handle the cases where c is an odd multiple of 0.5. } double c_int; if (modf(c, &c_int) != 0.0) { throw std::runtime_error(msg); } if (c_int == 0.0) { return 1.0; // Don't expect to get here, though. } else if (c_int == 1.0) { return Substitute(cos(x), true); } else if (c_int > 1.0) { // TODO(russt): Use // https://mathworld.wolfram.com/Multiple-AngleFormulas.html to avoid // this recursive computation. return Substitute( cos(x) * cos((c_int - 1) * x) - sin(x) * sin((c_int - 1) * x), true); } else if (c_int < 0.0) { return Substitute(cos(-c_int * x), true); } throw std::runtime_error("Got unexpected 0 < c_int < 1"); } Expression v{c}; for (const auto& [base, exponent] : base_to_exponent_map) { v *= pow(Substitute(base), Substitute(exponent)); } return v; } // Helper method to handle unary cases. [[nodiscard]] Expression VisitUnary( const std::function<Expression(const Expression&)>& pred, const Expression& e) const { // Getting here implies that get_argument(e) needs substitution. return pred(Substitute(get_argument(e), true)); } // Helper method to handle binary cases. [[nodiscard]] Expression VisitBinary( const std::function<Expression(const Expression&, const Expression&)>& pred, const Expression& e) const { return pred(Substitute(get_first_argument(e)), Substitute(get_second_argument(e))); } [[nodiscard]] Expression VisitPow(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return pow(Substitute(get_first_argument(e)), Substitute(get_second_argument(e))); } [[nodiscard]] Expression VisitDivision(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return Substitute(get_first_argument(e)) / Substitute(get_second_argument(e)); } [[nodiscard]] Expression VisitAbs(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(abs, e); } [[nodiscard]] Expression VisitLog(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(log, e); } [[nodiscard]] Expression VisitExp(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(exp, e); } [[nodiscard]] Expression VisitSqrt(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(sqrt, e); } [[nodiscard]] Expression VisitSin(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); // Do not support nested sin/cos. return VisitExpression<Expression, const SinCosVisitor, TrigStatus>( this, get_argument(e), kInsideSin); } [[nodiscard]] Expression VisitCos(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); // Do not support nested sin/cos. return VisitExpression<Expression, const SinCosVisitor, TrigStatus>( this, get_argument(e), kInsideCos); } [[nodiscard]] Expression VisitTan(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); // Do not support nested sin/cos. return Substitute(sin(get_argument(e))) / Substitute(cos(get_argument(e))); } [[nodiscard]] Expression VisitAsin(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(asin, e); } [[nodiscard]] Expression VisitAcos(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(acos, e); } [[nodiscard]] Expression VisitAtan(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(atan, e); } [[nodiscard]] Expression VisitAtan2(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitBinary(atan2, e); } [[nodiscard]] Expression VisitSinh(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(sinh, e); } [[nodiscard]] Expression VisitCosh(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(cosh, e); } [[nodiscard]] Expression VisitTanh(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(tanh, e); } [[nodiscard]] Expression VisitMin(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitBinary(min, e); } [[nodiscard]] Expression VisitMax(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitBinary(max, e); } [[nodiscard]] Expression VisitCeil(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(ceil, e); } [[nodiscard]] Expression VisitFloor(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); return VisitUnary(floor, e); } [[nodiscard]] Expression VisitIfThenElse(const Expression& e, TrigStatus status) const { DRAKE_THROW_UNLESS(status == kNotSinCos); // We don't support Formulas yet, so need to throw if the Formula requires // any substitutions. Variables vars = get_conditional_formula(e).GetFreeVariables(); for (const auto& sc : subs_) { if (vars.find(sc.first) != vars.end()) { throw std::runtime_error( "Substituting sin/cos into formulas is not supported yet"); } } // TODO(russt): substitute conditional once we visit formulas. return if_then_else(get_conditional_formula(e), Substitute(get_then_expression(e)), Substitute(get_else_expression(e))); } [[nodiscard]] Expression VisitUninterpretedFunction(const Expression&, TrigStatus) const { throw std::runtime_error( "SubstituteSinCos does not support uninterpreted functions."); } private: SinCosSubstitution subs_; }; } // namespace Expression Substitute(const Expression& e, const SinCosSubstitution& subs) { return SinCosVisitor(subs).Substitute(e); } namespace internal { symbolic::RationalFunction SubstituteStereographicProjectionImpl( const symbolic::Polynomial& e_poly, const std::vector<SinCos>& sin_cos, const symbolic::Variables& sin_cos_set, const VectorX<symbolic::Variable>& t, const symbolic::Variables& t_set, const VectorX<symbolic::Polynomial>& one_plus_t_angles_squared, const VectorX<symbolic::Polynomial>& two_t_angles, const VectorX<symbolic::Polynomial>& one_minus_t_angles_squared) { DRAKE_DEMAND(static_cast<int>(sin_cos.size()) == t.rows()); DRAKE_DEMAND(one_plus_t_angles_squared.size() == t.rows()); DRAKE_DEMAND(two_t_angles.size() == t.rows()); DRAKE_DEMAND(one_minus_t_angles_squared.size() == t.rows()); // We first count the degree of each sin(θᵢ) and cos(θᵢ) variable. // sin_cos_degrees[i] is the maximal of monomial.degree(cos(θᵢ)) + // monomial.degree(sin(θᵢ)) for every monomial in e_poly. std::vector<int> sin_cos_degrees(t.rows(), 0); for (const auto& [monomial, unused] : e_poly.monomial_to_coefficient_map()) { for (int i = 0; i < t.rows(); ++i) { const int n = monomial.degree(sin_cos[i].s) + monomial.degree(sin_cos[i].c); if (n > sin_cos_degrees[i]) { sin_cos_degrees[i] = n; } } } // The denominator is Πᵢ (1 + tᵢ²)ᵈⁱ, where dᵢ = sin_cos_degrees[i] symbolic::Polynomial denominator{1}; for (int i = 0; i < t.rows(); ++i) { const int d_i = sin_cos_degrees[i]; if (d_i > 0) { denominator *= pow(one_plus_t_angles_squared(i), d_i); } } // Now go through each monomial to compute the numerator. symbolic::Polynomial numerator{0}; for (const auto& [monomial, coeff] : e_poly.monomial_to_coefficient_map()) { // We substitute sin(θᵢ) and cos(θᵢ) in each monomial, but keep the rest of // the monomial. We store the substitution result in post_subs. // First the coefficient is unchanged. But since the coefficient might // contain `t` in its variables, we need to re-parse the coefficient with // indeterminates in t. symbolic::Polynomial post_subs = symbolic::Polynomial(coeff, t_set); // Loop through each variable in monomial for (const auto& [var, degree] : monomial.get_powers()) { if (sin_cos_set.find(var) == sin_cos_set.end()) { // This is not a sin or cos variable. Keep this variable after // substitution. post_subs *= symbolic::Monomial(var, degree); } } // Now I only need to handle each sin and cos variable as the other // variables have been included in post_subs already. for (int i = 0; i < t.rows(); ++i) { // If we have pow(sin(θᵢ), d₁)*pow(cos(θᵢ), d₂), we want to substitute it // as pow(2tᵢ, d₁)*pow(1−tᵢ², d₂) / pow(1+tᵢ², d₁+d₂). The denominator // already has the term pow(1+tᵢ², sin_cos_degrees[i]), hence we want the // term pow(2tᵢ, d₁)*pow(1−tᵢ², d₂) * pow(1+tᵢ², sin_cos_degrees[i]-d₁-d₂) // in the numerator. const int d1 = monomial.degree(sin_cos[i].s); const int d2 = monomial.degree(sin_cos[i].c); if (d1 > 0) { post_subs *= pow(two_t_angles(i), d1); } if (d2 > 0) { post_subs *= pow(one_minus_t_angles_squared(i), d2); } if (sin_cos_degrees[i] - d1 - d2 > 0) { post_subs *= pow(one_plus_t_angles_squared(i), sin_cos_degrees[i] - d1 - d2); } } numerator += post_subs; } return symbolic::RationalFunction(numerator, denominator); } } // namespace internal symbolic::RationalFunction SubstituteStereographicProjection( const symbolic::Polynomial& e_poly, const std::vector<SinCos>& sin_cos, const VectorX<symbolic::Variable>& t) { const symbolic::Monomial monomial_one{}; VectorX<symbolic::Polynomial> one_minus_t_square(t.rows()); VectorX<symbolic::Polynomial> two_t(t.rows()); VectorX<symbolic::Polynomial> one_plus_t_square(t.rows()); for (int i = 0; i < t.rows(); ++i) { one_minus_t_square[i] = symbolic::Polynomial( {{monomial_one, 1}, {symbolic::Monomial(t(i), 2), -1}}); two_t[i] = symbolic::Polynomial({{symbolic::Monomial(t(i), 1), 2}}); one_plus_t_square[i] = symbolic::Polynomial( {{monomial_one, 1}, {symbolic::Monomial(t(i), 2), 1}}); } symbolic::Variables sin_cos_set; for (const auto& sc : sin_cos) { sin_cos_set.insert(sc.s); sin_cos_set.insert(sc.c); } const symbolic::Variables t_set{t}; return internal::SubstituteStereographicProjectionImpl( e_poly, sin_cos, sin_cos_set, t, t_set, one_plus_t_square, two_t, one_minus_t_square); } symbolic::RationalFunction SubstituteStereographicProjection( const symbolic::Expression& e, const std::unordered_map<symbolic::Variable, symbolic::Variable>& subs) { // First substitute all cosθ and sinθ with cos_var and sin_var. SinCosSubstitution sin_cos_subs; symbolic::Variables sin_cos_vars; std::vector<SinCos> sin_cos_vec; sin_cos_vec.reserve(subs.size()); VectorX<symbolic::Variable> t_vars(subs.size()); int var_count = 0; for (const auto& [theta, t] : subs) { const SinCos sin_cos(Variable("s_" + theta.get_name()), Variable("c_" + theta.get_name()), SinCosSubstitutionType::kAngle); sin_cos_subs.emplace(theta, sin_cos); sin_cos_vars.insert(sin_cos.c); sin_cos_vars.insert(sin_cos.s); sin_cos_vec.push_back(sin_cos); t_vars(var_count) = t; var_count++; } const symbolic::Expression e_multilinear = Substitute(e, sin_cos_subs); // Now rewrite e_multilinear as a polynomial of sin and cos. const symbolic::Polynomial e_poly{e_multilinear, sin_cos_vars}; return SubstituteStereographicProjection(e_poly, sin_cos_vec, t_vars); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/trigonometric_polynomial.h
#pragma once #include <unordered_map> #include <utility> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/common/symbolic/expression.h" #include "drake/common/symbolic/rational_function.h" namespace drake { namespace symbolic { enum class SinCosSubstitutionType { /** Substitutes s <=> sin(q), c <=> cos(q). */ kAngle, /** Substitutes s <=> sin(q/2), c <=> cos(q/2), and prefers sin when the choice is ambiguous; e.g. cos(q) => 1 - 2s². */ kHalfAnglePreferSin, /** Substitutes s <=> sin(q/2), c <=> cos(q/2), and prefers cos when the choice is ambiguous; e.g. cos(q) => 2c² - 1. */ kHalfAnglePreferCos, }; /** Represents a pair of Variables corresponding to sin(q) and cos(q). */ struct SinCos { DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(SinCos); SinCos(Variable _s, Variable _c, SinCosSubstitutionType _type = SinCosSubstitutionType::kAngle) : s(std::move(_s)), c(std::move(_c)), type(_type) {} /** sin variable. */ Variable s{}; /** cos variable. */ Variable c{}; /** Allows a user to specify non-default substitutions, such as using half-angle formulas. */ SinCosSubstitutionType type{}; }; using SinCosSubstitution = std::unordered_map<Variable, SinCos>; /** Given a substitution map q => {s, c}, substitutes instances of sin(q) and cos(q) in `e` with `s` and `c`, with partial support for trigonometric expansions. For instance, @verbatim Variable x{"x"}, y{"y"}; Variable sx{"sx"}, cx{"cx"}, sy{"sy"}, cy{"cy"}; SinCosSubstitution subs; subs.emplace(x, SinCos(sx, cx)); subs.emplace(y, SinCos(sy, cy)); Expression e = Substitute(x * sin(x + y), subs); @endverbatim will result in the expression `x * (sx*cy + cx*sy)`. @param half_angle If true, then the same workflow replaces instances of sin(q/2) and cos(q/2) in `e` will be replaced with `s`, and `c`. @default false. The half-angle representation is more natural in many analysis computations for robots, for instance: https://underactuated.csail.mit.edu/lyapunov.html#trig_quadratic @throws std::exception if a trigonometric function is not a trigonometric polynomial in `q` or if the `e` requires a trigonometric expansion that not supported yet. @pydrake_mkdoc_identifier{sincos} */ Expression Substitute(const Expression& e, const SinCosSubstitution& subs); /** Matrix version of sin/cos substitution. @pydrake_mkdoc_identifier{sincos_matrix} */ template <typename Derived> MatrixLikewise<Expression, Derived> Substitute( const Eigen::MatrixBase<Derived>& m, const SinCosSubstitution& subs) { static_assert(std::is_same_v<typename Derived::Scalar, Expression>, "Substitute only accepts a matrix of symbolic::Expression."); // Note that the return type is written out explicitly to help gcc 5 (on // ubuntu). return m.unaryExpr([&subs](const Expression& e) { return Substitute(e, subs); }); } namespace internal { /* This is the actual implementation of SubstituteStereographicProjection(). We expose this function because repeated calls to SubstituteStereographicProjection() require re-constructing the polynomial 1+t², 2t, 1-t²; it is more efficient to construct these polynomials beforehand and then call SubstituteStereographicProjectionImpl() repeatedly. @param e_poly The polynomial before substitution. @param sin_cos The sin and cos variables in e_poly to be replaced. @param sin_cos_set The set including all variables in `sin_cos`. @param t We will replace sin and cos functions as rational functions of t. @param t_set The set of variables @p t. @param one_plus_t_angles_squared 1+t² @param two_t_angles 2t @param one_minus_t_angles_squared 1-t² @retval e_rational The rational polynomial after replacing sin/cos in @p e_poly with rational functions of t. @pre sin_cos, t, t_set, one_plus_t_angles_squared, two_t_angles, one_minus_t_angles_squared all have the same size. @pre The indeterminates in `e_poly` are `sin_cos`. */ symbolic::RationalFunction SubstituteStereographicProjectionImpl( const symbolic::Polynomial& e_poly, const std::vector<SinCos>& sin_cos, const symbolic::Variables& sin_cos_set, const VectorX<symbolic::Variable>& t, const symbolic::Variables& t_set, const VectorX<symbolic::Polynomial>& one_plus_t_angles_squared, const VectorX<symbolic::Polynomial>& two_t_angles, const VectorX<symbolic::Polynomial>& one_minus_t_angles_squared); } // namespace internal /** * Substitutes the variables representing sine and cosine functions with their * stereographic projection. * We replace cosθᵢ with (1-tᵢ²)/(1+tᵢ²), and sinθᵢ with 2tᵢ/(1+tᵢ²), and get a * rational polynomial. The indeterminates of this rational polynomial are t * together with the indeterminates in `e` that are not cosθ or sinθ. If the * input expression doesn't contain the sine and cosine functions, then the * returned rational has denominator being 1. Notice that the indeterminates of * `e` can include variables other than cosθ and sinθ, and we impose no * requirements on these variables that are not cosθ or sinθ. * * @param e The symbolic polynomial to be substituted. * @param sin_cos sin_cos(i) is the pair of variables (sᵢ, cᵢ), (where sᵢ=sinθᵢ, * cᵢ=cosθᵢ) as documented above. * @param t New variables to express cos and sin as rationals of t. tᵢ = * tan(θᵢ/2). * @pre t.rows() == sin_cos.size() * @return e_rational The rational polynomial of e after replacement. The * indeterminates of the polynomials are `t` together with the indeterminates in * `e` that are not cosθ or sinθ. Example * @verbatim * std::vector<SinCos> sin_cos; * sin_cos.emplace_back(symbolic::Variable("s0"), symbolic::Variable("c0")); * sin_cos.emplace_back(symbolic::Variable("s1"), symbolic::Variable("c1")); * Vector2<symbolic::Variable> t(symbolic::Variable("t0"), * symbolic::Variable("t1")); * const auto e_rational = * SubstituteStereographicProjection(t(0) * sin_cos[0].s*sin_cos[1].c + 1, * sin_cos, t); * // e_rational should be * // (2*t0*t0*(1-t1*t1) + (1+t0*t0)*(1+t1*t1)) * // -------------------------------------------- * // ((1+t0*t0)*(1+t1*t1)) * @endverbatim */ [[nodiscard]] symbolic::RationalFunction SubstituteStereographicProjection( const symbolic::Polynomial& e, const std::vector<SinCos>& sin_cos, const VectorX<symbolic::Variable>& t); } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/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 = "symbolic", visibility = ["//visibility:public"], deps = [ ":chebyshev_polynomial", ":codegen", ":expression", ":generic_polynomial", ":latex", ":monomial_util", ":polynomial", ":polynomial_basis", ":rational_function", ":replace_bilinear_terms", ":simplification", ":trigonometric_polynomial", ], ) drake_cc_library( name = "expression", hdrs = ["expression.h"], deps = [ "//common/symbolic/expression", ], ) drake_cc_library( name = "chebyshev_polynomial", srcs = ["chebyshev_polynomial.cc"], hdrs = ["chebyshev_polynomial.h"], deps = [ ":expression", ":polynomial", ], ) drake_cc_googletest( name = "chebyshev_polynomial_test", deps = [ ":chebyshev_polynomial", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_library( name = "codegen", srcs = ["codegen.cc"], hdrs = ["codegen.h"], deps = [ ":expression", ], ) drake_cc_googletest( name = "codegen_test", deps = [ ":codegen", ], ) drake_cc_library( name = "generic_polynomial", srcs = [ "chebyshev_basis_element.cc", "generic_polynomial.cc", "monomial_basis_element.cc", "polynomial_basis_element.cc", ], hdrs = [ "chebyshev_basis_element.h", "generic_polynomial.h", "monomial_basis_element.h", "polynomial_basis_element.h", ], deps = [ ":chebyshev_polynomial", ":expression", ], ) drake_cc_googletest( name = "chebyshev_basis_element_test", deps = [ ":generic_polynomial", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "generic_polynomial_test", deps = [ ":generic_polynomial", ":polynomial_basis", "//common/test_utilities:expect_no_throw", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "monomial_basis_element_test", deps = [ ":generic_polynomial", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "ostream_test", deps = [ ":generic_polynomial", ], ) drake_cc_googletest( name = "polynomial_basis_element_test", deps = [ ":generic_polynomial", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_library( name = "latex", srcs = ["latex.cc"], hdrs = ["latex.h"], deps = [ ":expression", ], ) drake_cc_googletest( name = "latex_test", deps = [ ":expression", ":latex", "//common/test_utilities:expect_throws_message", ], ) drake_cc_library( name = "monomial_util", srcs = ["monomial_util.cc"], hdrs = ["monomial_util.h"], deps = [ ":polynomial", ], ) drake_cc_googletest( name = "monomial_util_test", deps = [ ":monomial_util", "//common/test_utilities:expect_throws_message", ], ) drake_cc_library( name = "polynomial", srcs = [ "decompose.cc", "monomial.cc", "polynomial.cc", ], hdrs = [ "decompose.h", "monomial.h", "polynomial.h", ], interface_deps = [ ":expression", ], deps = [ "//math:quadratic_form", ], ) drake_cc_googletest( name = "decompose_test", deps = [ ":polynomial", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", ], ) drake_cc_googletest( name = "monomial_test", deps = [ ":monomial_util", ":polynomial", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "polynomial_test", deps = [ ":monomial_util", ":polynomial", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "polynomial_matrix_test", deps = [ ":polynomial", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_library( name = "polynomial_basis", hdrs = ["polynomial_basis.h"], deps = [ ":generic_polynomial", ":monomial_util", ":polynomial", ], ) drake_cc_googletest( name = "polynomial_basis_test", deps = [ ":polynomial_basis", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_library( name = "rational_function", srcs = ["rational_function.cc"], hdrs = ["rational_function.h"], deps = [ ":polynomial", ], ) drake_cc_googletest( name = "rational_function_test", deps = [ ":rational_function", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "rational_function_matrix_test", deps = [ ":rational_function", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_library( name = "replace_bilinear_terms", srcs = ["replace_bilinear_terms.cc"], hdrs = ["replace_bilinear_terms.h"], interface_deps = [ "//common:essential", "//common/symbolic:expression", ], deps = [ "//common/symbolic:polynomial", ], ) drake_cc_googletest( name = "replace_bilinear_terms_test", deps = [ ":replace_bilinear_terms", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_library( name = "simplification", srcs = ["simplification.cc"], hdrs = ["simplification.h"], deps = [ ":expression", ], ) drake_cc_googletest( name = "simplification_test", deps = [ ":simplification", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_library( name = "trigonometric_polynomial", srcs = ["trigonometric_polynomial.cc"], hdrs = ["trigonometric_polynomial.h"], deps = [ ":expression", ":rational_function", ], ) drake_cc_googletest( name = "trigonometric_polynomial_test", deps = [ ":trigonometric_polynomial", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) add_lint_tests()
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/replace_bilinear_terms.cc
#include "drake/common/symbolic/replace_bilinear_terms.h" #include <ostream> #include <sstream> #include <stdexcept> #include <unordered_map> #include "drake/common/symbolic/polynomial.h" namespace drake { namespace symbolic { using std::ostringstream; using std::runtime_error; using std::unordered_map; using MapVarToIndex = unordered_map<Variable::Id, int>; /* * Returns the map that maps x(i).get_id() to i. */ MapVarToIndex ConstructVarToIndexMap( const Eigen::Ref<const VectorX<symbolic::Variable>>& x) { MapVarToIndex map; map.reserve(x.rows()); for (int i = 0; i < x.rows(); ++i) { const auto it = map.find(x(i).get_id()); if (it != map.end()) { throw runtime_error("Input vector contains duplicate variable " + x(i).get_name()); } map.emplace_hint(it, x(i).get_id(), i); } return map; } Expression ReplaceBilinearTerms( const Expression& e, const Eigen::Ref<const VectorX<symbolic::Variable>>& x, const Eigen::Ref<const VectorX<symbolic::Variable>>& y, const Eigen::Ref<const MatrixX<symbolic::Expression>>& W) { DRAKE_ASSERT(W.rows() == x.rows() && W.cols() == y.rows()); const MapVarToIndex x_to_index_map = ConstructVarToIndexMap(x); const MapVarToIndex y_to_index_map = ConstructVarToIndexMap(y); // p_bilinear is a polynomial with x and y as indeterminates. const Variables variables_in_x_y{Variables{x} + Variables{y}}; const symbolic::Polynomial p_bilinear{e, variables_in_x_y}; const auto& map_bilinear = p_bilinear.monomial_to_coefficient_map(); symbolic::Polynomial poly; for (const auto& p : map_bilinear) { MapVarToIndex monomial_map; const int monomial_degree = p.first.total_degree(); for (const auto& var_power : p.first.get_powers()) { monomial_map.emplace(var_power.first.get_id(), var_power.second); } if (monomial_degree > 2) { ostringstream oss; oss << "The term " << p.first << " has degree larger than 2 on the variables"; throw runtime_error(oss.str()); } else if (monomial_degree < 2) { // Only linear or constant terms, do not need to replace the variables. poly.AddProduct(p.second, p.first); } else { // This monomial contains bilinear term in x and y. MapVarToIndex::const_iterator it_x_idx; MapVarToIndex::const_iterator it_y_idx; if (monomial_map.size() == 2) { // The monomial is in the form of x * y, namely two different // variables multiplying together. auto monomial_map_it = monomial_map.begin(); const Variable::Id var1_id{monomial_map_it->first}; ++monomial_map_it; const Variable::Id var2_id{monomial_map_it->first}; it_x_idx = x_to_index_map.find(var1_id); if (it_x_idx != x_to_index_map.end()) { // var1 is in x. it_y_idx = y_to_index_map.find(var2_id); } else { // var1 is in y. it_x_idx = x_to_index_map.find(var2_id); it_y_idx = y_to_index_map.find(var1_id); } } else { // The monomial is in the form of x * x, the square of a variable. const Variable::Id squared_var_id{monomial_map.begin()->first}; it_x_idx = x_to_index_map.find(squared_var_id); it_y_idx = y_to_index_map.find(squared_var_id); } if (it_x_idx == x_to_index_map.end() || it_y_idx == y_to_index_map.end()) { // This error would happen, if we ask // ReplaceBilinearTerms(x(i) * x(j), x, y, W). ostringstream oss; oss << "Term " << p.first << " is bilinear, but x and y does not have " "the corresponding variables."; throw runtime_error(oss.str()); } // w_xy_expr is the symbolic expression representing the bilinear term x * // y. const symbolic::Expression& w_xy_expr{ W(it_x_idx->second, it_y_idx->second)}; if (is_variable(w_xy_expr)) { const symbolic::Variable w_xy = symbolic::get_variable(w_xy_expr); if (variables_in_x_y.include(w_xy)) { // Case: w_xy is an indeterminate. poly.AddProduct(p.second, symbolic::Monomial{w_xy}); } else { // Case: w_xy is a decision variable. poly.AddProduct(w_xy * p.second, symbolic::Monomial{}); } } else { if (intersect(w_xy_expr.GetVariables(), variables_in_x_y).size() != 0) { // w_xy_expr contains a variable in x or y. ostringstream oss; oss << "W(" + std::to_string(it_x_idx->second) + "," + std::to_string(it_y_idx->second) + ")=" << w_xy_expr << "contains variables in x or y."; throw std::runtime_error(oss.str()); } poly.AddProduct(w_xy_expr * p.second, symbolic::Monomial{}); } } } return poly.ToExpression(); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/chebyshev_polynomial.h
#pragma once #include <ostream> #include <utility> #include <vector> #include <Eigen/Core> #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/common/hash.h" #include "drake/common/symbolic/expression.h" #include "drake/common/symbolic/polynomial.h" namespace drake { namespace symbolic { /** * Represents the Chebyshev polynomial of the first kind Tₙ(x). * One definition of Chebyshev polynomial of the first kind is * Tₙ(cos(θ)) = cos(nθ) * It can also be defined recursively as * * T₀(x) = 1 * T₁(x) = x * Tₙ₊₁(x) = 2xTₙ(x) − Tₙ₋₁(x) */ class ChebyshevPolynomial { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ChebyshevPolynomial) /** * Constructs a Chebyshev polynomial Tₙ(x) * @param var The variable x * @param degree The Chebyshev polynomial is of degree n. * @pre degree >= 0. */ ChebyshevPolynomial(Variable var, int degree); /** Getter for the variable. */ [[nodiscard]] const Variable& var() const { return var_; } /** Getter for the degree of the Chebyshev polynomial. */ [[nodiscard]] int degree() const { return degree_; } /** * Converts this Chebyshev polynomial to a polynomial with monomial basis. */ [[nodiscard]] Polynomial ToPolynomial() const; /** * Evaluates this Chebyshev polynomial at @p var_val. */ [[nodiscard]] double Evaluate(double var_val) const; /** * Checks if this and @p other represent the same Chebyshev polynomial. Two * Chebyshev polynomials are equal iff their variable and degree are the same, * or they both have degree 0. * @note T₀(x) = T₀(y) = 1 */ bool operator==(const ChebyshevPolynomial& other) const; /** Checks if this and @p other do not represent the same Chebyshev * polynomial. */ bool operator!=(const ChebyshevPolynomial& other) const; /** * Compare this to another Chebyshev polynomial, returns True if this is * regarded as less than the other, otherwise returns false. * * If this.var() < other.var(), return True. * If this.var() > other.var(), return False. * If this.var() == other.var(), then return this.degree() < * other.degree(). * * A special case is when this.degree() == 0 or other.degree() * == 0. In this case the variable doesn't matter, and we return this.degree() * < other.degree(). */ bool operator<(const ChebyshevPolynomial& other) const; /** * Computes the differentiation of a Chebyshev polynomial * dTₙ(x)/dx = nUₙ₋₁(x) * where Uₙ₋₁(x) is a Chebyshev polynomial of the second kind. Uₙ₋₁(x) can * be written as a summation of Chebyshev polynomials of the first kind * with lower degrees. * - If n is even dTₙ(x)/dx = 2n ∑ⱼ Tⱼ(x), j is odd and j <= n-1 * - If n is odd dTₙ(x)/dx = 2n ∑ⱼ Tⱼ(x) - n, j is even and j <= n-1 * - A special case is that dT₀(x)/dx = 0. * @retval chebyshev_coeff_pairs. sum(chebyshev_coeff_pairs[j].first * * chebyshev_coeff_pairs[j].second) is the differentiation dTₙ(x)/dx. If n is * even, then chebyshev_coeff_pairs[j] = (T₂ⱼ₋₁(x), 2n). If n is odd, then * chebyshev_coeff_pairs[j] = (T₂ⱼ(x), 2n) for j >= 1, and * chebyshev_coeff_pairs[0] = (T₀(x), n). * For the special case when degree() == 0, we return an empty vector. */ [[nodiscard]] std::vector<std::pair<ChebyshevPolynomial, double>> Differentiate() const; /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const ChebyshevPolynomial& item) noexcept { if (item.degree() == 0) { hash_append(hasher, item.degree()); } else { hash_append(hasher, std::make_pair(item.var().get_id(), item.degree())); } } private: Variable var_{}; int degree_{}; }; std::ostream& operator<<(std::ostream& out, const ChebyshevPolynomial& p); /** * Evaluates a Chebyshev polynomial at a given value. * @param var_val The value of the variable. * @param degree The degree of the Chebyshev polynomial. */ double EvaluateChebyshevPolynomial(double var_val, int degree); } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::ChebyshevPolynomial>. */ template <> struct hash<drake::symbolic::ChebyshevPolynomial> : public drake::DefaultHash { }; } // namespace std // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::symbolic::ChebyshevPolynomial> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/generic_polynomial.h
#pragma once #include <map> #include <ostream> #include <Eigen/Core> #include <fmt/format.h> #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/common/symbolic/chebyshev_basis_element.h" #include "drake/common/symbolic/expression.h" #include "drake/common/symbolic/monomial_basis_element.h" #include "drake/common/symbolic/polynomial_basis_element.h" namespace drake { namespace symbolic { /** * Represents symbolic generic polynomials using a given basis (for example, * monomial basis, Chebyshev basis, etc). A generic symbolic polynomial keeps a * mapping from a basis element of indeterminates to its coefficient in a * symbolic expression. A generic polynomial `p` has to satisfy an invariant * such that `p.decision_variables() ∩ p.indeterminates() = ∅`. We have * CheckInvariant() method to check the invariant. * For polynomials using different basis, you could refer to section 3.1.5 of * Semidefinite Optimization and Convex Algebraic Geometry on the pros/cons of * each basis. * * We provide two instantiations of this template * - BasisElement = MonomialBasisElement * - BasisElement = ChebyshevBasisElement * @tparam BasisElement Must be a subclass of PolynomialBasisElement. */ template <typename BasisElement> class GenericPolynomial { public: static_assert( std::is_base_of_v<PolynomialBasisElement, BasisElement>, "BasisElement should be a derived class of PolynomialBasisElement"); /** Type of mapping from basis element to coefficient */ using MapType = std::map<BasisElement, Expression>; /** Constructs a zero polynomial. */ GenericPolynomial() = default; DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(GenericPolynomial) /** Constructs a default value. This overload is used by Eigen when * EIGEN_INITIALIZE_MATRICES_BY_ZERO is enabled. */ explicit GenericPolynomial(std::nullptr_t) : GenericPolynomial<BasisElement>() {} /** Constructs a generic polynomial from a map, basis_element → coefficient. * For example * @code{cc} * GenericPolynomial<MonomialBasiElement>( * {{MonomialBasisElement(x, 2), a}, {MonomialBasisElement(x, 3), a+b}}) * @endcode * constructs a polynomial ax²+(a+b)x³.*/ explicit GenericPolynomial(MapType init); /** Constructs a generic polynomial from a single basis element @p m. * @note that all variables in `m` are considered as indeterminates. Namely * the constructed generic polynomial contains the map with a single key `m`, * with the coefficient being 1. */ // Note that this implicit conversion is desirable to have a dot product of // two Eigen::Vector<BasisElement>s return a GenericPolynomial<BasisElement>. // NOLINTNEXTLINE(runtime/explicit) GenericPolynomial(const BasisElement& m); /** Constructs a polynomial from an expression @p e. Note that all variables * in `e` are considered as indeterminates. * * @throws std::exception if @p e is not a polynomial. */ explicit GenericPolynomial(const Expression& e); /** Constructs a polynomial from an expression @p e by decomposing it with * respect to @p indeterminates. * * @note The indeterminates for the polynomial are @p indeterminates. Even if * a variable in @p indeterminates does not show up in @p e, that variable is * still registered as an indeterminate in this polynomial, as * this->indeterminates() be the same as @p indeterminates. * * @throws std::exception if @p e is not a polynomial in @p * indeterminates. */ GenericPolynomial(const Expression& e, Variables indeterminates); /** Returns the indeterminates of this generic polynomial. */ [[nodiscard]] const Variables& indeterminates() const { return indeterminates_; } /** Returns the decision variables of this generic polynomial. */ [[nodiscard]] const Variables& decision_variables() const { return decision_variables_; } /** Sets the indeterminates to `new_indeterminates`. * * Changing the indeterminates will change * `basis_element_to_coefficient_map()`, and also potentially the degree of * the polynomial. Here is an example. * * @code * // p is a quadratic polynomial with x being the only indeterminate. * symbolic::GenericPolynomial<MonomialBasisElement> p(a * x * x + b * x + c, * {x}); * // p.basis_element_to_coefficient_map() contains {1: c, x: b, x*x:a}. * std::cout << p.TotalDegree(); // prints 2. * // Now set (a, b, c) to the indeterminates. p becomes a linear * // polynomial of a, b, c. * p.SetIndeterminates({a, b, c}); * // p.basis_element_to_coefficient_map() now is {a: x * x, b: x, c: 1}. * std::cout << p.TotalDegree(); // prints 1. * @endcode * This function can be expensive, as it potentially reconstructs the * polynomial (using the new indeterminates) from the expression. */ void SetIndeterminates(const Variables& new_indeterminates); /** Returns the map from each basis element to its coefficient. */ [[nodiscard]] const MapType& basis_element_to_coefficient_map() const { return basis_element_to_coefficient_map_; } /** Returns the highest degree of this generic polynomial in an indeterminate * @p v. */ [[nodiscard]] int Degree(const Variable& v) const; /** Returns the total degree of this generic polynomial. */ [[nodiscard]] int TotalDegree() const; /** Returns an equivalent symbolic expression of this generic polynomial.*/ [[nodiscard]] Expression ToExpression() const; /** * Differentiates this generic polynomial with respect to the variable @p x. * Note that a variable @p x can be either a decision variable or an * indeterminate. */ [[nodiscard]] GenericPolynomial<BasisElement> Differentiate( const Variable& x) const; /** Computes the Jacobian matrix J of the generic polynomial with respect to * @p vars. J(0,i) contains ∂f/∂vars(i). @p vars should be an Eigen column * vector of symbolic variables. */ template <typename Derived> Eigen::Matrix<GenericPolynomial<BasisElement>, 1, Derived::RowsAtCompileTime> Jacobian(const Eigen::MatrixBase<Derived>& vars) const { static_assert( std::is_same_v<typename Derived::Scalar, Variable> && (Derived::ColsAtCompileTime == 1), "The argument of GenericPolynomial::Jacobian() should be a vector of " "symbolic variables."); const VectorX<Expression>::Index n{vars.size()}; Eigen::Matrix<GenericPolynomial<BasisElement>, 1, Derived::RowsAtCompileTime> J{n}; for (VectorX<Expression>::Index i = 0; i < n; ++i) { J(i) = this->Differentiate(vars(i)); } return J; } /** * Evaluates this generic polynomial under a given environment @p env. * * @throws std::exception if there is a variable in this generic * polynomial whose assignment is not provided by @p env. */ [[nodiscard]] double Evaluate(const Environment& env) const; /** Partially evaluates this generic polynomial using an environment @p env. * * @throws std::exception if NaN is detected during evaluation. */ [[nodiscard]] GenericPolynomial<BasisElement> EvaluatePartial( const Environment& env) const; /** Partially evaluates this generic polynomial by substituting @p var with @p * c. * @throws std::exception if NaN is detected at any point during * evaluation. */ [[nodiscard]] GenericPolynomial<BasisElement> EvaluatePartial( const Variable& var, double c) const; /** Adds @p coeff * @p m to this generic polynomial. */ GenericPolynomial<BasisElement>& AddProduct(const Expression& coeff, const BasisElement& m); /** Removes the terms whose absolute value of the coefficients are smaller * than or equal to @p coefficient_tol. * For example, if the generic polynomial is 2x² + 3xy + 10⁻⁴x - 10⁻⁵, * then after calling RemoveTermsWithSmallCoefficients(1e-3), the returned * polynomial becomes 2x² + 3xy. * @param coefficient_tol A positive scalar. * @retval polynomial_cleaned A generic polynomial whose terms with small * coefficients are removed. */ [[nodiscard]] GenericPolynomial<BasisElement> RemoveTermsWithSmallCoefficients(double coefficient_tol) const; GenericPolynomial<BasisElement>& operator+=( const GenericPolynomial<BasisElement>& p); GenericPolynomial<BasisElement>& operator+=(const BasisElement& m); GenericPolynomial<BasisElement>& operator+=(double c); GenericPolynomial<BasisElement>& operator+=(const Variable& v); GenericPolynomial<BasisElement>& operator-=( const GenericPolynomial<BasisElement>& p); GenericPolynomial<BasisElement>& operator-=(const BasisElement& m); GenericPolynomial<BasisElement>& operator-=(double c); GenericPolynomial<BasisElement>& operator-=(const Variable& v); GenericPolynomial<BasisElement>& operator*=( const GenericPolynomial<BasisElement>& p); GenericPolynomial<BasisElement>& operator*=(const BasisElement& m); GenericPolynomial<BasisElement>& operator*=(double c); GenericPolynomial<BasisElement>& operator*=(const Variable& v); GenericPolynomial<BasisElement>& operator/=(double c); /** Returns true if this and @p p are structurally equal. */ [[nodiscard]] bool EqualTo(const GenericPolynomial<BasisElement>& p) const; /** Returns true if this generic polynomial and @p p are equal after expanding * the coefficients. */ [[nodiscard]] bool EqualToAfterExpansion( const GenericPolynomial<BasisElement>& p) const; /** Returns true if this polynomial and @p p are almost equal (the difference * in the corresponding coefficients are all less than @p tol), after * expanding the coefficients. */ bool CoefficientsAlmostEqual(const GenericPolynomial<BasisElement>& p, double tol) const; /** Returns a symbolic formula representing the condition where this * polynomial and @p p are the same. */ Formula operator==(const GenericPolynomial<BasisElement>& p) const; /** Returns a symbolic formula representing the condition where this * polynomial and @p p are not the same. */ Formula operator!=(const GenericPolynomial<BasisElement>& p) const; /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append( HashAlgorithm& hasher, const GenericPolynomial<BasisElement>& item) noexcept { using drake::hash_append; for (const auto& [basis_element, coeff] : item.basis_element_to_coefficient_map_) { hash_append(hasher, basis_element); hash_append(hasher, coeff); } } private: // Throws std::exception if there is a variable appeared in both of // decision_variables() and indeterminates(). void CheckInvariant() const; MapType basis_element_to_coefficient_map_; Variables indeterminates_; Variables decision_variables_; }; /** Defines an explicit SFINAE alias for use with return types to dissuade CTAD * from trying to instantiate an invalid GenericElement<> for operator * overloads, (if that's actually the case). * See discussion for more info: * https://github.com/robotlocomotion/drake/pull/14053#pullrequestreview-488744679 */ template <typename BasisElement> using GenericPolynomialEnable = std::enable_if_t<std::is_base_of_v<PolynomialBasisElement, BasisElement>, GenericPolynomial<BasisElement>>; template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-( const GenericPolynomial<BasisElement>& p) { return -1. * p; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+( GenericPolynomial<BasisElement> p1, const GenericPolynomial<BasisElement>& p2) { return p1 += p2; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+( GenericPolynomial<BasisElement> p, const BasisElement& m) { return p += m; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+( GenericPolynomial<BasisElement> p, double c) { return p += c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+( const BasisElement& m, GenericPolynomial<BasisElement> p) { return p += m; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+(const BasisElement& m1, const BasisElement& m2) { return GenericPolynomial<BasisElement>(m1) + m2; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+(const BasisElement& m, double c) { return GenericPolynomial<BasisElement>(m) + c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+( double c, GenericPolynomial<BasisElement> p) { return p += c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+(double c, const BasisElement& m) { return GenericPolynomial<BasisElement>(m) + c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+( GenericPolynomial<BasisElement> p, const Variable& v) { return p += v; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator+( const Variable& v, GenericPolynomial<BasisElement> p) { return p += v; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-( GenericPolynomial<BasisElement> p1, const GenericPolynomial<BasisElement>& p2) { return p1 -= p2; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-( GenericPolynomial<BasisElement> p, const BasisElement& m) { return p -= m; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-( GenericPolynomial<BasisElement> p, double c) { return p -= c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-( const BasisElement& m, GenericPolynomial<BasisElement> p) { return p = -1 * p + m; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-(const BasisElement& m1, const BasisElement& m2) { return GenericPolynomial<BasisElement>(m1) - m2; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-(const BasisElement& m, double c) { return GenericPolynomial<BasisElement>(m) - c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-( double c, GenericPolynomial<BasisElement> p) { return p = -p + c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-(double c, const BasisElement& m) { return c - GenericPolynomial<BasisElement>(m); } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-( GenericPolynomial<BasisElement> p, const Variable& v) { return p -= v; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator-( const Variable& v, GenericPolynomial<BasisElement> p) { return GenericPolynomial<BasisElement>(v, p.indeterminates()) - p; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*( GenericPolynomial<BasisElement> p1, const GenericPolynomial<BasisElement>& p2) { return p1 *= p2; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*( GenericPolynomial<BasisElement> p, const BasisElement& m) { return p *= m; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*( GenericPolynomial<BasisElement> p, double c) { return p *= c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*( const BasisElement& m, GenericPolynomial<BasisElement> p) { return p *= m; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*(const BasisElement& m, double c) { return GenericPolynomial<BasisElement>(m) * c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*( double c, GenericPolynomial<BasisElement> p) { return p *= c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*(double c, const BasisElement& m) { return GenericPolynomial<BasisElement>(m) * c; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*( GenericPolynomial<BasisElement> p, const Variable& v) { return p *= v; } template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator*( const Variable& v, GenericPolynomial<BasisElement> p) { return p *= v; } /** Returns `p / v`. */ template <typename BasisElement> GenericPolynomialEnable<BasisElement> operator/( GenericPolynomial<BasisElement> p, double v) { return p /= v; } /** Returns polynomial @p raised to @p n. * @param p The base polynomial. * @param n The exponent of the power. @pre n>=0. * */ template <typename BasisElement> GenericPolynomialEnable<BasisElement> pow( const GenericPolynomial<BasisElement>& p, int n) { if (n < 0) { throw std::runtime_error( fmt::format("pow(): the degree should be non-negative, got {}.", n)); } else if (n == 0) { return GenericPolynomial<BasisElement>(BasisElement()); } else if (n == 1) { return p; } else if (n % 2 == 0) { const GenericPolynomial<BasisElement> half = pow(p, n / 2); return half * half; } else { const GenericPolynomial<BasisElement> half = pow(p, n / 2); return half * half * p; } } template <typename BasisElement> std::ostream& operator<<(std::ostream& os, const GenericPolynomial<BasisElement>& p) { const typename GenericPolynomial<BasisElement>::MapType& map{ p.basis_element_to_coefficient_map()}; if (map.empty()) { return os << 0; } auto it = map.begin(); os << it->second << "*" << it->first; for (++it; it != map.end(); ++it) { os << " + " << it->second << "*" << it->first; } return os; } extern template class GenericPolynomial<MonomialBasisElement>; extern template class GenericPolynomial<ChebyshevBasisElement>; } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::GenericPolynomial<BasisElement>>. */ template <typename BasisElement> struct hash<drake::symbolic::GenericPolynomial<BasisElement>> : public drake::DefaultHash {}; #if defined(__GLIBCXX__) // Inform GCC that this hash function is not so fast (i.e. for-loop inside). // This will enforce caching of hash results. See // https://gcc.gnu.org/onlinedocs/libstdc++/manual/unordered_associative.html // for details. template <typename BasisElement> struct __is_fast_hash<hash<drake::symbolic::GenericPolynomial<BasisElement>>> : std::false_type {}; #endif } // namespace std #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { // Defines Eigen traits needed for Matrix<drake::symbolic::Polynomial>. template <> struct NumTraits< drake::symbolic::GenericPolynomial<drake::symbolic::MonomialBasisElement>> : GenericNumTraits<drake::symbolic::GenericPolynomial< drake::symbolic::MonomialBasisElement>> { static inline int digits10() { return 0; } }; template <> struct NumTraits< drake::symbolic::GenericPolynomial<drake::symbolic::ChebyshevBasisElement>> : GenericNumTraits<drake::symbolic::GenericPolynomial< drake::symbolic::ChebyshevBasisElement>> { static inline int digits10() { return 0; } }; } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX) // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <typename BasisElement> struct formatter<drake::symbolic::GenericPolynomial<BasisElement>> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/codegen.cc
#include "drake/common/symbolic/codegen.h" #include <sstream> #include <stdexcept> #include <fmt/format.h> namespace drake { namespace symbolic { using std::ostream; using std::ostringstream; using std::runtime_error; using std::string; using std::to_string; using std::vector; CodeGenVisitor::CodeGenVisitor(const vector<Variable>& parameters) { for (vector<Variable>::size_type i = 0; i < parameters.size(); ++i) { id_to_idx_map_.emplace(parameters[i].get_id(), i); } } string CodeGenVisitor::CodeGen(const Expression& e) const { return VisitExpression<string>(this, e); } string CodeGenVisitor::VisitVariable(const Expression& e) const { const Variable& v{get_variable(e)}; const auto it{id_to_idx_map_.find(v.get_id())}; if (it == id_to_idx_map_.end()) { throw runtime_error("Variable index is not found."); } return "p[" + to_string(it->second) + "]"; } string CodeGenVisitor::VisitConstant(const Expression& e) const { return to_string(get_constant_value(e)); } string CodeGenVisitor::VisitAddition(const Expression& e) const { const double c{get_constant_in_addition(e)}; const auto& expr_to_coeff_map{get_expr_to_coeff_map_in_addition(e)}; ostringstream oss; oss << "(" << c; for (const auto& item : expr_to_coeff_map) { const Expression& e_i{item.first}; const double c_i{item.second}; oss << " + "; if (c_i == 1.0) { oss << CodeGen(e_i); } else { oss << "(" << c_i << " * " << CodeGen(e_i) << ")"; } } oss << ")"; return oss.str(); } string CodeGenVisitor::VisitMultiplication(const Expression& e) const { const double c{get_constant_in_multiplication(e)}; const auto& base_to_exponent_map{ get_base_to_exponent_map_in_multiplication(e)}; ostringstream oss; oss << "(" << c; for (const auto& item : base_to_exponent_map) { const Expression& e_1{item.first}; const Expression& e_2{item.second}; oss << " * "; if (is_one(e_2)) { oss << CodeGen(e_1); } else { oss << "pow(" << CodeGen(e_1) << ", " << CodeGen(e_2) << ")"; } } oss << ")"; return oss.str(); } // Helper method to handle unary cases. string CodeGenVisitor::VisitUnary(const string& f, const Expression& e) const { return f + "(" + CodeGen(get_argument(e)) + ")"; } // Helper method to handle binary cases. string CodeGenVisitor::VisitBinary(const string& f, const Expression& e) const { return f + "(" + CodeGen(get_first_argument(e)) + ", " + CodeGen(get_second_argument(e)) + ")"; } string CodeGenVisitor::VisitPow(const Expression& e) const { return VisitBinary("pow", e); } string CodeGenVisitor::VisitDivision(const Expression& e) const { return "(" + CodeGen(get_first_argument(e)) + " / " + CodeGen(get_second_argument(e)) + ")"; } string CodeGenVisitor::VisitAbs(const Expression& e) const { return VisitUnary("fabs", e); } string CodeGenVisitor::VisitLog(const Expression& e) const { return VisitUnary("log", e); } string CodeGenVisitor::VisitExp(const Expression& e) const { return VisitUnary("exp", e); } string CodeGenVisitor::VisitSqrt(const Expression& e) const { return VisitUnary("sqrt", e); } string CodeGenVisitor::VisitSin(const Expression& e) const { return VisitUnary("sin", e); } string CodeGenVisitor::VisitCos(const Expression& e) const { return VisitUnary("cos", e); } string CodeGenVisitor::VisitTan(const Expression& e) const { return VisitUnary("tan", e); } string CodeGenVisitor::VisitAsin(const Expression& e) const { return VisitUnary("asin", e); } string CodeGenVisitor::VisitAcos(const Expression& e) const { return VisitUnary("acos", e); } string CodeGenVisitor::VisitAtan(const Expression& e) const { return VisitUnary("atan", e); } string CodeGenVisitor::VisitAtan2(const Expression& e) const { return VisitBinary("atan2", e); } string CodeGenVisitor::VisitSinh(const Expression& e) const { return VisitUnary("sinh", e); } string CodeGenVisitor::VisitCosh(const Expression& e) const { return VisitUnary("cosh", e); } string CodeGenVisitor::VisitTanh(const Expression& e) const { return VisitUnary("tanh", e); } string CodeGenVisitor::VisitMin(const Expression& e) const { return VisitBinary("fmin", e); } string CodeGenVisitor::VisitMax(const Expression& e) const { return VisitBinary("fmax", e); } string CodeGenVisitor::VisitCeil(const Expression& e) const { return VisitUnary("ceil", e); } string CodeGenVisitor::VisitFloor(const Expression& e) const { return VisitUnary("floor", e); } string CodeGenVisitor::VisitIfThenElse(const Expression&) const { throw runtime_error("Codegen does not support if-then-else expressions."); } string CodeGenVisitor::VisitUninterpretedFunction(const Expression&) const { throw runtime_error("Codegen does not support uninterpreted functions."); } string CodeGen(const string& function_name, const vector<Variable>& parameters, const Expression& e) { ostringstream oss; // Add header for the main function. oss << "double " << function_name << "(const double* p) {\n"; // Codegen the expression. oss << " return " << CodeGenVisitor{parameters}.CodeGen(e) << ";\n"; // Add footer for the main function. oss << "}\n"; // <function_name>_meta_t type. oss << "typedef struct {\n" " /* p: input, vector */\n" " struct { int size; } p;\n" "} " << function_name << "_meta_t;\n"; // <function_name>_meta(). oss << function_name << "_meta_t " << function_name << "_meta() { return {{" << parameters.size() << "}}; }\n"; return oss.str(); } namespace internal { void CodeGenDenseData(const string& function_name, const vector<Variable>& parameters, const Expression* const data, const int size, ostream* const os) { // Add header for the main function. (*os) << "void " << function_name << "(const double* p, double* m) {\n"; const CodeGenVisitor visitor{parameters}; for (int i = 0; i < size; ++i) { (*os) << " " << "m[" << i << "] = " << visitor.CodeGen(data[i]) << ";\n"; } // Add footer for the main function. (*os) << "}\n"; } void CodeGenDenseMeta(const string& function_name, const int parameter_size, const int rows, const int cols, ostream* const os) { // <function_name>_meta_t type. (*os) << "typedef struct {\n" " /* p: input, vector */\n" " struct { int size; } p;\n" " /* m: output, matrix */\n" " struct { int rows; int cols; } m;\n" "} " << function_name << "_meta_t;\n"; // <function_name>_meta(). (*os) << function_name << "_meta_t " << function_name << "_meta() { return {{" << parameter_size << "}, {" << rows << ", " << cols << "}}; }\n"; } void CodeGenSparseData(const string& function_name, const vector<Variable>& parameters, const int outer_index_size, const int non_zeros, const int* const outer_index_ptr, const int* const inner_index_ptr, const Expression* const value_ptr, ostream* const os) { // Print header. (*os) << fmt::format( "void {}(const double* p, int* outer_indices, int* " "inner_indices, double* values) {{\n", function_name); for (int i = 0; i < outer_index_size; ++i) { (*os) << fmt::format(" outer_indices[{0}] = {1};\n", i, outer_index_ptr[i]); } for (int i = 0; i < non_zeros; ++i) { (*os) << fmt::format(" inner_indices[{0}] = {1};\n", i, inner_index_ptr[i]); } const CodeGenVisitor visitor{parameters}; for (int i = 0; i < non_zeros; ++i) { (*os) << fmt::format(" values[{0}] = {1};\n", i, visitor.CodeGen(value_ptr[i])); } // Print footer. (*os) << "}\n"; } void CodeGenSparseMeta(const string& function_name, const int parameter_size, const int rows, const int cols, const int non_zeros, const int outer_indices, const int inner_indices, ostream* const os) { // <function_name>_meta_t type. (*os) << "typedef struct {\n" " /* p: input, vector */\n" " struct { int size; } p;\n" " /* m: output, matrix */\n" " struct {\n" " int rows;\n" " int cols;\n" " int non_zeros;\n" " int outer_indices;\n" " int inner_indices;\n" " } m;\n" "} " << function_name << "_meta_t;\n"; // <function_name>_meta(). (*os) << fmt::format( "{0}_meta_t {1}_meta() {{ return {{{{{2}}}, {{{3}, {4}, {5}, {6}, " "{7}}}}}; }}\n", function_name, function_name, parameter_size, rows, cols, non_zeros, outer_indices, inner_indices); } } // namespace internal std::string CodeGen( const std::string& function_name, const std::vector<Variable>& parameters, const Eigen::Ref<const Eigen::SparseMatrix<Expression>>& M) { DRAKE_ASSERT(M.isCompressed()); ostringstream oss; internal::CodeGenSparseData(function_name, parameters, M.cols() + 1, M.nonZeros(), M.outerIndexPtr(), M.innerIndexPtr(), M.valuePtr(), &oss); internal::CodeGenSparseMeta(function_name, parameters.size(), M.rows(), M.cols(), M.nonZeros(), M.cols() + 1, M.nonZeros(), &oss); return oss.str(); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/monomial.h
#pragma once #include <cstddef> #include <map> #include <ostream> #include <utility> #include <Eigen/Core> #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/common/hash.h" #include "drake/common/symbolic/expression.h" // Some of our Eigen template specializations live in polynomial.h, so we // must only have been included from that file. This helps prevent us from // triggering undefined behavior due to the order of template specializations. #ifndef DRAKE_COMMON_SYMBOLIC_POLYNOMIAL_H // NOLINTNEXTLINE(whitespace/line_length) #error Do not directly include this file. Use "drake/common/symbolic/polynomial.h". #endif namespace drake { namespace symbolic { /** Represents a monomial, a product of powers of variables with non-negative integer exponents. Note that it does not include the coefficient part of a monomial. */ class Monomial { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Monomial) /** Constructs a monomial equal to 1. Namely the total degree is zero. */ Monomial() = default; /** Constructs a default value. This overload is used by Eigen when EIGEN_INITIALIZE_MATRICES_BY_ZERO is enabled. */ explicit Monomial(std::nullptr_t) : Monomial() {} /** Constructs a monomial from `powers`. @throws std::exception if `powers` includes a negative exponent. */ explicit Monomial(const std::map<Variable, int>& powers); /** Constructs a monomial from a vector of variables `vars` and their corresponding integer exponents `exponents`. For example, `%Monomial([x, y, z], [2, 0, 1])` constructs a monomial `x²z`. @pre The size of `vars` should be the same as the size of `exponents`. @throws std::exception if `exponents` includes a negative integer. */ Monomial(const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& exponents); /** Converts an expression to a monomial if the expression is written as ∏ᵢpow(xᵢ, kᵢ), otherwise throws a runtime error. @pre is_polynomial(e) should be true. */ explicit Monomial(const Expression& e); /** Constructs a monomial from `var`. */ explicit Monomial(const Variable& var); /** Constructs a monomial from `var` and `exponent`. */ Monomial(const Variable& var, int exponent); /** Returns the degree of this monomial in a variable `v`. */ int degree(const Variable& v) const; /** Returns the total degree of this monomial. */ int total_degree() const { return total_degree_; } /** Returns the set of variables in this monomial. */ Variables GetVariables() const; /** Returns the internal representation of %Monomial, the map from a base (Variable) to its exponent (int). */ const std::map<Variable, int>& get_powers() const { return powers_; } /** Evaluates under a given environment `env`. @throws std::exception if there is a variable in this monomial whose assignment is not provided by `env`. */ double Evaluate(const Environment& env) const; /** Evaluates the monomial for a batch of data. We return monomial_vals such that monomial_vals(j) is obtained by substituting `vars(i)` with `vars_values(i, j)`, note that `vars_values.rows() == vars.rows()` and `vars_values.cols() == monomial_vals.rows()`. @param vars The variables whose value will be substituted. `vars` must contain all variables in this->GetVariables(). Also `vars` cannot contain any duplicate variables, namely vars(i) != vars(j) if i != j. @param vars_values The i'th column of `vars_values` is the i'th data for `vars`. @throw std::exception if `vars` doesn't contain all the variables in `this->GetVariables()`. */ Eigen::VectorXd Evaluate( const Eigen::Ref<const VectorX<symbolic::Variable>>& vars, const Eigen::Ref<const Eigen::MatrixXd>& vars_values) const; /** Partially evaluates using a given environment `env`. The evaluation result is of type pair<double, Monomial>. The first component (a double) represents the coefficient part while the second component represents the remaining parts of the monomial which was not evaluated. Example 1. Evaluate with a fully-specified environment (x³*y²).EvaluatePartial({{x, 2}, {y, 3}}) = (2³ * 3² = 8 * 9 = 72, %Monomial{} = 1). Example 2. Evaluate with a partial environment (x³*y²).EvaluatePartial({{x, 2}}) = (2³ = 8, y²). */ std::pair<double, Monomial> EvaluatePartial(const Environment& env) const; /** Returns a symbolic expression representing this monomial. */ Expression ToExpression() const; /** Checks if this monomial and `m` represent the same monomial. Two monomials are equal iff they contain the same variable raised to the same exponent. */ bool operator==(const Monomial& m) const; /** Checks if this monomial and `m` do not represent the same monomial. */ bool operator!=(const Monomial& m) const; /** Returns this monomial multiplied by `m`. */ Monomial& operator*=(const Monomial& m); /** Returns this monomial raised to `p`. @throws std::exception if `p` is negative. */ Monomial& pow_in_place(int p); /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const Monomial& item) noexcept { using drake::hash_append; // We do not send total_degree_ to the hasher, because it is already fully // represented by powers_ -- it is just a cached tally of the exponents. hash_append(hasher, item.powers_); } private: int total_degree_{0}; std::map<Variable, int> powers_; friend std::ostream& operator<<(std::ostream& out, const Monomial& m); }; std::ostream& operator<<(std::ostream& out, const Monomial& m); /** Returns a multiplication of two monomials, `m1` and `m2`. */ Monomial operator*(Monomial m1, const Monomial& m2); /** Returns `m` raised to `p`. @throws std::exception if `p` is negative. */ Monomial pow(Monomial m, int p); } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::Monomial>. */ template <> struct hash<drake::symbolic::Monomial> : public drake::DefaultHash {}; } // namespace std #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { /* Eigen scalar type traits for Matrix<drake::symbolic::Monomial>. */ template <> struct NumTraits<drake::symbolic::Monomial> : GenericNumTraits<drake::symbolic::Monomial> { static inline int digits10() { return 0; } }; namespace internal { /* Informs Eigen how to cast drake::symbolic::Monomial to drake::symbolic::Expression. */ template <> EIGEN_DEVICE_FUNC inline drake::symbolic::Expression cast( const drake::symbolic::Monomial& m) { return m.ToExpression(); } } // namespace internal } // namespace Eigen // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::symbolic::Monomial> : drake::ostream_formatter {}; } // namespace fmt #endif // !defined(DRAKE_DOXYGEN_CXX)
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/decompose.cc
#include "drake/common/symbolic/decompose.h" #include <map> #include <stdexcept> #include <string> #include <tuple> #include <vector> #include <fmt/format.h> #include "drake/common/fmt_eigen.h" #include "drake/math/quadratic_form.h" namespace drake { namespace symbolic { using std::ostringstream; using std::runtime_error; using std::string; namespace { // Helper class for IsAffine functions below where an instance of this class // is passed to Eigen::MatrixBase::visit() function. class IsAffineVisitor { public: IsAffineVisitor() = default; explicit IsAffineVisitor(const Variables& variables) : variables_{&variables} {} // Called for the first coefficient. Needed for Eigen::MatrixBase::visit() // function. void init(const Expression& e, const Eigen::Index i, const Eigen::Index j) { (*this)(e, i, j); } // Called for all other coefficients. Needed for Eigen::MatrixBase::visit() // function. void operator()(const Expression& e, const Eigen::Index, const Eigen::Index) { // Note that `IsNotAffine` is only called when we have not found a // non-affine element yet. found_non_affine_element_ = found_non_affine_element_ || IsNotAffine(e); } [[nodiscard]] bool result() const { return !found_non_affine_element_; } private: // Returns true if `e` is *not* affine in variables_ (if exists) or all // variables in `e`. [[nodiscard]] bool IsNotAffine(const Expression& e) const { // TODO(#16393) This check is incorrect when variables_ is non-null. if (!e.is_polynomial()) { return true; } const Polynomial p{(variables_ != nullptr) ? Polynomial{e, *variables_} : Polynomial{e}}; return p.TotalDegree() > 1; } bool found_non_affine_element_{false}; const Variables* const variables_{nullptr}; }; } // namespace bool IsAffine(const Eigen::Ref<const MatrixX<Expression>>& m, const Variables& vars) { if (m.size() == 0) { return true; } IsAffineVisitor visitor{vars}; m.visit(visitor); return visitor.result(); } bool IsAffine(const Eigen::Ref<const MatrixX<Expression>>& m) { if (m.size() == 0) { return true; } IsAffineVisitor visitor; m.visit(visitor); return visitor.result(); } namespace { void ThrowError(const string& type, const string& expression, const string& additional_msg) { throw runtime_error("While decomposing an expression, we detected a " + type + " expression: " + expression + additional_msg + "."); } // A helper function to implement DecomposeLinearExpressions and // DecomposeAffineExpressions functions. It finds the coefficient of the // monomial `m` in the `map` and fills `M(i)` with the value. If the monomial // `m` does not appear in `map`, it uses `0.0` instead. If the coefficient is // not a constant, it throws a runtime_error. template <typename Derived> void FindCoefficientAndFill(const Polynomial::MapType& map, const Monomial& m, const int i, const Eigen::MatrixBase<Derived>& M) { const auto it = map.find(m); // Here, we use const_cast hack. See // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html for // details. Eigen::MatrixBase<Derived>& M_dummy = const_cast<Eigen::MatrixBase<Derived>&>(M); if (it != map.end()) { // m should have a constant coefficient. if (!is_constant(it->second)) { ThrowError("non-constant", it->second.to_string(), ""); } M_dummy(i) = get_constant_value(it->second); } else { M_dummy(i) = 0.0; } } } // namespace // TODO(soonho-tri): Refactor DecomposeAffineExpressions and // DecomposeLinearExpressions to factor common parts out. void DecomposeLinearExpressions( const Eigen::Ref<const VectorX<Expression>>& expressions, const Eigen::Ref<const VectorX<symbolic::Variable>>& vars, EigenPtr<Eigen::MatrixXd> M) { DRAKE_DEMAND(M != nullptr); DRAKE_DEMAND(M->rows() == expressions.rows() && M->cols() == vars.rows()); for (int i = 0; i < expressions.size(); ++i) { const Expression& e{expressions(i)}; if (!e.is_polynomial()) { ThrowError("non-polynomial", e.to_string(), ""); // e should be a polynomial. } const Polynomial p{e, Variables{vars}}; if (p.TotalDegree() > 1) { ThrowError( "non-linear", e.to_string(), fmt::format(" of indeterminates {}", fmt_eigen(vars.transpose()))); // e should be linear. } const Polynomial::MapType& map{p.monomial_to_coefficient_map()}; if (map.contains(Monomial{})) { // e should not have a constant term. ThrowError( "non-linear", e.to_string(), fmt::format(" of indeterminates {}, with a constant term {}. " "This is an affine expression; a linear should have no " "constant terms.", fmt_eigen(vars.transpose()), map.at(Monomial{}))); } // Fill M(i, j). for (int j = 0; j < vars.size(); ++j) { FindCoefficientAndFill(map, Monomial{vars.coeff(j)}, j, M->row(i)); } } } void DecomposeAffineExpressions( const Eigen::Ref<const VectorX<Expression>>& expressions, const Eigen::Ref<const VectorX<symbolic::Variable>>& vars, EigenPtr<Eigen::MatrixXd> M, EigenPtr<Eigen::VectorXd> v) { DRAKE_DEMAND(M != nullptr && v != nullptr); DRAKE_DEMAND(M->rows() == expressions.rows() && M->cols() == vars.rows()); DRAKE_DEMAND(v->rows() == expressions.rows()); for (int i = 0; i < expressions.size(); ++i) { const Expression& e{expressions(i)}; if (!e.is_polynomial()) { ThrowError("non-polynomial", e.to_string(), ""); // e should be a polynomial. } const Polynomial p{e, Variables{vars}}; if (p.TotalDegree() > 1) { ThrowError( "non-linear", e.to_string(), fmt::format(" of indeterminates {}", fmt_eigen(vars.transpose()))); // e should be linear. } const Polynomial::MapType& map{p.monomial_to_coefficient_map()}; // Fill M(i, j). for (int j = 0; j < vars.size(); ++j) { FindCoefficientAndFill(map, Monomial{vars.coeff(j)}, j, M->row(i)); } // Fill v(i). FindCoefficientAndFill(map, Monomial{}, i, *v); } } void ExtractAndAppendVariablesFromExpression( const Expression& e, VectorX<Variable>* vars, std::unordered_map<Variable::Id, int>* map_var_to_index) { DRAKE_DEMAND(static_cast<int>(map_var_to_index->size()) == vars->size()); for (const Variable& var : e.GetVariables()) { if (map_var_to_index->find(var.get_id()) == map_var_to_index->end()) { map_var_to_index->emplace(var.get_id(), vars->size()); const int vars_size = vars->size(); vars->conservativeResize(vars_size + 1, Eigen::NoChange); (*vars)(vars_size) = var; } } } std::pair<VectorX<Variable>, std::unordered_map<Variable::Id, int>> ExtractVariablesFromExpression(const Expression& e) { int var_count = 0; const symbolic::Variables var_set = e.GetVariables(); VectorX<Variable> vars(var_set.size()); std::unordered_map<Variable::Id, int> map_var_to_index{}; map_var_to_index.reserve(var_set.size()); for (const Variable& var : var_set) { map_var_to_index.emplace(var.get_id(), var_count); vars(var_count++) = var; } return make_pair(vars, map_var_to_index); } std::pair<VectorX<Variable>, std::unordered_map<Variable::Id, int>> ExtractVariablesFromExpression( const Eigen::Ref<const VectorX<Expression>>& expressions) { std::vector<Variable> var_vec; std::unordered_map<Variable::Id, int> map_var_to_index{}; for (int i = 0; i < expressions.rows(); ++i) { for (const Variable& var : expressions(i).GetVariables()) { if (!map_var_to_index.contains(var.get_id())) { map_var_to_index.emplace(var.get_id(), var_vec.size()); var_vec.push_back(var); } } } VectorX<Variable> vars = Eigen::Map<VectorX<Variable>>(var_vec.data(), var_vec.size()); return make_pair(std::move(vars), std::move(map_var_to_index)); } void DecomposeQuadraticPolynomial( const symbolic::Polynomial& poly, const std::unordered_map<Variable::Id, int>& map_var_to_index, Eigen::MatrixXd* Q, Eigen::VectorXd* b, double* c) { const int num_variables = map_var_to_index.size(); DRAKE_DEMAND(Q->rows() == num_variables); DRAKE_DEMAND(Q->cols() == num_variables); DRAKE_DEMAND(b->rows() == num_variables); Q->setZero(); b->setZero(); *c = 0; for (const auto& p : poly.monomial_to_coefficient_map()) { DRAKE_ASSERT(is_constant(p.second)); DRAKE_DEMAND(!is_zero(p.second)); const double coefficient = get_constant_value(p.second); const symbolic::Monomial& p_monomial = p.first; if (p_monomial.total_degree() > 2) { ostringstream oss; oss << p.first << " has order higher than 2 and it cannot be handled by " "DecomposeQuadraticPolynomial." << std::endl; throw runtime_error(oss.str()); } const auto& monomial_powers = p_monomial.get_powers(); if (monomial_powers.size() == 2) { // cross terms. auto it = monomial_powers.begin(); const int x1_index = map_var_to_index.at(it->first.get_id()); DRAKE_DEMAND(it->second == 1); ++it; const int x2_index = map_var_to_index.at(it->first.get_id()); DRAKE_DEMAND(it->second == 1); (*Q)(x1_index, x2_index) += coefficient; (*Q)(x2_index, x1_index) = (*Q)(x1_index, x2_index); } else if (monomial_powers.size() == 1) { // Two cases // 1. quadratic term a*x^2 // 2. linear term b*x auto it = monomial_powers.begin(); DRAKE_DEMAND(it->second == 2 || it->second == 1); const int x_index = map_var_to_index.at(it->first.get_id()); if (it->second == 2) { // quadratic term a * x^2 (*Q)(x_index, x_index) += 2 * coefficient; } else if (it->second == 1) { // linear term b * x. (*b)(x_index) += coefficient; } } else { // constant term. *c += coefficient; } } } void DecomposeAffineExpressions(const Eigen::Ref<const VectorX<Expression>>& v, Eigen::MatrixXd* A, Eigen::VectorXd* b, VectorX<Variable>* vars) { // 0. Setup map_var_to_index and var_vec. std::unordered_map<Variable::Id, int> map_var_to_index; std::tie(*vars, map_var_to_index) = ExtractVariablesFromExpression(v); // 1. Construct decompose v as // v = A * vars + b *A = Eigen::MatrixXd::Zero(v.rows(), vars->rows()); *b = Eigen::VectorXd::Zero(v.rows()); Eigen::RowVectorXd Ai(A->cols()); for (int i{0}; i < v.size(); ++i) { const Expression& e_i{v(i)}; DecomposeAffineExpression(e_i, map_var_to_index, &Ai, b->data() + i); A->row(i) = Ai; } } int DecomposeAffineExpression( const symbolic::Expression& e, const std::unordered_map<symbolic::Variable::Id, int>& map_var_to_index, EigenPtr<Eigen::RowVectorXd> coeffs, double* constant_term) { DRAKE_DEMAND(coeffs->cols() == static_cast<int>(map_var_to_index.size())); coeffs->setZero(); *constant_term = 0; if (!e.is_polynomial()) { std::ostringstream oss; oss << "Expression " << e << "is not a polynomial.\n"; throw std::runtime_error(oss.str()); } const symbolic::Polynomial poly{e}; int num_variable = 0; for (const auto& p : poly.monomial_to_coefficient_map()) { const auto& p_monomial = p.first; DRAKE_ASSERT(is_constant(p.second)); const double p_coeff = symbolic::get_constant_value(p.second); if (p_monomial.total_degree() > 1) { std::stringstream oss; oss << "Expression " << e << " is non-linear."; throw std::runtime_error(oss.str()); } else if (p_monomial.total_degree() == 1) { // Linear coefficient. const auto& p_monomial_powers = p_monomial.get_powers(); DRAKE_DEMAND(p_monomial_powers.size() == 1); const symbolic::Variable::Id var_id = p_monomial_powers.begin()->first.get_id(); (*coeffs)(map_var_to_index.at(var_id)) = p_coeff; if (p_coeff != 0) { ++num_variable; } } else { // Constant term. *constant_term = p_coeff; } } return num_variable; } std::tuple<bool, Eigen::MatrixXd, Eigen::VectorXd, VectorX<Variable>> DecomposeL2NormExpression(const symbolic::Expression& e, double psd_tol, double coefficient_tol) { DRAKE_THROW_UNLESS(psd_tol >= 0); DRAKE_THROW_UNLESS(coefficient_tol >= 0); Eigen::MatrixXd A; Eigen::VectorXd b; VectorX<Variable> vars; if (e.get_kind() != ExpressionKind::Sqrt) { return {false, A, b, vars}; } const Expression& arg = get_argument(e); if (!arg.is_polynomial()) { return {false, A, b, vars}; } const symbolic::Polynomial poly{arg}; const int total_degree{poly.TotalDegree()}; if (total_degree != 2) { return {false, A, b, vars}; } auto e_extracted = ExtractVariablesFromExpression(e); vars = std::move(e_extracted.first); const auto& map_var_to_index = e_extracted.second; // First decompose into the form 0.5 * x' * Q * x + r' * x + s. Eigen::MatrixXd Q(vars.size(), vars.size()); Eigen::VectorXd r(vars.size()); double s; DecomposeQuadraticPolynomial(poly, map_var_to_index, &Q, &r, &s); Q *= 0.5; A = math::DecomposePSDmatrixIntoXtransposeTimesX( Q, psd_tol, true /* return empty if not psd */); if (A.rows() == 0) { return {false, A, b, vars}; } b = A.transpose().colPivHouseholderQr().solve(0.5 * r); if ((A.transpose() * b - 0.5 * r).array().abs().maxCoeff() > coefficient_tol) { return {false, A, b, vars}; } if (std::abs(s - b.dot(b)) > coefficient_tol) { return {false, A, b, vars}; } return {true, A, b, vars}; } namespace { typedef std::tuple<VectorX<Expression>, VectorX<Expression>, Expression> LumpedFactorization; // Visitor class to implement DecomposeLumpedParameters. class DecomposeLumpedParametersVisitor { public: LumpedFactorization Decompose(const Expression& e, const Variables& parameters) const { // Note that it calls `Expression::Expand()` here. return Visit(e.Expand(), parameters); } private: LumpedFactorization Visit(const Expression& e, const Variables& parameters) const { return VisitExpression<LumpedFactorization>(this, e, parameters); } LumpedFactorization VisitVariable(const Expression& e, const Variables& parameters) const { const Variable& var{get_variable(e)}; if (parameters.include(var)) { // W = [1], alpha = [e], w0 = [0] return LumpedFactorization{Vector1<Expression>{1}, Vector1<Expression>{e}, 0}; } else { // W = [], alpha = [], w0 = [e] return LumpedFactorization{Vector0<Expression>{}, Vector0<Expression>{}, e}; } } LumpedFactorization VisitConstant(const Expression& e, const Variables&) const { return LumpedFactorization{Vector0<Expression>{}, Vector0<Expression>{}, e}; } LumpedFactorization VisitAddition(const Expression& e, const Variables& parameters) const { // Temporary storage to hold the elements of w(n) (as a key) and the // elements of α(parameters) (as a value) for e. We use a map to avoid // duplicates. std::map<Expression, Expression> w_map; // e = c₀ + ∑ᵢ (cᵢ * eᵢ) // => [c₁w₁, c₂w₂, ...]*[α₁, α₂, ...] + (c₀ + ∑ᵢ cᵢw0ᵢ) // except for matching terms. Expression w0 = get_constant_in_addition(e); for (const std::pair<const Expression, double>& p : get_expr_to_coeff_map_in_addition(e)) { const Expression& e_i{p.first}; const double c_i{p.second}; const auto [w_i, alpha_i, w0_i] = Visit(e_i, parameters); w0 += c_i * w0_i; // TODO(russt): generalize this to matching up to a constant factor. for (int j = 0; j < w_i.size(); j++) { auto it = w_map.emplace(c_i * w_i[j], 0).first; it->second += alpha_i[j]; } } VectorX<Expression> w(w_map.size()); VectorX<Expression> alpha(w_map.size()); int i = 0; for (const auto& [key, value] : w_map) { w[i] = key; alpha[i++] = value; } return LumpedFactorization{w, alpha, w0}; } // Handle basic multiplication: e = a * b LumpedFactorization SimpleMultiplication(const LumpedFactorization& a, const LumpedFactorization& b) const { const auto& [w_a, alpha_a, w0_a] = a; const auto& [w_b, alpha_b, w0_b] = b; // Avoid adding terms with zero coefficients, otherwise they start to // accumulate quickly. const bool nonzero_w0a = !is_zero(w0_a); const bool nonzero_w0b = !is_zero(w0_b); // a*b = (wa*αa + w₀a) (wb*αb + w₀b) // = w₀a*w₀b + ∑ᵢⱼ(waᵢ*wbⱼ * αaᵢ*αbⱼ) + ∑ⱼw₀a*wbⱼ*αbⱼ + ∑ᵢw₀b*waᵢ*αaᵢ const auto N = w_a.size() * w_b.size() + (nonzero_w0a ? w_b.size() : 0) + (nonzero_w0b ? w_a.size() : 0); VectorX<Expression> w(N); VectorX<Expression> alpha(N); const Expression w0 = w0_a * w0_b; if (w_a.size() * w_b.size() != 0) { w.head(w_a.size() * w_b.size()) << w_a * w_b.transpose(); alpha.head(w_a.size() * w_b.size()) << alpha_a * alpha_b.transpose(); } if (nonzero_w0a) { const auto offset = w_a.size() * w_b.size(); w.segment(offset, w_b.size()) = w0_a * w_b; alpha.segment(offset, w_b.size()) = alpha_b; } if (nonzero_w0b) { w.tail(w_a.size()) = w0_b * w_a; alpha.tail(w_a.size()) = alpha_a; } // TODO(russt): Avoid duplicates. return LumpedFactorization(w, alpha, w0); } LumpedFactorization VisitMultiplication(const Expression& e, const Variables& parameters) const { const double c = get_constant_in_multiplication(e); LumpedFactorization f({}, {}, {c}); // e = c * ∏ᵢ pow(baseᵢ, exponentᵢ). for (const std::pair<const Expression, Expression>& p : get_base_to_exponent_map_in_multiplication(e)) { const Expression& base_i{p.first}; const Expression& exponent_i{p.second}; const auto [w, alpha, w0] = SimpleMultiplication( f, is_one(exponent_i) ? Visit(base_i, parameters) : VisitPow(pow(base_i, exponent_i), parameters)); // Watch out for aliasing (do I need .eval() in this case?). f = LumpedFactorization{w.eval(), alpha.eval(), w0}; } return f; } LumpedFactorization VisitPow(const Expression& e, const Variables& parameters) const { const Expression& exponent{get_second_argument(e)}; const Variables vars = e.GetVariables(); if (vars.IsSubsetOf(parameters)) { // All parameters. return LumpedFactorization{ Vector1<Expression>{1}, Vector1<Expression>{e}, {0}}; } else if (intersect(vars, parameters).empty()) { // All non-parameters. return LumpedFactorization{{}, {}, e}; } else if (is_constant(exponent)) { // Note(russt): I don't *think* that this code is reachable, since the // Expand() called at the beginning of the decomposition will break apart // cases like this. But we can implement this if we ever determine it is // needed, e.g., repeated calls to SimpleMultiplication. throw runtime_error( fmt::format("{} CAN be factored into lumped parameters, but this " "case has not been implemented yet.", e)); } else { throw runtime_error( fmt::format("{} cannot be factored into lumped parameters, since it " "depends on both parameters and non-parameter variables " "in a non-multiplicative way.", e)); } } LumpedFactorization VisitNonPolynomialTerm( const Expression& e, const Variables& parameters) const { // Must be either all parameters or all non-parameters. const Variables& vars = e.GetVariables(); if (vars.IsSubsetOf(parameters)) { return LumpedFactorization{ Vector1<Expression>{1}, Vector1<Expression>{e}, {0}}; } else if (intersect(vars, parameters).empty()) { return LumpedFactorization{{}, {}, e}; } else { throw runtime_error( fmt::format("{} cannot be factored into lumped parameters, since it " "depends on both parameters and non-parameter variables.", e)); } } LumpedFactorization VisitDivision(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitAbs(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitLog(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitExp(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitSqrt(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitSin(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitCos(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitTan(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitAsin(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitAcos(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitAtan(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitAtan2(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitSinh(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitCosh(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitTanh(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitMin(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitMax(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitCeil(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitFloor(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitIfThenElse(const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } LumpedFactorization VisitUninterpretedFunction( const Expression& e, const Variables& parameters) const { return VisitNonPolynomialTerm(e, parameters); } // Makes VisitExpression a friend of this class so that it can use private // methods. friend LumpedFactorization drake::symbolic::VisitExpression< LumpedFactorization>(const DecomposeLumpedParametersVisitor*, const Expression&, const Variables&); }; } // namespace std::tuple<MatrixX<Expression>, VectorX<Expression>, VectorX<Expression>> DecomposeLumpedParameters( const Eigen::Ref<const VectorX<Expression>>& f, const Eigen::Ref<const VectorX<Variable>>& parameters) { const DecomposeLumpedParametersVisitor visitor{}; // Compute Wα (avoiding duplicate α) by filling a map from alpha to the // corresponding column of W. std::map<Expression, VectorX<Expression>> alpha_map; VectorX<Expression> w0(f.size()); for (int i = 0; i < f.size(); i++) { const auto [w, alpha, this_w0] = visitor.Decompose(f[i], Variables(parameters)); w0[i] = this_w0; for (int j = 0; j < alpha.size(); j++) { auto it = alpha_map.emplace(alpha[j], VectorX<Expression>::Zero(f.size())) .first; (it->second)[i] += w[j]; // add to element i of column j. } } MatrixX<Expression> W = MatrixX<Expression>::Zero(f.size(), alpha_map.size()); VectorX<Expression> alpha(alpha_map.size()); int j = 0; for (const auto& [key, value] : alpha_map) { alpha[j] = key; W.col(j++) = value; } return {W, alpha, w0}; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/simplification.cc
#include "drake/common/symbolic/simplification.h" #include <map> #include <optional> #include <stdexcept> #include <utility> #include "drake/common/drake_assert.h" namespace drake { namespace symbolic { using std::function; using std::map; using std::runtime_error; namespace { // Implements a first-order unification algorithm. // // For more information, read Section 8.2. Syntactic unification of [1]. // // [1] Baader, F., & Snyder, W. (2001). Unification Theory. Handbook of // Automated Reasoning. // URL: https://www.cs.bu.edu/~snyder/publications/UnifChapter.pdf class UnificationVisitor { public: // Matches the expression `e` with the pattern `p` and tries to find a // substitution which will transform the pattern `p` into the expression `e` // when applied. Returns a substitution if found. Otherwise, returns a // `nullopt`. // // Consider the following example: // // Pattern: p ≡ sin(x) * cos(y) // Expression: e ≡ sin(a + b) * cos(c). // // `Unify(p, e)` returns a substitution `{x ↦ (a + b), y ↦ c}`. Note that // applying this substitution to the pattern `p = sin(x) * cos(y)`, we have // the expression `e = sin(a+b) * cos(c)`. // // Consider another example: // // Pattern: p ≡ sin(x * y) // Expression: e ≡ sin(a + b) // // In this case, there is no way to match `e` with `p` because `a + b` is not // matched with `x * y`. Therefore, `Unify(p, e)` returns `nullopt`. [[nodiscard]] std::optional<Substitution> Unify(const Pattern& p, const Expression& e) const { Substitution subst; if (Unify(p, e, &subst)) { return subst; } else { return std::nullopt; } } private: // It visits the pattern `p` and the expression `e` recursively and updates // the output parameter `subst`. // // Returns `false` if it fails to match `e` and `p`. Otherwise, returns true. bool Unify(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitExpression<bool>(this, p, e, subst); } bool VisitVariable(const Pattern& p, const Expression& e, Substitution* const subst) const { // Case: `p` is a variable `v`. // // We need to update `subst` to include `v ↦ e`. It fails if `subst` // already includes an entry `v` but `subst[v]` is not `e`. const Variable& v{get_variable(p)}; const auto it = subst->find(v); if (it != subst->end()) { return e.EqualTo(it->second); } subst->emplace(v, e); return true; } bool VisitConstant(const Pattern& p, const Expression& e, Substitution* const) const { // Case: `p` is a constant `c`. // // `e` should be `c` for this unification to be successful. return is_constant(e) && (get_constant_value(e) == get_constant_value(p)); } // Visits the pattern `p` and the expression `e`, updates the substitution @p // subst, and returns true if `p` and `e` are matched. Otherwise, returns // false without modifying the substitution @p subst. // // This code handles the case where `p` is an addition expression. If the // expression `e` is not an addition, the unification fails immediately. // // // Internal Representation of addition expressions // ----------------------------------------------- // // An addition expression is represented as a pair of 1) its double // coefficient and 2) an ordered map, std::map<Expression, double>. For // example, `3 + 2x + 3x²` is represented as // // constant coefficient: 3 // ordered map: {x ↦ 2, x² ↦ 3}. // // Note that keys in std::map<Expression, double> is compared by // Expression::Less. // // Note that there exists a zero-coefficient even if it is not explicitly // provided by a user. For example, `a + b` is represented internally as // // constant coefficient: 0 // ordered map: {a ↦ 1, b ↦ 1}. // // // Unification (First attempt) // --------------------------- // // Let the pattern `p` and the expression `e` be the summations of terms as // follows: // // p ≡ c₀ + c₁t₁ + ... cₙtₙ. // e ≡ c'₀ + c'₁t'₁ + ... c'ₘt'ₘ. // // Now, we derive the condition for the pattern `p` and the expression `e` // to be matched. // // 1) We require that the expression should be longer than the pattern to be // matched. That is, // // n ≤ m. // // 2) The constant parts of the pattern and the expression should be the // same. That is, // // c₀ = c'₀. // // 3) Each summand of the pattern and the expression should be matched except // for the last one. That is, // // Unify(cᵢtᵢ, c'ᵢtᵢ) for all i ∈ [1, n-1]. // // 4) Finally, the last summand in the pattern, cₙtₙ, and the rest of // unmatched summands in the expression, c'ₙt'ₙ + ... + c'ₘt'ₘ should // be matched. That is, // // Unify(cₙtₙ, c'ₙt'ₙ + ... + c'ₘt'ₘ). // // // Problem of the first attempt and an extension to the algorithm // -------------------------------------------------------------- // // Let's say that a user wants to match a pattern, p ≡ a + b, and an // expression, e ≡ 2 + x. There exists a substitution, {a ↦ 2, b ↦ x}, which // unifies the two. However, the above algorithm fails to find this // substitution. This is because the pattern, p ≡ a + b, is represented // internally as `p ≡ 0 + a + b`. As a result, the above algorithm rejects (p, // e) because the length of e, 2, is smaller than the length of p, 3. // // A solution to this problem is to do the case analysis: // // 1. Zero lead-coeff in Pattern ∧ Zero lead-coeff in Expression. // Pattern: c₁t₁ + ... + cₙtₙ // Expression: c'₁t'₁ + ... + c'ₘt'ₘ // // => Unify(cᵢtᵢ, c'ᵢt'ᵢ) for all i ∈ [1, n-1] and match the rest. // // Example: p ≡ a + b // e ≡ x + y + z // Result = match with {a ↦ x, b ↦ y + z} // // 2. Zero lead-coeff in Pattern ∧ Non-zero lead-coeff in Expression. // Pattern: c₁t₁ + ... + cₙtₙ // Expression: c'₀ + c'₁t'₁ + ... + c'ₘt'ₘ // // => Unify(cᵢtᵢ, c'ᵢ₋₁t'ᵢ₋₁) for all i ∈ [1, n-1] and match the // rest (where t'₀ = 1.0). // // Example: p ≡ a + b // e ≡ 1 + x + y + z // Result = match with {a ↦ 1, b ↦ x + y + z} // // 3. Non-zero lead-coeff in Pattern ∧ Zero lead-coeff in Expression. // Pattern: c₀ + c₁t₁ + ... + cₙtₙ // Expression: c'₁t'₁ + ... + c'ₘt'ₘ // // => To unify p and e, c₀ should be matched with c'₁t'₁. This requires // `c'₁t'₁` to be a constant, which is not the case by // construction. Therefore, this case always fails. // // Example: p ≡ 3 + a + b // e ≡ x + y // Result = fail // // 4. Non-zero lead-coeff in Pattern ∧ Non-zero lead-coeff in Expression. // Pattern: c₀ + c₁t₁ + ... + cₙtₙ // Expression: c'₀ + c'₁t'₁ + ... + c'ₘt'ₘ // // => Check c₀ = c'₀, Unify(cᵢtᵢ, c'ᵢt'ᵢ) for all i ∈ [1, n-1], unify // the rest. // // Example: p ≡ 3 + a + b // e ≡ 3 + x + y + z // Result = match with {a ↦ x, b ↦ y + z} // // Note that Case 1 and Case 4 can be handled together (see // VisitAdditionAligned below), while we need a separate routine for the Case // 2 (see VisitAdditionSkewed below). // // // Incompleteness // -------------- // // Note that this pattern-matching algorithm is incomplete as we perform the // left-to-right pattern-matching over the "ordered" summands of the pattern // and the expression. It is possible that our algorithm rejects a pair of a // pattern and an expression while there exists a substitution unifying the // two. Consider the following example: // // p ≡ t₁ + t₂ // e ≡ t'₁ + t'₂ // // Our algorithm checks if Unify(t₁, t'₁) and Unify(t₂, t'₂) hold. If this // condition does not hold, this algorithm rejects the pair (p, e). However, // it is possible that Unify(t₁, t'₂) and Unify(t₁, t'₂) hold instead. // // To be complete, it needs to check all possible re-orderings of the pattern // `p` and the expression `e`, which is not tractable in practice. We decide // to use this incomplete algorithm rather than an intractable, yet complete // approach. bool VisitAddition(const Pattern& p, const Expression& e, Substitution* const subst) const { if (!is_addition(e)) { return false; } const double c0_p{get_constant_in_addition(p)}; const double c0_e{get_constant_in_addition(e)}; const auto& map_p = get_expr_to_coeff_map_in_addition(p); const auto& map_e = get_expr_to_coeff_map_in_addition(e); if (c0_p == 0.0) { if (c0_e == 0.0) { return VisitAdditionAligned(c0_p, map_p, c0_e, map_e, subst); } else { return VisitAdditionSkewed(map_p, c0_e, map_e, subst); } } else { if (c0_e == 0.0) { return false; // Case 3. } else { return VisitAdditionAligned(c0_p, map_p, c0_e, map_e, subst); } } } // Helper method for VisitAddition. // // We perform the left-to-right pattern-matching over p and e: // p ≡ c₀ + (c₁t₁ + ... + cₙtₙ) // e ≡ c'₀ + (c'₁t'₁ + ... + c'ₘt'ₘ) // // Note that this method takes care of the cases where either (c₀ = c'₀ = 0) // or (c₀ ≠ 0 and c'₀ ≠ 0). VisitAddition calls `VisitAdditionSkewed` for // other cases. // // The following conditions must be satisfied for this unification to // be successful: // // 1) c₀ = c'₀. // 2) n ≤ m. // 3) For all i ∈ [1, n - 1], Unify(cᵢtᵢ, c'ᵢt'ᵢ) holds. // 4) Unify(cₙtₙ, c'ₙt'ₙ + ... + c'ₘt'ₘ) holds. bool VisitAdditionAligned(const double c0_p, const map<Expression, double>& map_p, const double c0_e, const map<Expression, double>& map_e, Substitution* const subst) const { DRAKE_ASSERT((c0_p == 0.0 && c0_e == 0.0) || (c0_p != 0.0 && c0_e != 0.0)); if (c0_p != c0_e) { return false; } const size_t n{map_p.size()}; const size_t m{map_e.size()}; if (!(n <= m)) { return false; } return VisitAdditionCheckPairs(map_p.begin(), map_e.begin(), n, m, subst); } // Helper method for VisitAddition. // // We perform the left-to-right pattern-matching over p and e: // p ≡ c₁t₁ + ... + cₙtₙ // e ≡ c'₀ + c'₁t'₁ + ... + c'ₘt'ₘ // // Note that p does not have the constant term (c₀ = 0) while e has a non-zero // constant term (c'₀ ≠ 0). // // The following conditions must be satisfied for this unification to be // successful: // // 1) n ≤ m + 1. // 2) Unify(c₁t₁, c'₀). // 3) For all i ∈ [2, n - 1], Unify(cᵢtᵢ, c'ᵢ₋₁t'ᵢ₋₁) holds. // 4) Unify(cₙtₙ, c'ₙ₋₁t'ₙ₋₁ + ... + c'ₘt'ₘ) holds. bool VisitAdditionSkewed(const map<Expression, double>& map_p, const double c0_e, const map<Expression, double>& map_e, Substitution* const subst) const { DRAKE_ASSERT(c0_e != 0.0); const size_t n{map_p.size()}; const size_t m{map_e.size()}; if (!(n <= m + 1)) { return false; } auto it_p = map_p.begin(); if (!Unify(it_p->first * it_p->second, c0_e, subst)) { return false; } ++it_p; auto it_e = map_e.begin(); return VisitAdditionCheckPairs(it_p, it_e, n - 1, m, subst); } // Helper method for VisitAdditionAligned and VisitAdditionSkewed. // // `it_p` and `n` represent a summation `p ≡ c₁t₁ + ... + cₙtₙ` and // `it_e` and `m` represent another summation `e ≡ c'₁t'₁ + ... + c'ₘt'ₘ`. // Note that we have a precondition that n is less than or equal to m. // This helper method performs the following unifications and updates the // output parameter `subst`. // // - For the first n - 1 pairs, Unify(cᵢtᵢ, c'ᵢt'ᵢ), for i ∈ [1, n-1]. // - Unify the last element of p with the rest of elements in e. That is, // Unify(cₙtₙ, c'ₙt'ₙ + ... c'ₘt'ₘ). bool VisitAdditionCheckPairs(map<Expression, double>::const_iterator it_p, map<Expression, double>::const_iterator it_e, const int n, const int m, Substitution* const subst) const { DRAKE_ASSERT(n <= m); int i = 1; for (; i < n; ++i, ++it_p, ++it_e) { // Check Unify(cᵢtᵢ, c'ᵢt'ᵢ) holds. const double ci_p{it_p->second}; const double ci_e{it_e->second}; const Expression& ti_p{it_p->first}; const Expression& ti_e{it_e->first}; if (!Unify(ci_p * ti_p, ci_e * ti_e, subst)) { return false; } } // Check Unify(cₙtₙ, c'ₙt'ₙ + ... + c'ₘt'ₘ) holds. const Expression last_term_p{it_p->first * it_p->second}; Expression rest_of_e{0.0}; for (; i <= m; ++i, ++it_e) { rest_of_e += it_e->first * it_e->second; } return Unify(last_term_p, rest_of_e, subst); } // Visits the pattern `p` and the expression `e`, updates the substitution // @p subst, and returns true if `p` and `e` are matched. Otherwise, returns // false without modifying the substitution @p subst. // // This code handles the case where `p` is a multiplication expression. If // the expression `e` is not a multiplication, the unification fails // immediately. // // // Internal Representation of multiplication expression // ---------------------------------------------------- // // A multiplication expression is represented as a pair of its constant factor // of double and an ordered map, std::map<Expression, Expression> which maps a // base expression to its exponent. For example, `3 * pow(x, 2) * pow(y, 3)` // is represented as // // constant factor: 3 // ordered map: {x ↦ 2, y ↦ 3}. // // Note that there exists the constant factor "one" even if it is not // explicitly provided by a user. For example, `pow(x, 1) * pow(y, 1)` is // represented internally as // // constant coefficient: 1 // ordered map: {x ↦ 1, y ↦ 1}. // // // Unification (First attempt) // --------------------------- // // Let the pattern `p` and the expression `e` be the products of factors as // follows: // // p ≡ c * pow(b₁,t₁) * ... * pow(bₙ, tₙ) // e ≡ c' * pow(b'₁, t'₁) * ... * pow(b'ₘ, t'ₘ) // // Now, we derive the condition for the pattern `p` and the expression `e` // to be matched. // // 1) We require that the expression should be longer than the pattern to be // matched. That is, // // n ≤ m. // // 2) The constant factors of the pattern and the expression should be the // same. That is, // // c₀ = c'₀. // // 3) Each factor of the pattern and the expression should be matched except // for the last one. That is, // // Unify(pow(bᵢ, tᵢ), pow(b'ᵢ, tᵢ)) for all i ∈ [1, n-1]. // // 4) Finally, the last factor in the pattern, pow(bₙ, tₙ), and the rest of // unmatched factors in the expression, pow(b'ₙ, t'ₙ) * ... * // pow(b'ₘ, t'ₘ) should be matched. That is, // // Unify(pow(bₙ, tₙ), pow(b'ₙ, t'ₙ) * ... * pow(b'ₘ, t'ₘ)). // // // Problem of the first attempt and an extension to the algorithm // -------------------------------------------------------------- // // Let's say that a user wants to match a pattern p ≡ a * b and an expression // 2 * x. There exists a substitution, {a ↦ 2, b ↦ x}, which unifies the // two. However, the above algorithm fails to find this substitution. This is // because the pattern, p ≡ a * b, is represented as `p ≡ 1 * a * b`. As a // result, the algorithm rejects (p, e) because e is not as long as p. // // A solution to this problem is to do the case analysis: // // 1. Lead-coeff in Pattern = 1 ∧ lead-coeff in Expression = 1 // Pattern: pow(b₁,t₁) * ... * pow(bₙ, tₙ) // Expression: pow(b'₁, t'₁) * ... * pow(b'ₘ, t'ₘ) // // => Unify(pow(bᵢ, tᵢ), pow(b'ᵢ, t'ᵢ)) for all i ∈ [1, n-1] and unify // the rest. // // Example: p ≡ a * b // e ≡ x * y * z // Result = match with {a ↦ x, b ↦ y * z} // // 2. Lead-coeff in Pattern = 1 ∧ Lead-coeff in Expression ≠ 1. // // Pattern: pow(b₁,t₁) * ... * pow(bₙ, tₙ) // Expression: c' * pow(b'₁, t'₁) * ... * pow(b'ₘ, t'ₘ) // // => Unify(pow(b₁, t₁), c'), Unify(pow(bᵢ, tᵢ), pow(b'ᵢ₋₁, // t'ᵢ₋₁)) for all i ∈ [2, n-1], and unify the rest. // // Example: p ≡ a * b // e ≡ 2 * x * y * z // Result = match with {a ↦ 2, b ↦ x * y * z} // // 3. Lead-coeff in Pattern ≠ 1 ∧ Lead-coeff in Expression = 1. // // Pattern: c * pow(b₁,t₁) * ... * pow(bₙ, tₙ) // Expression: pow(b'₁, t'₁) * ... * pow(b'ₘ, t'ₘ) // // => To unify p and e, c should be matched with pow(b'₁, t'₁). This // requires `pow(b'₁, t'₁)` to be a constant, which is not the case // by construction. Therefore, this case always fails. // // Example: p ≡ 2 * a * b // e ≡ x * y * z // Result = fail // // 4. Lead-coeff in Pattern ≠ 1 ∧ Lead-coeff in Expression ≠ 1. // // Pattern: c * pow(b₁,t₁) * ... * pow(bₙ, tₙ) // Expression: c' * pow(b'₁, t'₁) * ... * pow(b'ₘ, t'ₘ) // // => Check c = c', Unify(pow(bᵢ, tᵢ), pow(b'ᵢ, t'ᵢ)) for all i ∈ [1, // n-1], and unify the rest. // // Example: p ≡ 3 * a * b // e ≡ 3 * x * y * z // Result = match with {a ↦ x, b ↦ * y * z} // // Note that Case 1 and Case 4 can be handled together (in // VisitMultiplicationAligned below), while we need a separate routine for // Case 2 (in VisitMultiplicationSkewed below). // // // Incompleteness // -------------- // // See the "Incompleteness" section in VisitAddition. // bool VisitMultiplication(const Pattern& p, const Expression& e, Substitution* const subst) const { const double c_p{get_constant_in_multiplication(p)}; if (c_p < 0.0) { // Internally, an unary expression `-e` is represented as a multiplicative // expression `-1 * e`. The following line allows us to match expressions // with a pattern with unary minus. return Unify(-p, -e, subst); } if (!is_multiplication(e)) { return false; } const double c_e{get_constant_in_multiplication(e)}; const auto& map_p = get_base_to_exponent_map_in_multiplication(p); const auto& map_e = get_base_to_exponent_map_in_multiplication(e); if (c_p == 1.0) { if (c_e == 1.0) { return VisitMultiplicationAligned(c_p, map_p, c_e, map_e, subst); } else { return VisitMultiplicationSkewed(map_p, c_e, map_e, subst); } } else { if (c_e == 1.0) { return false; // Case 3. } else { return VisitMultiplicationAligned(c_p, map_p, c_e, map_e, subst); } } } // Helper method for VisitMultiplication. // // We perform left-to-right pattern-matching over p and e: // // p := c * (pow(b₁, t₁) * ... * pow(bₙ, tₙ)) // e := c' * (pow(b'₁, t'₁) * ... * pow(b'ₘ, t'ₘ)) // // Note that this method takes care of the cases where either (c = c' = 1) or // (c₀ ≠ 1 and c'₀ ≠ 1). VisitMultiplication calls `VisitMultiplicationSkewed` // for other cases. // // The following conditions must be satisfied for this unification to be // successful: // // 1) c == c' // 2) n ≤ m // 3) For all i ∈ [1, n - 1], Unify(pow(bᵢ, tᵢ), pow(b'ᵢ, t'ᵢ)) holds. // 4) Unify(pow(bₙ, tₙ), pow(b'ₙ, t'ₙ) * ... * pow(b'ₘ, t'ₘ)) holds. bool VisitMultiplicationAligned(const double c_p, const map<Expression, Expression>& map_p, const double c_e, const map<Expression, Expression>& map_e, Substitution* const subst) const { DRAKE_ASSERT((c_p == 1.0 && c_e == 1.0) || (c_p != 1.0 && c_e != 1.0)); if (c_p != c_e) { return false; } const size_t n{map_p.size()}; const size_t m{map_e.size()}; if (!(n <= m)) { return false; } return VisitMultiplicationCheckPairs(map_p.begin(), map_e.begin(), n, m, subst); } // Helper method for VisitMultiplication. // // We perform left-to-right pattern-matching over p and e: // // p := (pow(b₁, t₁) * ... * pow(bₙ, tₙ)) // e := c' * (pow(b'₁, t'₁) * ... * pow(b'ₘ, t'ₘ)) // // Note that this method handles the case where c' ≠ 1.0. // // The following conditions must be satisfied for this unification to be // successful: // // 1) n ≤ m + 1. // 2) Unify(pow(b₁, t₁), c'). // 3) For all i ∈ [2, n - 1], // Unify(pow(bᵢ, tᵢ), pow(b'ᵢ₋₁, t'ᵢ₋₁)) holds. // 4) Unify(pow(bₙ, tₙ), pow(b'ₙ, t'ₙ) * ... * pow(b'ₘ, t'ₘ)) holds. bool VisitMultiplicationSkewed(const map<Expression, Expression>& map_p, const double c_e, const map<Expression, Expression>& map_e, Substitution* const subst) const { DRAKE_ASSERT(c_e != 1.0); const size_t n{map_p.size()}; const size_t m{map_e.size()}; if (!(n <= m + 1)) { return false; } auto it_p = map_p.begin(); if (!Unify(pow(it_p->first, it_p->second), c_e, subst)) { return false; } ++it_p; auto it_e = map_e.begin(); return VisitMultiplicationCheckPairs(it_p, it_e, n - 1, m, subst); } // Helper method for VisitMultiplicationAligned and VisitMultiplicationSkewed. // // `it_p` and `n` represent a product `p = pow(b₁, t₁) * ... * pow(bₙ, tₙ)` // and `it_e` and `m` represent another product `e = pow(b'₁, t'₁) * pow(b'ₘ, // t'ₘ)`. Note that we have a precondition that n is less than or equal to m. // This helper method performs the following unifications and updates the // output parameter `subst`. // // - For the first n - 1 pairs, Unify(pow(bᵢ, tᵢ), pow(b'ᵢ, t'ᵢ)), // for i ∈ [1, n-1]. // - Unify the last element of p with the rest of elements in e. That is, // Unify(pow(bₙ, tₙ), pow(b'ₙ, t'ₙ) * ... * pow(b'ₘ, t'ₘ)). bool VisitMultiplicationCheckPairs( map<Expression, Expression>::const_iterator it_p, map<Expression, Expression>::const_iterator it_e, const int n, const int m, Substitution* const subst) const { DRAKE_ASSERT(n >= 1 && n <= m); // Checks Unify(pow(bᵢ, tᵢ), pow(b'ᵢ, t'ᵢ)) holds. int i = 1; for (; i < n; ++i, ++it_p, ++it_e) { const Expression& bi_p{it_p->first}; const Expression& bi_e{it_e->first}; const Expression& ti_p{it_p->second}; const Expression& ti_e{it_e->second}; if (!Unify(pow(bi_p, ti_p), pow(bi_e, ti_e), subst)) { return false; } } // Checks Unify(pow(bₙ, tₙ), pow(b'ₙ, t'ₙ) * ... * pow(b'ₘ, t'ₘ)). const Expression last_term_p{pow(it_p->first, it_p->second)}; Expression rest_of_e{1.0}; for (; i <= m; ++i, ++it_e) { rest_of_e *= pow(it_e->first, it_e->second); } return Unify(last_term_p, rest_of_e, subst); } // Helper method to handle unary cases. bool VisitUnary(const function<bool(const Expression&)>& pred, const Pattern& p, const Expression& e, Substitution* const subst) const { return pred(e) && Unify(get_argument(p), get_argument(e), subst); } // Helper method to handle binary cases. bool VisitBinary(const function<bool(const Expression&)>& pred, const Pattern& p, const Expression& e, Substitution* const subst) const { return pred(e) && Unify(get_first_argument(p), get_first_argument(e), subst) && Unify(get_second_argument(p), get_second_argument(e), subst); } bool VisitPow(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitBinary(&is_pow, p, e, subst); } bool VisitDivision(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitBinary(&is_division, p, e, subst); } bool VisitAbs(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_abs, p, e, subst); } bool VisitLog(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_log, p, e, subst); } bool VisitExp(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_exp, p, e, subst); } bool VisitSqrt(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_sqrt, p, e, subst); } bool VisitSin(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_sin, p, e, subst); } bool VisitCos(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_cos, p, e, subst); } bool VisitTan(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_tan, p, e, subst); } bool VisitAsin(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_asin, p, e, subst); } bool VisitAcos(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_acos, p, e, subst); } bool VisitAtan(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_atan, p, e, subst); } bool VisitAtan2(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitBinary(&is_atan2, p, e, subst); } bool VisitSinh(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_sinh, p, e, subst); } bool VisitCosh(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_cosh, p, e, subst); } bool VisitTanh(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_tanh, p, e, subst); } bool VisitMin(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitBinary(&is_min, p, e, subst); } bool VisitMax(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitBinary(&is_max, p, e, subst); } bool VisitCeil(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_ceil, p, e, subst); } bool VisitFloor(const Pattern& p, const Expression& e, Substitution* const subst) const { return VisitUnary(&is_floor, p, e, subst); } bool VisitIfThenElse(const Pattern&, const Expression&, Substitution* const) const { // TODO(soonho): Support this. throw runtime_error( "Unification algorithm does not support if-then-else-expressions, yet"); } bool VisitUninterpretedFunction(const Pattern&, const Expression&, Substitution* const) const { // TODO(soonho): Support this. throw runtime_error( "Unification algorithm does not support uninterpreted functions, yet"); } // Makes VisitExpression a friend of this class so that it can use private // methods. friend bool VisitExpression<bool>(const UnificationVisitor*, const Pattern&, const Expression&, Substitution* const&); }; // Unifies the expression `e` with the pattern `p`. std::optional<Substitution> Unify(const Pattern& p, const Expression& e) { return UnificationVisitor{}.Unify(p, e); } } // namespace Rewriter MakeRuleRewriter(const RewritingRule& rule) { return [rule](const Expression& e) { const std::optional<Substitution> subst{Unify(rule.lhs(), e)}; if (subst) { return rule.rhs().Substitute(*subst); } else { return e; } }; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/codegen.h
#pragma once #include <sstream> #include <string> #include <unordered_map> #include <vector> #include <Eigen/Core> #include <Eigen/Sparse> #include "drake/common/drake_copyable.h" #include "drake/common/symbolic/expression.h" namespace drake { namespace symbolic { /// Visitor class for code generation. class CodeGenVisitor { public: using IdToIndexMap = std::unordered_map<Variable::Id, std::vector<Variable>::size_type>; DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(CodeGenVisitor) /// Constructs an instance of this visitor class using the vector of /// variables, @p parameters. This visitor will map a symbolic variable `var` /// into `p[n]` where `n` is the index of the variable `var` in the given @p /// parameters. explicit CodeGenVisitor(const std::vector<Variable>& parameters); /// Generates C expression for the expression @p e. [[nodiscard]] std::string CodeGen(const Expression& e) const; private: [[nodiscard]] std::string VisitVariable(const Expression& e) const; [[nodiscard]] std::string VisitConstant(const Expression& e) const; [[nodiscard]] std::string VisitAddition(const Expression& e) const; [[nodiscard]] std::string VisitMultiplication(const Expression& e) const; // Helper method to handle unary cases. [[nodiscard]] std::string VisitUnary(const std::string& f, const Expression& e) const; // Helper method to handle binary cases. [[nodiscard]] std::string VisitBinary(const std::string& f, const Expression& e) const; [[nodiscard]] std::string VisitPow(const Expression& e) const; [[nodiscard]] std::string VisitDivision(const Expression& e) const; [[nodiscard]] std::string VisitAbs(const Expression& e) const; [[nodiscard]] std::string VisitLog(const Expression& e) const; [[nodiscard]] std::string VisitExp(const Expression& e) const; [[nodiscard]] std::string VisitSqrt(const Expression& e) const; [[nodiscard]] std::string VisitSin(const Expression& e) const; [[nodiscard]] std::string VisitCos(const Expression& e) const; [[nodiscard]] std::string VisitTan(const Expression& e) const; [[nodiscard]] std::string VisitAsin(const Expression& e) const; [[nodiscard]] std::string VisitAcos(const Expression& e) const; [[nodiscard]] std::string VisitAtan(const Expression& e) const; [[nodiscard]] std::string VisitAtan2(const Expression& e) const; [[nodiscard]] std::string VisitSinh(const Expression& e) const; [[nodiscard]] std::string VisitCosh(const Expression& e) const; [[nodiscard]] std::string VisitTanh(const Expression& e) const; [[nodiscard]] std::string VisitMin(const Expression& e) const; [[nodiscard]] std::string VisitMax(const Expression& e) const; [[nodiscard]] std::string VisitCeil(const Expression& e) const; [[nodiscard]] std::string VisitFloor(const Expression& e) const; [[nodiscard]] std::string VisitIfThenElse(const Expression& e) const; [[nodiscard]] std::string VisitUninterpretedFunction( const Expression& e) const; // Makes VisitExpression a friend of this class so that it can use private // methods. friend std::string VisitExpression<std::string>(const CodeGenVisitor*, const Expression&); IdToIndexMap id_to_idx_map_; }; /// @defgroup codegen Code Generation /// @ingroup technical_notes /// @{ /// Provides `CodeGen` functions which generate C99 code to evaluate symbolic /// expressions and matrices. /// /// @note Generated code does not contain `#include` directives while it may use /// math functions defined in `<math.h>` such as `sin`, `cos`, `exp`, and `log`. /// A user of generated code is responsible to include `<math.h>` if needed to /// compile generated code. /// For a given symbolic expression @p e, generates two C functions, /// `<function_name>` and `<function_name>_meta`. The generated /// `<function_name>` function takes an array of doubles for parameters and /// returns an evaluation result. `<function_name>_meta` returns a nested struct /// from which a caller can obtain the following information: /// - `.p.size`: the size of input parameters. /// /// @param[in] function_name Name of the generated C function. /// @param[in] parameters Vector of variables provide the ordering of /// symbolic variables. /// @param[in] e Symbolic expression to codegen. /// /// For example, `Codegen("f", {x, y}, 1 + sin(x) + cos(y))` generates the /// following string. /// /// @code /// double f(const double* p) { /// return (1 + sin(p[0]) + cos(p[1])); /// } /// typedef struct { /// /* p: input, vector */ /// struct { int size; } p; /// } f_meta_t; /// f_meta_t f_meta() { return {{2}}; } /// @endcode /// /// Note that in this example `x` and `y` are mapped to `p[0]` and `p[1]` /// respectively because we passed `{x, y}` to `Codegen`. std::string CodeGen(const std::string& function_name, const std::vector<Variable>& parameters, const Expression& e); namespace internal { // Generates code for the internal representation of a matrix, @p data, using // @p function_name, @p parameters, and @p size. It outputs the generated code // to the output stream @p os. // // @note This function is used to implement std::string // drake::symbolic::CodeGen(const std::string &, const std::vector<Variable>&, // const Eigen::PlainObjectBase<Derived>&). void CodeGenDenseData(const std::string& function_name, const std::vector<Variable>& parameters, const Expression* data, int size, std::ostream* os); // Generates code for the meta information and outputs to the output stream @p // os. // // @note This function is used to implement std::string // drake::symbolic::CodeGen(const std::string &, const std::vector<Variable>&, // const Eigen::PlainObjectBase<Derived>&). void CodeGenDenseMeta(const std::string& function_name, int parameter_size, int rows, int cols, std::ostream* os); } // namespace internal /// For a given symbolic dense matrix @p M, generates two C functions, /// `<function_name>` and `<function_name>_meta`. The generated /// `<function_name>` takes two parameters: /// /// - const double* p : An array of doubles for input parameters. /// - double* m : An array of doubles to store the evaluation result. /// /// `<function_name>_meta()` returns a nested struct from which a caller can /// obtain the following information: /// - `.p.size`: the size of input parameters. /// - `.m.rows`: the number of rows in the matrix. /// - `.m.cols`: the number of columns in the matrix. /// /// Please consider the following example: /// /// @code /// Eigen::Matrix<symbolic::Expression, 2, 2, Eigen::ColMajor> M; /// M(0, 0) = 1.0; /// M(1, 0) = 3 + x + y; /// M(0, 1) = 4 * y; /// M(1, 1) = sin(x); /// CodeGen("f", {x, y}, M); /// @endcode /// /// When executed, the last line of the above example generates the following /// code: /// /// @code /// void f(const double* p, double* m) { /// m[0] = 1.000000; /// m[1] = (3 + p[0] + p[1]); /// m[2] = (4 * p[1]); /// m[3] = sin(p[0]); /// } /// typedef struct { /// /* p: input, vector */ /// struct { /// int size; /// } p; /// /* m: output, matrix */ /// struct { /// int rows; /// int cols; /// } m; /// } f_meta_t; /// f_meta_t f_meta() { return {{2}, {2, 2}}; } /// @endcode /// /// Note that in this example, the matrix `M` is stored in column-major order /// and the `CodeGen` function respects the storage order in the generated code. /// If `M` were stored in row-major order, `CodeGen` would return the following: /// /// @code /// void f(const double* p, double* m) { /// m[0] = 1.000000; /// m[1] = (4 * p[1]); /// m[2] = (3 + p[0] + p[1]); /// m[3] = sin(p[0]); /// } /// @endcode template <typename Derived> std::string CodeGen(const std::string& function_name, const std::vector<Variable>& parameters, const Eigen::PlainObjectBase<Derived>& M) { static_assert(std::is_same_v<typename Derived::Scalar, Expression>, "CodeGen should take a symbolic matrix."); std::ostringstream oss; internal::CodeGenDenseData(function_name, parameters, M.data(), M.cols() * M.rows(), &oss); internal::CodeGenDenseMeta(function_name, parameters.size(), M.rows(), M.cols(), &oss); return oss.str(); } /// For a given symbolic column-major sparse matrix @p M, generates two C /// functions, `<function_name>` and `<function_name>_meta`. The generated /// `<function_name>` is used to construct a sparse matrix of double which /// stores the evaluation result of the symbolic matrix @p M for a given /// double-precision floating-point assignment for the symbolic variables in @p /// M. `<function_name>` takes one input parameter `p` and three output /// parameters (`outer_indicies`, `inner_indices`, and `values`). /// /// - const double* p : An array of doubles for input parameters. /// - int* outer_indices : An array of integer to store the starting positions /// of the inner vectors. /// - int* inner_indices : An array of integer to store the array of inner /// indices. /// - double* values : An array of doubles to store the evaluated non-zero /// elements. /// /// The three outputs, (`outer_indices`, `inner_indices`, `values`), represent a /// sparse matrix in the widely-used Compressed Column Storage (CCS) scheme. For /// more information about the CCS scheme, please read /// https://eigen.tuxfamily.org/dox/group__TutorialSparse.html. /// /// `<function_name>_meta()` returns a nested struct from which a caller can /// obtain the following information: /// - `.p.size`: the size of input parameters. /// - `.m.rows`: the number of rows in the matrix. /// - `.m.cols`: the number of columns in the matrix. /// - `.m.non_zeros`: the number of non-zero elements in the matrix. /// - `.m.outer_indices`: the length of the outer_indices. /// - `.m.inner_indices`: the length of the inner_indices. /// /// @throws std::exception if @p M is not compressed. // TODO(soonho-tri): Support row-major sparse matrices. /// /// Please consider the following example which generates code for a 3x6 /// sparse matrix. /// /// @code /// 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(); /// // | x 0 0 0 z 0| /// // | 0 0 y 0 0 0| /// // | 0 0 0 y 0 y| /// CodeGen("f", {x, y, z}, m); /// @endcode /// /// When executed, the last line of the above example generates the following /// code: /// /// @code /// 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; /// } m; /// } f_meta_t; /// f_meta_t f_meta() { return {{3}, {3, 6, 5}}; } /// @endcode /// /// In the following example, we show how to use the generated function to /// evaluate the symbolic matrix and construct a sparse matrix of double using /// `Eigen::Map`. /// /// @code /// // set up param, outer_indices, inner_indices, and values. /// f_meta_t meta = f_meta(); /// const Eigen::Vector3d param{1 /* x */, 2 /* y */, 3 /* z */}; /// std::vector<int> outer_indices(meta.m.cols + 1); /// std::vector<int> inner_indices(meta.m.non_zeros); /// std::vector<double> values(meta.m.non_zeros); /// /// // call f to fill outer_indices, inner_indices, and values. /// f(param.data(), outer_indices.data(), inner_indices.data(), values.data()); /// /// // use Eigen::Map to turn (outer_indices, inner_indices, values) into a /// // sparse matrix. /// 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()}; /// @endcode std::string CodeGen( const std::string& function_name, const std::vector<Variable>& parameters, const Eigen::Ref<const Eigen::SparseMatrix<Expression, Eigen::ColMajor>>& M); /// @} End of codegen group. } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/monomial_basis_element.h
#pragma once #include <map> #include <utility> #include <Eigen/Core> #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/common/hash.h" #include "drake/common/symbolic/chebyshev_basis_element.h" #include "drake/common/symbolic/polynomial_basis_element.h" namespace drake { namespace symbolic { /** * MonomialBasisElement represents a monomial, a product of powers of variables * with non-negative integer exponents. Note that it doesn't not include the * coefficient part of a monomial. So x, x³y, xy²z are all valid * MonomialBasisElement instances, but 1+x or 2xy²z are not. * TODO(hongkai.dai): deprecate Monomial class and replace Monomial class with * MonomialBasisElement class. * For more information regarding the motivation of this class, please see * Drake github issue #13602 and #13803. */ class MonomialBasisElement : public PolynomialBasisElement { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(MonomialBasisElement) /** Constructs a monomial equal to 1. Namely the toal degree is zero. */ MonomialBasisElement(); /** Constructs a default value. This overload is used by Eigen when * EIGEN_INITIALIZE_MATRICES_BY_ZERO is enabled. */ explicit MonomialBasisElement(std::nullptr_t) : MonomialBasisElement() {} /** * Constructs a MonomialBasisElement from variable to degree map. */ explicit MonomialBasisElement( const std::map<Variable, int>& var_to_degree_map); /** * Converts an expression to a monomial if the expression is written as * ∏ᵢpow(xᵢ, kᵢ), otherwise throws a runtime error. * @pre is_polynomial(e) should be true. */ explicit MonomialBasisElement(const Expression& e); /** Constructs a Monomial from a vector of variables `vars` and their * corresponding integer degrees `degrees`. * For example, `MonomialBasisElement([x, y, z], [2, 0, 1])` constructs a * MonomialBasisElement `x²z`. * * @pre The size of `vars` should be the same as the size of `degrees`. * @throws std::exception if `degrees` includes a negative integer. */ MonomialBasisElement(const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& degrees); /** * Constructs a monomial basis element with only one variable, and the degree * is 1. */ explicit MonomialBasisElement(const Variable& var); /** * Constructs a monomial basis element with only one variable, and the degree * of that variable is given by @p degree. */ MonomialBasisElement(const Variable& var, int degree); /** Partially evaluates using a given environment @p env. The evaluation * result is of type pair<double, MonomialBasisElement>. The first component * (: double) represents the coefficient part while the second component * represents the remaining parts of the MonomialBasisElement which was not * evaluated. * * Example 1. Evaluate with a fully-specified environment * (x³*y²).EvaluatePartial({{x, 2}, {y, 3}}) * = (2³ * 3² = 8 * 9 = 72, MonomialBasisElement{} = 1). * * Example 2. Evaluate with a partial environment * (x³*y²).EvaluatePartial({{x, 2}}) * = (2³ = 8, y²). */ [[nodiscard]] std::pair<double, MonomialBasisElement> EvaluatePartial( const Environment& env) const; /** Returns this monomial raised to @p p. * @throws std::exception if @p p is negative. */ MonomialBasisElement& pow_in_place(int p); /** * Compares two MonomialBasisElement in lexicographic order. */ bool operator<(const MonomialBasisElement& other) const; /** * Differentiates this MonomialBasisElement. * Since dxⁿ/dx = nxⁿ⁻¹, we return the map from the MonomialBasisElement to * its coefficient. So if this MonomialBasisElement is x³y², then * differentiate with x will return (x²y² → 3) as dx³y²/dx = 3x²y² * If @p var is not a variable in MonomialBasisElement, then returns an empty * map. */ [[nodiscard]] std::map<MonomialBasisElement, double> Differentiate( const Variable& var) const; /** * Integrates this MonomialBasisElement on a variable. * Since ∫ xⁿ dx = 1 / (n+1) xⁿ⁺¹, we return the map from the * MonomialBasisElement to its coefficient in the integration result. So if * this MonomialBasisElement is x³y², then we return (x⁴y² → 1/4) as ∫ x³y²dx * = 1/4 x⁴y². If @p var is not a variable in this MonomialBasisElement, for * example ∫ x³y²dz = x³y²z, then we return (x³y²z → 1) */ [[nodiscard]] std::map<MonomialBasisElement, double> Integrate( const Variable& var) const; /** Merges this basis element with another basis element @p other by merging * their var_to_degree_map. This is equivalent to multiplying this monomial * basis element in place with monomial basis element @p other. */ void MergeBasisElementInPlace(const MonomialBasisElement& other); /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const MonomialBasisElement& item) noexcept { using drake::hash_append; // We do not send total_degree_ to the hasher, because it is already fully // represented by var_to_degree_map_ -- it is just a cached tally of the // exponents. hash_append(hasher, item.var_to_degree_map()); } /** * Converts this monomial to Chebyshev polynomial basis. For example, * * - For x², it returns 0.5T₂(x) + 0.5T₀(x). * - For x²y³, it returns 1/8T₂(x)T₃(y) + 3/8T₂(x)T₁(y) + 1/8T₀(x)T₃(y) + * 3/8T₀(x)T₁(y). * * We return the map from each ChebyshevBasisElement to its coefficient. * For example, when this = x², it returns {[T₂(x)⇒0.5], [T₀(x)⇒0.5]}. * When this = x²y³, it returns {[T₂(x)T₃(y)⇒1/8], [T₂(x)T₁(y)⇒3/8], * [T₀(x)T₃(y)⇒1/8], [T₀(x)T₁(y)⇒3/8]}. */ [[nodiscard]] std::map<ChebyshevBasisElement, double> ToChebyshevBasis() const; /** * Converts this monomial to a weighted sum of basis elements of type * BasisElement. We return the map from each BasisElement to its coefficient. * For example, if BasisElement=ChebyshevBasisElement, then when this = x²y³, * it returns {[T₂(x)T₃(y)⇒1/8], [T₂(x)T₁(y)⇒3/8], [T₀(x)T₃(y)⇒1/8], * [T₀(x)T₁(y)⇒3/8]}. * @note Currently we only support @tparam BasisElement being * MonomialBasisElement and ChebyshevBasisElement. */ template <typename BasisElement> std::map<BasisElement, double> ToBasis() const { static_assert(std::is_same_v<BasisElement, MonomialBasisElement> || std::is_same_v<BasisElement, ChebyshevBasisElement>, "MonomialBasisElement::ToBasis() does not support this " "BasisElement type."); if constexpr (std::is_same_v<BasisElement, MonomialBasisElement>) { return {{*this, 1.}}; } return ToChebyshevBasis(); } private: [[nodiscard]] double DoEvaluate(double variable_val, int degree) const override; [[nodiscard]] Expression DoToExpression() const override; }; std::ostream& operator<<(std::ostream& out, const MonomialBasisElement& m); /** Returns a multiplication of two monomials, @p m1 and @p m2. * @note that we return a map from the monomial product to its coefficient. This * map has size 1, and the coefficient is also 1. We return a map instead of the * MonomialBasisElement directly, because we want operator* to have the same * return signature as other PolynomialBasisElement. For example, the product * between two ChebyshevBasisElement objects is a weighted sum of * ChebyshevBasisElement objects. * @note we do not provide operator*= function for this class, since operator*= * would return MonomialBasisElement, which is different from operator*. */ std::map<MonomialBasisElement, double> operator*( const MonomialBasisElement& m1, const MonomialBasisElement& m2); /** Returns @p m raised to @p p. * @note that we return a map from the monomial power to its coefficient. This * map has size 1, and the coefficient is also 1. We return a map instead of the * MonomialBasisElement directly, because we want pow() to have the same * return signature as other PolynomialBasisElement. For example, the power * of a ChebyshevBasisElement object is a weighted sum of ChebyshevBasisElement * objects. * @throws std::exception if @p p is negative. */ std::map<MonomialBasisElement, double> pow(MonomialBasisElement m, int p); } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::MonomialBasisElement>. */ template <> struct hash<drake::symbolic::MonomialBasisElement> : public drake::DefaultHash { }; } // namespace std #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { // Eigen scalar type traits for Matrix<drake::symbolic::MonomialBasisElement>. template <> struct NumTraits<drake::symbolic::MonomialBasisElement> : GenericNumTraits<drake::symbolic::MonomialBasisElement> { static inline int digits10() { return 0; } }; namespace internal { // Informs Eigen how to cast drake::symbolic::MonomialBasisElement to // drake::symbolic::Expression. template <> EIGEN_DEVICE_FUNC inline drake::symbolic::Expression cast( const drake::symbolic::MonomialBasisElement& m) { return m.ToExpression(); } } // namespace internal } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX) // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::symbolic::MonomialBasisElement> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/decompose.h
#pragma once #include <string> #include <tuple> #include <unordered_map> #include <utility> #include "drake/common/eigen_types.h" #include "drake/common/symbolic/expression.h" #include "drake/common/symbolic/polynomial.h" // TODO(soonho-tri): Migrate the functions in drake/solvers:symbolic_extract to // this file. namespace drake { namespace symbolic { /** Checks if every element in `m` is affine in `vars`. @note If `m` is an empty matrix, it returns true. */ bool IsAffine(const Eigen::Ref<const MatrixX<Expression>>& m, const Variables& vars); /** Checks if every element in `m` is affine. @note If `m` is an empty matrix, it returns true. */ bool IsAffine(const Eigen::Ref<const MatrixX<Expression>>& m); /** Decomposes @p expressions into @p M * @p vars. @throws std::exception if @p expressions is not linear in @p vars. @pre M.rows() == expressions.rows() && M.cols() == vars.rows(). */ void DecomposeLinearExpressions( const Eigen::Ref<const VectorX<Expression>>& expressions, const Eigen::Ref<const VectorX<Variable>>& vars, EigenPtr<Eigen::MatrixXd> M); /** Decomposes @p expressions into @p M * @p vars + @p v. @throws std::exception if @p expressions is not affine in @p vars. @pre M.rows() == expressions.rows() && M.cols() == vars.rows(). @pre v.rows() == expressions.rows(). */ void DecomposeAffineExpressions( const Eigen::Ref<const VectorX<Expression>>& expressions, const Eigen::Ref<const VectorX<Variable>>& vars, EigenPtr<Eigen::MatrixXd> M, EigenPtr<Eigen::VectorXd> v); /** Given an expression `e`, extract all variables inside `e`, append these variables to `vars` if they are not included in `vars` yet. @param[in] e A symbolic expression. @param[in,out] vars As an input, `vars` contain the variables before extracting expression `e`. As an output, the variables in `e` that were not included in `vars`, will be appended to the end of `vars`. @param[in,out] map_var_to_index. map_var_to_index is of the same size as `vars`, and map_var_to_index[vars(i).get_id()] = i. This invariance holds for map_var_to_index both as the input and as the output. @note This function is very slow if you call this function within a loop as it involves repeated heap memory allocation. Consider using ExtractVariablesFromExpression. */ void ExtractAndAppendVariablesFromExpression( const symbolic::Expression& e, VectorX<Variable>* vars, std::unordered_map<symbolic::Variable::Id, int>* map_var_to_index); /** Given an expression `e`, extracts all variables inside `e`. @param[in] e A symbolic expression. @retval pair pair.first is the variables in `e`. pair.second is the mapping from the variable ID to the index in pair.first, such that pair.second[pair.first(i).get_id()] = i */ std::pair<VectorX<Variable>, std::unordered_map<symbolic::Variable::Id, int>> ExtractVariablesFromExpression(const symbolic::Expression& e); /** * Overloads ExtractVariablesFromExpression but with a vector of expressions. */ std::pair<VectorX<Variable>, std::unordered_map<Variable::Id, int>> ExtractVariablesFromExpression( const Eigen::Ref<const VectorX<Expression>>& expressions); /** Given a quadratic polynomial @p poly, decomposes it into the form 0.5 * x' * Q * x + b' * x + c @param[in] poly Quadratic polynomial to decompose. @param[in] map_var_to_index maps variables in `poly.GetVariables()` to the index in the vector `x`. @param Q[out] The Hessian of the quadratic expression. @pre The size of Q should be `num_variables x num_variables`. Q is a symmetric matrix. @param b[out] The linear term of the quadratic expression. @pre The size of `b` should be `num_variables`. @param c[out] The constant term of the quadratic expression. */ void DecomposeQuadraticPolynomial( const symbolic::Polynomial& poly, const std::unordered_map<symbolic::Variable::Id, int>& map_var_to_index, Eigen::MatrixXd* Q, Eigen::VectorXd* b, double* c); /** Given a vector of affine expressions v, decompose it to \f$ v = A vars + b \f$ @param[in] v A vector of affine expressions @param[out] A The matrix containing the linear coefficients. @param[out] b The vector containing all the constant terms. @param[out] vars All variables. */ void DecomposeAffineExpressions( const Eigen::Ref<const VectorX<symbolic::Expression>>& v, Eigen::MatrixXd* A, Eigen::VectorXd* b, VectorX<Variable>* vars); /** Decomposes an affine combination @p e = c0 + c1 * v1 + ... cn * vn into the following: constant term : c0 coefficient vector : [c1, ..., cn] variable vector : [v1, ..., vn] Then, it extracts the coefficient and the constant term. A map from variable ID to int, @p map_var_to_index, is used to decide a variable's index in a linear combination. \pre 1. @c coeffs is a row vector of double, whose length matches with the size of @c map_var_to_index. 2. e.is_polynomial() is true. 3. e is an affine expression. 4. all values in `map_var_to_index` should be in the range [0, map_var_to_index.size()) @param[in] e The symbolic affine expression @param[in] map_var_to_index A mapping from variable ID to variable index, such that map_var_to_index[vi.get_ID()] = i. @param[out] coeffs A row vector. coeffs(i) = ci. @param[out] constant_term c0 in the equation above. @return num_variable. Number of variables in the expression. 2 * x(0) + 3 has 1 variable, 2 * x(0) + 3 * x(1) - 2 * x(0) has 1 variable. */ int DecomposeAffineExpression( const symbolic::Expression& e, const std::unordered_map<symbolic::Variable::Id, int>& map_var_to_index, EigenPtr<Eigen::RowVectorXd> coeffs, double* constant_term); /** Given a vector of Expressions @p f and a list of @p parameters we define all additional variables in @p f to be a vector of "non-parameter variables", n. This method returns a factorization of @p f into an equivalent "data matrix", W, which depends only on the non-parameter variables, and a "lumped parameter vector", α, which depends only on @p parameters: f = W(n)*α(parameters) + w0(n). @note The current implementation makes some simple attempts to minimize the number of lumped parameters, but more simplification could be implemented relatively easily. Optimal simplification, however, involves the complexity of comparing two arbitrary Expressions (see Expression::EqualTo for more details). @throw std::exception if @p f is not decomposable in this way (cells containing @p parameters may only be added or multiplied with cells containing non-parameter variables). @returns W(n), α(parameters), and w0(n). */ std::tuple<MatrixX<Expression>, VectorX<Expression>, VectorX<Expression>> DecomposeLumpedParameters( const Eigen::Ref<const VectorX<Expression>>& f, const Eigen::Ref<const VectorX<Variable>>& parameters); /** Decomposes an L2 norm @p e = |Ax+b|₂ into A, b, and the variable vector x (or returns false if the decomposition is not possible). In order for the decomposition to succeed, the following conditions must be met: 1. e is a sqrt expression. 2. e.get_argument() is a polynomial of degree 2, which can be expressed as a quadratic form (Ax+b)ᵀ(Ax+b). @param e The symbolic affine expression @param psd_tol The tolerance for checking positive semidefiniteness. Eigenvalues less that this threshold are considered to be zero. Matrices with negative eigenvalues less than this threshold are considered to be not positive semidefinite, and will cause the decomposition to fail. @param coefficient_tol The absolute tolerance for checking that the coefficients of the expression inside the sqrt match the coefficients of |Ax+b|₂². @return [is_l2norm, A, b, vars] where is_l2norm is true iff the decomposition was successful, and if is_l2norm is true then |A*vars + b|₂ = e. */ std::tuple<bool, Eigen::MatrixXd, Eigen::VectorXd, VectorX<Variable>> DecomposeL2NormExpression(const symbolic::Expression& e, double psd_tol = 1e-8, double coefficient_tol = 1e-8); } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/rational_function.h
#pragma once #include <ostream> #include "drake/common/fmt_ostream.h" #include "drake/common/symbolic/polynomial.h" namespace drake { namespace symbolic { /** * Represents symbolic rational function. A function f(x) is a rational * function, if f(x) = p(x) / q(x), where both p(x) and q(x) are polynomials of * x. Note that rational functions are closed under (+, -, x, /). One * application of rational function is in polynomial optimization, where we * represent (or approximate) functions using rational functions, and then * convert the constraint f(x) = h(x) (where h(x) is a polynomial) to a * polynomial constraint p(x) - q(x) * h(x) = 0, or convert the inequality * constraint f(x) >= h(x) as p(x) - q(x) * h(x) >= 0 if we know q(x) > 0. * * This class represents a special subset of the symbolic::Expression. While a * symbolic::Expression can represent a rational function, extracting the * numerator and denominator, generally, is quite difficult; for instance, from * p1(x) / q1(x) + p2(x) / q2(x) + ... + pn(x) / qn(x). This class's explicit * structure facilitates this decomposition. */ class RationalFunction { public: /** Constructs a zero rational function 0 / 1. */ RationalFunction(); DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(RationalFunction) /** * Constructs the rational function: numerator / denominator. * @param numerator The numerator of the fraction. * @param denominator The denominator of the fraction. * @pre denominator is not equal to zero. * @pre None of the indeterminates in the numerator can be decision variables * in the denominator; similarly none of the indeterminates in the denominator * can be decision variables in the numerator. */ RationalFunction(Polynomial numerator, Polynomial denominator); /** * Constructs the rational function: p / 1. Note that we use 1 as the * denominator. * @param p The numerator of the rational function. */ explicit RationalFunction(const Polynomial& p); /** * Constructs the rational function: m / 1 for any type which can * be cast to a monomial * @param m The numerator of the rational function. */ explicit RationalFunction(const Monomial& m); /** * Constructs the rational function: c / 1. Note that we use 1 as the * denominator. * @param c The numerator of the rational function. */ explicit RationalFunction(double c); /** * Evaluates this rational function under a given environment @p env. * @throws std::exception if there is a variable in this rational function * whose assignment is not provided by @p env. */ [[nodiscard]] double Evaluate(const Environment& env) const; ~RationalFunction() = default; /// Getter for the numerator. [[nodiscard]] const Polynomial& numerator() const { return numerator_; } /// Getter for the denominator. [[nodiscard]] const Polynomial& denominator() const { return denominator_; } RationalFunction& operator+=(const RationalFunction& f); RationalFunction& operator+=(const Polynomial& p); RationalFunction& operator+=(const Monomial& m); RationalFunction& operator+=(double c); RationalFunction& operator-=(const RationalFunction& f); RationalFunction& operator-=(const Polynomial& p); RationalFunction& operator-=(const Monomial& m); RationalFunction& operator-=(double c); RationalFunction& operator*=(const RationalFunction& f); RationalFunction& operator*=(const Polynomial& p); RationalFunction& operator*=(const Monomial& m); RationalFunction& operator*=(double c); /** * @throws std::exception if the numerator of the divisor is structurally * equal to zero. Note that this does not guarantee that the denominator of * the result is not zero after expansion. */ RationalFunction& operator/=(const RationalFunction& f); /** * @throws std::exception if the divisor is structurally equal to zero. * Note that this does not guarantee that the denominator of the result is not * zero after expansion. */ RationalFunction& operator/=(const Polynomial& p); RationalFunction& operator/=(const Monomial& m); /** * @throws std::exception if c is 0 */ RationalFunction& operator/=(double c); /** * Unary minus operation for rational function. * if f(x) = p(x) / q(x), then -f(x) = (-p(x)) / q(x) */ friend RationalFunction operator-(RationalFunction f); /** * Returns true if this rational function and f are structurally equal. */ [[nodiscard]] bool EqualTo(const RationalFunction& f) const; /** * Returns a symbolic formula representing the condition where this rational * function and @p f are the same. * If f1 = p1 / q1, f2 = p2 / q2, then f1 == f2 <=> p1 * q2 == p2 * q1 */ Formula operator==(const RationalFunction& f) const; /** * Returns a symbolic formula representing the condition where this rational * function and @p f are not the same. */ Formula operator!=(const RationalFunction& f) const; friend std::ostream& operator<<(std::ostream&, const RationalFunction& f); /// Returns an equivalent symbolic expression of this rational function. [[nodiscard]] Expression ToExpression() const; /// Sets the indeterminates of the numerator and denominator polynomials void SetIndeterminates(const Variables& new_indeterminates); private: // Throws std::exception if an indeterminate of the denominator (numerator, // respectively) is a decision variable of the numerator (denominator). void CheckIndeterminates() const; Polynomial numerator_; Polynomial denominator_; }; RationalFunction operator+(RationalFunction f1, const RationalFunction& f2); RationalFunction operator+(RationalFunction f, const Polynomial& p); RationalFunction operator+(const Polynomial& p, RationalFunction f); RationalFunction operator+(const Monomial& m, RationalFunction f); RationalFunction operator+(RationalFunction f, const Monomial& m); RationalFunction operator+(RationalFunction f, double c); RationalFunction operator+(double c, RationalFunction f); RationalFunction operator-(RationalFunction f1, const RationalFunction& f2); RationalFunction operator-(RationalFunction f, const Polynomial& p); RationalFunction operator-(const Polynomial& p, const RationalFunction& f); RationalFunction operator-(RationalFunction f, double c); RationalFunction operator-(double c, RationalFunction f); RationalFunction operator-(const Monomial& m, RationalFunction f); RationalFunction operator-(RationalFunction f, const Monomial& m); RationalFunction operator*(RationalFunction f1, const RationalFunction& f2); RationalFunction operator*(RationalFunction f, const Polynomial& p); RationalFunction operator*(const Polynomial& p, RationalFunction f); RationalFunction operator*(RationalFunction f, double c); RationalFunction operator*(double c, RationalFunction f); RationalFunction operator*(const Monomial& m, RationalFunction f); RationalFunction operator*(RationalFunction f, const Monomial& m); /** * @throws std::exception if the numerator of the divisor is structurally * equal to zero. Note that this does not guarantee that the denominator of the * result is not zero after expansion. */ RationalFunction operator/(RationalFunction f1, const RationalFunction& f2); /** * @throws std::exception if the divisor is structurally equal to zero. * Note that this does not guarantee that the denominator of the result is not * zero after expansion. */ RationalFunction operator/(RationalFunction f, const Polynomial& p); /** * @throws std::exception if the numerator of the divisor is structurally * equal to zero. Note that this does not guarantee that the denominator of the * result is not zero after expansion. */ RationalFunction operator/(const Polynomial& p, const RationalFunction& f); /** * @throws std::exception if c is 0 */ RationalFunction operator/(RationalFunction f, double c); /** * @throws std::exception if the numerator of the divisor is structurally * equal to zero. Note that this does not guarantee that the denominator of the * result is not zero after expansion. */ RationalFunction operator/(double c, const RationalFunction& f); RationalFunction operator/(const Monomial& m, RationalFunction f); RationalFunction operator/(RationalFunction f, const Monomial& m); /** * Returns the rational function @p f raised to @p n. * If n is positive, (f/g)ⁿ = fⁿ / gⁿ; * If n is negative, (f/g)ⁿ = g⁻ⁿ / f⁻ⁿ; * (f/g)⁰ = 1 / 1. */ RationalFunction pow(const RationalFunction& f, int n); /** * Provides the following operations: * * - Matrix<RF> * Matrix<Polynomial> => Matrix<RF> * - Matrix<RF> * Matrix<double> => Matrix<RF> * - Matrix<Polynomial> * Matrix<RF> => Matrix<RF> * - Matrix<double> * Matrix<RF> => Matrix<RF> * * where RF is a shorthand for RationalFunction. * * @note that these operator overloadings are necessary even after providing * Eigen::ScalarBinaryOpTraits. See * https://stackoverflow.com/questions/41494288/mixing-scalar-types-in-eigen * for more information */ #if defined(DRAKE_DOXYGEN_CXX) template <typename MatrixL, typename MatrixR> Eigen::Matrix<RationalFunction, MatrixL::RowsAtCompileTime, MatrixR::ColsAtCompileTime> operator*(const MatrixL& lhs, const MatrixR& rhs); #else template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && ((std::is_same_v<typename MatrixL::Scalar, RationalFunction> && (std::is_same_v<typename MatrixR::Scalar, Polynomial> || std::is_same_v<typename MatrixR::Scalar, double>)) || (std::is_same_v<typename MatrixR::Scalar, RationalFunction> && (std::is_same_v<typename MatrixL::Scalar, Polynomial> || std::is_same_v<typename MatrixL::Scalar, double>))), Eigen::Matrix<RationalFunction, MatrixL::RowsAtCompileTime, MatrixR::ColsAtCompileTime>> operator*(const MatrixL& lhs, const MatrixR& rhs) { return lhs.template cast<RationalFunction>() * rhs.template cast<RationalFunction>(); } #endif } // namespace symbolic } // namespace drake #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { // Defines Eigen traits needed for Matrix<drake::symbolic::RationalFunction>. template <> struct NumTraits<drake::symbolic::RationalFunction> : GenericNumTraits<drake::symbolic::RationalFunction> { static inline int digits10() { return 0; } }; // Informs Eigen that BinaryOp(LhsType, RhsType) gets ResultType. #define DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS(LhsType, RhsType, BinaryOp, \ ResultType) \ template <> \ struct ScalarBinaryOpTraits<LhsType, RhsType, BinaryOp<LhsType, RhsType>> { \ enum { Defined = 1 }; \ typedef ResultType ReturnType; \ }; // Informs Eigen that LhsType op RhsType gets ResultType // where op ∈ {+, -, *, /, conj_product}. #define DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( \ LhsType, RhsType, ResultType) \ DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS(LhsType, RhsType, \ internal::scalar_sum_op, ResultType) \ DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS( \ LhsType, RhsType, internal::scalar_difference_op, ResultType) \ DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS( \ LhsType, RhsType, internal::scalar_product_op, ResultType) \ DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS( \ LhsType, RhsType, internal::scalar_conj_product_op, ResultType) // Informs Eigen that RationalFunction op Polynomial gets RationalFunction // where op ∈ {+, -, *, conj_product}. DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::RationalFunction, drake::symbolic::Polynomial, drake::symbolic::RationalFunction) // Informs Eigen that Polynomial op RationalFunction gets RationalFunction // where op ∈ {+, -, *, conj_product}. DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Polynomial, drake::symbolic::RationalFunction, drake::symbolic::RationalFunction) // Informs Eigen that double op RationalFunction gets RationalFunction // where op ∈ {+, -, *, conj_product}. DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( double, drake::symbolic::RationalFunction, drake::symbolic::RationalFunction) // Informs Eigen that RationalFunction op double gets RationalFunction // where op ∈ {+, -, *, conj_product}. DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::RationalFunction, double, drake::symbolic::RationalFunction) #undef DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS #undef DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS namespace numext { template <> bool equal_strict(const drake::symbolic::RationalFunction& x, const drake::symbolic::RationalFunction& y); template <> EIGEN_STRONG_INLINE bool not_equal_strict( const drake::symbolic::RationalFunction& x, const drake::symbolic::RationalFunction& y) { return !Eigen::numext::equal_strict(x, y); } } // namespace numext } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX) // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::symbolic::RationalFunction> : drake::ostream_formatter { }; } // namespace fmt
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/polynomial.cc
#include "drake/common/symbolic/polynomial.h" #include <algorithm> #include <map> #include <numeric> #include <sstream> #include <stdexcept> #include <unordered_map> #include <utility> #include <fmt/format.h> #define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/expression/expression_cell.h" #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/decompose.h" #include "drake/common/text_logging.h" using std::accumulate; using std::make_pair; using std::map; using std::ostream; using std::ostringstream; using std::pair; using std::runtime_error; using std::to_string; namespace drake { namespace symbolic { namespace { // Note that `.Expand()` is needed in the following kinds of cases: // e1 := (a + b)² // e2 := - (a² + 2ab + b²) // Without expanding the terms, they would not report as EqualTo. bool AreEqualAfterExpanding(const Expression& e1, const Expression& e2) { const Expression& e1_expanded = e1.is_expanded() ? e1 : e1.Expand(); const Expression& e2_expanded = e2.is_expanded() ? e2 : e2.Expand(); return e1_expanded.EqualTo(e2_expanded); } // Helper function to add coeff * m to a map (Monomial → Expression). // Used to implement DecomposePolynomialVisitor::VisitAddition and // Polynomial::Add. void DoAddProduct(const Expression& coeff, const Monomial& m, Polynomial::MapType* const map) { if (is_zero(coeff)) { return; } auto it = map->find(m); if (it != map->end()) { // m ∈ dom(map) Expression& existing_coeff = it->second; if (AreEqualAfterExpanding(-coeff, existing_coeff)) { map->erase(it); } else { existing_coeff += coeff; } } else { // m ∉ dom(map) map->emplace_hint(it, m, coeff); } } // Visitor class to implement `Polynomial(const Expression& e, const // Variables& indeterminates)` constructor which decomposes an expression e // w.r.t. indeterminates. class DecomposePolynomialVisitor { public: Polynomial::MapType Decompose(const Expression& e, const Variables& indeterminates) const { // Note that it calls `Expression::Expand()` here. return Visit(e.Expand(), indeterminates); } private: Polynomial::MapType Visit(const Expression& e, const Variables& indeterminates) const { return VisitExpression<Polynomial::MapType>(this, e, indeterminates); } Polynomial::MapType VisitVariable(const Expression& e, const Variables& indeterminates) const { const Variable& var{get_variable(e)}; if (indeterminates.include(var)) { // Monomial : var, coefficient : 1 return Polynomial::MapType{{{Monomial{var}, 1}}}; } else { // Monomial : 1, coefficient : var return Polynomial::MapType{{{Monomial{}, var}}}; } } Polynomial::MapType VisitConstant(const Expression& e, const Variables&) const { const double v{get_constant_value(e)}; if (v != 0) { return Polynomial::MapType{{{Monomial(), v}}}; // = v. } return Polynomial::MapType{}; // = 0. } Polynomial::MapType VisitAddition(const Expression& e, const Variables& indeterminates) const { // e = c₀ + ∑ᵢ (cᵢ * eᵢ) Polynomial::MapType new_map; const double c_0{get_constant_in_addition(e)}; if (c_0 != 0) { new_map.emplace(Monomial{}, c_0); } for (const pair<const Expression, double>& p : get_expr_to_coeff_map_in_addition(e)) { const Expression& e_i{p.first}; const double c_i{p.second}; // e = c₀ + ∑ᵢ (cᵢ * eᵢ) = c₀ + ∑ᵢ (cᵢ * (∑ⱼ mⱼ * cⱼ)) // ~~~~~~~~~~~ // Monomial of eᵢ // = c₀ + ∑ᵢ ∑ⱼ ((cᵢ * cⱼ) * mⱼ) // Note that we have cᵢ ≠ 0 ∧ cⱼ ≠ 0 → (cᵢ * cⱼ) ≠ 0. const Polynomial::MapType map_i = Visit(e_i, indeterminates); for (const pair<const Monomial, Expression>& term : map_i) { const Monomial& m_j{term.first}; const Expression& c_j{term.second}; // Add (cᵢ * cⱼ) * mⱼ. DoAddProduct(c_i * c_j, m_j, &new_map); } } return new_map; } Polynomial::MapType VisitMultiplication( const Expression& e, const Variables& indeterminates) const { // e = c * ∏ᵢ pow(baseᵢ, exponentᵢ). const double c = get_constant_in_multiplication(e); DRAKE_DEMAND(c != 0); Expression coeff{c}; Monomial m{}; for (const pair<const Expression, Expression>& p : get_base_to_exponent_map_in_multiplication(e)) { const Expression& base_i{p.first}; const Expression& exponent_i{p.second}; const pair<Monomial, Expression> result_i{ VisitPow(base_i, exponent_i, indeterminates)}; const Monomial& m_i{result_i.first}; const Expression& coeff_i{result_i.second}; m *= m_i; coeff *= coeff_i; } DRAKE_DEMAND(!symbolic::is_zero(coeff)); return Polynomial::MapType{{m, coeff}}; } pair<Monomial, Expression> VisitPow(const Expression& base, const Expression& exponent, const Variables& indeterminates) const { if (intersect(base.GetVariables(), indeterminates).empty()) { // Case: vars(baseᵢ) ∩ indeterminates = ∅. if (!intersect(exponent.GetVariables(), indeterminates).empty()) { // An indeterminate should not be in an exponent for the whole // expression to be a polynomial. For example, aˣ is not a // polynomial. That is, vars(exponentᵢ) ∩ indeterminates = ∅ should // hold. ostringstream oss; oss << "Exponent " << exponent << " includes an indeterminates " << indeterminates << "."; throw runtime_error(oss.str()); } return make_pair(Monomial{}, pow(base, exponent)); } else { // Case: vars(baseᵢ) ∩ indeterminates ≠ ∅. // exponentᵢ should be a positive integer. if (!is_constant(exponent) || !is_positive_integer(get_constant_value(exponent))) { ostringstream oss; oss << "Given the base " << base << ", the Exponent " << exponent << " should be a positive integer but it is not the case."; throw runtime_error(oss.str()); } const int n{static_cast<int>(get_constant_value(exponent))}; Expression coeff{1.0}; Monomial m{}; // `base` should be a product of indeterminates because `e` is a // pre-expanded term. if (!is_variable(base) && !is_multiplication(base)) { ostringstream oss; oss << "Base " << base << " is not a product of indeterminates, " << indeterminates; throw runtime_error(oss.str()); } for (const Variable& var : base.GetVariables()) { if (indeterminates.include(var)) { m *= Monomial{var, n}; } else { coeff *= pow(Expression{var}, exponent); } } return make_pair(m, coeff); } } Polynomial::MapType VisitPow(const Expression& e, const Variables& indeterminates) const { const Expression& base{get_first_argument(e)}; const Expression& exponent{get_second_argument(e)}; const pair<Monomial, Expression> result{ VisitPow(base, exponent, indeterminates)}; return Polynomial::MapType{{{result.first, result.second}}}; } Polynomial::MapType VisitDivision(const Expression& e, const Variables& indeterminates) const { // e = e₁ / e₂ const Expression& e1{get_first_argument(e)}; const Expression& e2{get_second_argument(e)}; // We require that the denominator e₂ is free of indeterminates for e to be // a polynomial. This is because canceling a common factor is not a sound // simplification. For example, `(x² + x) / x` is not equivalent to `x + 1` // since the former is not defined at x = 0 while the latter is a total // function over R. // vars(e₂) ∩ indeterminates = ∅. if (!intersect(e2.GetVariables(), indeterminates).empty()) { ostringstream oss; oss << "In " << e1 << " / " << e2 << ", the denominator " << e2 << " should be free of the indeterminates, " << indeterminates << "."; throw runtime_error(oss.str()); } // Since e₁ is already expanded, we have: // // e = e₁ / e₂ // = (∑ᵢ cᵢ * monomialᵢ) / e₂ // = (∑ᵢ (cᵢ/e₂) * monomialᵢ // // where monomialᵢ is a monomial of indeterminates and cᵢ/e₂ is an // expression free of indeterminates (which possibly includes decision // variables). Polynomial::MapType map{Visit(e1, indeterminates)}; for (auto& item : map) { item.second /= e2; } return map; } // For a non-polynomial term, e, we return a map {1 ↦ e}. We require e to be // free of indeterminates. For example, `VisitNonPolynomialTerm(sin(a + b), // {x})` returns `{1 ↦ sin(a + b)}`. However, `VisitNonPolynomialTerm(sin(a + // x), {x})` throws an exception because `sin(a + x)` includes an // indeterminate `x`. Polynomial::MapType VisitNonPolynomialTerm( const Expression& e, const Variables& indeterminates) const { // vars(e) ∩ indeterminates = ∅. if (!intersect(e.GetVariables(), indeterminates).empty()) { ostringstream oss; oss << "The non-polynomial term " << e << " should be free of the indeterminates " << indeterminates << "."; throw runtime_error(oss.str()); } return {{Monomial{}, e}}; // = {1 ↦ e}. } Polynomial::MapType VisitAbs(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitLog(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitExp(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitSqrt(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitSin(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitCos(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitTan(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitAsin(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitAcos(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitAtan(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitAtan2(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitSinh(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitCosh(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitTanh(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitMin(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitMax(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitCeil(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitFloor(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitIfThenElse(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } Polynomial::MapType VisitUninterpretedFunction( const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } // Makes VisitExpression a friend of this class so that it can use private // methods. friend Polynomial::MapType drake::symbolic::VisitExpression<Polynomial::MapType>( const DecomposePolynomialVisitor*, const Expression&, const Variables&); }; Variables GetIndeterminates(const Polynomial::MapType& m) { Variables vars; for (const pair<const Monomial, Expression>& p : m) { const Monomial& m_i{p.first}; vars.insert(m_i.GetVariables()); } return vars; } Variables GetDecisionVariables(const Polynomial::MapType& m) { Variables vars; for (const pair<const Monomial, Expression>& p : m) { const Expression& e_i{p.second}; vars.insert(e_i.GetVariables()); } return vars; } } // namespace Polynomial::Polynomial(MapType map) : monomial_to_coefficient_map_{std::move(map)}, indeterminates_{GetIndeterminates(monomial_to_coefficient_map_)}, decision_variables_{GetDecisionVariables(monomial_to_coefficient_map_)} { // Remove all [monomial, coeff] pair in monomial_to_coefficient_map_ if // symbolic::is_zero(coeff) is true; for (auto it = monomial_to_coefficient_map_.begin(); it != monomial_to_coefficient_map_.end();) { if (symbolic::is_zero(it->second)) { it = monomial_to_coefficient_map_.erase(it); } else { ++it; } } DRAKE_ASSERT_VOID(CheckInvariant()); }; Polynomial::Polynomial(const Monomial& m) : monomial_to_coefficient_map_{{m, 1}}, indeterminates_{m.GetVariables()}, decision_variables_{} { // No need to call CheckInvariant() because the following should hold. DRAKE_ASSERT(decision_variables().empty()); } Polynomial::Polynomial(const Variable& v) : Polynomial{v, {v}} { // No need to call CheckInvariant() because the following should hold. DRAKE_ASSERT(decision_variables().empty()); } Polynomial::Polynomial(const Expression& e) : Polynomial{e, e.GetVariables()} { // No need to call CheckInvariant() because the following should hold. DRAKE_ASSERT(decision_variables().empty()); } Polynomial::Polynomial(const Expression& e, Variables indeterminates) : monomial_to_coefficient_map_{DecomposePolynomialVisitor{}.Decompose( e, indeterminates)}, indeterminates_{std::move(indeterminates)}, decision_variables_{GetDecisionVariables(monomial_to_coefficient_map_)} { DRAKE_ASSERT_VOID(CheckInvariant()); } const Variables& Polynomial::indeterminates() const { return indeterminates_; } void Polynomial::SetIndeterminates(const Variables& new_indeterminates) { if (new_indeterminates.IsSupersetOf(indeterminates_) && intersect(decision_variables_, new_indeterminates).empty()) { indeterminates_ = new_indeterminates; } else { // TODO(soonho-tri): Optimize this part. *this = Polynomial{ToExpression(), new_indeterminates}; } } const Variables& Polynomial::decision_variables() const { return decision_variables_; } int Polynomial::Degree(const Variable& v) const { int degree{0}; for (const pair<const Monomial, Expression>& p : monomial_to_coefficient_map_) { const Monomial& m{p.first}; degree = std::max(degree, m.degree(v)); } return degree; } int Polynomial::TotalDegree() const { int degree{0}; for (const pair<const Monomial, Expression>& p : monomial_to_coefficient_map_) { const Monomial& m{p.first}; degree = std::max(degree, m.total_degree()); } return degree; } const Polynomial::MapType& Polynomial::monomial_to_coefficient_map() const { return monomial_to_coefficient_map_; } Expression Polynomial::ToExpression() const { // Returns ∑ᵢ (cᵢ * mᵢ). return accumulate( monomial_to_coefficient_map_.begin(), monomial_to_coefficient_map_.end(), Expression{0.0}, [](const Expression& init, const pair<const Monomial, Expression>& p) { const Monomial& m{p.first}; const Expression& coeff{p.second}; return init + (coeff * m.ToExpression()); }); } namespace { // Differentiates a monomial `m` with respect to a variable `x`. This is a // helper function to implement Polynomial::Differentiate() method. It returns a // pair `(n, m₁ * xⁿ⁻¹ * m₂)` where `d/dx (m₁ * xⁿ * m₂) = n * m₁ * xⁿ⁻¹ * m₂` // holds. For example, d/dx x²y = 2xy and `DifferentiateMonomial(x²y, x)` // returns `(2, xy)`. pair<int, Monomial> DifferentiateMonomial(const Monomial& m, const Variable& x) { if (!m.get_powers().contains(x)) { // x does not appear in m. Returns (0, 1). return make_pair(0, Monomial{}); } map<Variable, int> powers{m.get_powers()}; auto it = powers.find(x); DRAKE_ASSERT(it != powers.end() && it->second >= 1); const int n{it->second--}; if (it->second == 0) { powers.erase(it); } return make_pair(n, Monomial{powers}); } } // namespace Polynomial Polynomial::Differentiate(const Variable& x) const { if (indeterminates().include(x)) { // Case: x is an indeterminate. // d/dx ∑ᵢ (cᵢ * mᵢ) = ∑ᵢ d/dx (cᵢ * mᵢ) // = ∑ᵢ (cᵢ * d/dx mᵢ) Polynomial::MapType map; for (const pair<const Monomial, Expression>& term : monomial_to_coefficient_map_) { const Monomial& m{term.first}; const Expression& coeff{term.second}; const pair<int, Monomial> m_prime{ DifferentiateMonomial(m, x)}; // = d/dx m. DoAddProduct(coeff * m_prime.first, m_prime.second, &map); // Add cᵢ * d/dx m. } return Polynomial{map}; } else if (decision_variables().include(x)) { // Case: x is a decision variable. // d/dx ∑ᵢ (cᵢ * mᵢ) = ∑ᵢ d/dx (cᵢ * mᵢ) // = ∑ᵢ ((d/dx cᵢ) * mᵢ) Polynomial::MapType map; for (const pair<const Monomial, Expression>& term : monomial_to_coefficient_map_) { const Monomial& m{term.first}; const Expression& coeff{term.second}; DoAddProduct(coeff.Differentiate(x), m, &map); // Add (d/dx cᵢ) * m. } return Polynomial{map}; } else { // The variable `x` does not appear in this polynomial. return Polynomial{}; // Zero polynomial. } } Polynomial Polynomial::Integrate(const Variable& x) const { if (decision_variables().include(x)) { ostringstream oss; oss << x << " is a decision variable of polynomial " << *this << ". Integration with respect to decision variables is not " << "supported yet."; throw runtime_error(oss.str()); } // Case: x is an indeterminate (or does not appear). // ∫ ∑ᵢ (cᵢ * mᵢ) dx = ∑ᵢ (cᵢ * ∫ mᵢ dx) Polynomial::MapType map; for (const pair<const Monomial, Expression>& term : monomial_to_coefficient_map_) { const Monomial& m{term.first}; const Expression& coeff{term.second}; int n = 0; auto new_powers = m.get_powers(); auto it = new_powers.find(x); if (it != new_powers.end()) { n = it->second++; } else { new_powers.emplace_hint(it, x, 1); } DoAddProduct((coeff / (n + 1)).Expand(), Monomial(new_powers), &map); } return Polynomial{map}; } Polynomial Polynomial::Integrate(const Variable& x, double a, double b) const { // Note: This is still correct if a > b. const auto p = this->Integrate(x); return p.EvaluatePartial(x, b) - p.EvaluatePartial(x, a); } double Polynomial::Evaluate(const Environment& env) const { return accumulate( monomial_to_coefficient_map_.begin(), monomial_to_coefficient_map_.end(), 0.0, [&env](const double v, const pair<const Monomial, Expression>& item) { const Monomial& monomial{item.first}; const Expression& coeff{item.second}; return v + monomial.Evaluate(env) * coeff.Evaluate(env); }); } Polynomial Polynomial::EvaluatePartial(const Environment& env) const { MapType new_map; // Will use this to construct the return value. for (const auto& product_i : monomial_to_coefficient_map_) { const Expression& coeff_i{product_i.second}; const Expression coeff_i_partial_evaluated{coeff_i.EvaluatePartial(env)}; const Monomial& monomial_i{product_i.first}; const pair<double, Monomial> partial_eval_result{ monomial_i.EvaluatePartial(env)}; const double coeff_from_subst{partial_eval_result.first}; const Monomial& monomial_from_subst{partial_eval_result.second}; const Expression new_coeff_i{coeff_i_partial_evaluated * coeff_from_subst}; auto it = new_map.find(monomial_from_subst); if (it == new_map.end()) { new_map.emplace_hint(it, monomial_from_subst, new_coeff_i); } else { it->second += new_coeff_i; } } return Polynomial{new_map}; } Polynomial Polynomial::EvaluatePartial(const Variable& var, const double c) const { return EvaluatePartial({{{var, c}}}); } Eigen::VectorXd Polynomial::EvaluateIndeterminates( const Eigen::Ref<const VectorX<symbolic::Variable>>& indeterminates, const Eigen::Ref<const Eigen::MatrixXd>& indeterminates_values) const { Eigen::VectorXd polynomial_values = Eigen::VectorXd::Zero(indeterminates_values.cols()); for (const auto& [monomial, coeff] : monomial_to_coefficient_map_) { const symbolic::Expression& coeff_expanded = coeff.is_expanded() ? coeff : coeff.Expand(); if (!is_constant(coeff_expanded)) { throw std::runtime_error( fmt::format("Polynomial::EvaluateIndeterminates: the coefficient {} " "is not a constant", coeff_expanded.to_string())); } const double coeff_val = get_constant_value(coeff_expanded); polynomial_values += coeff_val * monomial.Evaluate(indeterminates, indeterminates_values); } return polynomial_values; } void Polynomial::EvaluateWithAffineCoefficients( const Eigen::Ref<const VectorX<symbolic::Variable>>& indeterminates, const Eigen::Ref<const Eigen::MatrixXd>& indeterminates_values, Eigen::MatrixXd* A, VectorX<symbolic::Variable>* decision_variables, Eigen::VectorXd* b) const { // First put all the decision variables into an Eigen vector. decision_variables->resize(decision_variables_.size()); std::unordered_map<symbolic::Variable::Id, int> map_var_to_index; int variable_count = 0; for (const auto& var : decision_variables_) { (*decision_variables)(variable_count) = var; map_var_to_index.emplace(var.get_id(), variable_count); variable_count++; } const int num_indeterminate_samples = indeterminates_values.cols(); A->resize(num_indeterminate_samples, variable_count); A->setZero(); b->resize(num_indeterminate_samples); b->setZero(); // Each term in the polynomial is m(x) * c, where m(x) is the // monomial and c is the coefficient of the monomial. Since each coefficient // c can be written as c = a_coeff * decision_variables + b_coeff, this // term can be written as m(x)*a_coeff * decision_variables + m(x)*b_coeff. Eigen::RowVectorXd a_coeff(decision_variables->rows()); double b_coeff; for (const auto& [monomial, monomial_coeff] : monomial_to_coefficient_map_) { a_coeff.setZero(); b_coeff = 0; const symbolic::Expression monomial_coeff_expand = monomial_coeff.Expand(); DecomposeAffineExpression(monomial_coeff_expand, map_var_to_index, &a_coeff, &b_coeff); const Eigen::VectorXd monomial_vals = monomial.Evaluate(indeterminates, indeterminates_values); *A += monomial_vals * a_coeff; *b += monomial_vals * b_coeff; } } Polynomial& Polynomial::operator+=(const Polynomial& p) { for (const pair<const Monomial, Expression>& item : p.monomial_to_coefficient_map_) { const Monomial& m{item.first}; const Expression& coeff{item.second}; DoAddProduct(coeff, m, &monomial_to_coefficient_map_); } indeterminates_ += p.indeterminates(); decision_variables_ += p.decision_variables(); DRAKE_ASSERT_VOID(CheckInvariant()); return *this; } Polynomial& Polynomial::operator+=(const Monomial& m) { // No need to call CheckInvariant() since it's called inside of Add. return AddProduct(1.0, m); } Polynomial& Polynomial::operator+=(const double c) { // No need to call CheckInvariant() since it's called inside of Add. return AddProduct(c, Monomial{}); } Polynomial& Polynomial::operator+=(const Variable& v) { if (indeterminates().include(v)) { return AddProduct(1.0, Monomial{v}); } else { return AddProduct(v, Monomial{}); } } Polynomial& Polynomial::operator-=(const Polynomial& p) { // No need to call CheckInvariant() since it's called inside of operator+=. return *this += -p; } Polynomial& Polynomial::operator-=(const Monomial& m) { // No need to call CheckInvariant() since it's called inside of Add. return AddProduct(-1.0, m); } Polynomial& Polynomial::operator-=(const double c) { // No need to call CheckInvariant() since it's called inside of Add. return AddProduct(-c, Monomial{}); } Polynomial& Polynomial::operator-=(const Variable& v) { if (indeterminates().include(v)) { return AddProduct(-1.0, Monomial{v}); } else { return AddProduct(-v, Monomial{}); } } Polynomial& Polynomial::operator*=(const Polynomial& p) { // (c₁₁ * m₁₁ + ... + c₁ₙ * m₁ₙ) * (c₂₁ * m₂₁ + ... + c₂ₘ * m₂ₘ) // = (c₁₁ * m₁₁ + ... + c₁ₙ * m₁ₙ) * c₂₁ * m₂₁ + ... + // (c₁₁ * m₁₁ + ... + c₁ₙ * m₁ₙ) * c₂ₘ * m₂ₘ MapType new_map{}; for (const auto& p1 : monomial_to_coefficient_map_) { for (const auto& p2 : p.monomial_to_coefficient_map()) { const Monomial new_monomial{p1.first * p2.first}; const Expression new_coeff{p1.second * p2.second}; DoAddProduct(new_coeff, new_monomial, &new_map); } } monomial_to_coefficient_map_ = std::move(new_map); indeterminates_ += p.indeterminates(); decision_variables_ += p.decision_variables(); DRAKE_ASSERT_VOID(CheckInvariant()); return *this; } Polynomial& Polynomial::operator*=(const Monomial& m) { MapType new_map; for (const pair<const Monomial, Expression>& p : monomial_to_coefficient_map_) { const Monomial& m_i{p.first}; const Expression& coeff_i{p.second}; new_map.emplace(m * m_i, coeff_i); } monomial_to_coefficient_map_ = std::move(new_map); indeterminates_ += m.GetVariables(); DRAKE_ASSERT_VOID(CheckInvariant()); return *this; } Polynomial& Polynomial::operator*=(const double c) { if (c == 0) { this->monomial_to_coefficient_map_.clear(); return *this; } for (pair<const Monomial, Expression>& p : monomial_to_coefficient_map_) { Expression& coeff = p.second; coeff *= c; } // No need to call CheckInvariant() since `c` doesn't include a variable // and c != 0. return *this; } Polynomial& Polynomial::operator*=(const Variable& v) { if (indeterminates().include(v)) { return *this *= Monomial{v}; } else { for (auto& p : monomial_to_coefficient_map_) { Expression& coeff = p.second; coeff *= v; } decision_variables_.insert(v); return *this; } } bool Polynomial::EqualTo(const Polynomial& p) const { // We do not use unordered_map<Monomial, Expression>::operator== as it uses // Expression::operator== (which returns a symbolic formula) instead of // Expression::EqualTo(which returns a bool), when the coefficient is a // symbolic expression. const Polynomial::MapType& map1{monomial_to_coefficient_map_}; const Polynomial::MapType& map2{p.monomial_to_coefficient_map()}; if (map1.size() != map2.size()) { return false; } for (const auto& pair1 : map1) { const Monomial& m{pair1.first}; const Expression& e1{pair1.second}; const auto it = map2.find(m); if (it == map2.end()) { // m is not in map2, so map1 and map2 are not the same. return false; } const Expression& e2{it->second}; if (!e1.EqualTo(e2)) { return false; } } return true; } bool Polynomial::CoefficientsAlmostEqual(const Polynomial& p, double tolerance) const { return (*this - p) .Expand() .RemoveTermsWithSmallCoefficients(tolerance) .EqualTo(Polynomial()); } Formula Polynomial::operator==(const Polynomial& p) const { // 1) Let diff = p - (this polynomial). // 2) Extract the condition where diff is zero. // That is, all coefficients should be zero. const Polynomial diff{p - *this}; Formula ret{Formula::True()}; for (const pair<const Monomial, Expression>& item : diff.monomial_to_coefficient_map_) { const Expression& coeff{item.second}; ret = ret && (coeff == 0.0); } return ret; } Formula Polynomial::operator!=(const Polynomial& p) const { return !(*this == p); } Polynomial& Polynomial::AddProduct(const Expression& coeff, const Monomial& m) { DoAddProduct(coeff, m, &monomial_to_coefficient_map_); indeterminates_ += m.GetVariables(); decision_variables_ += coeff.GetVariables(); DRAKE_ASSERT_VOID(CheckInvariant()); return *this; } Polynomial Polynomial::SubstituteAndExpand( const std::unordered_map<Variable, Polynomial>& indeterminate_substitution, SubstituteAndExpandCacheData* substitutions_cached_data) const { SubstituteAndExpandCacheData substitutions_default_obj; SubstituteAndExpandCacheData* cached_data_ptr = substitutions_cached_data == nullptr ? &substitutions_default_obj : substitutions_cached_data; std::map<Monomial, Polynomial, internal::CompareMonomial>* substitutions = cached_data_ptr->get_data(); for (const auto& var : indeterminates_) { DRAKE_DEMAND(indeterminate_substitution.find(var) != indeterminate_substitution.cend()); const Polynomial cur_sub{indeterminate_substitution.at(var).Expand()}; const Monomial cur_monomial{var}; if (substitutions->find(cur_monomial) != substitutions->cend()) { if (!substitutions->at(cur_monomial).EqualTo(cur_sub)) { drake::log()->warn( "SubstituteAndExpand(): the passed substitutions_cached_data " "contains a different expansion for {} than is contained in " "indeterminate_substitutions. Substitutions_cached_data contains " "{}, but indeterminate_substitutions contains {}. It is very " "likely that substitutions_cached_data is storing expansions which " "are inconsistent and so you should not trust the output of this " "method.", cur_monomial, substitutions->at(cur_monomial), cur_sub); } } else { substitutions->emplace(cur_monomial, cur_sub); } } MapType new_polynomial_coeff_map; // Ensures the base case of the constant term monomial is always reached. substitutions->insert_or_assign(Monomial(), Polynomial(1)); // Find the largest (in the lexicographic order) monomial for which we // have already computed the expansion. auto find_nearest_cached_monomial = [&substitutions]( const Monomial& monomial) { auto nearest_cached_monomial_iter = std::prev(substitutions->lower_bound(monomial)); while (!((*nearest_cached_monomial_iter).first) .GetVariables() .IsSubsetOf(monomial.GetVariables())) { nearest_cached_monomial_iter = std::prev(nearest_cached_monomial_iter); } return (*nearest_cached_monomial_iter).first; }; // Given a monomial, compute its expansion using the saved expansions in // substitutions and by repeated squaring. If the total degree of monomial is // not 1 (i.e. monomial is not a pure indeterminate), then the expanded // substitution will be added to the substitutions map. auto compute_substituted_monomial_expansion = [&indeterminate_substitution, &substitutions, &find_nearest_cached_monomial]( const Monomial& monomial, auto&& compute_substituted_monomial_expansion_recursion_handle) -> const Polynomial& { // If the monomial total degree is 1, it is an indeterminate and so we can // just find the substitution. if (monomial.total_degree() == 1) { return indeterminate_substitution.at(*monomial.GetVariables().begin()); } // Base case. Since the map substitutions is non-empty and contains the // monomial 1 the recursion is guaranteed to terminate. if (substitutions->find(monomial) != substitutions->cend()) { return substitutions->at(monomial); } // Find the largest (in the lexicographic order) monomial for which we // have already computed the expansion. Monomial nearest_cached_monomial = find_nearest_cached_monomial(monomial); // If the nearest cached monomial is 1, then we do not have a cached // substitution for it. In this case, we will compute the expansion // using the successive squaring method. For example, x³y⁵ would be // computed as (xy²)²(xy). // // If the nearest cached monomial is not 1, we recurse on the remaining // powers. The reason we do not perform successive squaring immediately // is to enable us to potentially find a larger power immediately. For // example, if we are expanding x³y⁵, and substitutions only contains // the keys {1, xy²}, then the nearest cached monomial is xy². // The remaining monomial would be x²y³. Applying the successive // squaring method would require us to compute the expansion of xy. // Recursing immediately would enable us to again use the substitution // of xy². We wish to use the stored substitutions as much as possible, // and so we prefer to recurse immediately. if (nearest_cached_monomial == Monomial()) { Polynomial expanded_substitution{1}; std::map<Variable, int> halved_powers; for (const auto& [var, power] : monomial.get_powers()) { halved_powers.emplace(var, static_cast<int>(std::floor(power / 2))); // If the current power is odd, we perform a substitution of the // degree 1 monomial. if (power % 2 == 1) { expanded_substitution *= indeterminate_substitution.at(var); } } const Monomial halved_monomials{halved_powers}; const Monomial& halved_monomials_squared{pow(halved_monomials, 2)}; const Polynomial& halved_power_substitution{ compute_substituted_monomial_expansion_recursion_handle( halved_monomials, compute_substituted_monomial_expansion_recursion_handle)}; // Store the remaining substitution in case it is useful for later. We do // not need to attempt to store the halved_power_substitutions since they // should already be stored by the recursive call to // compute_substituted_monomial_expansion_recursion_handle. if (substitutions->find(halved_monomials_squared) == substitutions->cend()) { substitutions->emplace(halved_monomials_squared, pow(halved_power_substitution, 2).Expand()); } expanded_substitution *= substitutions->at(halved_monomials_squared); substitutions->emplace(monomial, expanded_substitution.Expand()); } else { std::map<Variable, int> remaining_powers; const std::map<Variable, int>& cached_powers{ nearest_cached_monomial.get_powers()}; for (const auto& [var, power] : monomial.get_powers()) { if (cached_powers.find(var) != cached_powers.cend()) { remaining_powers.emplace(var, power - cached_powers.at(var)); } else { remaining_powers.emplace(var, power); } } const Monomial remaining_monomials{remaining_powers}; const Polynomial& remaining_substitution{ compute_substituted_monomial_expansion_recursion_handle( remaining_monomials, compute_substituted_monomial_expansion_recursion_handle)}; substitutions->emplace( monomial, (substitutions->at(nearest_cached_monomial) * remaining_substitution) .Expand()); } return substitutions->at(monomial); }; for (const auto& [old_monomial, old_coeff] : monomial_to_coefficient_map_) { // If substitutions doesn't contain the current substitution create it // now. if (old_monomial.total_degree() != 1 && substitutions->find(old_monomial) == substitutions->cend()) { compute_substituted_monomial_expansion( old_monomial, compute_substituted_monomial_expansion); } // Now go through and add the substitution to the appropriate monomial // in the new polynomial. const Polynomial& substitution_map = (old_monomial.total_degree() == 1 ? indeterminate_substitution.at( *old_monomial.GetVariables().begin()) : substitutions->at(old_monomial)); for (const auto& [new_monomial, new_coeff] : substitution_map.monomial_to_coefficient_map()) { if (new_polynomial_coeff_map.find(new_monomial) == new_polynomial_coeff_map.cend()) { new_polynomial_coeff_map.insert({new_monomial, Expression()}); } new_polynomial_coeff_map.at(new_monomial) += (new_coeff * old_coeff).Expand(); } } return Polynomial{new_polynomial_coeff_map}; } Polynomial Polynomial::Expand() const { Polynomial::MapType expanded_poly_map; for (const auto& [monomial, coeff] : monomial_to_coefficient_map_) { const symbolic::Expression coeff_expanded = coeff.Expand(); if (!symbolic::is_zero(coeff_expanded)) { expanded_poly_map.emplace(monomial, coeff_expanded); } } return symbolic::Polynomial(std::move(expanded_poly_map)); } Polynomial Polynomial::RemoveTermsWithSmallCoefficients( double coefficient_tol) const { DRAKE_DEMAND(coefficient_tol > 0); MapType cleaned_polynomial{}; for (const auto& term : monomial_to_coefficient_map_) { if (is_constant(term.second) && std::abs(get_constant_value(term.second)) <= coefficient_tol) { // The coefficients are small. continue; } else { cleaned_polynomial.emplace_hint(cleaned_polynomial.end(), term.first, term.second); } } return Polynomial(cleaned_polynomial); } namespace { bool IsEvenOrOdd(const Polynomial& p, bool check_even) { for (const auto& [monomial, coeff] : p.monomial_to_coefficient_map()) { // If we check p is even/odd, then we only need to check monomials with // odd/even-degrees have coefficient = 0 if (monomial.total_degree() % 2 == static_cast<int>(check_even)) { const symbolic::Expression& coeff_expanded = coeff.is_expanded() ? coeff : coeff.Expand(); if (!(is_constant(coeff_expanded) && get_constant_value(coeff_expanded) == 0)) { return false; } } } return true; } } // namespace bool Polynomial::IsEven() const { return IsEvenOrOdd(*this, true /* check_even=true */); } bool Polynomial::IsOdd() const { return IsEvenOrOdd(*this, false /* check_even=false*/); } Eigen::VectorXcd Polynomial::Roots() const { if (indeterminates().size() != 1) { throw runtime_error(fmt::format( "{} is not a univariate polynomial; it has indeterminates {}.", *this, indeterminates())); } // We find the roots by computing the eigenvalues of the companion matrix. // See https://en.wikipedia.org/wiki/Polynomial_root-finding_algorithms and // https://www.mathworks.com/help/matlab/ref/roots.html. const int degree = TotalDegree(); Eigen::MatrixXd C = Eigen::MatrixXd::Zero(degree, degree); for (int i = 0; i < degree - 1; ++i) { C(i + 1, i) = 1; } double leading_coefficient = 0; for (const auto& [monomial, coeff] : monomial_to_coefficient_map()) { if (!is_constant(coeff)) { throw runtime_error(fmt::format( "Polynomial::Roots() only supports polynomials with constant " "coefficients. This polynomial has coefficient {} for the " "monomial {}.", coeff, monomial)); } const int power = monomial.total_degree(); if (power == degree) { leading_coefficient = get_constant_value(coeff); } else { C(0, degree - power - 1) = -get_constant_value(coeff); } } C.row(0) /= leading_coefficient; return C.eigenvalues(); } void Polynomial::CheckInvariant() const { // TODO(hongkai.dai and soonho.kong): improves the computation time of // CheckInvariant(). See github issue // https://github.com/RobotLocomotion/drake/issues/10229 Variables vars{intersect(decision_variables(), indeterminates())}; if (!vars.empty()) { ostringstream oss; oss << "Polynomial " << *this << " does not satisfy the invariant because the following variable(s) " "are used as decision variables and indeterminates at the same " "time:\n" << vars << "."; throw runtime_error(oss.str()); } // Check if any [monomial, coeff] pair has symbolic::is_zero(coeff) for (const auto& [monomial, coeff] : monomial_to_coefficient_map_) { if (symbolic::is_zero(coeff)) { ostringstream oss; oss << "Polynomial " << *this << " does not satisfy the invariant because the coefficient of the " "monomial " << monomial << " is 0.\n"; throw runtime_error(oss.str()); } } } Polynomial operator-(const Polynomial& p) { return -1 * p; } Polynomial operator+(Polynomial p1, const Polynomial& p2) { return p1 += p2; } Polynomial operator+(Polynomial p, const Monomial& m) { return p += m; } Polynomial operator+(const Monomial& m, Polynomial p) { return p += m; } Polynomial operator+(const Monomial& m1, const Monomial& m2) { return Polynomial(m1) + m2; } Polynomial operator+(Polynomial p, const double c) { return p += c; } Polynomial operator+(const double c, Polynomial p) { return p += c; } Polynomial operator+(const Monomial& m, const double c) { return Polynomial(m) + c; } Polynomial operator+(const double c, const Monomial& m) { return c + Polynomial(m); } Polynomial operator+(Polynomial p, const Variable& v) { return p += v; } Polynomial operator+(const Variable& v, Polynomial p) { return p += v; } Expression operator+(const Expression& e, const Polynomial& p) { return e + p.ToExpression(); } Expression operator+(const Polynomial& p, const Expression& e) { return p.ToExpression() + e; } Polynomial operator-(Polynomial p1, const Polynomial& p2) { return p1 -= p2; } Polynomial operator-(Polynomial p, const Monomial& m) { return p -= m; } Polynomial operator-(const Monomial& m, Polynomial p) { return p = -1 * p + m; // p' = m - p = -1 * p + m. } Polynomial operator-(const Monomial& m1, const Monomial& m2) { return Polynomial(m1) - m2; } Polynomial operator-(Polynomial p, const double c) { return p -= c; } Polynomial operator-(const double c, Polynomial p) { return p = -p + c; } Polynomial operator-(const Monomial& m, const double c) { return Polynomial(m) - c; } Polynomial operator-(const double c, const Monomial& m) { return c - Polynomial(m); } Polynomial operator-(Polynomial p, const Variable& v) { return p -= v; } Polynomial operator-(const Variable& v, const Polynomial& p) { return Polynomial(v, p.indeterminates()) - p; } Expression operator-(const Expression& e, const Polynomial& p) { return e - p.ToExpression(); } Expression operator-(const Polynomial& p, const Expression& e) { return p.ToExpression() - e; } Polynomial operator*(Polynomial p1, const Polynomial& p2) { return p1 *= p2; } Polynomial operator*(Polynomial p, const Monomial& m) { return p *= m; } Polynomial operator*(const Monomial& m, Polynomial p) { return p *= m; } Polynomial operator*(const double c, Polynomial p) { return p *= c; } Polynomial operator*(Polynomial p, const double c) { return p *= c; } Polynomial operator*(const Monomial& m, double c) { return Polynomial(m) * c; } Polynomial operator*(double c, const Monomial& m) { return c * Polynomial(m); } Polynomial operator*(Polynomial p, const Variable& v) { return p *= v; } Polynomial operator*(const Variable& v, Polynomial p) { return p *= v; } Expression operator*(const Expression& e, const Polynomial& p) { return e * p.ToExpression(); } Expression operator*(const Polynomial& p, const Expression& e) { return p.ToExpression() * e; } Polynomial operator/(Polynomial p, const double v) { for (auto& item : p.monomial_to_coefficient_map_) { item.second /= v; } return p; } Expression operator/(const double v, const Polynomial& p) { return v / p.ToExpression(); } Expression operator/(const Expression& e, const Polynomial& p) { return e / p.ToExpression(); } Expression operator/(const Polynomial& p, const Expression& e) { return p.ToExpression() / e; } Polynomial pow(const Polynomial& p, int n) { // TODO(soonho-tri): Optimize this by not relying on ToExpression() method. return Polynomial{pow(p.ToExpression(), n), p.indeterminates()}; } MatrixX<Polynomial> Jacobian(const Eigen::Ref<const VectorX<Polynomial>>& f, const Eigen::Ref<const VectorX<Variable>>& vars) { DRAKE_DEMAND(vars.size() != 0); const auto n{f.size()}; const auto m{vars.size()}; MatrixX<Polynomial> J(n, m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { J(i, j) = f[i].Differentiate(vars[j]); } } return J; } ostream& operator<<(ostream& os, const Polynomial& p) { const Polynomial::MapType& map{p.monomial_to_coefficient_map()}; if (map.empty()) { return os << 0; } auto it = map.begin(); os << it->second << "*" << it->first; for (++it; it != map.end(); ++it) { os << " + " << it->second << "*" << it->first; } return os; } } // namespace symbolic } // namespace drake // We must define this in the cc file so that symbolic_formula.h is fully // defined (not just forward declared) when comparing. namespace Eigen { namespace numext { template <> bool equal_strict(const drake::symbolic::Polynomial& x, const drake::symbolic::Polynomial& y) { return static_cast<bool>(x == y); } } // namespace numext } // namespace Eigen
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/latex.cc
#include "drake/common/symbolic/latex.h" #include <optional> #include <sstream> #include <stdexcept> namespace drake { namespace symbolic { using std::optional; using std::ostringstream; using std::runtime_error; using std::string; using std::to_string; namespace { // If `value` is an integer multiple of `famous_constant_value`, returns the // latex for the multiplied constant `{int_coeff}{famous_constant_latex}`. std::optional<string> multiple_of_famous_constant( double value, double famous_constant_value, string famous_constant_latex) { const double epsilon = 1e-14; if (std::abs(value) < epsilon) { // Handle zero. return std::nullopt; } const double coeff = std::round(value / famous_constant_value); const double difference = coeff * famous_constant_value - value; if (std::abs(difference) < epsilon) { if (coeff == 1.0) { return famous_constant_latex; } else if (coeff == -1.0) { return "-" + famous_constant_latex; } return ToLatex(coeff, 0) + famous_constant_latex; } return std::nullopt; } // Visitor class for code generation. class LatexVisitor { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LatexVisitor) explicit LatexVisitor(int precision) : precision_{precision} {}; // Generates latex expression for the expression @p e. [[nodiscard]] std::string Latex(const Expression& e) const { return VisitExpression<string>(this, e); } [[nodiscard]] std::string Latex(const Formula& f) const { return VisitFormula(f, true); } private: [[nodiscard]] std::string VisitVariable(const Expression& e) const { std::string s = get_variable(e).to_string(); // Use subscripts for variable indices. // x(a) => x_{a}, x(a,b) => x_{a,b}, etc. const auto start_paren = s.find_first_of('('); const auto end_paren = s.find_last_of(')'); if (start_paren != std::string::npos && end_paren != std::string::npos && end_paren > start_paren) { s.replace(end_paren, 1, "}"); s.replace(start_paren, 1, "_{"); } return s; } [[nodiscard]] std::string VisitConstant(const Expression& e) const { return ToLatex(get_constant_value(e), precision_); } [[nodiscard]] std::string VisitAddition(const Expression& e) const { const double c{get_constant_in_addition(e)}; const auto& expr_to_coeff_map{get_expr_to_coeff_map_in_addition(e)}; ostringstream oss; bool print_plus{false}; oss << "("; if (c != 0.0) { oss << ToLatex(c, precision_); print_plus = true; } for (const auto& [term, coeff] : expr_to_coeff_map) { if (coeff > 0.0) { if (print_plus) { oss << " + "; } // Do not print "1 * t" if (coeff != 1.0) { oss << ToLatex(coeff, precision_); } } else { // Instead of printing "+ (- E)", just print "- E". oss << " - "; if (coeff != -1.0) { oss << ToLatex((-coeff), precision_); } } oss << Latex(term); print_plus = true; } oss << ")"; return oss.str(); } [[nodiscard]] std::string VisitMultiplication(const Expression& e) const { const double c{get_constant_in_multiplication(e)}; const auto& base_to_exponent_map{ get_base_to_exponent_map_in_multiplication(e)}; bool print_space = false; ostringstream oss; if (c != 1.0) { oss << ToLatex(c, precision_); print_space = true; } for (const auto& [e_1, e_2] : base_to_exponent_map) { if (print_space) { oss << " "; } if (is_one(e_2)) { oss << Latex(e_1); } else { oss << Latex(e_1) << "^{" << Latex(e_2) << "}"; } print_space = true; } return oss.str(); } // Helper method to handle unary cases. [[nodiscard]] string VisitUnary(const string& f, const Expression& e) const { return "\\" + f + "{" + Latex(get_argument(e)) + "}"; } // Helper method to handle binary cases. [[nodiscard]] string VisitBinary(const string& f, const Expression& e) const { return "\\" + f + "\\{" + Latex(get_first_argument(e)) + ", " + Latex(get_second_argument(e)) + "\\}"; } [[nodiscard]] string VisitPow(const Expression& e) const { return Latex(get_first_argument(e)) + "^{" + Latex(get_second_argument(e)) + "}"; } [[nodiscard]] string VisitDivision(const Expression& e) const { return "\\frac{" + Latex(get_first_argument(e)) + "}{" + Latex(get_second_argument(e)) + "}"; } [[nodiscard]] string VisitAbs(const Expression& e) const { return "|" + Latex(get_argument(e)) + "|"; } [[nodiscard]] string VisitLog(const Expression& e) const { return VisitUnary("log", e); } [[nodiscard]] string VisitExp(const Expression& e) const { return "e^{" + Latex(get_argument(e)) + "}"; } [[nodiscard]] string VisitSqrt(const Expression& e) const { return VisitUnary("sqrt", e); } [[nodiscard]] string VisitSin(const Expression& e) const { return VisitUnary("sin", e); } [[nodiscard]] string VisitCos(const Expression& e) const { return VisitUnary("cos", e); } [[nodiscard]] string VisitTan(const Expression& e) const { return VisitUnary("tan", e); } [[nodiscard]] string VisitAsin(const Expression& e) const { return VisitUnary("asin", e); } [[nodiscard]] string VisitAcos(const Expression& e) const { return VisitUnary("acos", e); } [[nodiscard]] string VisitAtan(const Expression& e) const { return VisitUnary("atan", e); } [[nodiscard]] string VisitAtan2(const Expression& e) const { return "\\atan{\\frac{" + Latex(get_first_argument(e)) + "}{" + Latex(get_second_argument(e)) + "}}"; } [[nodiscard]] string VisitSinh(const Expression& e) const { return VisitUnary("sinh", e); } [[nodiscard]] string VisitCosh(const Expression& e) const { return VisitUnary("cosh", e); } [[nodiscard]] string VisitTanh(const Expression& e) const { return VisitUnary("tanh", e); } [[nodiscard]] string VisitMin(const Expression& e) const { return VisitBinary("min", e); } [[nodiscard]] string VisitMax(const Expression& e) const { return VisitBinary("max", e); } [[nodiscard]] string VisitCeil(const Expression& e) const { return "\\lceil " + Latex(get_argument(e)) + " \\rceil"; } [[nodiscard]] string VisitFloor(const Expression& e) const { return "\\lfloor " + Latex(get_argument(e)) + " \\rfloor"; } [[nodiscard]] string VisitIfThenElse(const Expression& e) const { std::ostringstream oss; oss << "\\begin{cases} "; oss << Latex(get_then_expression(e)) << " & \\text{if } "; oss << Latex(get_conditional_formula(e)) << ", \\\\ "; oss << Latex(get_else_expression(e)) << " & \\text{otherwise}."; oss << "\\end{cases}"; return oss.str(); } [[nodiscard]] string VisitUninterpretedFunction(const Expression&) const { throw runtime_error("ToLatex does not support uninterpreted functions."); } // The parameter `polarity` is to indicate whether it processes `f` (if // `polarity` is true) or `¬f` (if `polarity` is false). [[nodiscard]] std::string VisitFormula(const Formula& f, const bool polarity = true) const { return symbolic::VisitFormula<std::string>(this, f, polarity); } [[nodiscard]] std::string VisitFalse(const Formula&, const bool polarity) const { return polarity ? "\\text{false}" : "\\text{true}"; } [[nodiscard]] std::string VisitTrue(const Formula&, const bool polarity) const { return polarity ? "\\text{true}" : "\\text{false}"; } [[nodiscard]] std::string VisitVariable(const Formula& f, const bool polarity) const { return (polarity ? "" : "\\neg") + get_variable(f).to_string(); } [[nodiscard]] std::string VisitEqualTo(const Formula& f, const bool polarity) const { return Latex(get_lhs_expression(f)) + (polarity ? " = " : " \\neq ") + Latex(get_rhs_expression(f)); } [[nodiscard]] std::string VisitNotEqualTo(const Formula& f, const bool polarity) const { return Latex(get_lhs_expression(f)) + (polarity ? " \\neq " : " = ") + Latex(get_rhs_expression(f)); } [[nodiscard]] std::string VisitGreaterThan(const Formula& f, const bool polarity) const { return Latex(get_lhs_expression(f)) + (polarity ? " > " : " \\le ") + Latex(get_rhs_expression(f)); } [[nodiscard]] std::string VisitGreaterThanOrEqualTo( const Formula& f, const bool polarity) const { return Latex(get_lhs_expression(f)) + (polarity ? " \\ge " : " < ") + Latex(get_rhs_expression(f)); } [[nodiscard]] std::string VisitLessThan(const Formula& f, const bool polarity) const { return Latex(get_lhs_expression(f)) + (polarity ? " < " : " \\ge ") + Latex(get_rhs_expression(f)); } [[nodiscard]] std::string VisitLessThanOrEqualTo(const Formula& f, const bool polarity) const { return Latex(get_lhs_expression(f)) + (polarity ? " \\le " : " > ") + Latex(get_rhs_expression(f)); } [[nodiscard]] std::string VisitConjunction(const Formula& f, const bool polarity) const { ostringstream oss; bool print_symbol = false; for (const auto& o : get_operands(f)) { if (print_symbol) { oss << (polarity ? " \\land " : " \\lor "); } oss << VisitFormula(o, polarity); print_symbol = true; } return oss.str(); } [[nodiscard]] std::string VisitDisjunction(const Formula& f, const bool polarity) const { ostringstream oss; bool print_symbol = false; for (const auto& o : get_operands(f)) { if (print_symbol) { oss << (polarity ? " \\lor " : " \\land "); } oss << VisitFormula(o, polarity); print_symbol = true; } return oss.str(); } [[nodiscard]] std::string VisitNegation(const Formula& f, const bool polarity) const { return VisitFormula(get_operand(f), !polarity); } [[nodiscard]] std::string VisitForall(const Formula& f, const bool polarity) const { // TODO(russt): The polarity==False case can be further reduced into // ∃v₁...vₙ. (¬f). However, we do not have a representation // FormulaExists(∃) yet. Revisit this when we add FormulaExists. ostringstream oss; if (!polarity) { oss << "\\neg "; } oss << "\\forall " << VisitVariables(get_quantified_variables(f)) << ": " << get_quantified_formula(f); return oss.str(); } [[nodiscard]] std::string VisitIsnan(const Formula& f, const bool polarity) const { ostringstream oss; if (!polarity) { oss << "\\neg "; } oss << "\\text{isnan}(" << Latex(get_unary_expression(f)) << ")"; return oss.str(); } [[nodiscard]] std::string VisitPositiveSemidefinite( const Formula& f, const bool polarity) const { DRAKE_ASSERT(polarity); // "Not PSD" could be an arbitrary matrix. return ToLatex(get_matrix_in_positive_semidefinite(f), precision_) + " \\succeq 0"; } // Note: This method is not called directly from VisitExpression; but can be // used by other methods in this class. [[nodiscard]] std::string VisitVariables(const Variables& vars) const { ostringstream oss; bool delimiter = false; for (const auto& v : vars) { if (delimiter) { oss << ", "; } oss << VisitVariable(v); delimiter = true; } return oss.str(); } // Makes VisitExpression a friend of this class so that it can use private // methods. friend std::string VisitExpression<std::string>(const LatexVisitor*, const Expression&); // Makes VisitFormula a friend of this class so that it can use private // methods. friend std::string symbolic::VisitFormula<std::string>(const LatexVisitor*, const Formula&, const bool&); int precision_; }; } // namespace string ToLatex(const Expression& e, int precision) { return LatexVisitor{precision}.Latex(e); } string ToLatex(const Formula& f, int precision) { return LatexVisitor{precision}.Latex(f); } string ToLatex(double val, int precision) { if (std::isnan(val)) { return "\\text{NaN}"; } if (std::isinf(val)) { return val < 0 ? "-\\infty" : "\\infty"; } if (optional<string> result = multiple_of_famous_constant(val, M_PI, "\\pi")) { return *result; } if (optional<string> result = multiple_of_famous_constant(val, M_E, "e")) { return *result; } double intpart; if (std::modf(val, &intpart) == 0.0) { // Then it's an integer. Note that we can't static_cast<int>() because it // might not be a *small* integer. return fmt::format("{:.0f}", val); } std::ostringstream oss; oss.precision(precision); oss << std::fixed << val; return oss.str(); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/monomial.cc
/* clang-format off to disable clang-format-includes */ // NOLINTNEXTLINE(build/include): Our header file is included by polynomial.h. #include "drake/common/symbolic/polynomial.h" /* clang-format on */ #include <map> #include <numeric> #include <stdexcept> #include <utility> #include <fmt/format.h> #include "drake/common/drake_assert.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 { using std::accumulate; using std::logic_error; using std::make_pair; using std::map; using std::ostream; using std::ostringstream; using std::pair; using std::runtime_error; namespace { // Computes the total degree of a monomial. This method is used in a // constructor of Monomial to set its total degree at construction. int TotalDegree(const map<Variable, int>& powers) { return accumulate(powers.begin(), powers.end(), 0, [](const int degree, const pair<const Variable, int>& p) { return degree + p.second; }); } // Converts a symbolic expression @p e into an internal representation of // Monomial class, a mapping from a base (Variable) to its exponent (int). This // function is called inside of the constructor Monomial(const // symbolic::Expression&). map<Variable, int> ToMonomialPower(const Expression& e) { // TODO(soonho): Re-implement this function by using a Polynomial visitor. DRAKE_DEMAND(e.is_polynomial()); map<Variable, int> powers; if (is_one(e)) { // This block is deliberately left empty. } else if (is_constant(e)) { throw runtime_error("A constant not equal to 1, this is not a monomial."); } else if (is_variable(e)) { powers.emplace(get_variable(e), 1); } else if (is_pow(e)) { const Expression& base{get_first_argument(e)}; const Expression& exponent{get_second_argument(e)}; // The following holds because `e` is polynomial. DRAKE_DEMAND(is_constant(exponent)); // The following static_cast (double -> int) does not lose information // because of the precondition `e.is_polynomial()`. const int n{static_cast<int>(get_constant_value(exponent))}; powers = ToMonomialPower(base); // pow(base, n) => (∏ᵢ xᵢ)^ⁿ => ∏ᵢ (xᵢ^ⁿ) for (auto& p : powers) { p.second *= n; } } else if (is_multiplication(e)) { if (!is_one(get_constant_in_multiplication(e))) { throw runtime_error("The constant in the multiplication is not 1."); } // e = ∏ᵢ pow(baseᵢ, exponentᵢ). for (const auto& p : get_base_to_exponent_map_in_multiplication(e)) { for (const auto& q : ToMonomialPower(pow(p.first, p.second))) { auto it = powers.find(q.first); if (it == powers.end()) { powers.emplace(q.first, q.second); } else { it->second += q.second; } } } } else { throw runtime_error("This expression cannot be converted to a monomial."); } return powers; } // Converts a pair of variables and their integer exponents into an internal // representation of Monomial class, a mapping from a base (Variable) to its // exponent (int). This function is called in the constructor taking the same // types of arguments. map<Variable, int> ToMonomialPower( const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& exponents) { DRAKE_DEMAND(vars.size() == exponents.size()); map<Variable, int> powers; for (int i = 0; i < vars.size(); ++i) { if (exponents[i] > 0) { powers.emplace(vars[i], exponents[i]); } else if (exponents[i] < 0) { throw std::logic_error("The exponent is negative."); } } return powers; } } // namespace Monomial::Monomial(const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& exponents) : total_degree_{exponents.sum()}, powers_{ToMonomialPower(vars, exponents)} {} Monomial::Monomial(const Variable& var) : total_degree_{1}, powers_{{var, 1}} {} Monomial::Monomial(const Variable& var, const int exponent) : total_degree_{exponent} { DRAKE_DEMAND(exponent >= 0); if (exponent > 0) { powers_.emplace(var, exponent); } } Monomial::Monomial(const map<Variable, int>& powers) : total_degree_{TotalDegree(powers)} { for (const auto& p : powers) { const int exponent{p.second}; if (exponent > 0) { powers_.insert(p); } else if (exponent < 0) { throw std::logic_error("The exponent is negative."); } // Ignore the entry if exponent == 0. } } Monomial::Monomial(const Expression& e) : Monomial(ToMonomialPower(e.Expand())) {} int Monomial::degree(const Variable& v) const { const auto it = powers_.find(v); if (it == powers_.end()) { return 0; } else { return it->second; } } Variables Monomial::GetVariables() const { Variables vars{}; for (const pair<const Variable, int>& p : powers_) { vars += p.first; } return vars; } bool Monomial::operator==(const Monomial& m) const { // The first test below checks the number of factors in each monomial, e.g., x // * y^2 * z^3 differs from x * y^2 due to a different number of factors. x * // y^2 * z^3 and x * y^2 * z^7 have the same number of factors and this first // test is inconclusive as to whether the monomials are equal. if (powers_.size() != m.powers_.size()) return false; // The second test compares the variables and exponents on each factor, e.g., // x * y^2 * z^3 and x * y^2 * z^7 returns false (different exponent on z). // x * y^2 * z^3 and x * y^2 * b^3 returns false (different variable z vs. b). // x * y^2 * z^3 and x * y^2 * z^3 returns true (equal monomials). for (auto it1 = powers_.begin(), it2 = m.powers_.begin(); it1 != powers_.end(); ++it1, ++it2) { const Variable& var1{it1->first}; const Variable& var2{it2->first}; const int exponent1{it1->second}; const int exponent2{it2->second}; if (!var1.equal_to(var2) || exponent1 != exponent2) { return false; } } return true; } bool Monomial::operator!=(const Monomial& m) const { return !(*this == m); } double Monomial::Evaluate(const Environment& env) const { return accumulate( powers_.begin(), powers_.end(), 1.0, [this, &env](const double v, const pair<const Variable, int>& p) { const Variable& var{p.first}; const auto it = env.find(var); if (it == env.end()) { ostringstream oss; oss << "Monomial " << *this << " cannot be evaluated with the given " "environment which does not provide an entry " "for variable = " << var << "."; throw runtime_error(oss.str()); } else { const double base{it->second}; const int exponent{p.second}; return v * std::pow(base, exponent); } }); } Eigen::VectorXd Monomial::Evaluate( const Eigen::Ref<const VectorX<symbolic::Variable>>& vars, const Eigen::Ref<const Eigen::MatrixXd>& vars_values) const { DRAKE_DEMAND(vars.rows() == vars_values.rows()); Eigen::ArrayXd monomial_vals = Eigen::ArrayXd::Ones(vars_values.cols()); for (int i = 0; i < vars.rows(); ++i) { auto it = powers_.find(vars(i)); if (it != powers_.end()) { monomial_vals *= vars_values.row(i).array().pow(it->second); } } const symbolic::Variables vars_set(vars); if (static_cast<int>(vars_set.size()) != vars.rows()) { throw std::invalid_argument( "Monomial::Evaluate(): vars contains repeated variables."); } for (const auto& [var, degree] : powers_) { if (vars_set.find(var) == vars_set.end()) { throw std::invalid_argument(fmt::format( "Monomial::Evaluate(): {} is not present in vars", var.get_name())); } } return monomial_vals.matrix(); } pair<double, Monomial> Monomial::EvaluatePartial(const Environment& env) const { double coeff{1.0}; map<Variable, int> new_powers; for (const auto& p : powers_) { const Variable& var{p.first}; const int exponent{p.second}; auto it = env.find(var); if (it != env.end()) { double base{it->second}; coeff *= std::pow(base, exponent); } else { new_powers.insert(p); } } return make_pair(coeff, Monomial(new_powers)); } Expression Monomial::ToExpression() const { return ExpressionMulFactory(powers_).GetExpression(); } Monomial& Monomial::operator*=(const Monomial& m) { for (const auto& p : m.get_powers()) { const Variable& var{p.first}; const int exponent{p.second}; auto it = powers_.find(var); if (it == powers_.end()) { powers_.insert(p); } else { it->second += exponent; } total_degree_ += exponent; } return *this; } Monomial& Monomial::pow_in_place(const int p) { if (p < 0) { ostringstream oss; oss << "Monomial::pow(int p) is called with a negative p = " << p; throw runtime_error(oss.str()); } if (p == 0) { total_degree_ = 0; powers_.clear(); } else if (p > 1) { for (auto& item : powers_) { int& exponent{item.second}; exponent *= p; } total_degree_ *= p; } // If p == 1, NO OP. return *this; } ostream& operator<<(ostream& out, const Monomial& m) { if (m.powers_.empty()) { return out << 1; } auto it = m.powers_.begin(); out << it->first; if (it->second > 1) { out << "^" << it->second; } for (++it; it != m.powers_.end(); ++it) { out << " * "; out << it->first; if (it->second > 1) { out << "^" << it->second; } } return out; } Monomial operator*(Monomial m1, const Monomial& m2) { m1 *= m2; return m1; } Monomial pow(Monomial m, const int p) { return m.pow_in_place(p); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/generic_polynomial.cc
#include "drake/common/symbolic/generic_polynomial.h" #include <algorithm> #include <map> #include <sstream> #include <stdexcept> #include <utility> #define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/expression/expression_cell.h" #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER using std::accumulate; using std::make_pair; using std::map; using std::ostringstream; using std::pair; using std::runtime_error; namespace drake { namespace symbolic { namespace { using MonomialBasisMapType = GenericPolynomial<MonomialBasisElement>::MapType; // Note that `.Expand()` is needed in the following kinds of cases: // e1 := (a + b)² // e2 := - (a² + 2ab + b²) // Without expanding the terms, they would not report as EqualTo. bool AreEqualAfterExpanding(const Expression& e1, const Expression& e2) { const Expression& e1_expanded = e1.is_expanded() ? e1 : e1.Expand(); const Expression& e2_expanded = e2.is_expanded() ? e2 : e2.Expand(); return e1_expanded.EqualTo(e2_expanded); } // Helper function to add coeff * m to a map (BasisElement→ Expression). // Used to implement DecomposePolynomialVisitor::VisitAddition and // GenericPolynomial::Add. template <typename BasisElement> void DoAddProduct( const Expression& coeff, const BasisElement& basis_element, typename GenericPolynomial<BasisElement>::MapType* const map) { if (is_zero(coeff)) { return; } auto it = map->find(basis_element); if (it != map->end()) { // basis_element ∈ dom(map) Expression& existing_coeff = it->second; if (AreEqualAfterExpanding(-coeff, existing_coeff)) { map->erase(it); } else { existing_coeff += coeff; } } else { // basis_element ∉ dom(map) map->emplace_hint(it, basis_element, coeff); } } // Visitor class to implement `Polynomial(const Expression& e, const // Variables& indeterminates)` constructor which decomposes an expression e // w.r.t. indeterminates. class DecomposePolynomialVisitor { public: MonomialBasisMapType Decompose(const Expression& e, const Variables& indeterminates) const { // Note that it calls `Expression::Expand()` here. return Visit(e.Expand(), indeterminates); } private: MonomialBasisMapType Visit(const Expression& e, const Variables& indeterminates) const { return VisitExpression<MonomialBasisMapType>(this, e, indeterminates); } MonomialBasisMapType VisitVariable(const Expression& e, const Variables& indeterminates) const { const Variable& var{get_variable(e)}; if (indeterminates.include(var)) { // Monomial : var, coefficient : 1 return MonomialBasisMapType{{{MonomialBasisElement{var}, 1}}}; } else { // Monomial : 1, coefficient : var return MonomialBasisMapType{{{MonomialBasisElement{}, var}}}; } } MonomialBasisMapType VisitConstant(const Expression& e, const Variables&) const { const double v{get_constant_value(e)}; if (v != 0) { return MonomialBasisMapType{{{MonomialBasisElement(), v}}}; // = v. } return MonomialBasisMapType{}; // = 0. } MonomialBasisMapType VisitAddition(const Expression& e, const Variables& indeterminates) const { // e = c₀ + ∑ᵢ (cᵢ * eᵢ) MonomialBasisMapType new_map; const double c_0{get_constant_in_addition(e)}; if (c_0 != 0) { new_map.emplace(MonomialBasisElement{}, c_0); } for (const auto& [e_i, c_i] : get_expr_to_coeff_map_in_addition(e)) { // e = c₀ + ∑ᵢ (cᵢ * eᵢ) = c₀ + ∑ᵢ (cᵢ * (∑ⱼ mⱼ * cⱼ)) // ~~~~~~~~~~~ // Monomial of eᵢ // = c₀ + ∑ᵢ ∑ⱼ ((cᵢ * cⱼ) * mⱼ) // Note that we have cᵢ ≠ 0 ∧ cⱼ ≠ 0 → (cᵢ * cⱼ) ≠ 0. const MonomialBasisMapType map_i = Visit(e_i, indeterminates); for (const auto& [m_j, c_j] : map_i) { // Add (cᵢ * cⱼ) * mⱼ. DoAddProduct(c_i * c_j, m_j, &new_map); } } return new_map; } MonomialBasisMapType VisitMultiplication( const Expression& e, const Variables& indeterminates) const { // e = c * ∏ᵢ pow(baseᵢ, exponentᵢ). const double c = get_constant_in_multiplication(e); Expression coeff{c}; MonomialBasisElement m{}; for (const auto& [base_i, exponent_i] : get_base_to_exponent_map_in_multiplication(e)) { const auto [m_i, coeff_i] = VisitPow(base_i, exponent_i, indeterminates); m.MergeBasisElementInPlace(m_i); coeff *= coeff_i; } return MonomialBasisMapType{{m, coeff}}; } pair<MonomialBasisElement, Expression> VisitPow( const Expression& base, const Expression& exponent, const Variables& indeterminates) const { if (intersect(base.GetVariables(), indeterminates).empty()) { // Case: vars(baseᵢ) ∩ indeterminates = ∅. if (!intersect(exponent.GetVariables(), indeterminates).empty()) { // An indeterminate should not be in an exponent for the whole // expression to be a polynomial. For example, aˣ is not a // polynomial. That is, vars(exponentᵢ) ∩ indeterminates = ∅ should // hold. ostringstream oss; oss << "Exponent " << exponent << " includes an indeterminates " << indeterminates << "."; throw runtime_error(oss.str()); } return make_pair(MonomialBasisElement{}, pow(base, exponent)); } else { // Case: vars(baseᵢ) ∩ indeterminates ≠ ∅. Moreover, we have // vars(baseᵢ) ⊆ indeterminates as baseᵢ is already expanded. // exponentᵢ should be a positive integer. if (!is_constant(exponent) || !is_positive_integer(get_constant_value(exponent))) { ostringstream oss; oss << "Given the base " << base << ", the Exponent " << exponent << " should be a positive integer but it is not the case."; throw runtime_error(oss.str()); } const int n{static_cast<int>(get_constant_value(exponent))}; // `base` should be an indeterminate because `e` is a pre-expanded term. if (!is_variable(base)) { ostringstream oss; oss << "Base " << base << " is not an indeterminate, " << indeterminates; throw runtime_error(oss.str()); } // Since we call e.Expand() before `Visit` function, `base` is already // expanded. If the variables in base intersect with indeterminates, then // it has to be a subset of indeterminates. DRAKE_ASSERT(base.GetVariables().IsSubsetOf(indeterminates)); DRAKE_ASSERT(base.GetVariables().size() == 1); return make_pair(MonomialBasisElement{get_variable(base), n}, 1.0); } } MonomialBasisMapType VisitPow(const Expression& e, const Variables& indeterminates) const { const Expression& base{get_first_argument(e)}; const Expression& exponent{get_second_argument(e)}; const pair<MonomialBasisElement, Expression> result{ VisitPow(base, exponent, indeterminates)}; return MonomialBasisMapType{{{result.first, result.second}}}; } MonomialBasisMapType VisitDivision(const Expression& e, const Variables& indeterminates) const { // e = e₁ / e₂ const Expression& e1{get_first_argument(e)}; const Expression& e2{get_second_argument(e)}; // We require that the denominator e₂ is free of indeterminates for e to be // a polynomial. This is because canceling a common factor is not a sound // simplification. For example, `(x² + x) / x` is not equivalent to `x + 1` // since the former is not defined at x = 0 while the latter is a total // function over R. // vars(e₂) ∩ indeterminates = ∅. if (!intersect(e2.GetVariables(), indeterminates).empty()) { ostringstream oss; oss << "In " << e1 << " / " << e2 << ", the denominator " << e2 << " should be free of the indeterminates, " << indeterminates << "."; throw runtime_error(oss.str()); } // Since e₁ is already expanded, we have: // // e = e₁ / e₂ // = (∑ᵢ cᵢ * monomialᵢ) / e₂ // = (∑ᵢ (cᵢ/e₂) * monomialᵢ // // where monomialᵢ is a monomial of indeterminates and cᵢ/e₂ is an // expression free of indeterminates (which possibly includes decision // variables). MonomialBasisMapType map{Visit(e1, indeterminates)}; for (auto& item : map) { item.second /= e2; } return map; } // For a non-polynomial term, e, we return a map {1 ↦ e}. We require e to be // free of indeterminates. For example, `VisitNonPolynomialTerm(sin(a + b), // {x})` returns `{1 ↦ sin(a + b)}`. However, `VisitNonPolynomialTerm(sin(a + // x), {x})` throws an exception because `sin(a + x)` includes an // indeterminate `x`. MonomialBasisMapType VisitNonPolynomialTerm( const Expression& e, const Variables& indeterminates) const { // vars(e) ∩ indeterminates = ∅. if (!intersect(e.GetVariables(), indeterminates).empty()) { ostringstream oss; oss << "The non-polynomial term " << e << " should be free of the indeterminates " << indeterminates << "."; throw runtime_error(oss.str()); } return {{MonomialBasisElement{}, e}}; // = {1 ↦ e}. } MonomialBasisMapType VisitAbs(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitLog(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitExp(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitSqrt(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitSin(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitCos(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitTan(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitAsin(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitAcos(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitAtan(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitAtan2(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitSinh(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitCosh(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitTanh(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitMin(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitMax(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitCeil(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitFloor(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitIfThenElse(const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } MonomialBasisMapType VisitUninterpretedFunction( const Expression& e, const Variables& indeterminates) const { return VisitNonPolynomialTerm(e, indeterminates); } // Makes VisitExpression a friend of this class so that it can use private // methods. friend MonomialBasisMapType drake::symbolic::VisitExpression<MonomialBasisMapType>( const DecomposePolynomialVisitor*, const Expression&, const Variables&); }; template <typename BasisElement> Variables GetIndeterminates( const typename GenericPolynomial<BasisElement>::MapType& m) { Variables vars; for (const pair<const BasisElement, Expression>& p : m) { const BasisElement& m_i{p.first}; vars += m_i.GetVariables(); } return vars; } template <typename BasisElement> Variables GetDecisionVariables( const typename GenericPolynomial<BasisElement>::MapType& m) { Variables vars; for (const pair<const BasisElement, Expression>& p : m) { const Expression& e_i{p.second}; vars += e_i.GetVariables(); } return vars; } } // namespace template <typename BasisElement> GenericPolynomial<BasisElement>::GenericPolynomial(MapType init) : basis_element_to_coefficient_map_{std::move(init)}, indeterminates_{ GetIndeterminates<BasisElement>(basis_element_to_coefficient_map_)}, decision_variables_{GetDecisionVariables<BasisElement>( basis_element_to_coefficient_map_)} { DRAKE_ASSERT_VOID(CheckInvariant()); } template <typename BasisElement> void GenericPolynomial<BasisElement>::CheckInvariant() const { // TODO(hongkai.dai and soonho.kong): improves the computation time of // CheckInvariant(). See github issue // https://github.com/RobotLocomotion/drake/issues/10229 Variables vars{intersect(decision_variables(), indeterminates())}; if (!vars.empty()) { ostringstream oss; oss << "Polynomial " << *this << " does not satisfy the invariant because the following variable(s) " "are used as decision variables and indeterminates at the same " "time:\n" << vars << "."; throw runtime_error(oss.str()); } } template <typename BasisElement> GenericPolynomial<BasisElement>::GenericPolynomial(const BasisElement& m) : basis_element_to_coefficient_map_{{m, 1}}, indeterminates_{m.GetVariables()}, decision_variables_{} { // No need to call CheckInvariant() because the following should hold. DRAKE_ASSERT(decision_variables().empty()); } template <typename BasisElement> GenericPolynomial<BasisElement>::GenericPolynomial(const Expression& e) : GenericPolynomial<BasisElement>{e, e.GetVariables()} { // No need to call CheckInvariant() because the following should hold. DRAKE_ASSERT(decision_variables().empty()); } template <typename BasisElement> GenericPolynomial<BasisElement>::GenericPolynomial(const Expression& e, Variables indeterminates) : indeterminates_{std::move(indeterminates)} { const std::map<MonomialBasisElement, Expression> monomial_to_coefficient_map = DecomposePolynomialVisitor{}.Decompose(e, indeterminates_); if constexpr (std::is_same_v<BasisElement, MonomialBasisElement>) { basis_element_to_coefficient_map_ = std::move(monomial_to_coefficient_map); } else { for (const auto& [monomial, coeff] : monomial_to_coefficient_map) { const std::map<BasisElement, double> monomial_to_basis_element = monomial.template ToBasis<BasisElement>(); for (const auto& [basis_element, coeff2] : monomial_to_basis_element) { DoAddProduct(coeff2 * coeff, basis_element, &basis_element_to_coefficient_map_); } } } decision_variables_ = GetDecisionVariables<BasisElement>(basis_element_to_coefficient_map_); // No need to call CheckInvariant() because DecomposePolynomialVisitor is // supposed to make sure the invariant holds as a post-condition. } template <typename BasisElement> void GenericPolynomial<BasisElement>::SetIndeterminates( const Variables& new_indeterminates) { if (new_indeterminates.IsSupersetOf(indeterminates_) && intersect(decision_variables_, new_indeterminates).empty()) { indeterminates_ = new_indeterminates; } else { // TODO(soonho-tri): Optimize this part. *this = GenericPolynomial<BasisElement>{ToExpression(), new_indeterminates}; } } template <typename BasisElement> int GenericPolynomial<BasisElement>::Degree(const Variable& v) const { int degree{0}; for (const pair<const BasisElement, Expression>& p : basis_element_to_coefficient_map_) { degree = std::max(degree, p.first.degree(v)); } return degree; } template <typename BasisElement> int GenericPolynomial<BasisElement>::TotalDegree() const { int degree{0}; for (const pair<const BasisElement, Expression>& p : basis_element_to_coefficient_map_) { degree = std::max(degree, p.first.total_degree()); } return degree; } template <typename BasisElement> Expression GenericPolynomial<BasisElement>::ToExpression() const { // Returns ∑ᵢ (cᵢ * mᵢ). return accumulate(basis_element_to_coefficient_map_.begin(), basis_element_to_coefficient_map_.end(), Expression{0.0}, [](const Expression& init, const pair<const BasisElement, Expression>& p) { const BasisElement& m{p.first}; const Expression& coeff{p.second}; return init + (coeff * m.ToExpression()); }) .Expand(); } template <typename BasisElement> GenericPolynomial<BasisElement> GenericPolynomial<BasisElement>::Differentiate( const Variable& x) const { if (this->indeterminates_.include(x)) { // x is an indeterminate. GenericPolynomial<BasisElement>::MapType map; for (const auto& [basis_element, coeff] : this->basis_element_to_coefficient_map_) { // Take the derivative of basis_element m as dm/dx = sum_{key} // basis_element_gradient[key] * key. const std::map<BasisElement, double> basis_element_gradient = basis_element.Differentiate(x); for (const auto& p : basis_element_gradient) { DoAddProduct(coeff * p.second, p.first, &map); } } return GenericPolynomial<BasisElement>(map); } else if (decision_variables_.include(x)) { // x is a decision variable. GenericPolynomial<BasisElement>::MapType map; for (const auto& [basis_element, coeff] : basis_element_to_coefficient_map_) { DoAddProduct(coeff.Differentiate(x), basis_element, &map); } return GenericPolynomial<BasisElement>(map); } else { // The variable `x` does not appear in this polynomial. Returns zero // polynomial. return GenericPolynomial<BasisElement>(); } } template <typename BasisElement> double GenericPolynomial<BasisElement>::Evaluate(const Environment& env) const { return accumulate( basis_element_to_coefficient_map_.begin(), basis_element_to_coefficient_map_.end(), 0.0, [&env](const double v, const pair<BasisElement, Expression>& item) { const BasisElement& basis_element{item.first}; const Expression& coeff{item.second}; return v + basis_element.Evaluate(env) * coeff.Evaluate(env); }); } template <typename BasisElement> GenericPolynomial<BasisElement> GenericPolynomial<BasisElement>::EvaluatePartial(const Environment& env) const { MapType new_map; // Will use this to construct the return value. for (const auto& [basis_element, coeff] : basis_element_to_coefficient_map_) { const Expression coeff_partial_evaluated{coeff.EvaluatePartial(env)}; const pair<double, BasisElement> partial_eval_result{ basis_element.EvaluatePartial(env)}; const Expression new_coeff{coeff_partial_evaluated * partial_eval_result.first}; const BasisElement& new_basis_element{partial_eval_result.second}; auto it = new_map.find(new_basis_element); if (it == new_map.end()) { new_map.emplace_hint(it, new_basis_element, new_coeff); } else { it->second += new_coeff; } } return GenericPolynomial<BasisElement>(new_map); } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator+=( const GenericPolynomial<BasisElement>& p) { for (const auto& [basis_element, coeff] : p.basis_element_to_coefficient_map()) { DoAddProduct(coeff, basis_element, &basis_element_to_coefficient_map_); } indeterminates_ += p.indeterminates(); decision_variables_ += p.decision_variables(); DRAKE_ASSERT_VOID(CheckInvariant()); return *this; } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator+=( const BasisElement& m) { // No need to call CheckInvariant since it's called inside of AddProduct. return AddProduct(1.0, m); } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator+=( const double c) { // No need to call CheckInvariant since it's called inside of AddProduct. return AddProduct(c, BasisElement{}); } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator+=( const Variable& v) { if (indeterminates().include(v)) { this->AddProduct(1.0, BasisElement{v}); } else { this->AddProduct(v, BasisElement{}); } return *this; } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator-=( const GenericPolynomial<BasisElement>& p) { return *this += -p; } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator-=( const BasisElement& m) { // No need to call CheckInvariant() since it's called inside of Add. return AddProduct(-1.0, m); } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator-=( double c) { // No need to call CheckInvariant() since it's called inside of Add. return AddProduct(-c, BasisElement{}); } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator-=( const Variable& v) { if (indeterminates().include(v)) { return AddProduct(-1.0, BasisElement{v}); } else { return AddProduct(-v, BasisElement{}); } } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator*=( const GenericPolynomial<BasisElement>& p) { // (c₁₁ * m₁₁ + ... + c₁ₙ * m₁ₙ) * (c₂₁ * m₂₁ + ... + c₂ₘ * m₂ₘ) // = (c₁₁ * m₁₁ + ... + c₁ₙ * m₁ₙ) * c₂₁ * m₂₁ + ... + // (c₁₁ * m₁₁ + ... + c₁ₙ * m₁ₙ) * c₂ₘ * m₂ₘ // Notice that m₁ᵢ * m₂ⱼ = ∑ₖ dᵢⱼₖ mᵢⱼₖ, namely the product of two basis // elements m₁ᵢ * m₂ⱼ is the weighted sum of a series of new basis elements. // For example, when we use MonomialBasisElement, m₁ᵢ * m₂ⱼ = 1 * mᵢⱼ; when we // use ChebyshevBasisElement, Tᵢ(x) * Tⱼ(x) = 0.5 * Tᵢ₊ⱼ(x) + 0.5 * Tᵢ₋ⱼ(x) MapType new_map{}; for (const auto& [basis_element1, coeff1] : basis_element_to_coefficient_map()) { for (const auto& [basis_element2, coeff2] : p.basis_element_to_coefficient_map()) { // basis_element_products stores the product of two basis elements as a // weighted sum of new basis elements. const std::map<BasisElement, double> basis_element_products{ basis_element1 * basis_element2}; const Expression coeff_product{coeff1 * coeff2}; for (const auto& [new_basis, new_basis_coeff] : basis_element_products) { DoAddProduct(new_basis_coeff * coeff_product, new_basis, &new_map); } } } basis_element_to_coefficient_map_ = std::move(new_map); indeterminates_ += p.indeterminates(); decision_variables_ += p.decision_variables(); DRAKE_ASSERT_VOID(CheckInvariant()); return *this; } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator*=( const BasisElement& m) { MapType new_map; for (const auto& [basis_element, coeff] : basis_element_to_coefficient_map_) { const std::map<BasisElement, double> basis_element_product{basis_element * m}; for (const auto& [new_basis_element, coeff_product] : basis_element_product) { DoAddProduct(coeff_product * coeff, new_basis_element, &new_map); } } basis_element_to_coefficient_map_ = std::move(new_map); indeterminates_ += m.GetVariables(); DRAKE_ASSERT_VOID(CheckInvariant()); return *this; } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator*=( double c) { for (auto& p : basis_element_to_coefficient_map_) { Expression& coeff = p.second; coeff *= c; } return *this; } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator*=( const Variable& v) { if (indeterminates().include(v)) { return *this *= BasisElement{v}; } else { for (auto& p : basis_element_to_coefficient_map_) { Expression& coeff = p.second; coeff *= v; } return *this; } } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::operator/=( double c) { for (auto& item : basis_element_to_coefficient_map_) { item.second /= c; } return *this; } template <typename BasisElement> GenericPolynomial<BasisElement>& GenericPolynomial<BasisElement>::AddProduct( const Expression& coeff, const BasisElement& m) { DoAddProduct(coeff, m, &basis_element_to_coefficient_map_); indeterminates_ += m.GetVariables(); decision_variables_ += coeff.GetVariables(); DRAKE_ASSERT_VOID(CheckInvariant()); return *this; } template <typename BasisElement> GenericPolynomial<BasisElement> GenericPolynomial<BasisElement>::RemoveTermsWithSmallCoefficients( double coefficient_tol) const { DRAKE_DEMAND(coefficient_tol >= 0); MapType cleaned_polynomial{}; for (const auto& [basis_element, coeff] : basis_element_to_coefficient_map_) { if (is_constant(coeff) && std::abs(get_constant_value(coeff)) <= coefficient_tol) { // The coefficients are small. continue; } else { cleaned_polynomial.emplace_hint(cleaned_polynomial.end(), basis_element, coeff); } } return GenericPolynomial<BasisElement>(cleaned_polynomial); } template <typename BasisElement> GenericPolynomial<BasisElement> GenericPolynomial<BasisElement>::EvaluatePartial(const Variable& var, const double c) const { return EvaluatePartial({{{var, c}}}); } namespace { template <typename BasisElement> bool GenericPolynomialEqual(const GenericPolynomial<BasisElement>& p1, const GenericPolynomial<BasisElement>& p2, bool do_expansion) { const typename GenericPolynomial<BasisElement>::MapType& map1{ p1.basis_element_to_coefficient_map()}; const typename GenericPolynomial<BasisElement>::MapType& map2{ p2.basis_element_to_coefficient_map()}; if (map1.size() != map2.size()) { return false; } // Since both map1 and map2 are ordered map, we can compare them one by one in // an ordered manner. auto it1 = map1.begin(); auto it2 = map2.begin(); while (it1 != map1.end()) { if (it1->first != (it2->first)) { return false; } const Expression& e1{it1->second}; const Expression& e2{it2->second}; if (do_expansion) { if (!e1.Expand().EqualTo(e2.Expand())) { return false; } } else { if (!e1.EqualTo(e2)) { return false; } } it1++; it2++; } return true; } } // namespace template <typename BasisElement> bool GenericPolynomial<BasisElement>::EqualTo( const GenericPolynomial<BasisElement>& p) const { return GenericPolynomialEqual<BasisElement>(*this, p, false); } template <typename BasisElement> bool GenericPolynomial<BasisElement>::EqualToAfterExpansion( const GenericPolynomial<BasisElement>& p) const { return GenericPolynomialEqual<BasisElement>(*this, p, true); } template <typename BasisElement> bool GenericPolynomial<BasisElement>::CoefficientsAlmostEqual( const GenericPolynomial<BasisElement>& p, double tol) const { auto it1 = this->basis_element_to_coefficient_map_.begin(); auto it2 = p.basis_element_to_coefficient_map_.begin(); while (it1 != this->basis_element_to_coefficient_map_.end() && it2 != this->basis_element_to_coefficient_map().end()) { if (it1->first == it2->first) { const symbolic::Expression coeff_diff = it1->second - it2->second; if (is_constant(coeff_diff) && std::abs(get_constant_value(coeff_diff)) <= tol) { it1++; it2++; continue; } else { return false; } } else if (it1->first < it2->first) { if (is_constant(it1->second) && std::abs(get_constant_value(it1->second)) < tol) { it1++; continue; } else { return false; } } else { if (is_constant(it2->second) && std::abs(get_constant_value(it2->second)) < tol) { it2++; continue; } else { return false; } } } while (it1 != this->basis_element_to_coefficient_map().end()) { if (is_constant(it1->second) && std::abs(get_constant_value(it1->second)) < tol) { it1++; continue; } else { return false; } } while (it2 != p.basis_element_to_coefficient_map().end()) { if (is_constant(it2->second) && std::abs(get_constant_value(it2->second)) < tol) { it2++; continue; } else { return false; } } return true; } template <typename BasisElement> Formula GenericPolynomial<BasisElement>::operator==( const GenericPolynomial<BasisElement>& p) const { // 1) Let diff = p - (this polynomial). // 2) Extract the condition where diff is zero. // That is, all coefficients should be zero. const GenericPolynomial<BasisElement> diff{p - *this}; Formula ret{Formula::True()}; for (const pair<const BasisElement, Expression>& item : diff.basis_element_to_coefficient_map_) { const Expression& coeff{item.second}; // ret is the conjunction of symbolic formulas. Don't confuse `&&` here // with the "logical and" operation between booleans. ret = ret && (coeff == 0.0); } return ret; } template <typename BasisElement> Formula GenericPolynomial<BasisElement>::operator!=( const GenericPolynomial<BasisElement>& p) const { return !(*this == p); } template class GenericPolynomial<MonomialBasisElement>; template class GenericPolynomial<ChebyshevBasisElement>; } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/chebyshev_polynomial.cc
#include "drake/common/symbolic/chebyshev_polynomial.h" namespace drake { namespace symbolic { ChebyshevPolynomial::ChebyshevPolynomial(Variable var, int degree) : var_{std::move(var)}, degree_{degree} { DRAKE_DEMAND(degree_ >= 0); } namespace { // We represent a Chebyshev polynomial as a map from monomial degree to its // coefficient, so T₂(x) = 2x²-1 is represented by a vector // Eigen::Vector3d(-1, 0, 2). // In monomial_coeffs, each of its column represented one Chebyshev polynomial, // At the start of the function: // monomial_coeffs.col(*next_col_index) represents Tₙ₊₁(x), // monomial_coeffs.col(*current_col_index) represents Tₙ(x) // monomial_coeffs.col(*prev_col_index) represents Tₙ₋₁(x). // At the end of this function, we increment n by 1, and // monomial_coeffs.col(*next_col_index) represents Tₙ₊₂(x), // monomial_coeffs.col(*current_col_index) represents Tₙ₊₁(x), // monomial_coeffs.col(*prev_col_index) represents Tₙ(x). void ToPolynomialImpl(Eigen::Matrix<int, Eigen::Dynamic, 3>* monomial_coeffs, int* next_col_index, int* current_col_index, int* prev_col_index) { // Use the recursive function Tₙ₊₂(x) = 2xTₙ₊₁(x) − Tₙ(x) // First put Tₙ₊₂(x) in the column prev_col_index, then point next_col_index // to Tₙ₊₂(x) monomial_coeffs->block(1, *prev_col_index, monomial_coeffs->rows() - 1, 1) = 2 * monomial_coeffs->block(0, *next_col_index, monomial_coeffs->rows() - 1, 1); (*monomial_coeffs)(0, *prev_col_index) = 0; monomial_coeffs->col(*prev_col_index) -= monomial_coeffs->col(*current_col_index); const int tmp = *prev_col_index; *prev_col_index = *current_col_index; *current_col_index = *next_col_index; *next_col_index = tmp; } } // namespace Polynomial ChebyshevPolynomial::ToPolynomial() const { if (degree_ == 0) { // Return 1. return Polynomial(Monomial()); } else if (degree_ == 1) { // Return x. return Polynomial(Monomial(var_, 1)); } else if (degree_ == 2) { // Return 2x^2 - 1 return Polynomial({{Monomial(var_, 2), 2}, {Monomial(), -1}}); } else { // Use the recursion Tₙ₊₁(x) = 2xTₙ(x) − Tₙ₋₁(x) // We represent a Chebyshev polynomial as a map from monomial degree to its // coefficient, so T₂(x) = 2x²-1 is represented by a vector // Eigen::Vector3d(-1, 0, 2). Eigen::Matrix<int, Eigen::Dynamic, 3> monomial_coeffs = Eigen::Matrix<int, Eigen::Dynamic, 3>::Zero(degree_ + 1, 3); int next_col_index = 0; int current_col_index = 1; int prev_col_index = 2; // Set monomial_coeffs.col(0) to T₂(x) = 2x^2-1. monomial_coeffs(0, next_col_index) = -1; monomial_coeffs(2, next_col_index) = 2; // Set monomial_coeffs.col(1) to T₁(x) = x. monomial_coeffs(1, current_col_index) = 1; // Set monomial_coeffs.col(2) to T₀(x) = 1. monomial_coeffs(0, prev_col_index) = 1; // Now call ToPolynomialImpl for degree - 2 times, // monomial_coeffs.col(next_col_index) stores the monomial to coefficient // map for this Chebyshev polynomial. for (int i = 0; i < degree_ - 2; ++i) { ToPolynomialImpl(&monomial_coeffs, &next_col_index, &current_col_index, &prev_col_index); } Polynomial::MapType monomial_to_coefficient_map; for (int i = 0; i <= degree_; ++i) { if (monomial_coeffs(i, next_col_index) != 0) { monomial_to_coefficient_map.emplace(Monomial(var_, i), monomial_coeffs(i, next_col_index)); } } return Polynomial(monomial_to_coefficient_map); } } namespace { // At the beginning of the function // poly_prev_val stores Tₙ₋₁(x) // poly_curr_val stores Tₙ(x) // At the end of the function, we increment n by 1, and // poly_prev_val stores Tₙ(x) // poly_curr_val stores Tₙ₊₁(x) void EvalImpl(double x_val, double* poly_curr_val, double* poly_prev_val) { const double old_poly_curr_val = *poly_curr_val; *poly_curr_val = 2 * x_val * (*poly_curr_val) - (*poly_prev_val); *poly_prev_val = old_poly_curr_val; } } // namespace double EvaluateChebyshevPolynomial(double var_val, int degree) { if (degree == 0) { return 1; } else if (degree == 1) { return var_val; } else { // Instead of using the equation // Tₙ(x) = cos(n*arccos(x)) when -1 <= x <= 1 // Tₙ(x) = cosh(n*arccos(x)) when x >= 1 // Tₙ(x) = (-1)ⁿcosh(n*arccos(-x)) when x <= -1 // we compute the evaluation recursively. The main motivation is that the // recursive computation is numerically more stable than using arccos / // arccosh function. double poly_prev_val = 1; double poly_curr_val = var_val; for (int i = 0; i <= degree - 2; ++i) { EvalImpl(var_val, &poly_curr_val, &poly_prev_val); } return poly_curr_val; } } double ChebyshevPolynomial::Evaluate(double var_val) const { return EvaluateChebyshevPolynomial(var_val, degree_); } bool ChebyshevPolynomial::operator==(const ChebyshevPolynomial& other) const { if (degree() == 0 && other.degree() == 0) { return true; } return var().equal_to(other.var()) && degree() == other.degree(); } bool ChebyshevPolynomial::operator!=(const ChebyshevPolynomial& other) const { return !(*this == other); } std::vector<std::pair<ChebyshevPolynomial, double>> ChebyshevPolynomial::Differentiate() const { if (degree_ == 0) { // dT₀(x)/dx = 0, we return an empty vector. return std::vector<std::pair<ChebyshevPolynomial, double>>(); } if (degree_ % 2 == 0) { // even degree Chebyshev polynomial, its derivative is // dTₙ(x)/dx = 2n ∑ⱼ Tⱼ(x), j is odd and j <= n-1 std::vector<std::pair<ChebyshevPolynomial, double>> derivative; derivative.reserve(degree_ / 2); for (int j = 1; j <= degree_ / 2; ++j) { derivative.emplace_back(ChebyshevPolynomial(var_, 2 * j - 1), 2 * degree_); } return derivative; } else { // Odd degree Chebyshev polynomial, its derivative is dTₙ(x)/dx = 2n ∑ⱼ // Tⱼ(x) - n, j is even and j <= n-1 std::vector<std::pair<ChebyshevPolynomial, double>> derivative; derivative.reserve((degree_ + 1) / 2); // 2n*T₀(x) − n = n*T₀(x) since T₀(x)=1 derivative.emplace_back(ChebyshevPolynomial(var_, 0), degree_); for (int j = 1; j < (degree_ + 1) / 2; ++j) { derivative.emplace_back(ChebyshevPolynomial(var_, 2 * j), 2 * degree_); } return derivative; } } std::ostream& operator<<(std::ostream& out, const ChebyshevPolynomial& p) { if (p.degree() == 0) { out << "T0()"; } else { out << "T" << p.degree() << "(" << p.var() << ")"; } return out; } bool ChebyshevPolynomial::operator<(const ChebyshevPolynomial& other) const { // First the special case if either or both lhs and rhs has degree 0. if (degree() == 0 || other.degree() == 0) { return degree() < other.degree(); } else if (var().get_id() < other.var().get_id()) { return true; } else if (var() == other.var() && degree() < other.degree()) { return true; } return false; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/monomial_util.h
#pragma once #include <cstddef> #include <functional> #include <map> #include <set> #include <unordered_map> #include <Eigen/Core> #include "drake/common/drake_assert.h" #include "drake/common/hash.h" #include "drake/common/symbolic/polynomial.h" namespace drake { namespace symbolic { /** Implements Graded reverse lexicographic order. * * @tparam VariableOrder VariableOrder{}(v1, v2) is true if v1 < v2. * * We first compare the total degree of the monomial; if there is a tie, then we * use the lexicographical order as the tie breaker, but a monomial with higher * order in lexicographical order is considered lower order in graded reverse * lexicographical order. * * Take MonomialBasis({x, y, z}, 2) as an example, with the order x > y > z. To * get the graded reverse lexicographical order, we take the following steps: * * First find all the monomials using the total degree. The monomials with * degree 2 are {x^2, y^2, z^2, xy, xz, yz}. The monomials with degree 1 are {x, * y, z}, and the monomials with degree 0 is {1}. To break the tie between * monomials with the same total degree, first sort them in the reverse * lexicographical order, namely x < y < z in the reverse lexicographical * order. The lexicographical order compares two monomial by first comparing the * exponent of the largest variable, if there is a tie then go forth to the * second largest variable. Thus z^2 > zy >zx > y^2 > yx > x^2. Finally reverse * the order as x^2 > xy > y^2 > xz > yz > z^2. * * There is an introduction to monomial order in * https://en.wikipedia.org/wiki/Monomial_order, and an introduction to graded * reverse lexicographical order in * https://en.wikipedia.org/wiki/Monomial_order#Graded_reverse_lexicographic_order */ template <typename VariableOrder> struct GradedReverseLexOrder { /** Returns true if m1 > m2 under the Graded reverse lexicographic order. */ bool operator()(const Monomial& m1, const Monomial& m2) const { const int d1{m1.total_degree()}; const int d2{m2.total_degree()}; if (d1 > d2) { return true; } if (d2 > d1) { return false; } // d1 == d2 if (d1 == 0) { // Because both of them are 1. return false; } const std::map<Variable, int>& powers1{m1.get_powers()}; const std::map<Variable, int>& powers2{m2.get_powers()}; std::map<Variable, int>::const_iterator it1{powers1.cbegin()}; std::map<Variable, int>::const_iterator it2{powers2.cbegin()}; while (it1 != powers1.cend() && it2 != powers2.cend()) { const Variable& var1{it1->first}; const Variable& var2{it2->first}; const int exponent1{it1->second}; const int exponent2{it2->second}; if (variable_order_(var2, var1)) { return true; } else if (variable_order_(var1, var2)) { return false; } else { // var1 == var2 if (exponent1 == exponent2) { ++it1; ++it2; } else { return exponent2 > exponent1; } } } // When m1 and m2 are identical. return false; } private: VariableOrder variable_order_; }; namespace internal { /** Generates [b * m for m in MonomialBasis(vars, degree)] and push them to * bin. Used as a helper function to implement MonomialBasis. * * @tparam MonomialOrder provides a monomial ordering. * TODO(hongkai.dai): Remove this method and use * AddPolynomialBasisElementsOfDegreeN in polynomial_basis.h instead when we * deprecate Monomial class. */ template <typename MonomialOrder> void AddMonomialsOfDegreeN(const Variables& vars, int degree, const Monomial& b, std::set<Monomial, MonomialOrder>* const bin) { DRAKE_ASSERT(!vars.empty()); if (degree == 0) { bin->insert(b); return; } const Variable& var{*vars.cbegin()}; bin->insert(b * Monomial{var, degree}); if (vars.size() == 1) { return; } for (int i{degree - 1}; i >= 0; --i) { AddMonomialsOfDegreeN(vars - var, degree - i, b * Monomial{var, i}, bin); } } enum class DegreeType { kEven, ///< Even degree kOdd, ///< Odd degree kAny, ///< Any degree }; /** Returns all monomials up to a given degree under the graded reverse * lexicographic order. This is called by MonomialBasis functions defined below. * * @tparam rows Number of rows or Dynamic * @param degree_type If degree_type is kAny, then the monomials' degrees are no * larger than @p degree. If degree_type is kEven, then the monomial's degrees * are even numbers no larger than @p degree. If degree_type is kOdd, then the * monomial degrees are odd numbers no larger than @p degree. */ template <int rows> Eigen::Matrix<Monomial, rows, 1> ComputeMonomialBasis( const Variables& vars, int degree, DegreeType degree_type = DegreeType::kAny) { DRAKE_DEMAND(!vars.empty()); DRAKE_DEMAND(degree >= 0); // 1. Collect monomials. std::set<Monomial, GradedReverseLexOrder<std::less<Variable>>> monomials; int start_degree = 0; int degree_stride = 1; switch (degree_type) { case DegreeType::kAny: { start_degree = 0; degree_stride = 1; break; } case DegreeType::kEven: { start_degree = 0; degree_stride = 2; break; } case DegreeType::kOdd: { start_degree = 1; degree_stride = 2; } } for (int i = start_degree; i <= degree; i += degree_stride) { AddMonomialsOfDegreeN(vars, i, Monomial{}, &monomials); } // 2. Prepare the return value, basis. DRAKE_DEMAND((rows == Eigen::Dynamic) || (static_cast<size_t>(rows) == monomials.size())); Eigen::Matrix<Monomial, rows, 1> basis(monomials.size()); size_t i{0}; for (const auto& m : monomials) { basis[i] = m; i++; } return basis; } } // namespace internal /** Returns all monomials up to a given degree under the graded reverse * lexicographic order. Note that graded reverse lexicographic order uses the * total order among Variable which is based on a variable's unique ID. For * example, for a given variable ordering x > y > z, `MonomialBasis({x, y, z}, * 2)` returns a column vector `[x^2, xy, y^2, xz, yz, z^2, x, y, z, 1]`. * * @pre @p vars is a non-empty set. * @pre @p degree is a non-negative integer. */ Eigen::Matrix<Monomial, Eigen::Dynamic, 1> MonomialBasis(const Variables& vars, int degree); // Computes "n choose k", the number of ways, disregarding order, that k objects // can be chosen from among n objects. It is used in the following MonomialBasis // function. constexpr int NChooseK(int n, int k) { return (k == 0) ? 1 : (n * NChooseK(n - 1, k - 1)) / k; } /** Returns all monomials up to a given degree under the graded reverse * lexicographic order. * * @tparam n number of variables. * @tparam degree maximum total degree of monomials to compute. * * @pre @p vars is a non-empty set. * @pre vars.size() == @p n. */ template <int n, int degree> Eigen::Matrix<Monomial, NChooseK(n + degree, degree), 1> MonomialBasis( const Variables& vars) { static_assert(n > 0, "n should be a positive integer."); static_assert(degree >= 0, "degree should be a non-negative integer."); DRAKE_ASSERT(vars.size() == n); return internal::ComputeMonomialBasis<NChooseK(n + degree, degree)>(vars, degree); } /** Returns all the monomials (in graded reverse lexicographic order) such * that the total degree for each set of variables is no larger than a specific * degree. For example if x_set = {x₀, x₁} and y_set = {y₀, y₁}, then * MonomialBasis({{x_set, 2}, {y_set, 1}}) will include all the monomials, whose * total degree of x_set is no larger than 2, and the total degree of y_set is * no larger than 1. Hence it can include monomials such as x₀x₁y₀, but not * x₀y₀y₁ because the total degree for y_set is 2. So it would return the * following set of monomials (ignoring the ordering) {x₀²y₀, x₀²y₁, x₀x₁y₀, * x₀x₁y₁, x₁²y₀, x₁²y₀, x₀y₀, x₀y₁, x₁y₀, x₁y₁, x₀², x₀x₁, x₁², x₀, x₁, y₀, y₁, * 1}. * @param variables_degree `(vars, degree)` maps each set of variables `vars` to * the maximal degree of these variables in the monomial. Namely the summation * of the degree of each variable in `vars` is no larger than `degree`. * @pre The variables in `variables_degree` don't overlap. * @pre The degree in `variables_degree` are non-negative. */ [[nodiscard]] VectorX<Monomial> MonomialBasis( const std::unordered_map<Variables, int>& variables_degree); /** Returns all even degree monomials up to a given degree under the graded * reverse lexicographic order. A monomial has an even degree if its total * degree is even. So xy is an even degree monomial (degree 2) while x²y is not * (degree 3). Note that graded reverse lexicographic order uses the total order * among Variable which is based on a variable's unique ID. For example, for a * given variable ordering x > y > z, `EvenDegreeMonomialBasis({x, y, z}, 2)` * returns a column vector `[x², xy, y², xz, yz, z², 1]`. * * @pre @p vars is a non-empty set. * @pre @p degree is a non-negative integer. */ Eigen::Matrix<Monomial, Eigen::Dynamic, 1> EvenDegreeMonomialBasis( const Variables& vars, int degree); /** Returns all odd degree monomials up to a given degree under the graded * reverse lexicographic order. A monomial has an odd degree if its total * degree is odd. So x²y is an odd degree monomial (degree 3) while xy is not * (degree 2). Note that graded reverse lexicographic order uses the total order * among Variable which is based on a variable's unique ID. For example, for a * given variable ordering x > y > z, `OddDegreeMonomialBasis({x, y, z}, 3)` * returns a column vector `[x³, x²y, xy², y³, x²z, xyz, y²z, xz², yz², z³, x, * y, z]` * * @pre @p vars is a non-empty set. * @pre @p degree is a non-negative integer. */ Eigen::Matrix<Monomial, Eigen::Dynamic, 1> OddDegreeMonomialBasis( const Variables& vars, int degree); /** Generates all the monomials of `x`, such that the degree for x(i) is no larger than 1 for every x(i) in `x`. @param x The variables whose monomials are generated. @param sort_monomial If true, the returned monomials are sorted in the graded reverse lexicographic order. For example if x = (x₀, x₁) with x₀< x₁, then this function returns [x₀x₁, x₁, x₀, 1]. If sort_monomial=false, then we return the monomials in an arbitrary order. */ [[nodiscard]] VectorX<Monomial> CalcMonomialBasisOrderUpToOne( const Variables& x, bool sort_monomial = false); } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/monomial_basis_element.cc
#include "drake/common/symbolic/monomial_basis_element.h" #include <map> #include <numeric> #include <stdexcept> #include <utility> #include <vector> #include "drake/common/drake_assert.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 { namespace { // Converts a symbolic expression @p e into an internal representation of // Monomial class, a mapping from a base (Variable) to its exponent (int). This // function is called inside of the constructor Monomial(const // symbolic::Expression&). std::map<Variable, int> ToMonomialPower(const Expression& e) { // TODO(soonho): Re-implement this function by using a Polynomial visitor. DRAKE_DEMAND(e.is_polynomial()); std::map<Variable, int> powers; if (is_one(e)) { // This block is deliberately left empty. } else if (is_constant(e)) { throw std::runtime_error( "A constant not equal to 1, this is not a monomial."); } else if (is_variable(e)) { powers.emplace(get_variable(e), 1); } else if (is_pow(e)) { const Expression& base{get_first_argument(e)}; const Expression& exponent{get_second_argument(e)}; // The following holds because `e` is polynomial. DRAKE_DEMAND(is_constant(exponent)); // The following static_cast (double -> int) does not lose information // because of the precondition `e.is_polynomial()`. const int n{static_cast<int>(get_constant_value(exponent))}; powers = ToMonomialPower(base); // pow(base, n) => (∏ᵢ xᵢ)^ⁿ => ∏ᵢ (xᵢ^ⁿ) for (auto& p : powers) { p.second *= n; } } else if (is_multiplication(e)) { if (!is_one(get_constant_in_multiplication(e))) { throw std::runtime_error("The constant in the multiplication is not 1."); } // e = ∏ᵢ pow(baseᵢ, exponentᵢ). for (const auto& p : get_base_to_exponent_map_in_multiplication(e)) { for (const auto& q : ToMonomialPower(pow(p.first, p.second))) { auto it = powers.find(q.first); if (it == powers.end()) { powers.emplace(q.first, q.second); } else { it->second += q.second; } } } } else { throw std::runtime_error( "This expression cannot be converted to a monomial."); } return powers; } // Converts a pair of variables and their integer exponents into an internal // representation of Monomial class, a mapping from a base (Variable) to its // exponent (int). This function is called in the constructor taking the same // types of arguments. } // namespace MonomialBasisElement::MonomialBasisElement( const std::map<Variable, int>& var_to_degree_map) : PolynomialBasisElement(var_to_degree_map) {} MonomialBasisElement::MonomialBasisElement( const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& degrees) : PolynomialBasisElement(vars, degrees) {} MonomialBasisElement::MonomialBasisElement(const Variable& var) : MonomialBasisElement({{var, 1}}) {} MonomialBasisElement::MonomialBasisElement(const Variable& var, int degree) : MonomialBasisElement({{var, degree}}) {} MonomialBasisElement::MonomialBasisElement() : PolynomialBasisElement() {} MonomialBasisElement::MonomialBasisElement(const Expression& e) : MonomialBasisElement(ToMonomialPower(e.Expand())) {} bool MonomialBasisElement::operator<(const MonomialBasisElement& other) const { return this->lexicographical_compare(other); } std::pair<double, MonomialBasisElement> MonomialBasisElement::EvaluatePartial( const Environment& env) const { double coeff{}; std::map<Variable, int> new_basis_element; DoEvaluatePartial(env, &coeff, &new_basis_element); return std::make_pair(coeff, MonomialBasisElement(new_basis_element)); } double MonomialBasisElement::DoEvaluate(double variable_val, int degree) const { return std::pow(variable_val, degree); } Expression MonomialBasisElement::DoToExpression() const { // It builds this base_to_exponent_map and uses ExpressionMulFactory to build // a multiplication expression. 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(); } std::ostream& operator<<(std::ostream& out, const MonomialBasisElement& m) { if (m.var_to_degree_map().empty()) { return out << 1; } auto it = m.var_to_degree_map().begin(); out << it->first; if (it->second > 1) { out << "^" << it->second; } for (++it; it != m.var_to_degree_map().end(); ++it) { out << " * "; out << it->first; if (it->second > 1) { out << "^" << it->second; } } return out; } MonomialBasisElement& MonomialBasisElement::pow_in_place(const int p) { if (p < 0) { std::ostringstream oss; oss << "MonomialBasisElement::pow(int p) is called with a negative p = " << p; throw std::runtime_error(oss.str()); } if (p == 0) { int* total_degree = get_mutable_total_degree(); *total_degree = 0; get_mutable_var_to_degree_map()->clear(); } else if (p > 1) { for (auto& item : *get_mutable_var_to_degree_map()) { int& exponent{item.second}; exponent *= p; } int* total_degree = get_mutable_total_degree(); *total_degree *= p; } // If p == 1, NO OP. return *this; } std::map<MonomialBasisElement, double> MonomialBasisElement::Differentiate( const Variable& var) const { std::map<Variable, int> new_var_to_degree_map = var_to_degree_map(); auto it = new_var_to_degree_map.find(var); if (it == new_var_to_degree_map.end()) { return {}; } const int degree = it->second; it->second--; return {{MonomialBasisElement(new_var_to_degree_map), degree}}; } std::map<MonomialBasisElement, double> MonomialBasisElement::Integrate( const Variable& var) const { auto new_var_to_degree_map = var_to_degree_map(); auto it = new_var_to_degree_map.find(var); if (it == new_var_to_degree_map.end()) { // var is not a variable in var_to_degree_map. Append it to // new_var_to_degree_map. new_var_to_degree_map.emplace_hint(it, var, 1); return {{MonomialBasisElement(new_var_to_degree_map), 1.}}; } const int degree = it->second; it->second++; return {{MonomialBasisElement(new_var_to_degree_map), 1. / (degree + 1)}}; } namespace { // Convert a univariate monomial to a weighted sum of Chebyshev polynomials // For example x³ = 0.25T₃(x) + 0.75T₁(x) // We return a vector of (degree, coeff) to represent the weighted sum of // Chebyshev polynomials. For example, 0.25T₃(x) + 0.75T₁(x) is represented // as [(3, 0.25), (1, 0.75)]. std::vector<std::pair<int, double>> UnivariateMonomialToChebyshevBasis( int degree) { if (degree == 0) { // Return T0(x) return std::vector<std::pair<int, double>>{{{0, 1}}}; } // According to equation 3.35 of // https://archive.siam.org/books/ot99/OT99SampleChapter.pdf, we know that // xⁿ = 2 ¹⁻ⁿ∑ₖ cₖ Tₙ₋₂ₖ(x), k = 0, ..., floor(n/2) // where cₖ = 0.5 nchoosek(n, k) if k=n/2, and cₖ = nchoosek(n, k) // otherwise // Note that the euqation 3.35 of the referenced doc is not entirely correct, // specifically the special case (half the coefficient) should be k = n/2 // instead of k=0. const int half_n = degree / 2; std::vector<std::pair<int, double>> result(half_n + 1); result[0] = std::make_pair(degree, std::pow(2, 1 - degree)); for (int k = 1; k < half_n + 1; ++k) { // Use the relationshipe nchoosek(n, k) = nchoosek(n, k-1) * (n-k+1)/k double new_coeff = result[k - 1].second * static_cast<double>(degree - k + 1) / static_cast<double>(k); if (2 * k == degree) { new_coeff /= 2; } result[k] = std::make_pair(degree - 2 * k, new_coeff); } return result; } std::map<ChebyshevBasisElement, double> MonomialToChebyshevBasisRecursive( std::map<Variable, int> var_to_degree_map) { if (var_to_degree_map.empty()) { // 1 = T0() return {{ChebyshevBasisElement(), 1}}; } auto it = var_to_degree_map.begin(); const Variable var_first = it->first; // If we want to convert xⁿyᵐzˡ to Chebyshev basis, we could first convert xⁿ // to Chebyshev basis as xⁿ=∑ᵢcᵢTᵢ(x), and convert yᵐzˡ to Chebyshev basis as // yᵐzˡ = ∑ⱼ,ₖdⱼₖTⱼ(y)Tₖ(z), then we multiply them as // xⁿyᵐzˡ // = xⁿ*(yᵐzˡ) // = ∑ᵢcᵢTᵢ(x) * ∑ⱼ,ₖdⱼₖTⱼ(y)Tₖ(z) // = ∑ᵢ,ⱼ,ₖcᵢdⱼₖTᵢ(x)Tⱼ(y)Tₖ(z) // first_univariate_in_chebyshev contains the degree/coefficient pairs (i, cᵢ) // above. const std::vector<std::pair<int, double>> first_univariate_in_chebyshev = UnivariateMonomialToChebyshevBasis(it->second); var_to_degree_map.erase(it); // remaining_chebyshevs contains the chebyshev polynomial/coefficient pair // (Tⱼ(y)Tₖ(z), dⱼₖ) const std::map<ChebyshevBasisElement, double> remaining_chebyshevs = MonomialToChebyshevBasisRecursive(var_to_degree_map); std::map<ChebyshevBasisElement, double> result; for (const auto& [degree_x, coeff_x] : first_univariate_in_chebyshev) { for (const auto& [remaining_vars, coeff_remaining_vars] : remaining_chebyshevs) { std::map<Variable, int> new_chebyshev_var_to_degree_map = remaining_vars.var_to_degree_map(); // Multiply Tᵢ(x) to each term Tⱼ(y)Tₖ(z) to get the new // ChebyshevBasisElement. new_chebyshev_var_to_degree_map.emplace_hint( new_chebyshev_var_to_degree_map.end(), var_first, degree_x); // Multiply cᵢ to dⱼₖ to get the new coefficient. const double new_coeff = coeff_remaining_vars * coeff_x; result.emplace(ChebyshevBasisElement(new_chebyshev_var_to_degree_map), new_coeff); } } return result; } } // namespace std::map<ChebyshevBasisElement, double> MonomialBasisElement::ToChebyshevBasis() const { return MonomialToChebyshevBasisRecursive(var_to_degree_map()); } void MonomialBasisElement::MergeBasisElementInPlace( const MonomialBasisElement& other) { this->DoMergeBasisElementInPlace(other); } std::map<MonomialBasisElement, double> operator*( const MonomialBasisElement& m1, const MonomialBasisElement& m2) { std::map<Variable, int> var_to_degree_map_product = m1.var_to_degree_map(); for (const auto& [var, degree] : m2.var_to_degree_map()) { auto it = var_to_degree_map_product.find(var); if (it == var_to_degree_map_product.end()) { var_to_degree_map_product.emplace(var, degree); } else { it->second += degree; } } MonomialBasisElement product(var_to_degree_map_product); return std::map<MonomialBasisElement, double>{{{product, 1.}}}; } std::map<MonomialBasisElement, double> pow(MonomialBasisElement m, int p) { return std::map<MonomialBasisElement, double>{{{m.pow_in_place(p), 1.}}}; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/polynomial.h
#pragma once #include <algorithm> #include <functional> #include <map> #include <ostream> #include <unordered_map> #include <utility> #include <Eigen/Core> #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/common/symbolic/expression.h" #define DRAKE_COMMON_SYMBOLIC_POLYNOMIAL_H #include "drake/common/symbolic/monomial.h" #undef DRAKE_COMMON_SYMBOLIC_POLYNOMIAL_H namespace drake { namespace symbolic { namespace internal { /* Compares two monomials using the lexicographic order. It is used in symbolic::Polynomial::MapType. See https://en.wikipedia.org/wiki/Monomial_order for different monomial orders. */ struct CompareMonomial { bool operator()(const Monomial& m1, const Monomial& m2) const { const auto& powers1 = m1.get_powers(); const auto& powers2 = m2.get_powers(); return std::lexicographical_compare( powers1.begin(), powers1.end(), powers2.begin(), powers2.end(), [](const std::pair<const Variable, int>& p1, const std::pair<const Variable, int>& p2) { const Variable& v1{p1.first}; const int i1{p1.second}; const Variable& v2{p2.first}; const int i2{p2.second}; if (v1.less(v2)) { // m2 does not have the variable v1 explicitly, so we treat it as if // it has (v1)⁰. That is, we need "return i1 < 0", but i1 should be // positive, so this case always returns false. return false; } if (v2.less(v1)) { // m1 does not have the variable v2 explicitly, so we treat it as // if it has (v2)⁰. That is, we need "return 0 < i2", but i2 should // be positive, so it always returns true. return true; } return i1 < i2; }); } }; } // namespace internal /** Represents symbolic polynomials. A symbolic polynomial keeps a mapping from a monomial of indeterminates to its coefficient in a symbolic expression. A polynomial `p` has to satisfy an invariant such that `p.decision_variables() ∩ p.indeterminates() = ∅`. We have CheckInvariant() method to check the invariant. @anchor polynomial_variable_operation <h3> Operation between a %Polynomial and a %Variable </h3> Note that for arithmetic operations ⊕ (where ⊕ can be +,-,*) between a Polynomial `p` and a Variable `v`, if the variable `v` is an indeterminate of the polynomial `p`, then we regard `v` as a monomial with indeterminate `v` with coefficient 1; on the other hand, if the variable `v` is not an indeterminate of `p`, then we regard `v` as a monomial with 0 degree and coefficient `v`, and `v` will be appended to decision_variables() of the resulted polynomial. For example, if p = ax²+y where (x,y) are indeterminates and a is a decision variable, then in the operation p + y, the result stores the monomial-to-coefficient mapping as {(x² -> a), (y -> 2)}; on the other hand, in the operation p + b, b is regarded as a 0-degree monomial with coefficient b, and p + b stores the monomial-to-coefficient mapping as {(x² -> a), (y -> 1), (1 -> b)}, with (p + b).decision_variables() being {a, b}. If you want to append the variable `v` to the indeterminates of the p⊕v, then explicitly convert it to a monomial as p ⊕ symbolic::Monomial(v). <!-- TODO(hongkai.dai) when symbolic::GenericPolynomial is ready, we will deprecate symbolic::Polynomial class, and create an alias using symbolic::Polynomial=symbolic::GenericPolynomial<MonomialBasisElement>; We will copy the unit tests in symbolic_polynomial_test.cc to symbolic_generic_polynomial_test.cc --> */ class Polynomial { public: using MapType = std::map<Monomial, Expression, internal::CompareMonomial>; /** Constructs a zero polynomial. */ Polynomial() = default; DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Polynomial) /** Constructs a default value. This overload is used by Eigen when EIGEN_INITIALIZE_MATRICES_BY_ZERO is enabled. */ explicit Polynomial(std::nullptr_t) : Polynomial() {} /** Constructs a polynomial from a map, Monomial → Expression. */ explicit Polynomial(MapType map); /** Constructs a polynomial from a monomial `m`. Note that all variables in `m` are considered as indeterminates. Note that this implicit conversion is desirable to have a dot product of two Eigen::Vector<Monomial>s return a Polynomial. */ // NOLINTNEXTLINE(runtime/explicit) Polynomial(const Monomial& m); /** Constructs a polynomial from a varaible `v`. Note that v is considered an indeterminate. */ explicit Polynomial(const Variable& v); /** Constructs a polynomial from an expression `e`. Note that all variables in `e` are considered as indeterminates. @throws std::exception if `e` is not a polynomial. */ explicit Polynomial(const Expression& e); /** Constructs a polynomial from an expression `e` by decomposing it with respect to `indeterminates`. @note It collects the intersection of the variables appeared in `e` and the provided `indeterminates`. @throws std::exception if `e` is not a polynomial in `indeterminates`. */ Polynomial(const Expression& e, Variables indeterminates); /** Returns the indeterminates of this polynomial. */ [[nodiscard]] const Variables& indeterminates() const; /** Returns the decision variables of this polynomial. */ [[nodiscard]] const Variables& decision_variables() const; /** Sets the indeterminates to `new_indeterminates`. Changing the indeterminates would change `monomial_to_coefficient_map()`, and also potentially the degree of the polynomial. Here is an example. @code // p is a quadratic polynomial with x being the indeterminates. symbolic::Polynomial p(a * x * x + b * x + c, {x}); // p.monomial_to_coefficient_map() contains {1: c, x: b, x*x:a}. std::cout << p.TotalDegree(); // prints 2. // Now set (a, b, c) to the indeterminates. p becomes a linear // polynomial of a, b, c. p.SetIndeterminates({a, b, c}); // p.monomial_to_coefficient_map() now is {a: x * x, b: x, c: 1}. std::cout << p.TotalDegree(); // prints 1. @endcode */ void SetIndeterminates(const Variables& new_indeterminates); /** Returns the highest degree of this polynomial in a variable `v`. */ [[nodiscard]] int Degree(const Variable& v) const; /** Returns the total degree of this polynomial. */ [[nodiscard]] int TotalDegree() const; /** Returns the mapping from a Monomial to its corresponding coefficient of this polynomial. We maintain the invariance that for any [monomial, coeff] pair in monomial_to_coefficient_map(), symbolic:is_zero(coeff) is false. */ [[nodiscard]] const MapType& monomial_to_coefficient_map() const; /** Returns an equivalent symbolic expression of this polynomial. */ [[nodiscard]] Expression ToExpression() const; /** Differentiates this polynomial with respect to the variable `x`. Note that a variable `x` can be either a decision variable or an indeterminate. */ [[nodiscard]] Polynomial Differentiate(const Variable& x) const; /** Computes the Jacobian matrix J of the polynomial with respect to `vars`. J(0,i) contains ∂f/∂vars(i). */ template <typename Derived> [[nodiscard]] Eigen::Matrix<Polynomial, 1, Derived::RowsAtCompileTime> Jacobian(const Eigen::MatrixBase<Derived>& vars) const { static_assert(std::is_same_v<typename Derived::Scalar, Variable> && (Derived::ColsAtCompileTime == 1), "The argument of Polynomial::Jacobian should be a vector of " "symbolic variables."); const VectorX<Expression>::Index n{vars.size()}; Eigen::Matrix<Polynomial, 1, Derived::RowsAtCompileTime> J{1, n}; for (VectorX<Expression>::Index i = 0; i < n; ++i) { J(0, i) = Differentiate(vars(i)); } return J; } /** Integrates this polynomial with respect to an indeterminate `x`. Integration with respect to decision variables is not supported yet. If `x` is not an indeterminate nor decision variable, then it will be added to the list of indeterminates. @throws std::exception if `x` is a decision variable. */ [[nodiscard]] Polynomial Integrate(const Variable& x) const; /** Computes the definite integrate of this polynomial with respect to the indeterminate `x` over the domain [a, b]. Integration with respect to decision variables is not supported yet. @throws std::exception if `x` is a decision variable. */ [[nodiscard]] Polynomial Integrate(const Variable& x, double a, double b) const; /** Evaluates this polynomial under a given environment `env`. @throws std::exception if there is a variable in this polynomial whose assignment is not provided by `env`. */ [[nodiscard]] double Evaluate(const Environment& env) const; /** Partially evaluates this polynomial using an environment `env`. @throws std::exception if NaN is detected during evaluation. */ [[nodiscard]] Polynomial EvaluatePartial(const Environment& env) const; /** Partially evaluates this polynomial by substituting `var` with `c`. @throws std::exception if NaN is detected at any point during evaluation. */ [[nodiscard]] Polynomial EvaluatePartial(const Variable& var, double c) const; /** Evaluates the polynomial at a batch of indeterminates values. @param[in] indeterminates Must include all `this->indeterminates()` @param[in] indeterminates_values Each column of `indeterminates_values` stores one specific value of `indeterminates`; `indeterminates_values.rows() == indeterminates.rows()`. @return polynomial_values polynomial_values(j) is obtained by substituting indeterminates(i) in this polynomial with indeterminates_values(i, j) for all i. @throw std::exception if any coefficient in this polynomial is not a constant. */ [[nodiscard]] Eigen::VectorXd EvaluateIndeterminates( const Eigen::Ref<const VectorX<symbolic::Variable>>& indeterminates, const Eigen::Ref<const Eigen::MatrixXd>& indeterminates_values) const; /** Evaluates the polynomial at a batch of indeterminate values. For a polynomial whose coefficients are affine expressions of decision variables, we evaluate this polynomial on a batch of indeterminate values, and return the matrix representation of the evaluated affine expressions. For example if p(x) = (a+1)x² + b*x where a, b are decision variables, if we evaluate this polynomial on x = 1 and x = 2, then p(x) = a+b+1 and 4a+2b+4 respectively. We return the evaluation result as A * decision_variables + b, where A.row(i) * decision_variables + b(i) is the evaluation of the polynomial on indeterminates_values.col(i). @param[in] indeterminates Must include all this->indeterminates() @param[in] indeterminates_values A matrix representing a batch of values. Each column of `indeterminates_values` stores one specific value of `indeterminates`, where `indeterminates_values.rows() == indeterminates.rows()`. @param[out] A The coefficient of the evaluation results. @param[out] decision_variables The decision variables in the evaluation results. @param[out] b The constant terms in the evaluation results. @throw std::exception if the coefficients of this polynomial is not an affine expression of its decision variables. For example, the polynomial (2+sin(a)) * x² + 1 (where `a` is a decision variable and `x` is a indeterminate) doesn't have affine expression as its coefficient 2+sin(a). */ void EvaluateWithAffineCoefficients( const Eigen::Ref<const VectorX<symbolic::Variable>>& indeterminates, const Eigen::Ref<const Eigen::MatrixXd>& indeterminates_values, Eigen::MatrixXd* A, VectorX<symbolic::Variable>* decision_variables, Eigen::VectorXd* b) const; /** Adds `coeff` * `m` to this polynomial. */ Polynomial& AddProduct(const Expression& coeff, const Monomial& m); /** An encapsulated data type for use with the method SubstituteAndExpand. */ struct SubstituteAndExpandCacheData { public: std::map<Monomial, Polynomial, internal::CompareMonomial>* get_data() { return &data_; } private: friend class Polynomial; std::map<Monomial, Polynomial, internal::CompareMonomial> data_; }; /** Substitutes the monomials of this polynomial with new polynomial expressions and expand the polynomial to the monomial basis. For example, consider the substitution x = a(1-y) into the polynomial x¹⁴ + (x−1)². Repeatedly expanding the powers of x can take a long time using factory methods, so we store intermediate computations in the substitution map to avoid recomputing very high powers. @param indeterminate_substitution The substitutions of every indeterminate with the new desired expression. This map must contain each element of `indeterminates()`. For performance reasons, it is recommended that this map contains Expanded polynomials as its values, but this is not necessary. @param[in,out] substitutions_cached_data A container caching the higher order expansions of the `indeterminate_substitutions`. Typically, the first time an indeterminate_substitution is performed, this will be empty. If the same indeterminate_substitutions is used for multiple polynomials, passing this value will enable the user to re-use the expansions across multiple calls. For example, suppose we wish to perform the substitution x = a(1-y) into the polynomials p1 = x¹⁴ + (x−1)² and p2 = x⁷. A user may call p1.SubstituteAndExpand({x : a(1-y), substitutions_cached_data}) where substitutions_cached_data is a pointer to an empty container. As part of computing the expansion of p1, the expansion of x⁷ may get computed and stored in substitutions_cached_data, and so a subsequent call of p2.SubstituteAndExpand({x : a(1-y)}, substitutions_cached_data) would be very fast. Never reuse substitutions_cached_data if indeterminate_substitutions changes as this function will then compute an incorrect result. Note that this function is NOT responsible for ensuring that `substitutions_cached_data` is consistent i.e. this method will not throw an error if substitutions_cached_data contains the inconsistent substitutions {x: y, x²: 2y}. To ensure correct results, ensure that the passed substitutions_cached_data object is consistent with indeterminate_substitutions. The easiest way to do this is to pass a pointer to an empty substitutions_cached_data or nullopt to this function. */ [[nodiscard]] Polynomial SubstituteAndExpand( const std::unordered_map<Variable, Polynomial>& indeterminate_substitution, SubstituteAndExpandCacheData* substitutions_cached_data = nullptr) const; /** Expands each coefficient expression and returns the expanded polynomial. If any coefficient is equal to 0 after expansion, then remove that term from the returned polynomial. */ [[nodiscard]] Polynomial Expand() const; /** Removes the terms whose absolute value of the coefficients are smaller than or equal to `coefficient_tol`. For example, if the polynomial is 2x² + 3xy + 10⁻⁴x - 10⁻⁵, then after calling RemoveTermsWithSmallCoefficients(1e-3), the returned polynomial becomes 2x² + 3xy. @param coefficient_tol A positive scalar. @retval polynomial_cleaned A polynomial whose terms with small coefficients are removed. */ [[nodiscard]] Polynomial RemoveTermsWithSmallCoefficients( double coefficient_tol) const; /** Returns true if the polynomial is even, namely p(x) = p(-x). Meaning that the coefficient for all odd-degree monomials are 0. Returns false otherwise. Note that this is different from the p.TotalDegree() being an even number. */ [[nodiscard]] bool IsEven() const; /** Returns true if the polynomial is odd, namely p(x) = -p(-x). Meaning that the coefficient for all even-degree monomials are 0. Returns false otherwise. Note that this is different from the p.TotalDegree() being an odd number. */ [[nodiscard]] bool IsOdd() const; /** Returns the roots of a _univariate_ polynomial with constant coefficients as a column vector. There is no specific guarantee on the order of the returned roots. @throws std::exception if `this` is not univariate with constant coefficients. */ [[nodiscard]] Eigen::VectorXcd Roots() const; Polynomial& operator+=(const Polynomial& p); Polynomial& operator+=(const Monomial& m); Polynomial& operator+=(double c); /** Depending on whether `v` is an indeterminate of this polynomial, this operation generates different results. Refer to @ref polynomial_variable_operation "the class documentation" for more details. */ Polynomial& operator+=(const Variable& v); Polynomial& operator-=(const Polynomial& p); Polynomial& operator-=(const Monomial& m); Polynomial& operator-=(double c); /** Depending on whether `v` is an indeterminate of this polynomial, this operation generates different results. Refer to @ref polynomial_variable_operation "the class documentation" for more details. */ Polynomial& operator-=(const Variable& v); Polynomial& operator*=(const Polynomial& p); Polynomial& operator*=(const Monomial& m); Polynomial& operator*=(double c); /** Depending on whether `v` is an indeterminate of this polynomial, this operation generates different results. Refer to @ref polynomial_variable_operation "the class documentation" for more details. */ Polynomial& operator*=(const Variable& v); /** Returns true if this polynomial and `p` are structurally equal. */ [[nodiscard]] bool EqualTo(const Polynomial& p) const; /** Returns true if this polynomial and `p` are almost equal (the difference in the corresponding coefficients are all less than `tolerance`), after expanding the coefficients. */ [[nodiscard]] bool CoefficientsAlmostEqual(const Polynomial& p, double tolerance) const; /** Returns a symbolic formula representing the condition where this polynomial and `p` are the same. */ [[nodiscard]] Formula operator==(const Polynomial& p) const; /** Returns a symbolic formula representing the condition where this polynomial and `p` are not the same. */ [[nodiscard]] Formula operator!=(const Polynomial& p) const; /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const Polynomial& item) noexcept { using drake::hash_append; for (const auto& p : item.monomial_to_coefficient_map_) { hash_append(hasher, p.first); hash_append(hasher, p.second); } } friend Polynomial operator/(Polynomial p, double v); private: // Throws std::exception if any of the condition is true. // 1. There is a variable appeared in both of decision_variables() and // indeterminates(). // 2. There is a [monomial, coeff] pair in monomial_to_coefficient_map_ that // symbolic::is_zero(coeff) is true. void CheckInvariant() const; MapType monomial_to_coefficient_map_; Variables indeterminates_; Variables decision_variables_; }; /** Unary minus operation for polynomial. */ [[nodiscard]] Polynomial operator-(const Polynomial& p); [[nodiscard]] Polynomial operator+(Polynomial p1, const Polynomial& p2); [[nodiscard]] Polynomial operator+(Polynomial p, const Monomial& m); [[nodiscard]] Polynomial operator+(Polynomial p, double c); [[nodiscard]] Polynomial operator+(const Monomial& m, Polynomial p); [[nodiscard]] Polynomial operator+(const Monomial& m1, const Monomial& m2); [[nodiscard]] Polynomial operator+(const Monomial& m, double c); [[nodiscard]] Polynomial operator+(double c, Polynomial p); [[nodiscard]] Polynomial operator+(double c, const Monomial& m); [[nodiscard]] Polynomial operator+(Polynomial p, const Variable& v); [[nodiscard]] Polynomial operator+(const Variable& v, Polynomial p); [[nodiscard]] Expression operator+(const Expression& e, const Polynomial& p); [[nodiscard]] Expression operator+(const Polynomial& p, const Expression& e); [[nodiscard]] Polynomial operator-(Polynomial p1, const Polynomial& p2); [[nodiscard]] Polynomial operator-(Polynomial p, const Monomial& m); [[nodiscard]] Polynomial operator-(Polynomial p, double c); [[nodiscard]] Polynomial operator-(const Monomial& m, Polynomial p); [[nodiscard]] Polynomial operator-(const Monomial& m1, const Monomial& m2); [[nodiscard]] Polynomial operator-(const Monomial& m, double c); [[nodiscard]] Polynomial operator-(double c, Polynomial p); [[nodiscard]] Polynomial operator-(double c, const Monomial& m); [[nodiscard]] Polynomial operator-(Polynomial p, const Variable& v); [[nodiscard]] Polynomial operator-(const Variable& v, const Polynomial& p); [[nodiscard]] Expression operator-(const Expression& e, const Polynomial& p); [[nodiscard]] Expression operator-(const Polynomial& p, const Expression& e); [[nodiscard]] Polynomial operator*(Polynomial p1, const Polynomial& p2); [[nodiscard]] Polynomial operator*(Polynomial p, const Monomial& m); [[nodiscard]] Polynomial operator*(Polynomial p, double c); [[nodiscard]] Polynomial operator*(const Monomial& m, Polynomial p); // Note that `Monomial * Monomial -> Monomial` is provided in // monomial.h file. [[nodiscard]] Polynomial operator*(const Monomial& m, double c); [[nodiscard]] Polynomial operator*(double c, Polynomial p); [[nodiscard]] Polynomial operator*(double c, const Monomial& m); [[nodiscard]] Polynomial operator*(Polynomial p, const Variable& v); [[nodiscard]] Polynomial operator*(const Variable& v, Polynomial p); [[nodiscard]] Expression operator*(const Expression& e, const Polynomial& p); [[nodiscard]] Expression operator*(const Polynomial& p, const Expression& e); /** Returns `p / v`. */ [[nodiscard]] Polynomial operator/(Polynomial p, double v); [[nodiscard]] Expression operator/(double v, const Polynomial& p); [[nodiscard]] Expression operator/(const Expression& e, const Polynomial& p); [[nodiscard]] Expression operator/(const Polynomial& p, const Expression& e); /** Returns polynomial `p` raised to `n`. */ [[nodiscard]] Polynomial pow(const Polynomial& p, int n); std::ostream& operator<<(std::ostream& os, const Polynomial& p); /** Provides the following matrix operations: - Matrix<Polynomial> * Matrix<Monomial> => Matrix<Polynomial> - Matrix<Polynomial> * Matrix<Variable> => Matrix<Polynomial> - Matrix<Polynomial> * Matrix<double> => Matrix<Polynomial> - Matrix<Monomial> * Matrix<Polynomial> => Matrix<Polynomial> - Matrix<Monomial> * Matrix<Monomial> => Matrix<Polynomial> - Matrix<Monomial> * Matrix<Variable> => Matrix<Polynomial> - Matrix<Monomial> * Matrix<double> => Matrix<Polynomial> - Matrix<Variable> * Matrix<Polynomial> => Matrix<Polynomial> - Matrix<Variable> * Matrix<Monomial> => Matrix<Polynomial> - Matrix<double> * Matrix<Polynomial> => Matrix<Polynomial> - Matrix<double> * Matrix<Monomial> => Matrix<Polynomial> @note that these operator overloadings are necessary even after providing Eigen::ScalarBinaryOpTraits. See https://stackoverflow.com/questions/41494288/mixing-scalar-types-in-eigen for more information. */ #if defined(DRAKE_DOXYGEN_CXX) template <typename MatrixL, typename MatrixR> Eigen::Matrix<Polynomial, MatrixL::RowsAtCompileTime, MatrixR::ColsAtCompileTime> operator*(const MatrixL& lhs, const MatrixR& rhs); #else // clang-format off template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && // The LHS and RHS must be one of {Polynomial, Monomial, Variable, double}. (std::is_same_v<typename MatrixL::Scalar, Polynomial> || std::is_same_v<typename MatrixL::Scalar, Monomial> || std::is_same_v<typename MatrixL::Scalar, Variable> || std::is_same_v<typename MatrixL::Scalar, double>) && (std::is_same_v<typename MatrixR::Scalar, Polynomial> || std::is_same_v<typename MatrixR::Scalar, Monomial> || std::is_same_v<typename MatrixR::Scalar, Variable> || std::is_same_v<typename MatrixR::Scalar, double>) && // The LHS or RHS must be one of {Polynomial, Monomial}. (std::is_same_v<typename MatrixL::Scalar, Polynomial> || std::is_same_v<typename MatrixL::Scalar, Monomial> || std::is_same_v<typename MatrixR::Scalar, Polynomial> || std::is_same_v<typename MatrixR::Scalar, Monomial>) && // No specialization for Polynomial x Polynomial. !(std::is_same_v<typename MatrixL::Scalar, Polynomial> && std::is_same_v<typename MatrixR::Scalar, Polynomial>), Eigen::Matrix<Polynomial, MatrixL::RowsAtCompileTime, MatrixR::ColsAtCompileTime>> operator*(const MatrixL& lhs, const MatrixR& rhs) { return lhs.template cast<Polynomial>() * rhs.template cast<Polynomial>(); } // clang-format on #endif /** Provides the following matrix operations: - Matrix<Expression> * Matrix<Polynomial> => Matrix<Expression> - Matrix<Expression> * Matrix<Monomial> => Matrix<Expression> - Matrix<Polynomial> * Matrix<Expression> => Matrix<Expression> - Matrix<Monomial> * Matrix<Expression> => Matrix<Expression> @note that these operator overloadings are necessary even after providing Eigen::ScalarBinaryOpTraits. See https://stackoverflow.com/questions/41494288/mixing-scalar-types-in-eigen for more information. */ #if defined(DRAKE_DOXYGEN_CXX) template <typename MatrixL, typename MatrixR> Eigen::Matrix<Polynomial, MatrixL::RowsAtCompileTime, MatrixR::ColsAtCompileTime> operator*(const MatrixL& lhs, const MatrixR& rhs); #else // clang-format off template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && // The LHS and RHS must be one of {Expression, Polynomial, Monomial}. (std::is_same_v<typename MatrixL::Scalar, Expression> || std::is_same_v<typename MatrixL::Scalar, Polynomial> || std::is_same_v<typename MatrixL::Scalar, Monomial>) && (std::is_same_v<typename MatrixR::Scalar, Expression> || std::is_same_v<typename MatrixR::Scalar, Polynomial> || std::is_same_v<typename MatrixR::Scalar, Monomial>) && // Exactly one of the two sides must be an Expresion. (std::is_same_v<typename MatrixL::Scalar, Expression> ^ std::is_same_v<typename MatrixR::Scalar, Expression>), Eigen::Matrix<Expression, MatrixL::RowsAtCompileTime, MatrixR::ColsAtCompileTime>> operator*(const MatrixL& lhs, const MatrixR& rhs) { return lhs.template cast<Expression>() * rhs.template cast<Expression>(); } // clang-format on #endif } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::Polynomial>. */ template <> struct hash<drake::symbolic::Polynomial> : public drake::DefaultHash {}; #if defined(__GLIBCXX__) /* Informs GCC that this hash function is not so fast (i.e. for-loop inside). This will enforce caching of hash results. See https://gcc.gnu.org/onlinedocs/libstdc++/manual/unordered_associative.html for details. */ template <> struct __is_fast_hash<hash<drake::symbolic::Polynomial>> : std::false_type {}; #endif } // namespace std #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { /* Defines Eigen traits needed for Matrix<drake::symbolic::Polynomial>. */ template <> struct NumTraits<drake::symbolic::Polynomial> : GenericNumTraits<drake::symbolic::Polynomial> { static inline int digits10() { return 0; } }; /* Informs Eigen that BinaryOp(LhsType, RhsType) gets ResultType. */ #define DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS(LhsType, RhsType, BinaryOp, \ ResultType) \ template <> \ struct ScalarBinaryOpTraits<LhsType, RhsType, BinaryOp<LhsType, RhsType>> { \ enum { Defined = 1 }; \ typedef ResultType ReturnType; \ }; /* Informs Eigen that LhsType op RhsType gets ResultType where op ∈ {+, -, *, conj_product}. */ #define DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( \ LhsType, RhsType, ResultType) \ DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS(LhsType, RhsType, \ internal::scalar_sum_op, ResultType) \ DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS( \ LhsType, RhsType, internal::scalar_difference_op, ResultType) \ DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS( \ LhsType, RhsType, internal::scalar_product_op, ResultType) \ DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS( \ LhsType, RhsType, internal::scalar_conj_product_op, ResultType) /* Informs Eigen that Polynomial op Monomial gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Polynomial, drake::symbolic::Monomial, drake::symbolic::Polynomial) /* Informs Eigen that Polynomial op Variable gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Polynomial, drake::symbolic::Variable, drake::symbolic::Polynomial) /* Informs Eigen that Polynomial op double gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Polynomial, double, drake::symbolic::Polynomial) /* Informs Eigen that Monomial op Polynomial gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Monomial, drake::symbolic::Polynomial, drake::symbolic::Polynomial) /* Informs Eigen that Variable op Polynomial gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Variable, drake::symbolic::Polynomial, drake::symbolic::Polynomial) /* Informs Eigen that Monomial op Monomial gets Polynomial where op ∈ {+, -, *, conj_product}. Note that we inform Eigen that the return type of Monomial op Monomial is Polynomial, not Monomial, while Monomial * Monomial gets a Monomial in our implementation. This discrepancy is due to the implementation of Eigen's dot() method whose return type is scalar_product_op::ReturnType. For more information, check line 67 of Eigen/src/Core/Dot.h and line 767 of Eigen/src/Core/util/XprHelper.h. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Monomial, drake::symbolic::Monomial, drake::symbolic::Polynomial) /* Informs Eigen that Variable op Monomial gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Variable, drake::symbolic::Monomial, drake::symbolic::Polynomial) /* Informs Eigen that Monomial op Variable gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Monomial, drake::symbolic::Variable, drake::symbolic::Polynomial) /* Informs Eigen that Monomial op double gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Monomial, double, drake::symbolic::Polynomial) /* Informs Eigen that double op Polynomial gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( double, drake::symbolic::Polynomial, drake::symbolic::Polynomial) /* Informs Eigen that double op Monomial gets Polynomial where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( double, drake::symbolic::Monomial, drake::symbolic::Polynomial) /* Informs Eigen that Polynomial op Expression gets Expression where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Polynomial, drake::symbolic::Expression, drake::symbolic::Expression) /* Informs Eigen that Expression op Polynomial gets Expression where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Expression, drake::symbolic::Polynomial, drake::symbolic::Expression) /* Informs Eigen that Monomial op Expression gets Expression where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Monomial, drake::symbolic::Expression, drake::symbolic::Expression) /* Informs Eigen that Expression op Monomial gets Expression where op ∈ {+, -, *, conj_product}. */ DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS( drake::symbolic::Expression, drake::symbolic::Monomial, drake::symbolic::Expression) #undef DRAKE_SYMBOLIC_SCALAR_SUM_DIFF_PRODUCT_CONJ_PRODUCT_TRAITS #undef DRAKE_SYMBOLIC_SCALAR_BINARY_OP_TRAITS namespace internal { /* Informs Eigen how to cast drake::symbolic::Polynomial to drake::symbolic::Expression. */ template <> EIGEN_DEVICE_FUNC inline drake::symbolic::Expression cast( const drake::symbolic::Polynomial& p) { return p.ToExpression(); } } // namespace internal namespace numext { template <> bool equal_strict(const drake::symbolic::Polynomial& x, const drake::symbolic::Polynomial& y); template <> EIGEN_STRONG_INLINE bool not_equal_strict( const drake::symbolic::Polynomial& x, const drake::symbolic::Polynomial& y) { return !Eigen::numext::equal_strict(x, y); } } // namespace numext } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX) namespace drake { namespace symbolic { /** Evaluates a matrix `m` of symbolic polynomials using `env`. @returns a matrix of double whose size is the size of `m`. @throws std::exception if NaN is detected during evaluation. @pydrake_mkdoc_identifier{polynomial} */ template <typename Derived> [[nodiscard]] std::enable_if_t< std::is_same_v<typename Derived::Scalar, Polynomial>, MatrixLikewise<double, Derived>> Evaluate(const Eigen::MatrixBase<Derived>& m, const Environment& env) { return m.unaryExpr([&env](const Polynomial& p) { return p.Evaluate(env); }); } /** Computes the Jacobian matrix J of the vector function `f` with respect to `vars`. J(i,j) contains ∂f(i)/∂vars(j). @pre `vars` is non-empty. @pydrake_mkdoc_identifier{polynomial} */ [[nodiscard]] MatrixX<Polynomial> Jacobian( const Eigen::Ref<const VectorX<Polynomial>>& f, const Eigen::Ref<const VectorX<Variable>>& vars); /** Returns the polynomial m(x)ᵀ * Q * m(x), where m(x) is the monomial basis, and Q is the Gram matrix. @param monomial_basis m(x) in the documentation. A vector of monomials. @param gram_lower The lower triangular entries in Q, stacked columnwise into a vector. */ template <typename Derived1, typename Derived2> [[nodiscard]] typename std::enable_if< is_eigen_vector_of<Derived1, symbolic::Monomial>::value && (is_eigen_vector_of<Derived2, double>::value || is_eigen_vector_of<Derived2, symbolic::Variable>::value || is_eigen_vector_of<Derived2, symbolic::Expression>::value), symbolic::Polynomial>::type CalcPolynomialWLowerTriangularPart( const Eigen::MatrixBase<Derived1>& monomial_basis, const Eigen::MatrixBase<Derived2>& gram_lower) { DRAKE_DEMAND(monomial_basis.rows() * (monomial_basis.rows() + 1) / 2 == gram_lower.rows()); Polynomial::MapType monomial_coeff_map; for (int j = 0; j < monomial_basis.rows(); ++j) { for (int i = j; i < monomial_basis.rows(); ++i) { // Compute 2 * mᵢ(x) * Qᵢⱼ * mⱼ(x) if i != j, or mᵢ(x)²*Qᵢᵢ const auto monomial_product = monomial_basis(i) * monomial_basis(j); const auto& Qij = gram_lower(monomial_basis.rows() * j + i - (j + 1) * j / 2); const symbolic::Expression coeff = i == j ? Qij : 2 * Qij; auto it = monomial_coeff_map.find(monomial_product); if (it == monomial_coeff_map.end()) { monomial_coeff_map.emplace_hint(it, monomial_product, coeff); } else { it->second += coeff; } } } return Polynomial(monomial_coeff_map); } } // namespace symbolic } // namespace drake // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::symbolic::Polynomial> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/rational_function.cc
#include "drake/common/symbolic/rational_function.h" #include <utility> namespace drake { namespace symbolic { RationalFunction::RationalFunction() : numerator_{} /* zero polynomial */, denominator_{1} {} RationalFunction::RationalFunction(Polynomial numerator, Polynomial denominator) : numerator_{std::move(numerator)}, denominator_{std::move(denominator)} { DRAKE_DEMAND(!denominator_.monomial_to_coefficient_map() .empty() /* zero polynomial */); DRAKE_ASSERT_VOID(CheckIndeterminates()); } RationalFunction::RationalFunction(const Polynomial& p) : RationalFunction(p, Polynomial(1)) {} RationalFunction::RationalFunction(const Monomial& m) : RationalFunction(Polynomial(m)) {} RationalFunction::RationalFunction(double c) : RationalFunction(Polynomial(c), Polynomial(1)) {} bool RationalFunction::EqualTo(const RationalFunction& f) const { return numerator_.EqualTo(f.numerator()) && denominator_.EqualTo(f.denominator()); } double RationalFunction::Evaluate(const Environment& env) const { return numerator_.Evaluate(env) / denominator_.Evaluate(env); } Formula RationalFunction::operator==(const RationalFunction& f) const { return denominator_ * f.numerator() == numerator_ * f.denominator(); } Formula RationalFunction::operator!=(const RationalFunction& f) const { return !(*this == f); } std::ostream& operator<<(std::ostream& os, const RationalFunction& f) { os << "(" << f.numerator() << ") / (" << f.denominator() << ")"; return os; } void RationalFunction::CheckIndeterminates() const { const Variables vars1{intersect(numerator_.indeterminates(), denominator_.decision_variables())}; const Variables vars2{intersect(numerator_.decision_variables(), denominator_.indeterminates())}; if (!vars1.empty() || !vars2.empty()) { std::ostringstream oss; oss << "RationalFunction " << *this << " is invalid.\n"; if (!vars1.empty()) { oss << "The following variable(s) " "are used as indeterminates in the numerator and decision " "variables in the denominator at the same time:\n" << vars1 << ".\n"; } if (!vars2.empty()) { oss << "The following variable(s) " "are used as decision variables in the numerator and " "indeterminates variables in the denominator at the same time:\n" << vars2 << ".\n"; } throw std::logic_error(oss.str()); } } Expression RationalFunction::ToExpression() const { return numerator_.ToExpression() / denominator_.ToExpression(); } RationalFunction& RationalFunction::operator+=(const RationalFunction& f) { if (f.denominator().EqualTo(denominator_)) { numerator_ = numerator_ + f.numerator(); } else { numerator_ = numerator_ * f.denominator() + denominator_ * f.numerator(); denominator_ *= f.denominator(); } return *this; } RationalFunction& RationalFunction::operator+=(const Polynomial& p) { numerator_ = p * denominator_ + numerator_; return *this; } RationalFunction& RationalFunction::operator+=(const Monomial& m) { numerator_ = m * denominator_ + numerator_; return *this; } RationalFunction& RationalFunction::operator+=(double c) { numerator_ = c * denominator_ + numerator_; return *this; } RationalFunction& RationalFunction::operator-=(const RationalFunction& f) { *this += -f; return *this; } RationalFunction& RationalFunction::operator-=(const Polynomial& p) { *this += -p; return *this; } RationalFunction& RationalFunction::operator-=(const Monomial& m) { *this += -m; return *this; } RationalFunction& RationalFunction::operator-=(double c) { return *this += -c; } RationalFunction& RationalFunction::operator*=(const RationalFunction& f) { numerator_ *= f.numerator(); denominator_ *= f.denominator(); DRAKE_ASSERT_VOID(CheckIndeterminates()); return *this; } RationalFunction& RationalFunction::operator*=(const Polynomial& p) { numerator_ *= p; DRAKE_ASSERT_VOID(CheckIndeterminates()); return *this; } RationalFunction& RationalFunction::operator*=(const Monomial& m) { numerator_ *= m; DRAKE_ASSERT_VOID(CheckIndeterminates()); return *this; } RationalFunction& RationalFunction::operator*=(double c) { numerator_ *= c; return *this; } RationalFunction& RationalFunction::operator/=(const RationalFunction& f) { if (f.numerator().monomial_to_coefficient_map().empty()) { throw std::logic_error("RationalFunction: operator/=: The divider is 0."); } numerator_ *= f.denominator(); denominator_ *= f.numerator(); DRAKE_ASSERT_VOID(CheckIndeterminates()); return *this; } RationalFunction& RationalFunction::operator/=(const Polynomial& p) { if (p.monomial_to_coefficient_map().empty()) { throw std::logic_error("RationalFunction: operator/=: The divider is 0."); } denominator_ *= p; DRAKE_ASSERT_VOID(CheckIndeterminates()); return *this; } RationalFunction& RationalFunction::operator/=(const Monomial& m) { if (m.total_degree() == 0) { throw std::logic_error("RationalFunction: operator/=: The divider is 0."); } denominator_ *= m; DRAKE_ASSERT_VOID(CheckIndeterminates()); return *this; } RationalFunction& RationalFunction::operator/=(double c) { if (c == 0) { throw std::logic_error("RationalFunction: operator/=: The divider is 0."); } denominator_ *= c; return *this; } RationalFunction operator-(RationalFunction f) { f.numerator_ *= -1; return f; } RationalFunction operator+(RationalFunction f1, const RationalFunction& f2) { return f1 += f2; } RationalFunction operator+(RationalFunction f, const Polynomial& p) { return f += p; } RationalFunction operator+(const Polynomial& p, RationalFunction f) { return f += p; } RationalFunction operator+(RationalFunction f, const Monomial& m) { return f += m; } RationalFunction operator+(const Monomial& m, RationalFunction f) { return f += m; } RationalFunction operator+(RationalFunction f, double c) { return f += c; } RationalFunction operator+(double c, RationalFunction f) { return f += c; } RationalFunction operator-(RationalFunction f1, const RationalFunction& f2) { return f1 -= f2; } RationalFunction operator-(RationalFunction f, const Polynomial& p) { return f -= p; } RationalFunction operator-(const Polynomial& p, const RationalFunction& f) { return -f + p; } RationalFunction operator-(RationalFunction f, const Monomial& m) { return f -= m; } RationalFunction operator-(const Monomial& m, RationalFunction f) { return -f + m; } RationalFunction operator-(RationalFunction f, double c) { return f -= c; } RationalFunction operator-(double c, RationalFunction f) { return f = -f + c; } RationalFunction operator*(RationalFunction f1, const RationalFunction& f2) { return f1 *= f2; } RationalFunction operator*(RationalFunction f, const Polynomial& p) { return f *= p; } RationalFunction operator*(const Polynomial& p, RationalFunction f) { return f *= p; } RationalFunction operator*(RationalFunction f, const Monomial& m) { return f *= m; } RationalFunction operator*(const Monomial& m, RationalFunction f) { return f *= m; } RationalFunction operator*(RationalFunction f, double c) { return f *= c; } RationalFunction operator*(double c, RationalFunction f) { return f *= c; } RationalFunction operator/(RationalFunction f1, const RationalFunction& f2) { return f1 /= f2; } RationalFunction operator/(RationalFunction f, const Polynomial& p) { return f /= p; } RationalFunction operator/(const Polynomial& p, const RationalFunction& f) { if (f.numerator().monomial_to_coefficient_map().empty()) { throw std::logic_error("RationalFunction: operator/=: The divider is 0."); } return {p * f.denominator(), f.numerator()}; } RationalFunction operator/(RationalFunction f, const Monomial& m) { return f /= m; } RationalFunction operator/(const Monomial& m, RationalFunction f) { if (f.numerator().monomial_to_coefficient_map().empty()) { throw std::logic_error("RationalFunction: operator/=: The divider is 0."); } return {m * f.denominator(), f.numerator()}; } RationalFunction operator/(RationalFunction f, double c) { return f /= c; } RationalFunction operator/(double c, const RationalFunction& f) { if (f.numerator().monomial_to_coefficient_map().empty()) { throw std::logic_error("RationalFunction: operator/=: The divider is 0."); } return {c * f.denominator(), f.numerator()}; } RationalFunction pow(const RationalFunction& f, int n) { if (n == 0) { return {Polynomial(1), Polynomial(1)}; } else if (n >= 1) { return {pow(f.numerator(), n), pow(f.denominator(), n)}; } else { // n < 0 return {pow(f.denominator(), -n), pow(f.numerator(), -n)}; } } void RationalFunction::SetIndeterminates(const Variables& new_indeterminates) { numerator_.SetIndeterminates(new_indeterminates); denominator_.SetIndeterminates(new_indeterminates); } } // namespace symbolic } // namespace drake // We must define this in the cc file so that symbolic_formula.h is fully // defined (not just forward declared) when comparing. namespace Eigen { namespace numext { template <> bool equal_strict(const drake::symbolic::RationalFunction& x, const drake::symbolic::RationalFunction& y) { return static_cast<bool>(x == y); } } // namespace numext } // namespace Eigen
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/latex.h
#pragma once #include <sstream> #include <string> #include <unordered_map> #include <vector> #include <Eigen/Core> #include <Eigen/Sparse> #include "drake/common/drake_copyable.h" #include "drake/common/symbolic/expression.h" namespace drake { namespace symbolic { /// Generates a LaTeX string representation of `e` with floating point /// coefficients displayed using `precision`. /// @pydrake_mkdoc_identifier{expression} std::string ToLatex(const Expression& e, int precision = 3); /// Generates a LaTeX string representation of `f` with floating point /// coefficients displayed using `precision`. /// @pydrake_mkdoc_identifier{formula} std::string ToLatex(const Formula& f, int precision = 3); /// Generates a Latex string representation of `val` displayed with `precision`, /// with one exception. If the fractional part of `val` is exactly zero, then /// `val` is represented perfectly as an integer, and is displayed without the /// trailing decimal point and zeros (in this case, the `precision` argument is /// ignored). std::string ToLatex(double val, int precision = 3); /// Generates a LaTeX string representation of `M` with floating point /// coefficients displayed using `precision`. /// @pydrake_mkdoc_identifier{matrix} template <typename Derived> std::string ToLatex(const Eigen::PlainObjectBase<Derived>& M, int precision = 3) { std::ostringstream oss; oss << "\\begin{bmatrix}"; for (int i = 0; i < M.rows(); ++i) { for (int j = 0; j < M.cols(); ++j) { oss << " " << ToLatex(M(i, j), precision); if (j < M.cols() - 1) { oss << " &"; } } if (i < M.rows() - 1) { oss << " \\\\"; } } oss << " \\end{bmatrix}"; return oss.str(); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/polynomial_basis_element.h
#pragma once #include <map> #include <Eigen/Core> #include "drake/common/drake_copyable.h" #include "drake/common/symbolic/expression.h" namespace drake { namespace symbolic { /** * Each polynomial p(x) can be written as a linear combination of its basis * elements p(x) = ∑ᵢ cᵢ * ϕᵢ(x), where ϕᵢ(x) is the i'th element in the basis, * cᵢ is the coefficient of that element. The most commonly used basis is * monomials. For example in polynomial p(x) = 2x₀²x₁ + 3x₀x₁ + 2, x₀²x₁, x₀x₁ * and 1 are all elements of monomial basis. Likewise, a polynomial can be * written using other basis, such as Chebyshev polynomials, Legendre * polynomials, etc. For a polynomial written with Chebyshev polynomial basis * p(x) = 2T₂(x₀)T₁(x₁) + 3T₁(x₁) + 2T₂(x₀), T₂(x₀)T₁(x₁),T₁(x₁), and T₂(x₀) are * all elements of Chebyshev basis. This PolynomialBasisElement class represents * an element ϕᵢ(x) in the basis. We can think of an element of polynomial basis * as a mapping from the variable to its degree. So for monomial basis element * x₀²x₁, it can be thought of as a mapping {x₀ -> 2, x₁ -> 1}. For a Chebyshev * basis element T₂(x₀)T₁(x₁), it can be thought of as a mapping {x₀ -> 2, x₁ -> * 1}. * * Each of the derived class, `Derived`, should implement the following * functions * * - std::map<Derived, double> operator*(const Derived& A, const Derived&B) * - std::map<Derived, double> Derived::Differentiate(const Variable& var) * const; * - std::map<Derived, double> Derived::Integrate(const Variable& var) const; * - bool Derived::operator<(const Derived& other) const; * - std::pair<double, Derived> EvaluatePartial(const Environment& e) const; * - void MergeBasisElementInPlace(const Derived& other) * * The function lexicographical_compare can be used when implementing operator<. * The function DoEvaluatePartial can be used when implementing EvaluatePartial */ class PolynomialBasisElement { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PolynomialBasisElement) /** * Constructs a polynomial basis with empty var_to_degree map. This element * should be interpreted as 1. */ PolynomialBasisElement() = default; /** * Constructs a polynomial basis given the variable and the degree of that * variable. * @throws std::exception if any of the degree is negative. * @note we will ignore the variable with degree 0. */ explicit PolynomialBasisElement( const std::map<Variable, int>& var_to_degree_map); /** * Constructs a polynomial basis, such that it contains the variable-to-degree * map vars(i)→degrees(i). * @throws std::exception if @p vars contains repeated variables. * @throws std::exception if any degree is negative. */ PolynomialBasisElement(const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& degrees); virtual ~PolynomialBasisElement() = default; [[nodiscard]] const std::map<Variable, int>& var_to_degree_map() const { return var_to_degree_map_; } /** * Returns variable to degree map. * TODO(hongkai.dai): this function is added because Monomial class has * get_powers() function. We will remove this get_powers() function when * Monomial class is deprecated. */ [[nodiscard]] const std::map<Variable, int>& get_powers() const { return var_to_degree_map_; } /** Returns the total degree of a polynomial basis. This is the summation of * the degree for each variable. */ [[nodiscard]] int total_degree() const { return total_degree_; } /** Returns the degree of this PolynomialBasisElement in a variable @p v. If * @p v is not a variable in this PolynomialBasisElement, then returns 0.*/ [[nodiscard]] int degree(const Variable& v) const; [[nodiscard]] Variables GetVariables() const; /** Evaluates under a given environment @p env. * * @throws std::exception exception if there is a variable in this * monomial whose assignment is not provided by @p env. */ [[nodiscard]] double Evaluate(const Environment& env) const; bool operator==(const PolynomialBasisElement& other) const; bool operator!=(const PolynomialBasisElement& other) const; [[nodiscard]] Expression ToExpression() const; protected: /** * Compares two PolynomialBasisElement using lexicographical order. This * function is meant to be called by the derived class, to compare two * polynomial basis of the same derived class. */ [[nodiscard]] bool lexicographical_compare( const PolynomialBasisElement& other) const; [[nodiscard]] virtual bool EqualTo(const PolynomialBasisElement& other) const; // Partially evaluate a polynomial basis element, where @p e does not // necessarily contain all the variables in this basis element. The // evaluation result is coeff * new_basis_element. void DoEvaluatePartial(const Environment& e, double* coeff, std::map<Variable, int>* new_basis_element) const; int* get_mutable_total_degree() { return &total_degree_; } std::map<Variable, int>* get_mutable_var_to_degree_map() { return &var_to_degree_map_; } /** Merge this basis element with another basis element by merging their * var_to_degree_map. After merging, the degree of each variable is raised to * the sum of the degree in each basis element (if a variable does not show up * in either one of the basis element, we regard its degree to be 0). */ void DoMergeBasisElementInPlace(const PolynomialBasisElement& other); private: // This function evaluates the polynomial basis for a univariate polynomial at // a given degree. For example, for a monomial basis, this evaluates xⁿ where // x is the variable value and n is the degree; for a Chebyshev basis, this // evaluats the Chebyshev polynomial Tₙ(x). [[nodiscard]] virtual double DoEvaluate(double variable_val, int degree) const = 0; [[nodiscard]] virtual Expression DoToExpression() const = 0; // Internally, the polynomial basis is represented as a mapping from a // variable to its degree. std::map<Variable, int> var_to_degree_map_; int total_degree_{}; }; /** Implements Graded reverse lexicographic order. * * @tparam VariableOrder VariableOrder{}(v1, v2) is true if v1 < v2. * @tparam BasisElement A derived class of PolynomialBasisElement. * * We first compare the total degree of the PolynomialBasisElement; if there is * a tie, then we use the graded reverse lexicographical order as the tie * breaker. * * Take monomials with variables {x, y, z} and total degree<=2 as an * example, with the order x > y > z. To get the graded reverse lexicographical * order, we take the following steps: * * First find all the monomials using the total degree. The monomials with * degree 2 are {x², y², z², xy, xz, yz}. The monomials with degree 1 are {x, * y, z}, and the monomials with degree 0 is {1}. To break the tie between * monomials with the same total degree, first sort them in the reverse * lexicographical order, namely x < y < z. The lexicographical order compares * two monomials by first comparing the exponent of the largest variable, if * there is a tie then go forth to the second largest variable. Thus z² > zy >zx * > y² > yx > x². Finally reverse the order as x² > xy > y² > xz > yz > z² > x * > y > z. * * There is an introduction to monomial order in * https://en.wikipedia.org/wiki/Monomial_order, and an introduction to graded * reverse lexicographical order in * https://en.wikipedia.org/wiki/Monomial_order#Graded_reverse_lexicographic_order */ template <typename VariableOrder, typename BasisElement> struct BasisElementGradedReverseLexOrder { /** Returns true if m1 < m2 under the Graded reverse lexicographic order. */ bool operator()(const BasisElement& m1, const BasisElement& m2) const { const int d1{m1.total_degree()}; const int d2{m2.total_degree()}; if (d1 > d2) { return false; } if (d2 > d1) { return true; } // d1 == d2 if (d1 == 0) { // Because both of them are 1. return false; } const std::map<Variable, int>& powers1{m1.get_powers()}; const std::map<Variable, int>& powers2{m2.get_powers()}; std::map<Variable, int>::const_iterator it1{powers1.cbegin()}; std::map<Variable, int>::const_iterator it2{powers2.cbegin()}; while (it1 != powers1.cend() && it2 != powers2.cend()) { const Variable& var1{it1->first}; const Variable& var2{it2->first}; const int degree1{it1->second}; const int degree2{it2->second}; if (variable_order_(var2, var1)) { return false; } else if (variable_order_(var1, var2)) { return true; } else { // var1 == var2 if (degree1 == degree2) { ++it1; ++it2; } else { return degree1 > degree2; } } } // When m1 and m2 are identical. return false; } private: VariableOrder variable_order_; }; } // namespace symbolic } // namespace drake #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { namespace internal { // Informs Eigen how to cast drake::symbolic::PolynomialBasisElement to // drake::symbolic::Expression. template <> EIGEN_DEVICE_FUNC inline drake::symbolic::Expression cast( const drake::symbolic::PolynomialBasisElement& m) { return m.ToExpression(); } } // namespace internal } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX)
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/replace_bilinear_terms.h
#pragma once #include "drake/common/eigen_types.h" #include "drake/common/symbolic/expression.h" namespace drake { namespace symbolic { /** * Replaces all the bilinear product terms in the expression `e`, with the * corresponding terms in `W`, where `W` represents the matrix x * yᵀ, such that * after replacement, `e` does not have bilinear terms involving `x` and `y`. * For example, if e = x(0)*y(0) + 2 * x(0)*y(1) + x(1) * y(1) + 3 * x(1), `e` * has bilinear terms x(0)*y(0), x(0) * y(1) and x(2) * y(1), if we call * ReplaceBilinearTerms(e, x, y, W) where W(i, j) represent the term x(i) * * y(j), then this function returns W(0, 0) + 2 * W(0, 1) + W(1, 1) + 3 * x(1). * @param e An expression potentially contains bilinear products between x and * y. * @param x The bilinear product between `x` and `y` will be replaced by the * corresponding term in `W`. * @throws std::exception if `x` contains duplicate entries. * @param y The bilinear product between `x` and `y` will be replaced by the * corresponding term in `W. * @throws std::exception if `y` contains duplicate entries. * @param W Bilinear product term x(i) * y(j) will be replaced by W(i, j). If * W(i,j) is not a single variable, but an expression, then this expression * cannot contain a variable in either x or y. * @throws std::exception, if W(i, j) is not a single variable, and also * contains a variable in x or y. * @pre W.rows() == x.rows() and W.cols() == y.rows(). * @return The symbolic expression after replacing x(i) * y(j) with W(i, j). */ symbolic::Expression ReplaceBilinearTerms( const symbolic::Expression& e, const Eigen::Ref<const VectorX<symbolic::Variable>>& x, const Eigen::Ref<const VectorX<symbolic::Variable>>& y, const Eigen::Ref<const MatrixX<symbolic::Expression>>& W); } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/simplification.h
#pragma once #include <functional> #include <utility> #include "drake/common/symbolic/expression.h" namespace drake { namespace symbolic { /// A pattern is an expression which possibly includes variables which represent /// placeholders. It is used to construct a `RewritingRule`. using Pattern = Expression; /// A `RewritingRule`, `lhs => rhs`, consists of two Patterns `lhs` and `rhs`. A /// rewriting rule instructs a rewriter how to transform a given expression `e`. /// First, the rewriter tries to find a match between the expression `e` and the /// pattern `lhs`. If such a match is found, it applies the match result /// (substitution) to `rhs`. Otherwise, the same expression `e` is returned. class RewritingRule { public: /// Constructs a rewriting rule `lhs => rhs`. RewritingRule(Pattern lhs, Pattern rhs) : lhs_{std::move(lhs)}, rhs_{std::move(rhs)} {} /// Default copy constructor. RewritingRule(const RewritingRule&) = default; /// Default move constructor. RewritingRule(RewritingRule&&) = default; /// Deleted copy-assign operator. RewritingRule& operator=(const RewritingRule&) = delete; /// Deleted move-assign operator. RewritingRule& operator=(RewritingRule&&) = delete; /// Default destructor. ~RewritingRule() = default; /// Returns the const reference of the LHS of the rewriting rule. const Pattern& lhs() const { return lhs_; } /// Returns the const reference of the RHS of the rewriting rule. const Pattern& rhs() const { return rhs_; } private: const Pattern lhs_; const Pattern rhs_; }; /// A `Rewriter` is a function from an Expression to an Expression. using Rewriter = std::function<Expression(const Expression&)>; /// Constructs a rewriter based on a rewriting rule @p r. Rewriter MakeRuleRewriter(const RewritingRule& r); } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common
/home/johnshepherd/drake/common/symbolic/chebyshev_basis_element.h
#pragma once #include <map> #include <utility> #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/common/hash.h" #include "drake/common/symbolic/polynomial_basis_element.h" namespace drake { namespace symbolic { /** * ChebyshevBasisElement represents an element of Chebyshev polynomial basis, * written as the product of Chebyshev polynomials, in the form * Tₚ₀(x₀)Tₚ₁(x₁)...Tₚₙ(xₙ), where each Tₚᵢ(xᵢ) is a (univariate) Chebyshev * polynomial of degree pᵢ. */ class ChebyshevBasisElement : public PolynomialBasisElement { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ChebyshevBasisElement) /** Constructs a ChebyshevBasisElement equals to 1. */ ChebyshevBasisElement(); explicit ChebyshevBasisElement( const std::map<Variable, int>& var_to_degree_map); /** Constructs a Chebyshev polynomial T₁(var). */ explicit ChebyshevBasisElement(const Variable& var); /** Constructs a Chebyshev polynomial Tₙ(var) where n = degree. */ ChebyshevBasisElement(const Variable& var, int degree); /** Constructs a default value 1. This overload is used by Eigen when * EIGEN_INITIALIZE_MATRICES_BY_ZERO is enabled. */ explicit ChebyshevBasisElement(std::nullptr_t); ChebyshevBasisElement(const Eigen::Ref<const VectorX<Variable>>& vars, const Eigen::Ref<const Eigen::VectorXi>& degrees); ~ChebyshevBasisElement() override = default; /** * Compares two ChebyshevBasisElement in lexicographic order. */ bool operator<(const ChebyshevBasisElement& other) const; /** * Differentiates the ChebyshevBasisElement with respect to a variable. * We use the fact that * - If n is even dTₙ(x)/dx = 2n ∑ⱼ Tⱼ(x), j is odd and 1 <= j <= n-1 * - If n is odd dTₙ(x)/dx = 2n ∑ⱼ Tⱼ(x) - n, j is even and 0 <= j <= n-1 * We return `result`, a map from ChebyshevBasisElement to double, such that * sum(result.key() * result[key]) is the differentiation of `this` w.r.t the * variable. * For example if n is even, dTₙ(x)Tₘ(y)/dx = 2n∑ⱼ Tⱼ(x)Tₘ(y), j is odd and * 1 <= j <= n-1, then the returned result is {T₁(x)Tₘ(y), 2n}, {T₃(x)Tₘ(y), * 2n}, ..., {T₂ₙ₋₁(x)Tₘ(y), 2n}. A special case is that @p var is not a * variable in `this`, then we return an empty map. * @param var A variable to differentiate with. */ [[nodiscard]] std::map<ChebyshevBasisElement, double> Differentiate( const Variable& var) const; /** * Integrates a ChebyshevBasisElement for a variable. * We use the fact that * ∫ Tₙ(x)dx = 1/(2n+2)Tₙ₊₁(x) − 1/(2n−2)Tₙ₋₁(x) * A special case is ∫ T₀(x)dx = T₁(x) * @param var The variable to integrate. If @param var is not a variable in * this ChebyshevBasisElement, then the integration result is *this * T₁(var). * @retval result sum(key * result[key]) is the integration result. For * example, ∫ T₂(x)T₃(y)dx = 1/6*T₃(x)T₃(y) − 1/2 * T₁(x)T₃(y), then the * result is the map containing {T₃(x)T₃(y), 1/6} and {T₁(x)T₃(y), -1/2}. */ [[nodiscard]] std::map<ChebyshevBasisElement, double> Integrate( const Variable& var) const; /** Merges this Chebyshev basis element with another Chebyshev basis element * @p other by merging their var_to_degree_map. After merging, the degree of * each variable is raised to the sum of the degree in each basis element (if * a variable does not show up in either one of the basis element, we regard * its degree to be 0). For example, merging T₁(x)T₃(y) and T₂(x)T₄(z) gets * T₃(x)T₃(y)T₄(z). */ void MergeBasisElementInPlace(const ChebyshevBasisElement& other); /** Partially evaluates using a given environment @p env. The evaluation * result is of type pair<double, ChebyshevBasisElement>. The first component * (: double) represents the coefficient part while the second component * represents the remaining parts of the ChebyshevBasisElement which was not * evaluated, the product of the first and the second component is the result * of the partial evaluation. For example, if this ChebyshevBasisElement is * T₂(x)T₃(y)T₁(z), and @p env stores x→ 3, y→ 2, then the partial evaluation * is T₂(3)*T₃(2)*T₁(z) = 17 * 26 * T₁(z) = 442*T₁(z), then we return the pair * (442, T₁(z)). */ [[nodiscard]] std::pair<double, ChebyshevBasisElement> EvaluatePartial( const Environment& env) const; /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const ChebyshevBasisElement& item) noexcept { using drake::hash_append; // We do not send total_degree_ to the hasher, because it is already fully // represented by var_to_degree_map_ -- it is just a cached tally of the // exponents. hash_append(hasher, item.var_to_degree_map()); } private: [[nodiscard]] double DoEvaluate(double variable_val, int degree) const override; [[nodiscard]] Expression DoToExpression() const override; }; /** * Returns the product of two Chebyshev basis elements. * Since Tₘ(x) * Tₙ(x) = 0.5 (Tₘ₊ₙ(x) + Tₘ₋ₙ(x)) if m >= n, the product of * Chebyshev basis elements is the weighted sum of several Chebyshev basis * elements. For example T₁(x)T₂(y) * T₃(x)T₁(y) = 0.25*(T₄(x)T₃(y) + T₂(x)T₃(y) * + T₄(x)T₁(y) + T₂(x)T₁(y)) * @return the result of the product, from each ChebyshevBasisElement to its * coefficient. In the example above, it returns (T₄(x)T₃(y) -> 0.25), * (T₂(x)T₃(y) -> 0.25), (T₄(x)T₁(y) -> 0.25) and (T₂(x)T₁(y) -> 0.25) */ std::map<ChebyshevBasisElement, double> operator*( const ChebyshevBasisElement& a, const ChebyshevBasisElement& b); std::ostream& operator<<(std::ostream& out, const ChebyshevBasisElement& m); } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::ChebyshevBasisElement>. */ template <> struct hash<drake::symbolic::ChebyshevBasisElement> : public drake::DefaultHash {}; } // namespace std #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { // Eigen scalar type traits for Matrix<drake::symbolic::ChebyshevBasisElement>. template <> struct NumTraits<drake::symbolic::ChebyshevBasisElement> : GenericNumTraits<drake::symbolic::ChebyshevBasisElement> { static inline int digits10() { return 0; } }; } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX) // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::symbolic::ChebyshevBasisElement> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/expression_cell.cc
#define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/expression/expression_cell.h" #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include <algorithm> #include <cmath> #include <functional> #include <iomanip> #include <limits> #include <map> #include <memory> #include <numeric> #include <ostream> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include "drake/common/drake_assert.h" namespace drake { namespace symbolic { using std::accumulate; using std::all_of; using std::domain_error; using std::endl; using std::equal; using std::lexicographical_compare; using std::make_unique; using std::map; using std::numeric_limits; using std::ostream; using std::ostringstream; using std::pair; using std::runtime_error; using std::string; using std::vector; bool is_integer(const double v) { // v should be in [int_min, int_max]. if (!((numeric_limits<int>::lowest() <= v) && (v <= numeric_limits<int>::max()))) { return false; } double intpart{}; // dummy variable return modf(v, &intpart) == 0.0; } bool is_positive_integer(const double v) { return (v > 0) && is_integer(v); } bool is_non_negative_integer(const double v) { return (v >= 0) && is_integer(v); } namespace { // Returns true iff `e` does not wrap another sub-Expression, i.e., it's not a // UnaryExpressionCell, BinaryExpressionCell, etc. // // Pedantially, ExpressionNaN should return `true` here since it isn't wrapping // anything, but given the practical uses of this function it's easier to just // return `false` for NaNs. bool IsLeafExpression(const Expression& e) { return is_constant(e) || is_variable(e); } // Determines if the summation represented by term_to_coeff_map is // polynomial-convertible or not. This function is used in the // constructor of ExpressionAdd. bool determine_polynomial( const std::map<Expression, double>& term_to_coeff_map) { return all_of(term_to_coeff_map.begin(), term_to_coeff_map.end(), [](const pair<const Expression, double>& p) { return p.first.is_polynomial(); }); } // Determines if the product represented by term_to_coeff_map is // polynomial-convertible or not. This function is used in the // constructor of ExpressionMul. bool determine_polynomial( const std::map<Expression, Expression>& base_to_exponent_map) { return all_of(base_to_exponent_map.begin(), base_to_exponent_map.end(), [](const pair<const Expression, Expression>& p) { // For each base^exponent, it has to satisfy the following // conditions: // - base is polynomial-convertible. // - exponent is a non-negative integer. const Expression& base{p.first}; const Expression& exponent{p.second}; if (!base.is_polynomial() || !is_constant(exponent)) { return false; } const double e{get_constant_value(exponent)}; return is_non_negative_integer(e); }); } // Determines if pow(base, exponent) is polynomial-convertible or not. This // function is used in constructor of ExpressionPow. bool determine_polynomial(const Expression& base, const Expression& exponent) { // base ^ exponent is polynomial-convertible if the following hold: // - base is polynomial-convertible. // - exponent is a non-negative integer. if (!(base.is_polynomial() && is_constant(exponent))) { return false; } const double e{get_constant_value(exponent)}; return is_non_negative_integer(e); } Expression ExpandMultiplication(const Expression& e1, const Expression& e2, const Expression& e3); // Helper function expanding (e1 * e2). It assumes that both of e1 and e2 are // already expanded. Expression ExpandMultiplication(const Expression& e1, const Expression& e2) { // Precondition: e1 and e2 are already expanded. DRAKE_ASSERT(e1.EqualTo(e1.Expand())); DRAKE_ASSERT(e2.EqualTo(e2.Expand())); if (is_addition(e1)) { // (c0 + c1 * e_{1,1} + ... + c_n * e_{1, n}) * e2 // = c0 * e2 + c1 * e_{1,1} * e2 + ... + c_n * e_{1,n} * e2 const double c0{get_constant_in_addition(e1)}; const map<Expression, double>& m1{get_expr_to_coeff_map_in_addition(e1)}; ExpressionAddFactory fac; fac.AddExpression(ExpandMultiplication(c0, e2)); for (const pair<const Expression, double>& p : m1) { fac.AddExpression(ExpandMultiplication(p.second, p.first, e2)); } return std::move(fac).GetExpression(); } if (is_addition(e2)) { // e1 * (c0 + c1 * e_{2,1} + ... + c_n * e_{2, n}) // = e1 * c0 + e1 * c1 * e_{2,1} + ... + e1 * c_n * e_{2,n} const double c0{get_constant_in_addition(e2)}; const map<Expression, double>& m1{get_expr_to_coeff_map_in_addition(e2)}; ExpressionAddFactory fac; fac.AddExpression(ExpandMultiplication(e1, c0)); for (const pair<const Expression, double>& p : m1) { fac.AddExpression(ExpandMultiplication(e1, p.second, p.first)); } return std::move(fac).GetExpression(); } if (is_division(e1)) { const Expression& e1_1{get_first_argument(e1)}; const Expression& e1_2{get_second_argument(e1)}; if (is_division(e2)) { // ((e1_1 / e1_2) * (e2_1 / e2_2)).Expand() // => (e1_1 * e2_1).Expand() / (e1_2 * e2_2).Expand(). // // Note that e1_1, e1_2, e2_1, and e_2 are already expanded by the // precondition. const Expression& e2_1{get_first_argument(e2)}; const Expression& e2_2{get_second_argument(e2)}; return ExpandMultiplication(e1_1, e2_1) / ExpandMultiplication(e1_2, e2_2); } // ((e1_1 / e1_2) * e2).Expand() // => (e1_1 * e2).Expand() / e2. // // Note that e1_1, e1_2, and e_2 are already expanded by the precondition. return ExpandMultiplication(e1_1, e2) / e1_2; } if (is_division(e2)) { // (e1 * (e2_1 / e2_2)).Expand() // => (e1 * e2_1).Expand() / e2_2. // // Note that e1, e2_1, and e2_2 are already expanded by the precondition. const Expression& e2_1{get_first_argument(e2)}; const Expression& e2_2{get_second_argument(e2)}; return ExpandMultiplication(e1, e2_1) / e2_2; } return e1 * e2; } Expression ExpandMultiplication(const Expression& e1, const Expression& e2, const Expression& e3) { return ExpandMultiplication(ExpandMultiplication(e1, e2), e3); } // Helper function expanding pow(base, n). It assumes that base is expanded. Expression ExpandPow(const Expression& base, const int n) { // Precondition: base is already expanded. DRAKE_ASSERT(base.EqualTo(base.Expand())); DRAKE_ASSERT(n >= 1); if (n == 1) { return base; } const Expression pow_half{ExpandPow(base, n / 2)}; if (n % 2 == 1) { // pow(base, n) = base * pow(base, n / 2) * pow(base, n / 2) return ExpandMultiplication(base, pow_half, pow_half); } // pow(base, n) = pow(base, n / 2) * pow(base, n / 2) return ExpandMultiplication(pow_half, pow_half); } // Helper function expanding pow(base, exponent). It assumes that both of base // and exponent are already expanded. Expression ExpandPow(const Expression& base, const Expression& exponent) { // Precondition: base and exponent are already expanded. DRAKE_ASSERT(base.EqualTo(base.Expand())); DRAKE_ASSERT(exponent.EqualTo(exponent.Expand())); if (is_multiplication(base)) { // pow(c * ∏ᵢ pow(e₁ᵢ, e₂ᵢ), exponent) // = pow(c, exponent) * ∏ᵢ pow(e₁ᵢ, e₂ᵢ * exponent) const double c{get_constant_in_multiplication(base)}; auto map = get_base_to_exponent_map_in_multiplication(base); for (pair<const Expression, Expression>& p : map) { p.second = p.second * exponent; } return pow(c, exponent) * ExpressionMulFactory{1.0, map}.GetExpression(); } // Expand if // 1) base is an addition expression and // 2) exponent is a positive integer. if (!is_addition(base) || !is_constant(exponent)) { return pow(base, exponent); } const double e{get_constant_value(exponent)}; if (e <= 0 || !is_integer(e)) { return pow(base, exponent); } const int n{static_cast<int>(e)}; return ExpandPow(base, n); } } // namespace ExpressionCell::~ExpressionCell() = default; ExpressionCell::ExpressionCell(const ExpressionKind k, const bool is_poly, const bool is_expanded) : kind_{k}, is_polynomial_{is_poly}, is_expanded_{is_expanded} {} UnaryExpressionCell::UnaryExpressionCell(const ExpressionKind k, Expression e, const bool is_poly, const bool is_expanded) : ExpressionCell{k, is_poly, is_expanded}, e_{std::move(e)} {} void UnaryExpressionCell::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, e_); } Variables UnaryExpressionCell::GetVariables() const { return e_.GetVariables(); } bool UnaryExpressionCell::EqualTo(const ExpressionCell& e) const { // Expression::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const auto& unary_e = static_cast<const UnaryExpressionCell&>(e); return e_.EqualTo(unary_e.e_); } bool UnaryExpressionCell::Less(const ExpressionCell& e) const { // Expression::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const auto& unary_e = static_cast<const UnaryExpressionCell&>(e); return e_.Less(unary_e.e_); } double UnaryExpressionCell::Evaluate(const Environment& env) const { const double v{e_.Evaluate(env)}; return DoEvaluate(v); } BinaryExpressionCell::BinaryExpressionCell(const ExpressionKind k, Expression e1, Expression e2, const bool is_poly, const bool is_expanded) : ExpressionCell{k, is_poly, is_expanded}, e1_{std::move(e1)}, e2_{std::move(e2)} {} void BinaryExpressionCell::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, e1_); hash_append(*hasher, e2_); } Variables BinaryExpressionCell::GetVariables() const { Variables ret{e1_.GetVariables()}; ret.insert(e2_.GetVariables()); return ret; } bool BinaryExpressionCell::EqualTo(const ExpressionCell& e) const { // Expression::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const auto& binary_e = static_cast<const BinaryExpressionCell&>(e); return e1_.EqualTo(binary_e.e1_) && e2_.EqualTo(binary_e.e2_); } bool BinaryExpressionCell::Less(const ExpressionCell& e) const { // Expression::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const auto& binary_e = static_cast<const BinaryExpressionCell&>(e); if (e1_.Less(binary_e.e1_)) { return true; } if (binary_e.e1_.Less(e1_)) { return false; } // e1_ equals to binary_e.e1_, compare e2_ and binary_e.e2_ return e2_.Less(binary_e.e2_); } double BinaryExpressionCell::Evaluate(const Environment& env) const { const double v1{e1_.Evaluate(env)}; const double v2{e2_.Evaluate(env)}; return DoEvaluate(v1, v2); } ExpressionVar::ExpressionVar(Variable v) : ExpressionCell{ExpressionKind::Var, true, true}, var_{std::move(v)} { // Boolean symbolic variable should not be used in constructing symbolic // expressions. DRAKE_DEMAND(var_.get_type() != Variable::Type::BOOLEAN); } void ExpressionVar::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, var_); } Variables ExpressionVar::GetVariables() const { return {get_variable()}; } bool ExpressionVar::EqualTo(const ExpressionCell& e) const { // Expression::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); return var_.equal_to(static_cast<const ExpressionVar&>(e).var_); } bool ExpressionVar::Less(const ExpressionCell& e) const { // Expression::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); // Note the below is using the overloaded operator< between ExpressionVar // which is based on variable IDs. return var_.less(static_cast<const ExpressionVar&>(e).var_); } double ExpressionVar::Evaluate(const Environment& env) const { Environment::const_iterator const it{env.find(var_)}; if (it != env.cend()) { DRAKE_ASSERT(!std::isnan(it->second)); return it->second; } ostringstream oss; oss << "The following environment does not have an entry for the " "variable " << var_ << endl; oss << env << endl; throw runtime_error{oss.str()}; } Expression ExpressionVar::Expand() const { return Expression{var_}; } Expression ExpressionVar::EvaluatePartial(const Environment& env) const { const Environment::const_iterator it{env.find(var_)}; if (it != env.end()) { return it->second; } return Expression{var_}; } Expression ExpressionVar::Substitute(const Substitution& s) const { const Substitution::const_iterator it{s.find(var_)}; if (it != s.end()) { return it->second; } return Expression{var_}; } Expression ExpressionVar::Differentiate(const Variable& x) const { if (x.equal_to(var_)) { return Expression::One(); } return Expression::Zero(); } ostream& ExpressionVar::Display(ostream& os) const { return os << var_; } ExpressionNaN::ExpressionNaN() : ExpressionCell{ExpressionKind::NaN, false, false} {} void ExpressionNaN::HashAppendDetail(DelegatingHasher*) const {} Variables ExpressionNaN::GetVariables() const { return Variables{}; } bool ExpressionNaN::EqualTo(const ExpressionCell& e) const { // Expression::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); return true; } bool ExpressionNaN::Less(const ExpressionCell& e) const { // Expression::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); return false; } double ExpressionNaN::Evaluate(const Environment&) const { throw runtime_error("NaN is detected during Symbolic computation."); } Expression ExpressionNaN::Expand() const { throw runtime_error("NaN is detected during expansion."); } Expression ExpressionNaN::EvaluatePartial(const Environment&) const { throw runtime_error("NaN is detected during environment substitution."); } Expression ExpressionNaN::Substitute(const Substitution&) const { throw runtime_error("NaN is detected during substitution."); } Expression ExpressionNaN::Differentiate(const Variable&) const { throw runtime_error("NaN is detected during differentiation."); } ostream& ExpressionNaN::Display(ostream& os) const { return os << "NaN"; } ExpressionAdd::ExpressionAdd(const double constant, map<Expression, double> expr_to_coeff_map) : ExpressionCell{ExpressionKind::Add, determine_polynomial(expr_to_coeff_map), false}, constant_(constant), expr_to_coeff_map_(std::move(expr_to_coeff_map)) { DRAKE_ASSERT(!expr_to_coeff_map_.empty()); } void ExpressionAdd::HashAppendDetail(DelegatingHasher* hasher) const { using drake::hash_append; hash_append(*hasher, constant_); hash_append(*hasher, expr_to_coeff_map_); } Variables ExpressionAdd::GetVariables() const { Variables ret{}; for (const auto& p : expr_to_coeff_map_) { ret.insert(p.first.GetVariables()); } return ret; } bool ExpressionAdd::EqualTo(const ExpressionCell& e) const { // Expression::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const ExpressionAdd& add_e{static_cast<const ExpressionAdd&>(e)}; // Compare constant. if (constant_ != add_e.constant_) { return false; } return equal(expr_to_coeff_map_.cbegin(), expr_to_coeff_map_.cend(), add_e.expr_to_coeff_map_.cbegin(), add_e.expr_to_coeff_map_.cend(), [](const pair<const Expression, double>& p1, const pair<const Expression, double>& p2) { return p1.first.EqualTo(p2.first) && p1.second == p2.second; }); } bool ExpressionAdd::Less(const ExpressionCell& e) const { // Expression::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const ExpressionAdd& add_e{static_cast<const ExpressionAdd&>(e)}; // Compare the constants. if (constant_ < add_e.constant_) { return true; } if (add_e.constant_ < constant_) { return false; } // Compare the two maps. return lexicographical_compare( expr_to_coeff_map_.cbegin(), expr_to_coeff_map_.cend(), add_e.expr_to_coeff_map_.cbegin(), add_e.expr_to_coeff_map_.cend(), [](const pair<const Expression, double>& p1, const pair<const Expression, double>& p2) { const Expression& term1{p1.first}; const Expression& term2{p2.first}; if (term1.Less(term2)) { return true; } if (term2.Less(term1)) { return false; } const double coeff1{p1.second}; const double coeff2{p2.second}; return coeff1 < coeff2; }); } double ExpressionAdd::Evaluate(const Environment& env) const { return accumulate( expr_to_coeff_map_.begin(), expr_to_coeff_map_.end(), constant_, [&env](const double init, const pair<const Expression, double>& p) { return init + p.first.Evaluate(env) * p.second; }); } Expression ExpressionAdd::Expand() const { // (c0 + c1 * e_1 + ... + c_n * e_n).Expand() // = c0 + c1 * e_1.Expand() + ... + c_n * e_n.Expand() ExpressionAddFactory fac{constant_, {}}; for (const pair<const Expression, double>& p : expr_to_coeff_map_) { const Expression& e_i{p.first}; const double c_i{p.second}; fac.AddExpression( ExpandMultiplication(e_i.is_expanded() ? e_i : e_i.Expand(), c_i)); } return std::move(fac).GetExpression(); } Expression ExpressionAdd::EvaluatePartial(const Environment& env) const { return accumulate( expr_to_coeff_map_.begin(), expr_to_coeff_map_.end(), Expression{constant_}, [&env](const Expression& init, const pair<const Expression, double>& p) { return init + p.first.EvaluatePartial(env) * p.second; }); } Expression ExpressionAdd::Substitute(const Substitution& s) const { return accumulate( expr_to_coeff_map_.begin(), expr_to_coeff_map_.end(), Expression{constant_}, [&s](const Expression& init, const pair<const Expression, double>& p) { return init + p.first.Substitute(s) * p.second; }); } Expression ExpressionAdd::Differentiate(const Variable& x) const { // ∂/∂x (c_0 + c_1 * f_1 + ... + c_n * f_n) // = (∂/∂x c_0) + (∂/∂x c_1 * f_1) + ... + (∂/∂x c_n * f_n) // = 0.0 + c_1 * (∂/∂x f_1) + ... + c_n * (∂/∂x f_n) ExpressionAddFactory fac; for (const pair<const Expression, double>& p : expr_to_coeff_map_) { fac.AddExpression(p.second * p.first.Differentiate(x)); } return std::move(fac).GetExpression(); } ostream& ExpressionAdd::Display(ostream& os) const { DRAKE_ASSERT(!expr_to_coeff_map_.empty()); bool print_plus{false}; os << "("; if (constant_ != 0.0) { os << constant_; print_plus = true; } for (const auto& p : expr_to_coeff_map_) { DisplayTerm(os, print_plus, p.second, p.first); print_plus = true; } os << ")"; return os; } ostream& ExpressionAdd::DisplayTerm(ostream& os, const bool print_plus, const double coeff, const Expression& term) const { DRAKE_ASSERT(coeff != 0.0); if (coeff > 0.0) { if (print_plus) { os << " + "; } // Do not print "1 * t" if (coeff != 1.0) { os << coeff << " * "; } } else { // Instead of printing "+ (- E)", just print "- E". os << " - "; if (coeff != -1.0) { os << (-coeff) << " * "; } } os << term; return os; } ExpressionAddFactory::ExpressionAddFactory( const double constant, map<Expression, double> expr_to_coeff_map) : is_expanded_(false), constant_{constant}, expr_to_coeff_map_{std::move(expr_to_coeff_map)} { // Note that we set is_expanded_ to false to be conservative. We could imagine // inspecting the expr_to_coeff_map to compute a more precise value, but it's // not clear that doing so would improve our overall performance. } ExpressionAddFactory::ExpressionAddFactory(const ExpressionAdd& add) : ExpressionAddFactory{add.get_constant(), add.get_expr_to_coeff_map()} { is_expanded_ = add.is_expanded(); } void ExpressionAddFactory::AddExpression(const Expression& e) { if (is_constant(e)) { const double v{get_constant_value(e)}; return AddConstant(v); } if (is_addition(e)) { // Flattening return Add(to_addition(e)); } if (is_multiplication(e)) { const double constant{get_constant_in_multiplication(e)}; DRAKE_ASSERT(constant != 0.0); if (constant != 1.0) { // Instead of adding (1.0 * (constant * b1^t1 ... bn^tn)), // add (constant, 1.0 * b1^t1 ... bn^tn). return AddTerm(constant, ExpressionMulFactory( 1.0, get_base_to_exponent_map_in_multiplication(e)) .GetExpression()); } } return AddTerm(1.0, e); } void ExpressionAddFactory::Add(const ExpressionAdd& add) { AddConstant(add.get_constant()); AddMap(add.get_expr_to_coeff_map()); } ExpressionAddFactory& ExpressionAddFactory::operator=( const ExpressionAdd& add) { is_expanded_ = add.is_expanded(); constant_ = add.get_constant(); expr_to_coeff_map_ = add.get_expr_to_coeff_map(); return *this; } ExpressionAddFactory&& ExpressionAddFactory::Negate() && { constant_ = -constant_; for (auto& p : expr_to_coeff_map_) { p.second = -p.second; } return std::move(*this); } Expression ExpressionAddFactory::GetExpression() && { if (expr_to_coeff_map_.empty()) { return Expression{constant_}; } if (constant_ == 0.0 && expr_to_coeff_map_.size() == 1U) { // 0.0 + c1 * t1 -> c1 * t1 const auto it(expr_to_coeff_map_.cbegin()); return it->first * it->second; } auto result = make_unique<ExpressionAdd>(constant_, std::move(expr_to_coeff_map_)); if (is_expanded_) { result->set_expanded(); } return Expression{std::move(result)}; } void ExpressionAddFactory::AddConstant(const double constant) { constant_ += constant; } void ExpressionAddFactory::AddTerm(const double coeff, const Expression& term) { DRAKE_ASSERT(!is_constant(term)); DRAKE_ASSERT(coeff != 0.0); const auto it(expr_to_coeff_map_.find(term)); if (it != expr_to_coeff_map_.end()) { // Case1: term is already in the map double& this_coeff{it->second}; this_coeff += coeff; if (this_coeff == 0.0) { // If the coefficient becomes zero, remove the entry. // TODO(soonho-tri): The following operation is not sound since it cancels // `term` which might contain 0/0 problems. expr_to_coeff_map_.erase(it); // Note that we leave is_expanded_ unchanged here. We could imagine // inspecting the new expr_to_coeff_map_ to compute a more precise value, // but it's not clear that doing so would improve our overall performance. } } else { // Case2: term is not found in expr_to_coeff_map_. // Add the entry (term, coeff). expr_to_coeff_map_.emplace(term, coeff); // If the addend is not a leaf cell (i.e., if it's a cell type that nests // another Expression inside of itself), then conservatively we can no // longer be sure that our ExpressionAdd remains in expanded form. For // example calling `AddTerm(5, 2 + 3 * y)` produces a non-expanded result // `5 * (2 + 3 * y)`, i.e., `{2 + 3 * y} => 5` in the expr_to_coeff_map_. if (!is_variable(term)) { is_expanded_ = false; } } } void ExpressionAddFactory::AddMap( const map<Expression, double>& expr_to_coeff_map) { for (const auto& p : expr_to_coeff_map) { AddTerm(p.second, p.first); } } ExpressionMul::ExpressionMul(const double constant, map<Expression, Expression> base_to_exponent_map) : ExpressionCell{ExpressionKind::Mul, determine_polynomial(base_to_exponent_map), false}, constant_(constant), base_to_exponent_map_(std::move(base_to_exponent_map)) { DRAKE_ASSERT(!base_to_exponent_map_.empty()); } void ExpressionMul::HashAppendDetail(DelegatingHasher* hasher) const { using drake::hash_append; hash_append(*hasher, constant_); hash_append(*hasher, base_to_exponent_map_); } Variables ExpressionMul::GetVariables() const { Variables ret{}; for (const auto& p : base_to_exponent_map_) { ret.insert(p.first.GetVariables()); ret.insert(p.second.GetVariables()); } return ret; } bool ExpressionMul::EqualTo(const ExpressionCell& e) const { // Expression::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const ExpressionMul& mul_e{static_cast<const ExpressionMul&>(e)}; // Compare constant. if (constant_ != mul_e.constant_) { return false; } // Check each (term, coeff) pairs in two maps. return equal( base_to_exponent_map_.cbegin(), base_to_exponent_map_.cend(), mul_e.base_to_exponent_map_.cbegin(), mul_e.base_to_exponent_map_.cend(), [](const pair<const Expression, Expression>& p1, const pair<const Expression, Expression>& p2) { return p1.first.EqualTo(p2.first) && p1.second.EqualTo(p2.second); }); } bool ExpressionMul::Less(const ExpressionCell& e) const { // Expression::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const ExpressionMul& mul_e{static_cast<const ExpressionMul&>(e)}; // Compare the constants. if (constant_ < mul_e.constant_) { return true; } if (mul_e.constant_ < constant_) { return false; } // Compare the two maps. return lexicographical_compare( base_to_exponent_map_.cbegin(), base_to_exponent_map_.cend(), mul_e.base_to_exponent_map_.cbegin(), mul_e.base_to_exponent_map_.cend(), [](const pair<const Expression, Expression>& p1, const pair<const Expression, Expression>& p2) { const Expression& base1{p1.first}; const Expression& base2{p2.first}; if (base1.Less(base2)) { return true; } if (base2.Less(base1)) { return false; } const Expression& exp1{p1.second}; const Expression& exp2{p2.second}; return exp1.Less(exp2); }); } double ExpressionMul::Evaluate(const Environment& env) const { return accumulate( base_to_exponent_map_.begin(), base_to_exponent_map_.end(), constant_, [&env](const double init, const pair<const Expression, Expression>& p) { return init * std::pow(p.first.Evaluate(env), p.second.Evaluate(env)); }); } Expression ExpressionMul::Expand() const { // (c * ∏ᵢ pow(bᵢ, eᵢ)).Expand() // = c * ExpandMultiplication(∏ ExpandPow(bᵢ.Expand(), eᵢ.Expand())) return accumulate( base_to_exponent_map_.begin(), base_to_exponent_map_.end(), Expression{constant_}, [](const Expression& init, const pair<const Expression, Expression>& p) { const Expression& b_i{p.first}; const Expression& e_i{p.second}; return ExpandMultiplication( init, ExpandPow(b_i.is_expanded() ? b_i : b_i.Expand(), e_i.is_expanded() ? e_i : e_i.Expand())); }); } Expression ExpressionMul::EvaluatePartial(const Environment& env) const { return accumulate(base_to_exponent_map_.begin(), base_to_exponent_map_.end(), Expression{constant_}, [&env](const Expression& init, const pair<const Expression, Expression>& p) { return init * pow(p.first.EvaluatePartial(env), p.second.EvaluatePartial(env)); }); } Expression ExpressionMul::Substitute(const Substitution& s) const { return accumulate(base_to_exponent_map_.begin(), base_to_exponent_map_.end(), Expression{constant_}, [&s](const Expression& init, const pair<const Expression, Expression>& p) { return init * pow(p.first.Substitute(s), p.second.Substitute(s)); }); } // Computes ∂/∂x pow(f, g). Expression DifferentiatePow(const Expression& f, const Expression& g, const Variable& x) { if (is_constant(g)) { const Expression& n{g}; // alias n = g // Special case where exponent is a constant: // ∂/∂x pow(f, n) = n * pow(f, n - 1) * ∂/∂x f return n * pow(f, n - 1) * f.Differentiate(x); } if (is_constant(f)) { const Expression& n{f}; // alias n = f // Special case where base is a constant: // ∂/∂x pow(n, g) = log(n) * pow(n, g) * ∂/∂x g return log(n) * pow(n, g) * g.Differentiate(x); } // General case: // ∂/∂x pow(f, g) // = ∂/∂f pow(f, g) * ∂/∂x f + ∂/∂g pow(f, g) * ∂/∂x g // = g * pow(f, g - 1) * ∂/∂x f + log(f) * pow(f, g) * ∂/∂x g // = pow(f, g - 1) * (g * ∂/∂x f + log(f) * f * ∂/∂x g) return pow(f, g - 1) * (g * f.Differentiate(x) + log(f) * f * g.Differentiate(x)); } Expression ExpressionMul::Differentiate(const Variable& x) const { // ∂/∂x (c * f₁^g₁ * f₂^g₂ * ... * fₙ^gₙ //= c * [expr * (∂/∂x f₁^g₁) / f₁^g₁ + // expr * (∂/∂x f₂^g₂) / f₂^g₂ + // ... + // expr * (∂/∂x fₙ^gₙ) / fₙ^gₙ] // = c * expr * (∑ᵢ (∂/∂x fᵢ^gᵢ) / fᵢ^gᵢ) // where expr = (f₁^g₁ * f₂^g₂ * ... * fₙn^gₙ). // // We distribute (c * expr) into the summation. This possibly cancels the // division, "/ fᵢ^gᵢ", and results in a simpler formula. // // = ∑ᵢ (c * (∂/∂x fᵢ^gᵢ) / fᵢ^gᵢ * expr) // This factory will form the expression that we will return. ExpressionAddFactory add_fac; for (const pair<const Expression, Expression>& term : base_to_exponent_map_) { const Expression& base{term.first}; const Expression& exponent{term.second}; // This factory will form (c * (∂/∂x fᵢ^gᵢ) / fᵢ^gᵢ * expr). ExpressionMulFactory mul_fac{constant_, base_to_exponent_map_}; mul_fac.AddExpression(DifferentiatePow(base, exponent, x)); mul_fac.AddExpression(pow(base, -exponent)); add_fac.AddExpression(std::move(mul_fac).GetExpression()); } return std::move(add_fac).GetExpression(); } ostream& ExpressionMul::Display(ostream& os) const { DRAKE_ASSERT(!base_to_exponent_map_.empty()); bool print_mul{false}; os << "("; if (constant_ != 1.0) { os << constant_; print_mul = true; } for (const auto& p : base_to_exponent_map_) { DisplayTerm(os, print_mul, p.first, p.second); print_mul = true; } os << ")"; return os; } ostream& ExpressionMul::DisplayTerm(ostream& os, const bool print_mul, const Expression& base, const Expression& exponent) const { // Print " * pow(base, exponent)" if print_mul is true // Print "pow(base, exponent)" if print_mul is false // Print "base" instead of "pow(base, exponent)" if exponent == 1.0 if (print_mul) { os << " * "; } if (is_one(exponent)) { os << base; } else { os << "pow(" << base << ", " << exponent << ")"; } return os; } ExpressionMulFactory::ExpressionMulFactory( const double constant, map<Expression, Expression> base_to_exponent_map) : is_expanded_{false}, constant_{constant}, base_to_exponent_map_{std::move(base_to_exponent_map)} {} ExpressionMulFactory::ExpressionMulFactory( const map<Variable, int>& base_to_exponent_map) : is_expanded_{true}, constant_{1.0} { for (const auto& [base, exponent] : base_to_exponent_map) { base_to_exponent_map_.emplace(base, exponent); } } ExpressionMulFactory::ExpressionMulFactory(const ExpressionMul& mul) : ExpressionMulFactory{mul.get_constant(), mul.get_base_to_exponent_map()} { is_expanded_ = mul.is_expanded(); } void ExpressionMulFactory::AddExpression(const Expression& e) { if (constant_ == 0.0) { return; // Do nothing if it already represented 0. } if (is_zero(e)) { // X * 0 => 0. So clear the constant and the map. return SetZero(); } if (is_constant(e)) { return AddConstant(get_constant_value(e)); } if (is_multiplication(e)) { // Flattening return Add(to_multiplication(e)); } // Add e^1 return AddTerm(e, Expression{1.0}); } void ExpressionMulFactory::Add(const ExpressionMul& mul) { if (constant_ == 0.0) { return; // Do nothing if it already represented 0. } AddConstant(mul.get_constant()); AddMap(mul.get_base_to_exponent_map()); } void ExpressionMulFactory::SetZero() { is_expanded_ = true; constant_ = 0.0; base_to_exponent_map_.clear(); } ExpressionMulFactory& ExpressionMulFactory::operator=( const ExpressionMul& mul) { is_expanded_ = mul.is_expanded(); constant_ = mul.get_constant(); base_to_exponent_map_ = mul.get_base_to_exponent_map(); return *this; } ExpressionMulFactory&& ExpressionMulFactory::Negate() && { constant_ = -constant_; return std::move(*this); } Expression ExpressionMulFactory::GetExpression() && { if (base_to_exponent_map_.empty()) { return Expression{constant_}; } if (constant_ == 1.0 && base_to_exponent_map_.size() == 1U) { // 1.0 * c1^t1 -> c1^t1 const auto it(base_to_exponent_map_.cbegin()); return pow(it->first, it->second); } auto result = make_unique<ExpressionMul>(constant_, std::move(base_to_exponent_map_)); if (is_expanded_) { result->set_expanded(); } return Expression{std::move(result)}; } void ExpressionMulFactory::AddConstant(const double constant) { if (constant == 0.0) { return SetZero(); } constant_ *= constant; } void ExpressionMulFactory::AddTerm(const Expression& base, const Expression& exponent) { // The following assertion holds because of // ExpressionMulFactory::AddExpression. DRAKE_ASSERT(!(is_constant(base) && is_constant(exponent))); if (is_pow(base)) { // If (base, exponent) = (pow(e1, e2), exponent)), then add (e1, e2 * // exponent) // Example: (x^2)^3 => x^(2 * 3) return AddTerm(get_first_argument(base), get_second_argument(base) * exponent); } const auto it(base_to_exponent_map_.find(base)); if (it != base_to_exponent_map_.end()) { // base is already in map. // (= b1^e1 * ... * (base^this_exponent) * ... * en^bn). // Update it to be (... * (base^(this_exponent + exponent)) * ...) // Example: x^3 * x^2 => x^5 Expression& this_exponent = it->second; this_exponent += exponent; if (is_zero(this_exponent)) { // If it ends up with base^0 (= 1.0) then remove this entry from the map. // TODO(soonho-tri): The following operation is not sound since it can // cancels `base` which might include 0/0 problems. base_to_exponent_map_.erase(it); } else { // Conservatively, when adjusting an exponent we can no longer be sure // that our ExpressionMul remains in expanded form. Note that it's very // difficult to find a unit test where this line matters (is_expanded_ // is almost always "false" here already), but in any case setting this // to false here is conservative (at worst, a performance loss). is_expanded_ = false; } } else { // Product is not found in base_to_exponent_map_. Add the entry (base, // exponent). base_to_exponent_map_.emplace(base, exponent); // Conservatively, unless the new term is a simple exponentiation between // leaf expressions (i.e., constants or variables, not any cell type that // nests another Expression inside of itself), we can no longer be sure // that our ExpressionMul remains in expanded form. if (!(IsLeafExpression(base) && IsLeafExpression(exponent))) { is_expanded_ = false; } } } void ExpressionMulFactory::AddMap( const map<Expression, Expression>& base_to_exponent_map) { for (const auto& p : base_to_exponent_map) { AddTerm(p.first, p.second); } } ExpressionDiv::ExpressionDiv(const Expression& e1, const Expression& e2) : BinaryExpressionCell{ExpressionKind::Div, e1, e2, e1.is_polynomial() && is_constant(e2), false} {} namespace { // Helper class to implement ExpressionDiv::Expand. Given a symbolic expression // `e` and a constant `n`, it pushes the division in `e / n` inside for the // following cases: // // Case Addition : (c₀ + ∑ᵢ (cᵢ * eᵢ)) / n // => c₀/n + ∑ᵢ (cᵢ / n * eᵢ) // // Case Multiplication: (c₀ * ∏ᵢ (bᵢ * eᵢ)) / n // => c₀ / n * ∏ᵢ (bᵢ * eᵢ) // // Case Division : (e₁ / m) / n // => Recursively simplify e₁ / (n * m) // // (e₁ / e₂) / n // = (e₁ / n) / e₂ // => Recursively simplify (e₁ / n) and divide it by e₂ // // Other cases : e / n // => (1/n) * e // // Note that we use VisitExpression instead of VisitPolynomial because we want // to handle cases such as `(6xy / z) / 3` where (6xy / z) is not a polynomial // but it's desirable to simplify the expression into `2xy / z`. class DivExpandVisitor { public: [[nodiscard]] Expression Simplify(const Expression& e, const double n) const { return VisitExpression<Expression>(this, e, n); } private: [[nodiscard]] Expression VisitAddition(const Expression& e, const double n) const { // e = (c₀ + ∑ᵢ (cᵢ * eᵢ)) / n // => c₀/n + ∑ᵢ (cᵢ / n * eᵢ) const double constant{get_constant_in_addition(e)}; ExpressionAddFactory factory(constant / n, {}); for (const pair<const Expression, double>& p : get_expr_to_coeff_map_in_addition(e)) { factory.AddExpression(p.second / n * p.first); } return std::move(factory).GetExpression(); } [[nodiscard]] Expression VisitMultiplication(const Expression& e, const double n) const { // e = (c₀ * ∏ᵢ (bᵢ * eᵢ)) / n // => c₀ / n * ∏ᵢ (bᵢ * eᵢ) return ExpressionMulFactory{get_constant_in_multiplication(e) / n, get_base_to_exponent_map_in_multiplication(e)} .GetExpression(); } [[nodiscard]] Expression VisitDivision(const Expression& e, const double n) const { const Expression& e1{get_first_argument(e)}; const Expression& e2{get_second_argument(e)}; if (is_constant(e2)) { // e = (e₁ / m) / n // => Simplify `e₁ / (n * m)` const double m{get_constant_value(e2)}; return Simplify(e1, m * n); } else { // e = (e₁ / e₂) / n // => (e₁ / n) / e₂ return Simplify(e1, n) / e2; } } [[nodiscard]] Expression VisitVariable(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitConstant(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitLog(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitPow(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitAbs(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitExp(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitSqrt(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitSin(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitCos(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitTan(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitAsin(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitAcos(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitAtan(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitAtan2(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitSinh(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitCosh(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitTanh(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitMin(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitMax(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitCeil(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitFloor(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitIfThenElse(const Expression& e, const double n) const { return (1.0 / n) * e; } [[nodiscard]] Expression VisitUninterpretedFunction(const Expression& e, const double n) const { return (1.0 / n) * e; } // Makes VisitExpression a friend of this class so that VisitExpression can // use its private methods. friend Expression drake::symbolic::VisitExpression<Expression>( const DivExpandVisitor*, const Expression&, const double&); }; } // namespace Expression ExpressionDiv::Expand() const { const Expression& first{get_first_argument()}; const Expression& second{get_second_argument()}; const Expression e1{first.is_expanded() ? first : first.Expand()}; const Expression e2{second.is_expanded() ? second : second.Expand()}; if (is_constant(e2)) { // Simplifies the 'division by a constant' case, using DivExpandVisitor // defined above. return DivExpandVisitor{}.Simplify(e1, get_constant_value(e2)); } else { return (e1 / e2); } } Expression ExpressionDiv::EvaluatePartial(const Environment& env) const { return get_first_argument().EvaluatePartial(env) / get_second_argument().EvaluatePartial(env); } Expression ExpressionDiv::Substitute(const Substitution& s) const { return get_first_argument().Substitute(s) / get_second_argument().Substitute(s); } Expression ExpressionDiv::Differentiate(const Variable& x) const { // ∂/∂x (f / g) = (∂/∂x f * g - f * ∂/∂x g) / g^2 const Expression& f{get_first_argument()}; const Expression& g{get_second_argument()}; return (f.Differentiate(x) * g - f * g.Differentiate(x)) / pow(g, 2.0); } ostream& ExpressionDiv::Display(ostream& os) const { return os << "(" << get_first_argument() << " / " << get_second_argument() << ")"; } double ExpressionDiv::DoEvaluate(const double v1, const double v2) const { if (v2 == 0.0) { ostringstream oss; oss << "Division by zero: " << v1 << " / " << v2; this->Display(oss) << endl; throw runtime_error(oss.str()); } return v1 / v2; } ExpressionLog::ExpressionLog(const Expression& e) : UnaryExpressionCell{ExpressionKind::Log, e, false, e.is_expanded()} {} void ExpressionLog::check_domain(const double v) { if (!(v >= 0)) { ostringstream oss; oss << "log(" << v << ") : numerical argument out of domain. " << v << " is not in [0, +oo)" << endl; throw domain_error(oss.str()); } } Expression ExpressionLog::Expand() const { const Expression& arg{get_argument()}; return log(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionLog::EvaluatePartial(const Environment& env) const { return log(get_argument().EvaluatePartial(env)); } Expression ExpressionLog::Substitute(const Substitution& s) const { return log(get_argument().Substitute(s)); } Expression ExpressionLog::Differentiate(const Variable& x) const { // ∂/∂x log(f) = (∂/∂x f) / f const Expression& f{get_argument()}; return f.Differentiate(x) / f; } ostream& ExpressionLog::Display(ostream& os) const { return os << "log(" << get_argument() << ")"; } double ExpressionLog::DoEvaluate(const double v) const { check_domain(v); return std::log(v); } ExpressionAbs::ExpressionAbs(const Expression& e) : UnaryExpressionCell{ExpressionKind::Abs, e, false, e.is_expanded()} {} Expression ExpressionAbs::Expand() const { const Expression& arg{get_argument()}; return abs(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionAbs::EvaluatePartial(const Environment& env) const { return abs(get_argument().EvaluatePartial(env)); } Expression ExpressionAbs::Substitute(const Substitution& s) const { return abs(get_argument().Substitute(s)); } Expression ExpressionAbs::Differentiate(const Variable& x) const { if (GetVariables().include(x)) { const Expression& arg{get_argument()}; const Expression deriv = arg.Differentiate(x); return if_then_else(arg < 0, -deriv, if_then_else(arg == 0, Expression::NaN(), deriv)); } else { return Expression::Zero(); } } ostream& ExpressionAbs::Display(ostream& os) const { return os << "abs(" << get_argument() << ")"; } double ExpressionAbs::DoEvaluate(const double v) const { return std::fabs(v); } ExpressionExp::ExpressionExp(const Expression& e) : UnaryExpressionCell{ExpressionKind::Exp, e, false, e.is_expanded()} {} Expression ExpressionExp::Expand() const { const Expression& arg{get_argument()}; return exp(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionExp::EvaluatePartial(const Environment& env) const { return exp(get_argument().EvaluatePartial(env)); } Expression ExpressionExp::Substitute(const Substitution& s) const { return exp(get_argument().Substitute(s)); } Expression ExpressionExp::Differentiate(const Variable& x) const { // ∂/∂x exp(f) = exp(f) * (∂/∂x f) const Expression& f{get_argument()}; return exp(f) * f.Differentiate(x); } ostream& ExpressionExp::Display(ostream& os) const { return os << "exp(" << get_argument() << ")"; } double ExpressionExp::DoEvaluate(const double v) const { return std::exp(v); } ExpressionSqrt::ExpressionSqrt(const Expression& e) : UnaryExpressionCell{ExpressionKind::Sqrt, e, false, e.is_expanded()} {} void ExpressionSqrt::check_domain(const double v) { if (!(v >= 0)) { ostringstream oss; oss << "sqrt(" << v << ") : numerical argument out of domain. " << v << " is not in [0, +oo)" << endl; throw domain_error(oss.str()); } } Expression ExpressionSqrt::Expand() const { const Expression& arg{get_argument()}; return sqrt(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionSqrt::EvaluatePartial(const Environment& env) const { return sqrt(get_argument().EvaluatePartial(env)); } Expression ExpressionSqrt::Substitute(const Substitution& s) const { return sqrt(get_argument().Substitute(s)); } Expression ExpressionSqrt::Differentiate(const Variable& x) const { // ∂/∂x (sqrt(f)) = 1 / (2 * sqrt(f)) * (∂/∂x f) const Expression& f{get_argument()}; return 1 / (2 * sqrt(f)) * f.Differentiate(x); } ostream& ExpressionSqrt::Display(ostream& os) const { return os << "sqrt(" << get_argument() << ")"; } double ExpressionSqrt::DoEvaluate(const double v) const { check_domain(v); return std::sqrt(v); } ExpressionPow::ExpressionPow(const Expression& e1, const Expression& e2) : BinaryExpressionCell{ExpressionKind::Pow, e1, e2, determine_polynomial(e1, e2), IsLeafExpression(e1) && IsLeafExpression(e2)} {} void ExpressionPow::check_domain(const double v1, const double v2) { if (std::isfinite(v1) && (v1 < 0.0) && std::isfinite(v2) && !is_integer(v2)) { ostringstream oss; oss << "pow(" << v1 << ", " << v2 << ") : numerical argument out of domain. " << v1 << " is finite negative and " << v2 << " is finite non-integer." << endl; throw domain_error(oss.str()); } } Expression ExpressionPow::Expand() const { const Expression& e1{get_first_argument()}; const Expression& e2{get_second_argument()}; return ExpandPow(e1.is_expanded() ? e1 : e1.Expand(), e2.is_expanded() ? e2 : e2.Expand()); } Expression ExpressionPow::EvaluatePartial(const Environment& env) const { return pow(get_first_argument().EvaluatePartial(env), get_second_argument().EvaluatePartial(env)); } Expression ExpressionPow::Substitute(const Substitution& s) const { return pow(get_first_argument().Substitute(s), get_second_argument().Substitute(s)); } Expression ExpressionPow::Differentiate(const Variable& x) const { return DifferentiatePow(get_first_argument(), get_second_argument(), x); } ostream& ExpressionPow::Display(ostream& os) const { return os << "pow(" << get_first_argument() << ", " << get_second_argument() << ")"; } double ExpressionPow::DoEvaluate(const double v1, const double v2) const { check_domain(v1, v2); return std::pow(v1, v2); } ExpressionSin::ExpressionSin(const Expression& e) : UnaryExpressionCell{ExpressionKind::Sin, e, false, e.is_expanded()} {} Expression ExpressionSin::Expand() const { const Expression& arg{get_argument()}; return sin(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionSin::EvaluatePartial(const Environment& env) const { return sin(get_argument().EvaluatePartial(env)); } Expression ExpressionSin::Substitute(const Substitution& s) const { return sin(get_argument().Substitute(s)); } Expression ExpressionSin::Differentiate(const Variable& x) const { // ∂/∂x (sin f) = (cos f) * (∂/∂x f) const Expression& f{get_argument()}; return cos(f) * f.Differentiate(x); } ostream& ExpressionSin::Display(ostream& os) const { return os << "sin(" << get_argument() << ")"; } double ExpressionSin::DoEvaluate(const double v) const { return std::sin(v); } ExpressionCos::ExpressionCos(const Expression& e) : UnaryExpressionCell{ExpressionKind::Cos, e, false, e.is_expanded()} {} Expression ExpressionCos::Expand() const { const Expression& arg{get_argument()}; return cos(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionCos::EvaluatePartial(const Environment& env) const { return cos(get_argument().EvaluatePartial(env)); } Expression ExpressionCos::Substitute(const Substitution& s) const { return cos(get_argument().Substitute(s)); } Expression ExpressionCos::Differentiate(const Variable& x) const { // ∂/∂x (cos f) = - (sin f) * (∂/∂x f) const Expression& f{get_argument()}; return -sin(f) * f.Differentiate(x); } ostream& ExpressionCos::Display(ostream& os) const { return os << "cos(" << get_argument() << ")"; } double ExpressionCos::DoEvaluate(const double v) const { return std::cos(v); } ExpressionTan::ExpressionTan(const Expression& e) : UnaryExpressionCell{ExpressionKind::Tan, e, false, e.is_expanded()} {} Expression ExpressionTan::Expand() const { const Expression& arg{get_argument()}; return tan(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionTan::EvaluatePartial(const Environment& env) const { return tan(get_argument().EvaluatePartial(env)); } Expression ExpressionTan::Substitute(const Substitution& s) const { return tan(get_argument().Substitute(s)); } Expression ExpressionTan::Differentiate(const Variable& x) const { // ∂/∂x (tan f) = (1 / (cos f)^2) * (∂/∂x f) const Expression& f{get_argument()}; return (1 / pow(cos(f), 2)) * f.Differentiate(x); } ostream& ExpressionTan::Display(ostream& os) const { return os << "tan(" << get_argument() << ")"; } double ExpressionTan::DoEvaluate(const double v) const { return std::tan(v); } ExpressionAsin::ExpressionAsin(const Expression& e) : UnaryExpressionCell{ExpressionKind::Asin, e, false, e.is_expanded()} {} void ExpressionAsin::check_domain(const double v) { if (!((v >= -1.0) && (v <= 1.0))) { ostringstream oss; oss << "asin(" << v << ") : numerical argument out of domain. " << v << " is not in [-1.0, +1.0]" << endl; throw domain_error(oss.str()); } } Expression ExpressionAsin::Expand() const { const Expression& arg{get_argument()}; return asin(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionAsin::EvaluatePartial(const Environment& env) const { return asin(get_argument().EvaluatePartial(env)); } Expression ExpressionAsin::Substitute(const Substitution& s) const { return asin(get_argument().Substitute(s)); } Expression ExpressionAsin::Differentiate(const Variable& x) const { // ∂/∂x (asin f) = (1 / sqrt(1 - f^2)) (∂/∂x f) const Expression& f{get_argument()}; return (1 / sqrt(1 - pow(f, 2))) * f.Differentiate(x); } ostream& ExpressionAsin::Display(ostream& os) const { return os << "asin(" << get_argument() << ")"; } double ExpressionAsin::DoEvaluate(const double v) const { check_domain(v); return std::asin(v); } ExpressionAcos::ExpressionAcos(const Expression& e) : UnaryExpressionCell{ExpressionKind::Acos, e, false, e.is_expanded()} {} void ExpressionAcos::check_domain(const double v) { if (!((v >= -1.0) && (v <= 1.0))) { ostringstream oss; oss << "acos(" << v << ") : numerical argument out of domain. " << v << " is not in [-1.0, +1.0]" << endl; throw domain_error(oss.str()); } } Expression ExpressionAcos::Expand() const { const Expression& arg{get_argument()}; return acos(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionAcos::EvaluatePartial(const Environment& env) const { return acos(get_argument().EvaluatePartial(env)); } Expression ExpressionAcos::Substitute(const Substitution& s) const { return acos(get_argument().Substitute(s)); } Expression ExpressionAcos::Differentiate(const Variable& x) const { // ∂/∂x (acos f) = - 1 / sqrt(1 - f^2) * (∂/∂x f) const Expression& f{get_argument()}; return -1 / sqrt(1 - pow(f, 2)) * f.Differentiate(x); } ostream& ExpressionAcos::Display(ostream& os) const { return os << "acos(" << get_argument() << ")"; } double ExpressionAcos::DoEvaluate(const double v) const { check_domain(v); return std::acos(v); } ExpressionAtan::ExpressionAtan(const Expression& e) : UnaryExpressionCell{ExpressionKind::Atan, e, false, e.is_expanded()} {} Expression ExpressionAtan::Expand() const { const Expression& arg{get_argument()}; return atan(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionAtan::EvaluatePartial(const Environment& env) const { return atan(get_argument().EvaluatePartial(env)); } Expression ExpressionAtan::Substitute(const Substitution& s) const { return atan(get_argument().Substitute(s)); } Expression ExpressionAtan::Differentiate(const Variable& x) const { // ∂/∂x (atan f) = (1 / (1 + f^2)) * ∂/∂x f const Expression& f{get_argument()}; return (1 / (1 + pow(f, 2))) * f.Differentiate(x); } ostream& ExpressionAtan::Display(ostream& os) const { return os << "atan(" << get_argument() << ")"; } double ExpressionAtan::DoEvaluate(const double v) const { return std::atan(v); } ExpressionAtan2::ExpressionAtan2(const Expression& e1, const Expression& e2) : BinaryExpressionCell{ExpressionKind::Atan2, e1, e2, false, e1.is_expanded() && e2.is_expanded()} {} Expression ExpressionAtan2::Expand() const { const Expression& e1{get_first_argument()}; const Expression& e2{get_second_argument()}; return atan2(e1.is_expanded() ? e1 : e1.Expand(), e2.is_expanded() ? e2 : e2.Expand()); } Expression ExpressionAtan2::EvaluatePartial(const Environment& env) const { return atan2(get_first_argument().EvaluatePartial(env), get_second_argument().EvaluatePartial(env)); } Expression ExpressionAtan2::Substitute(const Substitution& s) const { return atan2(get_first_argument().Substitute(s), get_second_argument().Substitute(s)); } Expression ExpressionAtan2::Differentiate(const Variable& x) const { // ∂/∂x (atan2(f,g)) = (g * (∂/∂x f) - f * (∂/∂x g)) / (f^2 + g^2) const Expression& f{get_first_argument()}; const Expression& g{get_second_argument()}; return (g * f.Differentiate(x) - f * g.Differentiate(x)) / (pow(f, 2) + pow(g, 2)); } ostream& ExpressionAtan2::Display(ostream& os) const { return os << "atan2(" << get_first_argument() << ", " << get_second_argument() << ")"; } double ExpressionAtan2::DoEvaluate(const double v1, const double v2) const { return std::atan2(v1, v2); } ExpressionSinh::ExpressionSinh(const Expression& e) : UnaryExpressionCell{ExpressionKind::Sinh, e, false, e.is_expanded()} {} Expression ExpressionSinh::Expand() const { const Expression& arg{get_argument()}; return sinh(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionSinh::EvaluatePartial(const Environment& env) const { return sinh(get_argument().EvaluatePartial(env)); } Expression ExpressionSinh::Substitute(const Substitution& s) const { return sinh(get_argument().Substitute(s)); } Expression ExpressionSinh::Differentiate(const Variable& x) const { // ∂/∂x (sinh f) = cosh(f) * (∂/∂x f) const Expression& f{get_argument()}; return cosh(f) * f.Differentiate(x); } ostream& ExpressionSinh::Display(ostream& os) const { return os << "sinh(" << get_argument() << ")"; } double ExpressionSinh::DoEvaluate(const double v) const { return std::sinh(v); } ExpressionCosh::ExpressionCosh(const Expression& e) : UnaryExpressionCell{ExpressionKind::Cosh, e, false, e.is_expanded()} {} Expression ExpressionCosh::Expand() const { const Expression& arg{get_argument()}; return cosh(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionCosh::EvaluatePartial(const Environment& env) const { return cosh(get_argument().EvaluatePartial(env)); } Expression ExpressionCosh::Substitute(const Substitution& s) const { return cosh(get_argument().Substitute(s)); } Expression ExpressionCosh::Differentiate(const Variable& x) const { // ∂/∂x (cosh f) = sinh(f) * (∂/∂x f) const Expression& f{get_argument()}; return sinh(f) * f.Differentiate(x); } ostream& ExpressionCosh::Display(ostream& os) const { return os << "cosh(" << get_argument() << ")"; } double ExpressionCosh::DoEvaluate(const double v) const { return std::cosh(v); } ExpressionTanh::ExpressionTanh(const Expression& e) : UnaryExpressionCell{ExpressionKind::Tanh, e, false, e.is_expanded()} {} Expression ExpressionTanh::Expand() const { const Expression& arg{get_argument()}; return tanh(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionTanh::EvaluatePartial(const Environment& env) const { return tanh(get_argument().EvaluatePartial(env)); } Expression ExpressionTanh::Substitute(const Substitution& s) const { return tanh(get_argument().Substitute(s)); } Expression ExpressionTanh::Differentiate(const Variable& x) const { // ∂/∂x (tanh f) = 1 / (cosh^2(f)) * (∂/∂x f) const Expression& f{get_argument()}; return 1 / pow(cosh(f), 2) * f.Differentiate(x); } ostream& ExpressionTanh::Display(ostream& os) const { return os << "tanh(" << get_argument() << ")"; } double ExpressionTanh::DoEvaluate(const double v) const { return std::tanh(v); } ExpressionMin::ExpressionMin(const Expression& e1, const Expression& e2) : BinaryExpressionCell{ExpressionKind::Min, e1, e2, false, e1.is_expanded() && e2.is_expanded()} {} Expression ExpressionMin::Expand() const { const Expression& e1{get_first_argument()}; const Expression& e2{get_second_argument()}; return min(e1.is_expanded() ? e1 : e1.Expand(), e2.is_expanded() ? e2 : e2.Expand()); } Expression ExpressionMin::EvaluatePartial(const Environment& env) const { return min(get_first_argument().EvaluatePartial(env), get_second_argument().EvaluatePartial(env)); } Expression ExpressionMin::Substitute(const Substitution& s) const { return min(get_first_argument().Substitute(s), get_second_argument().Substitute(s)); } Expression ExpressionMin::Differentiate(const Variable& x) const { if (GetVariables().include(x)) { const Expression& e1{get_first_argument()}; const Expression& e2{get_second_argument()}; return if_then_else( e1 < e2, e1.Differentiate(x), if_then_else(e1 == e2, Expression::NaN(), e2.Differentiate(x))); } else { return Expression::Zero(); } } ostream& ExpressionMin::Display(ostream& os) const { return os << "min(" << get_first_argument() << ", " << get_second_argument() << ")"; } double ExpressionMin::DoEvaluate(const double v1, const double v2) const { return std::min(v1, v2); } ExpressionMax::ExpressionMax(const Expression& e1, const Expression& e2) : BinaryExpressionCell{ExpressionKind::Max, e1, e2, false, e1.is_expanded() && e2.is_expanded()} {} Expression ExpressionMax::Expand() const { const Expression& e1{get_first_argument()}; const Expression& e2{get_second_argument()}; return max(e1.is_expanded() ? e1 : e1.Expand(), e2.is_expanded() ? e2 : e2.Expand()); } Expression ExpressionMax::EvaluatePartial(const Environment& env) const { return max(get_first_argument().EvaluatePartial(env), get_second_argument().EvaluatePartial(env)); } Expression ExpressionMax::Substitute(const Substitution& s) const { return max(get_first_argument().Substitute(s), get_second_argument().Substitute(s)); } Expression ExpressionMax::Differentiate(const Variable& x) const { if (GetVariables().include(x)) { const Expression& e1{get_first_argument()}; const Expression& e2{get_second_argument()}; return if_then_else( e1 > e2, e1.Differentiate(x), if_then_else(e1 == e2, Expression::NaN(), e2.Differentiate(x))); } else { return Expression::Zero(); } } ostream& ExpressionMax::Display(ostream& os) const { return os << "max(" << get_first_argument() << ", " << get_second_argument() << ")"; } double ExpressionMax::DoEvaluate(const double v1, const double v2) const { return std::max(v1, v2); } ExpressionCeiling::ExpressionCeiling(const Expression& e) : UnaryExpressionCell{ExpressionKind::Ceil, e, false, e.is_expanded()} {} Expression ExpressionCeiling::Expand() const { const Expression& arg{get_argument()}; return ceil(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionCeiling::EvaluatePartial(const Environment& env) const { return ceil(get_argument().EvaluatePartial(env)); } Expression ExpressionCeiling::Substitute(const Substitution& s) const { return ceil(get_argument().Substitute(s)); } Expression ExpressionCeiling::Differentiate(const Variable& x) const { if (GetVariables().include(x)) { const Expression& arg{get_argument()}; // FYI: 'ceil(x) == floor(x)` is the same as `x % 1 == 0`. return if_then_else(ceil(arg) == floor(arg), Expression::NaN(), Expression::Zero()); } else { return Expression::Zero(); } } ostream& ExpressionCeiling::Display(ostream& os) const { return os << "ceil(" << get_argument() << ")"; } double ExpressionCeiling::DoEvaluate(const double v) const { return std::ceil(v); } ExpressionFloor::ExpressionFloor(const Expression& e) : UnaryExpressionCell{ExpressionKind::Floor, e, false, e.is_expanded()} {} Expression ExpressionFloor::Expand() const { const Expression& arg{get_argument()}; return floor(arg.is_expanded() ? arg : arg.Expand()); } Expression ExpressionFloor::EvaluatePartial(const Environment& env) const { return floor(get_argument().EvaluatePartial(env)); } Expression ExpressionFloor::Substitute(const Substitution& s) const { return floor(get_argument().Substitute(s)); } Expression ExpressionFloor::Differentiate(const Variable& x) const { if (GetVariables().include(x)) { const Expression& arg{get_argument()}; // FYI: 'ceil(x) == floor(x)` is the same as `x % 1 == 0`. return if_then_else(ceil(arg) == floor(arg), Expression::NaN(), Expression::Zero()); } else { return Expression::Zero(); } } ostream& ExpressionFloor::Display(ostream& os) const { return os << "floor(" << get_argument() << ")"; } double ExpressionFloor::DoEvaluate(const double v) const { return std::floor(v); } // ExpressionIfThenElse // -------------------- ExpressionIfThenElse::ExpressionIfThenElse(Formula f_cond, Expression e_then, Expression e_else) : ExpressionCell{ExpressionKind::IfThenElse, false, false}, f_cond_{std::move(f_cond)}, e_then_{std::move(e_then)}, e_else_{std::move(e_else)} {} void ExpressionIfThenElse::HashAppendDetail(DelegatingHasher* hasher) const { using drake::hash_append; hash_append(*hasher, f_cond_); hash_append(*hasher, e_then_); hash_append(*hasher, e_else_); } Variables ExpressionIfThenElse::GetVariables() const { Variables ret{f_cond_.GetFreeVariables()}; ret.insert(e_then_.GetVariables()); ret.insert(e_else_.GetVariables()); return ret; } bool ExpressionIfThenElse::EqualTo(const ExpressionCell& e) const { // Expression::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const ExpressionIfThenElse& ite_e{ static_cast<const ExpressionIfThenElse&>(e)}; return f_cond_.EqualTo(ite_e.f_cond_) && e_then_.EqualTo(ite_e.e_then_) && e_else_.EqualTo(ite_e.e_else_); } bool ExpressionIfThenElse::Less(const ExpressionCell& e) const { // Expression::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const ExpressionIfThenElse& ite_e{ static_cast<const ExpressionIfThenElse&>(e)}; if (f_cond_.Less(ite_e.f_cond_)) { return true; } if (ite_e.f_cond_.Less(f_cond_)) { return false; } if (e_then_.Less(ite_e.e_then_)) { return true; } if (ite_e.e_then_.Less(e_then_)) { return false; } return e_else_.Less(ite_e.e_else_); } double ExpressionIfThenElse::Evaluate(const Environment& env) const { if (f_cond_.Evaluate(env)) { return e_then_.Evaluate(env); } return e_else_.Evaluate(env); } Expression ExpressionIfThenElse::Expand() const { // TODO(soonho): use the following line when Formula::Expand() is implemented. // return if_then_else(f_cond_.Expand(), e_then_.Expand(), e_else_.Expand()); throw runtime_error("Not yet implemented."); } Expression ExpressionIfThenElse::EvaluatePartial(const Environment& env) const { // TODO(jwnimmer-tri) We could define a Formula::EvaluatePartial for improved // performance, if necessary. Substitution subst; for (const pair<const Variable, double>& p : env) { subst.emplace(p.first, p.second); } return if_then_else(f_cond_.Substitute(subst), e_then_.EvaluatePartial(env), e_else_.EvaluatePartial(env)); } Expression ExpressionIfThenElse::Substitute(const Substitution& s) const { return if_then_else(f_cond_.Substitute(s), e_then_.Substitute(s), e_else_.Substitute(s)); } Expression ExpressionIfThenElse::Differentiate(const Variable& x) const { if (GetVariables().include(x)) { if (is_relational(f_cond_)) { // In relational formulae, the discontinuity is at lhs == rhs. // TODO(ggould-tri) The logic of where/whether to find discontinuities // in a `Formula` belongs in that class, not here. That could also // handle eg the degenerate case of constant formulae. // Refer to #8648 for additional information. return if_then_else( get_lhs_expression(f_cond_) == get_rhs_expression(f_cond_), Expression::NaN(), if_then_else(f_cond_, e_then_.Differentiate(x), e_else_.Differentiate(x))); } else { // Because we cannot write an expression for whether the condition is // discontinuous at a given environment, we blanket disallow // differentiation where the condition contains the differentiand. We // hope that users can generally avoid this in practice, eg by using min // and max instead. ostringstream oss; Display(oss) << " is not differentiable with respect to " << x << "."; throw runtime_error(oss.str()); } } else { return Expression::Zero(); } } ostream& ExpressionIfThenElse::Display(ostream& os) const { return os << "(if " << f_cond_ << " then " << e_then_ << " else " << e_else_ << ")"; } // ExpressionUninterpretedFunction // -------------------- ExpressionUninterpretedFunction::ExpressionUninterpretedFunction( string name, vector<Expression> arguments) : ExpressionCell{ExpressionKind::UninterpretedFunction, false, all_of(arguments.begin(), arguments.end(), [](const Expression& arg) { return arg.is_expanded(); })}, name_{std::move(name)}, arguments_{std::move(arguments)} {} void ExpressionUninterpretedFunction::HashAppendDetail( DelegatingHasher* hasher) const { using drake::hash_append; hash_append(*hasher, name_); hash_append_range(*hasher, arguments_.begin(), arguments_.end()); } Variables ExpressionUninterpretedFunction::GetVariables() const { Variables ret; for (const Expression& arg : arguments_) { ret += arg.GetVariables(); } return ret; } bool ExpressionUninterpretedFunction::EqualTo(const ExpressionCell& e) const { // Expression::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const ExpressionUninterpretedFunction& uf_e{ static_cast<const ExpressionUninterpretedFunction&>(e)}; return name_ == uf_e.name_ && equal(arguments_.begin(), arguments_.end(), uf_e.arguments_.begin(), uf_e.arguments_.end(), [](const Expression& e1, const Expression& e2) { return e1.EqualTo(e2); }); } bool ExpressionUninterpretedFunction::Less(const ExpressionCell& e) const { // Expression::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == e.get_kind()); const ExpressionUninterpretedFunction& uf_e{ static_cast<const ExpressionUninterpretedFunction&>(e)}; if (name_ < uf_e.name_) { return true; } if (uf_e.name_ < name_) { return false; } return lexicographical_compare( arguments_.begin(), arguments_.end(), uf_e.arguments_.begin(), uf_e.arguments_.end(), [](const Expression& e1, const Expression& e2) { return e1.Less(e2); }); } double ExpressionUninterpretedFunction::Evaluate(const Environment&) const { throw runtime_error("Uninterpreted-function expression cannot be evaluated."); } Expression ExpressionUninterpretedFunction::Expand() const { vector<Expression> new_arguments; new_arguments.reserve(arguments_.size()); for (const Expression& arg : arguments_) { new_arguments.push_back(arg.is_expanded() ? arg : arg.Expand()); } return uninterpreted_function(name_, std::move(new_arguments)); } Expression ExpressionUninterpretedFunction::EvaluatePartial( const Environment& env) const { vector<Expression> new_arguments; new_arguments.reserve(arguments_.size()); for (const Expression& arg : arguments_) { new_arguments.push_back(arg.EvaluatePartial(env)); } return uninterpreted_function(name_, std::move(new_arguments)); } Expression ExpressionUninterpretedFunction::Substitute( const Substitution& s) const { vector<Expression> new_arguments; new_arguments.reserve(arguments_.size()); for (const Expression& arg : arguments_) { new_arguments.push_back(arg.Substitute(s)); } return uninterpreted_function(name_, std::move(new_arguments)); } Expression ExpressionUninterpretedFunction::Differentiate( const Variable& x) const { if (GetVariables().include(x)) { // This uninterpreted function does have `x` as an argument, but we don't // have sufficient information to differentiate it with respect to `x`. ostringstream oss; oss << "Uninterpreted-function expression "; Display(oss); oss << " is not differentiable with respect to " << x << "."; throw runtime_error(oss.str()); } else { // `x` is free in this uninterpreted function. return Expression::Zero(); } } ostream& ExpressionUninterpretedFunction::Display(ostream& os) const { os << name_ << "("; if (!arguments_.empty()) { auto it = arguments_.begin(); os << *(it++); for (; it != arguments_.end(); ++it) { os << ", " << *it; } } return os << ")"; } bool is_variable(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Var; } bool is_addition(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Add; } bool is_multiplication(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Mul; } bool is_division(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Div; } bool is_log(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Log; } bool is_abs(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Abs; } bool is_exp(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Exp; } bool is_sqrt(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Sqrt; } bool is_pow(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Pow; } bool is_sin(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Sin; } bool is_cos(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Cos; } bool is_tan(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Tan; } bool is_asin(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Asin; } bool is_acos(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Acos; } bool is_atan(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Atan; } bool is_atan2(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Atan2; } bool is_sinh(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Sinh; } bool is_cosh(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Cosh; } bool is_tanh(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Tanh; } bool is_min(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Min; } bool is_max(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Max; } bool is_ceil(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Ceil; } bool is_floor(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::Floor; } bool is_if_then_else(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::IfThenElse; } bool is_uninterpreted_function(const ExpressionCell& c) { return c.get_kind() == ExpressionKind::UninterpretedFunction; } const ExpressionVar& to_variable(const Expression& e) { DRAKE_ASSERT(is_variable(e)); return static_cast<const ExpressionVar&>(e.cell()); } ExpressionVar& to_variable(Expression* const e) { DRAKE_ASSERT(e && is_variable(*e)); return static_cast<ExpressionVar&>(e->mutable_cell()); } bool is_unary(const ExpressionCell& cell) { return (is_log(cell) || is_abs(cell) || is_exp(cell) || is_sqrt(cell) || is_sin(cell) || is_cos(cell) || is_tan(cell) || is_asin(cell) || is_acos(cell) || is_atan(cell) || is_sinh(cell) || is_cosh(cell) || is_tanh(cell) || is_ceil(cell) || is_floor(cell)); } const UnaryExpressionCell& to_unary(const Expression& e) { DRAKE_ASSERT(is_unary(e.cell())); return static_cast<const UnaryExpressionCell&>(e.cell()); } UnaryExpressionCell& to_unary(Expression* const e) { DRAKE_ASSERT(e && is_unary(e->cell())); return static_cast<UnaryExpressionCell&>(e->mutable_cell()); } bool is_binary(const ExpressionCell& cell) { return (is_division(cell) || is_pow(cell) || is_atan2(cell) || is_min(cell) || is_max(cell)); } const BinaryExpressionCell& to_binary(const Expression& e) { DRAKE_ASSERT(is_binary(e.cell())); return static_cast<const BinaryExpressionCell&>(e.cell()); } BinaryExpressionCell& to_binary(Expression* const e) { DRAKE_ASSERT(e && is_binary(e->cell())); return static_cast<BinaryExpressionCell&>(e->mutable_cell()); } const ExpressionAdd& to_addition(const Expression& e) { DRAKE_ASSERT(is_addition(e)); return static_cast<const ExpressionAdd&>(e.cell()); } ExpressionAdd& to_addition(Expression* const e) { DRAKE_ASSERT(e && is_addition(*e)); return static_cast<ExpressionAdd&>(e->mutable_cell()); } const ExpressionMul& to_multiplication(const Expression& e) { DRAKE_ASSERT(is_multiplication(e)); return static_cast<const ExpressionMul&>(e.cell()); } ExpressionMul& to_multiplication(Expression* const e) { DRAKE_ASSERT(e && is_multiplication(*e)); return static_cast<ExpressionMul&>(e->mutable_cell()); } const ExpressionDiv& to_division(const Expression& e) { DRAKE_ASSERT(is_division(e)); return static_cast<const ExpressionDiv&>(e.cell()); } ExpressionDiv& to_division(Expression* const e) { DRAKE_ASSERT(e && is_division(*e)); return static_cast<ExpressionDiv&>(e->mutable_cell()); } const ExpressionLog& to_log(const Expression& e) { DRAKE_ASSERT(is_log(e)); return static_cast<const ExpressionLog&>(e.cell()); } ExpressionLog& to_log(Expression* const e) { DRAKE_ASSERT(e && is_log(*e)); return static_cast<ExpressionLog&>(e->mutable_cell()); } const ExpressionAbs& to_abs(const Expression& e) { DRAKE_ASSERT(is_abs(e)); return static_cast<const ExpressionAbs&>(e.cell()); } ExpressionAbs& to_abs(Expression* const e) { DRAKE_ASSERT(e && is_abs(*e)); return static_cast<ExpressionAbs&>(e->mutable_cell()); } const ExpressionExp& to_exp(const Expression& e) { DRAKE_ASSERT(is_exp(e)); return static_cast<const ExpressionExp&>(e.cell()); } ExpressionExp& to_exp(Expression* const e) { DRAKE_ASSERT(e && is_exp(*e)); return static_cast<ExpressionExp&>(e->mutable_cell()); } const ExpressionSqrt& to_sqrt(const Expression& e) { DRAKE_ASSERT(is_sqrt(e)); return static_cast<const ExpressionSqrt&>(e.cell()); } ExpressionSqrt& to_sqrt(Expression* const e) { DRAKE_ASSERT(e && is_sqrt(*e)); return static_cast<ExpressionSqrt&>(e->mutable_cell()); } const ExpressionPow& to_pow(const Expression& e) { DRAKE_ASSERT(is_pow(e)); return static_cast<const ExpressionPow&>(e.cell()); } ExpressionPow& to_pow(Expression* const e) { DRAKE_ASSERT(e && is_pow(*e)); return static_cast<ExpressionPow&>(e->mutable_cell()); } const ExpressionSin& to_sin(const Expression& e) { DRAKE_ASSERT(is_sin(e)); return static_cast<const ExpressionSin&>(e.cell()); } ExpressionSin& to_sin(Expression* const e) { DRAKE_ASSERT(e && is_sin(*e)); return static_cast<ExpressionSin&>(e->mutable_cell()); } const ExpressionCos& to_cos(const Expression& e) { DRAKE_ASSERT(is_cos(e)); return static_cast<const ExpressionCos&>(e.cell()); } ExpressionCos& to_cos(Expression* const e) { DRAKE_ASSERT(e && is_cos(*e)); return static_cast<ExpressionCos&>(e->mutable_cell()); } const ExpressionTan& to_tan(const Expression& e) { DRAKE_ASSERT(is_tan(e)); return static_cast<const ExpressionTan&>(e.cell()); } ExpressionTan& to_tan(Expression* const e) { DRAKE_ASSERT(e && is_tan(*e)); return static_cast<ExpressionTan&>(e->mutable_cell()); } const ExpressionAsin& to_asin(const Expression& e) { DRAKE_ASSERT(is_asin(e)); return static_cast<const ExpressionAsin&>(e.cell()); } ExpressionAsin& to_asin(Expression* const e) { DRAKE_ASSERT(e && is_asin(*e)); return static_cast<ExpressionAsin&>(e->mutable_cell()); } const ExpressionAcos& to_acos(const Expression& e) { DRAKE_ASSERT(is_acos(e)); return static_cast<const ExpressionAcos&>(e.cell()); } ExpressionAcos& to_acos(Expression* const e) { DRAKE_ASSERT(e && is_acos(*e)); return static_cast<ExpressionAcos&>(e->mutable_cell()); } const ExpressionAtan& to_atan(const Expression& e) { DRAKE_ASSERT(is_atan(e)); return static_cast<const ExpressionAtan&>(e.cell()); } ExpressionAtan& to_atan(Expression* const e) { DRAKE_ASSERT(e && is_atan(*e)); return static_cast<ExpressionAtan&>(e->mutable_cell()); } const ExpressionAtan2& to_atan2(const Expression& e) { DRAKE_ASSERT(is_atan2(e)); return static_cast<const ExpressionAtan2&>(e.cell()); } ExpressionAtan2& to_atan2(Expression* const e) { DRAKE_ASSERT(e && is_atan2(*e)); return static_cast<ExpressionAtan2&>(e->mutable_cell()); } const ExpressionSinh& to_sinh(const Expression& e) { DRAKE_ASSERT(is_sinh(e)); return static_cast<const ExpressionSinh&>(e.cell()); } ExpressionSinh& to_sinh(Expression* const e) { DRAKE_ASSERT(e && is_sinh(*e)); return static_cast<ExpressionSinh&>(e->mutable_cell()); } const ExpressionCosh& to_cosh(const Expression& e) { DRAKE_ASSERT(is_cosh(e)); return static_cast<const ExpressionCosh&>(e.cell()); } ExpressionCosh& to_cosh(Expression* const e) { DRAKE_ASSERT(e && is_cosh(*e)); return static_cast<ExpressionCosh&>(e->mutable_cell()); } const ExpressionTanh& to_tanh(const Expression& e) { DRAKE_ASSERT(is_tanh(e)); return static_cast<const ExpressionTanh&>(e.cell()); } ExpressionTanh& to_tanh(Expression* const e) { DRAKE_ASSERT(e && is_tanh(*e)); return static_cast<ExpressionTanh&>(e->mutable_cell()); } const ExpressionMin& to_min(const Expression& e) { DRAKE_ASSERT(is_min(e)); return static_cast<const ExpressionMin&>(e.cell()); } ExpressionMin& to_min(Expression* const e) { DRAKE_ASSERT(e && is_min(*e)); return static_cast<ExpressionMin&>(e->mutable_cell()); } const ExpressionMax& to_max(const Expression& e) { DRAKE_ASSERT(is_max(e)); return static_cast<const ExpressionMax&>(e.cell()); } ExpressionMax& to_max(Expression* const e) { DRAKE_ASSERT(e && is_max(*e)); return static_cast<ExpressionMax&>(e->mutable_cell()); } const ExpressionCeiling& to_ceil(const Expression& e) { DRAKE_ASSERT(is_ceil(e)); return static_cast<const ExpressionCeiling&>(e.cell()); } ExpressionCeiling& to_ceil(Expression* const e) { DRAKE_ASSERT(e && is_ceil(*e)); return static_cast<ExpressionCeiling&>(e->mutable_cell()); } const ExpressionFloor& to_floor(const Expression& e) { DRAKE_ASSERT(is_floor(e)); return static_cast<const ExpressionFloor&>(e.cell()); } ExpressionFloor& to_floor(Expression* const e) { DRAKE_ASSERT(e && is_floor(*e)); return static_cast<ExpressionFloor&>(e->mutable_cell()); } const ExpressionIfThenElse& to_if_then_else(const Expression& e) { DRAKE_ASSERT(is_if_then_else(e)); return static_cast<const ExpressionIfThenElse&>(e.cell()); } ExpressionIfThenElse& to_if_then_else(Expression* const e) { DRAKE_ASSERT(e && is_if_then_else(*e)); return static_cast<ExpressionIfThenElse&>(e->mutable_cell()); } const ExpressionUninterpretedFunction& to_uninterpreted_function( const Expression& e) { DRAKE_ASSERT(is_uninterpreted_function(e)); return static_cast<const ExpressionUninterpretedFunction&>(e.cell()); } ExpressionUninterpretedFunction& to_uninterpreted_function( Expression* const e) { DRAKE_ASSERT(e && is_uninterpreted_function(*e)); return static_cast<ExpressionUninterpretedFunction&>(e->mutable_cell()); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/expression.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <algorithm> // for cpplint only #include <cmath> #include <cstddef> #include <functional> #include <limits> #include <map> #include <memory> #include <ostream> #include <random> #include <string> #include <type_traits> #include <unordered_map> #include <utility> #include <vector> #include <Eigen/Core> #include <Eigen/Sparse> #include "drake/common/cond.h" #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/drake_throw.h" #include "drake/common/dummy_value.h" #include "drake/common/eigen_types.h" #include "drake/common/extract_double.h" #include "drake/common/fmt.h" #include "drake/common/hash.h" #include "drake/common/random.h" namespace drake { namespace symbolic { class ExpressionCell; // In expression_cell.h class ExpressionVar; // In expression_cell.h class UnaryExpressionCell; // In expression_cell.h class BinaryExpressionCell; // In expression_cell.h class ExpressionAdd; // In expression_cell.h class ExpressionMul; // In expression_cell.h class ExpressionDiv; // In expression_cell.h class ExpressionLog; // In expression_cell.h class ExpressionAbs; // In expression_cell.h class ExpressionExp; // In expression_cell.h class ExpressionSqrt; // In expression_cell.h class ExpressionPow; // In expression_cell.h class ExpressionSin; // In expression_cell.h class ExpressionCos; // In expression_cell.h class ExpressionTan; // In expression_cell.h class ExpressionAsin; // In expression_cell.h class ExpressionAcos; // In expression_cell.h class ExpressionAtan; // In expression_cell.h class ExpressionAtan2; // In expression_cell.h class ExpressionSinh; // In expression_cell.h class ExpressionCosh; // In expression_cell.h class ExpressionTanh; // In expression_cell.h class ExpressionMin; // In expression_cell.h class ExpressionMax; // In expression_cell.h class ExpressionCeiling; // In expression_cell.h class ExpressionFloor; // In expression_cell.h class ExpressionIfThenElse; // In expression_cell.h class ExpressionUninterpretedFunction; // In expression_cell.h class Formula; // In formula.h class Expression; // Substitution is a map from a Variable to a symbolic expression. It is used in // Expression::Substitute and Formula::Substitute methods as an argument. using Substitution = std::unordered_map<Variable, Expression>; namespace internal { template <bool> struct Gemm; // Defined later in this file. } // namespace internal /** Represents a symbolic form of an expression. Its syntax tree is as follows: @verbatim E := Var | Constant | E + ... + E | E * ... * E | E / E | log(E) | abs(E) | exp(E) | sqrt(E) | pow(E, E) | sin(E) | cos(E) | tan(E) | asin(E) | acos(E) | atan(E) | atan2(E, E) | sinh(E) | cosh(E) | tanh(E) | min(E, E) | max(E, E) | ceil(E) | floor(E) | if_then_else(F, E, E) | NaN | uninterpreted_function(name, {v_1, ..., v_n}) @endverbatim In the implementation, Expression directly stores Constant values inline, but in all other cases stores a shared pointer to a const ExpressionCell class that is a super-class of different kinds of symbolic expressions (i.e., ExpressionAdd, ExpressionMul, ExpressionLog, ExpressionSin), which makes it efficient to copy, move, and assign to an Expression. @note -E is represented as -1 * E internally. @note A subtraction E1 - E2 is represented as E1 + (-1 * E2) internally. The following simple simplifications are implemented: @verbatim E + 0 -> E 0 + E -> E E - 0 -> E E - E -> 0 E * 1 -> E 1 * E -> E E * 0 -> 0 0 * E -> 0 E / 1 -> E E / E -> 1 pow(E, 0) -> 1 pow(E, 1) -> E E * E -> E^2 (= pow(E, 2)) sqrt(E * E) -> |E| (= abs(E)) sqrt(E) * sqrt(E) -> E @endverbatim Constant folding is implemented: @verbatim E(c1) + E(c2) -> E(c1 + c2) // c1, c2 are constants E(c1) - E(c2) -> E(c1 - c2) E(c1) * E(c2) -> E(c1 * c2) E(c1) / E(c2) -> E(c1 / c2) f(E(c)) -> E(f(c)) // c is a constant, f is a math function @endverbatim For the math functions which are only defined over a restricted domain (namely, log, sqrt, pow, asin, acos), we check the domain of argument(s), and throw std::domain_error exception if a function is not well-defined for a given argument(s). Relational operators over expressions (==, !=, <, >, <=, >=) return symbolic::Formula instead of bool. Those operations are declared in formula.h file. To check structural equality between two expressions a separate function, Expression::EqualTo, is provided. Regarding the arithmetic of an Expression when operating on NaNs, we have the following rules: 1. NaN values are extremely rare during typical computations. Because they are difficult to handle symbolically, we will round that up to "must never occur". We allow the user to form ExpressionNaN cells in a symbolic tree. For example, the user can initialize an Expression to NaN and then overwrite it later. However, evaluating a tree that has NaN in its evaluated sub-trees is an error (see rule (3) below). 2. It's still valid for code to check `isnan` in order to fail-fast. So we provide isnan(const Expression&) for the common case of non-NaN value returning False. This way, code can fail-fast with double yet still compile with Expression. 3. If there are expressions that embed separate cases (`if_then_else`), some of the sub-expressions may be not used in evaluation when they are in the not-taken case (for NaN reasons or any other reason). Bad values within those not-taken branches does not cause exceptions. 4. The isnan check is different than if_then_else. In the latter, the ExpressionNaN is within a dead sub-expression branch. In the former, it appears in an evaluated trunk. That goes against rule (1) where a NaN anywhere in a computation (other than dead code) is an error. @internal note for Drake developers: under the hood of Expression, we have an internal::BoxedCell helper class that uses NaN for pointer tagging; that's a distinct concept from the Expression::NaN() rules enumerated just above. symbolic::Expression can be used as a scalar type of Eigen types. */ class Expression { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Expression) ~Expression() = default; /** Default constructor. It constructs Zero(). */ Expression() = default; /** Constructs a constant. */ // NOLINTNEXTLINE(runtime/explicit): This conversion is desirable. Expression(double constant) : boxed_(std::isnan(constant) ? 0.0 : constant) { if (std::isnan(constant)) { ConstructExpressionCellNaN(); } } /** Constructs an expression from @p var. * @pre @p var is not a BOOLEAN variable. */ // NOLINTNEXTLINE(runtime/explicit): This conversion is desirable. Expression(const Variable& var); /** Returns expression kind. */ [[nodiscard]] ExpressionKind get_kind() const { return boxed_.get_kind(); } /** Collects variables in expression. */ [[nodiscard]] Variables GetVariables() const; /** Checks structural equality. * * Two expressions e1 and e2 are structurally equal when they have the same * internal AST(abstract-syntax tree) representation. Please note that we can * have two computationally (or extensionally) equivalent expressions which * are not structurally equal. For example, consider: * * e1 = 2 * (x + y) * e2 = 2x + 2y * * Obviously, we know that e1 and e2 are evaluated to the same value for all * assignments to x and y. However, e1 and e2 are not structurally equal by * the definition. Note that e1 is a multiplication expression * (is_multiplication(e1) is true) while e2 is an addition expression * (is_addition(e2) is true). * * One main reason we use structural equality in EqualTo is due to * Richardson's Theorem. It states that checking ∀x. E(x) = F(x) is * undecidable when we allow sin, asin, log, exp in E and F. Read * https://en.wikipedia.org/wiki/Richardson%27s_theorem for details. * * Note that for polynomial cases, you can use Expand method and check if two * polynomial expressions p1 and p2 are computationally equal. To do so, you * check the following: * * p1.Expand().EqualTo(p2.Expand()) */ [[nodiscard]] bool EqualTo(const Expression& e) const; /** Provides lexicographical ordering between expressions. This function is used as a compare function in map<Expression> and set<Expression> via std::less<drake::symbolic::Expression>. */ [[nodiscard]] bool Less(const Expression& e) const; /** Checks if this symbolic expression is convertible to Polynomial. */ [[nodiscard]] bool is_polynomial() const; /** Evaluates using a given environment (by default, an empty environment) and * a random number generator. If there is a random variable in this expression * which is unassigned in @p env, this method uses @p random_generator to * sample a value and use the value to substitute all occurrences of the * variable in this expression. * * @throws std::exception if there exists a non-random variable in this * expression whose assignment is not provided by * @p env. * @throws std::exception if an unassigned random variable is detected * while @p random_generator is `nullptr`. * @throws std::exception if NaN is detected during evaluation. */ double Evaluate(const Environment& env = Environment{}, RandomGenerator* random_generator = nullptr) const; /** Evaluates using an empty environment and a random number generator. It * uses @p random_generator to sample values for the random variables in this * expression. * * See the above overload for the exceptions that it might throw. */ double Evaluate(RandomGenerator* random_generator) const; /** Partially evaluates this expression using an environment @p * env. Internally, this method promotes @p env into a substitution * (Variable → Expression) and call Evaluate::Substitute with it. * * @throws std::exception if NaN is detected during evaluation. */ [[nodiscard]] Expression EvaluatePartial(const Environment& env) const; /** Returns true if this symbolic expression is already * expanded. Expression::Expand() uses this flag to avoid calling * ExpressionCell::Expand() on an pre-expanded expressions. * Expression::Expand() also sets this flag before returning the result. * * @note This check is conservative in that `false` does not always indicate * that the expression is not expanded. This is because exact checks can be * costly and we want to avoid the exact check at the construction time. */ [[nodiscard]] bool is_expanded() const; /** Expands out products and positive integer powers in expression. For * example, `(x + 1) * (x - 1)` is expanded to `x^2 - 1` and `(x + y)^2` is * expanded to `x^2 + 2xy + y^2`. Note that Expand applies recursively to * sub-expressions. For instance, `sin(2 * (x + y))` is expanded to `sin(2x + * 2y)`. It also simplifies "division by constant" cases. See * "drake/common/test/symbolic_expansion_test.cc" to find the examples. * * @throws std::exception if NaN is detected during expansion. */ [[nodiscard]] Expression Expand() const; /** Returns a copy of this expression replacing all occurrences of @p var * with @p e. * @throws std::exception if NaN is detected during substitution. */ [[nodiscard]] Expression Substitute(const Variable& var, const Expression& e) const; /** Returns a copy of this expression replacing all occurrences of the * variables in @p s with corresponding expressions in @p s. Note that the * substitutions occur simultaneously. For example, (x / y).Substitute({{x, * y}, {y, x}}) gets (y / x). * @throws std::exception if NaN is detected during substitution. */ [[nodiscard]] Expression Substitute(const Substitution& s) const; /** Differentiates this symbolic expression with respect to the variable @p * var. * @throws std::exception if it is not differentiable. */ [[nodiscard]] Expression Differentiate(const Variable& x) const; /** Let `f` be this Expression, computes a row vector of derivatives, * `[∂f/∂vars(0), ... , ∂f/∂vars(n-1)]` with respect to the variables * @p vars. */ [[nodiscard]] RowVectorX<Expression> Jacobian( const Eigen::Ref<const VectorX<Variable>>& vars) const; /** Returns string representation of Expression. */ [[nodiscard]] std::string to_string() const; /** Returns zero. */ static Expression Zero() { return 0.0; } /** Returns one. */ static Expression One() { return 1.0; } /** Returns Pi, the ratio of a circle’s circumference to its diameter. */ static Expression Pi() { return M_PI; } /** Return e, the base of natural logarithms. */ static Expression E() { return M_E; } /** Returns NaN (Not-a-Number). */ static Expression NaN(); /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const Expression& item) noexcept { DelegatingHasher delegating_hasher( [&hasher](const void* data, const size_t length) { return hasher(data, length); }); item.HashAppend(&delegating_hasher); } friend Expression operator+(Expression lhs, const Expression& rhs) { lhs += rhs; return lhs; } // NOLINTNEXTLINE(runtime/references) per C++ standard signature. friend Expression& operator+=(Expression& lhs, const Expression& rhs) { // Simplification: Expression(c1) + Expression(c2) => Expression(c1 + c2) // // Recall that BoxedCell can efficiently provide us with a `double` that is // either the Constant stored inside the box, or else is NaN. // // When both the lhs and rhs are constants, we need to perform the addition // inline, for performance. For that case, it's more efficient to perform // the sum and then check for NaN afterward (returning immediately in case // it wasn't, i.e., terms were Constant) rather that doing two separate // checks for lhs.is_constant() and rhs.is_constant() ahead of time. // // Note that operations on infinities might also produce a NaN as the // speculative value. That's fine, we'll handle it during AddImpl; that // case is rare, so doesn't need to be inline. const double speculative_value = lhs.boxed_.constant_or_nan() + rhs.boxed_.constant_or_nan(); if (!std::isnan(speculative_value)) { lhs.boxed_.update_constant(speculative_value); } else { lhs.AddImpl(rhs); } return lhs; } /** Provides prefix increment operator (i.e. ++x). */ Expression& operator++(); /** Provides postfix increment operator (i.e. x++). */ Expression operator++(int); /** Provides unary plus operator. */ friend Expression operator+(const Expression& e); friend Expression operator-(Expression lhs, const Expression& rhs) { lhs -= rhs; return lhs; } // NOLINTNEXTLINE(runtime/references) per C++ standard signature. friend Expression& operator-=(Expression& lhs, const Expression& rhs) { // Simplification: Expression(c1) - Expression(c2) => Expression(c1 - c2) // Refer to operator+= comment for how the speculative_value works here. const double speculative_value = lhs.boxed_.constant_or_nan() - rhs.boxed_.constant_or_nan(); if (!std::isnan(speculative_value)) { lhs.boxed_.update_constant(speculative_value); } else { lhs.SubImpl(rhs); } return lhs; } /** Provides unary minus operator. */ friend Expression operator-(const Expression& e); /** Provides prefix decrement operator (i.e. --x). */ Expression& operator--(); /** Provides postfix decrement operator (i.e. x--). */ Expression operator--(int); friend Expression operator*(Expression lhs, const Expression& rhs) { lhs *= rhs; return lhs; } // NOLINTNEXTLINE(runtime/references) per C++ standard signature. friend Expression& operator*=(Expression& lhs, const Expression& rhs) { // Simplification: Expression(c1) * Expression(c2) => Expression(c1 * c2) // Refer to operator+= comment for how the speculative_value works here. const double speculative_value = lhs.boxed_.constant_or_nan() * rhs.boxed_.constant_or_nan(); if (!std::isnan(speculative_value)) { lhs.boxed_.update_constant(speculative_value); } else { lhs.MulImpl(rhs); } return lhs; } friend Expression operator/(Expression lhs, const Expression& rhs) { lhs /= rhs; return lhs; } // NOLINTNEXTLINE(runtime/references) per C++ standard signature. friend Expression& operator/=(Expression& lhs, const Expression& rhs) { // Simplification: Expression(c1) / Expression(c2) => Expression(c1 / c2) // Refer to operator+= comment for how the speculative_value works here. // // We check rhs for zero here because DivImpl needs to throw an exception // in that case. TODO(jwnimmer-tri) I don't understand why we need to throw // during division by zero. The result is typically well-defined (infinity). const double rhs_or_nan = rhs.boxed_.constant_or_nan(); const double speculative_value = lhs.boxed_.constant_or_nan() / rhs_or_nan; if ((rhs_or_nan != 0.0) && !std::isnan(speculative_value)) { lhs.boxed_.update_constant(speculative_value); } else { lhs.DivImpl(rhs); } return lhs; } friend Expression log(const Expression& e); friend Expression abs(const Expression& e); friend Expression exp(const Expression& e); friend Expression sqrt(const Expression& e); friend Expression pow(const Expression& e1, const Expression& e2); friend Expression sin(const Expression& e); friend Expression cos(const Expression& e); friend Expression tan(const Expression& e); friend Expression asin(const Expression& e); friend Expression acos(const Expression& e); friend Expression atan(const Expression& e); friend Expression atan2(const Expression& e1, const Expression& e2); friend Expression sinh(const Expression& e); friend Expression cosh(const Expression& e); friend Expression tanh(const Expression& e); friend Expression min(const Expression& e1, const Expression& e2); friend Expression max(const Expression& e1, const Expression& e2); friend Expression clamp(const Expression& v, const Expression& lo, const Expression& hi); friend Expression ceil(const Expression& e); friend Expression floor(const Expression& e); /** Constructs if-then-else expression. @verbatim if_then_else(cond, expr_then, expr_else) @endverbatim The value returned by the above if-then-else expression is @p expr_then if @p cond is evaluated to true. Otherwise, it returns @p expr_else. The semantics is similar to the C++'s conditional expression constructed by its ternary operator, @c ?:. However, there is a key difference between the C++'s conditional expression and our @c if_then_else expression in a way the arguments are evaluated during the construction. - In case of the C++'s conditional expression, <tt> cond ? expr_then : expr_else</tt>, the then expression @c expr_then (respectively, the else expression @c expr_else) is \b only evaluated when the conditional expression @c cond is evaluated to \b true (respectively, when @c cond is evaluated to \b false). - In case of the symbolic expression, <tt>if_then_else(cond, expr_then, expr_else)</tt>, however, \b both arguments @c expr_then and @c expr_else are evaluated first and then passed to the @c if_then_else function. @note This function returns an \b expression and it is different from the C++'s if-then-else \b statement. @note While it is still possible to define <tt> min, max, abs</tt> math functions using @c if_then_else expression, it is highly \b recommended to use the provided native definitions for them because it allows solvers to detect specific math functions and to have a room for special optimizations. @note More information about the C++'s conditional expression and ternary operator is available at http://en.cppreference.com/w/cpp/language/operator_other#Conditional_operator. */ friend Expression if_then_else(const Formula& f_cond, const Expression& e_then, const Expression& e_else); friend Expression uninterpreted_function(std::string name, std::vector<Expression> arguments); friend std::ostream& operator<<(std::ostream& os, const Expression& e); friend void swap(Expression& a, Expression& b) { std::swap(a.boxed_, b.boxed_); } friend bool is_constant(const Expression& e); friend bool is_constant(const Expression& e, double value); friend bool is_nan(const Expression& e); friend bool is_variable(const Expression& e); friend bool is_addition(const Expression& e); friend bool is_multiplication(const Expression& e); friend bool is_division(const Expression& e); friend bool is_log(const Expression& e); friend bool is_abs(const Expression& e); friend bool is_exp(const Expression& e); friend bool is_sqrt(const Expression& e); friend bool is_pow(const Expression& e); friend bool is_sin(const Expression& e); friend bool is_cos(const Expression& e); friend bool is_tan(const Expression& e); friend bool is_asin(const Expression& e); friend bool is_acos(const Expression& e); friend bool is_atan(const Expression& e); friend bool is_atan2(const Expression& e); friend bool is_sinh(const Expression& e); friend bool is_cosh(const Expression& e); friend bool is_tanh(const Expression& e); friend bool is_min(const Expression& e); friend bool is_max(const Expression& e); friend bool is_ceil(const Expression& e); friend bool is_floor(const Expression& e); friend bool is_if_then_else(const Expression& e); friend bool is_uninterpreted_function(const Expression& e); friend double get_constant_value(const Expression& e); // Note that the following cast functions are only for low-level operations // and not exposed to the user of drake/common/symbolic/expression.h header. // These functions are declared in the expression_cell.h header. friend const ExpressionVar& to_variable(const Expression& e); friend const UnaryExpressionCell& to_unary(const Expression& e); friend const BinaryExpressionCell& to_binary(const Expression& e); friend const ExpressionAdd& to_addition(const Expression& e); friend const ExpressionMul& to_multiplication(const Expression& e); friend const ExpressionDiv& to_division(const Expression& e); friend const ExpressionLog& to_log(const Expression& e); friend const ExpressionAbs& to_abs(const Expression& e); friend const ExpressionExp& to_exp(const Expression& e); friend const ExpressionSqrt& to_sqrt(const Expression& e); friend const ExpressionPow& to_pow(const Expression& e); friend const ExpressionSin& to_sin(const Expression& e); friend const ExpressionCos& to_cos(const Expression& e); friend const ExpressionTan& to_tan(const Expression& e); friend const ExpressionAsin& to_asin(const Expression& e); friend const ExpressionAcos& to_acos(const Expression& e); friend const ExpressionAtan& to_atan(const Expression& e); friend const ExpressionAtan2& to_atan2(const Expression& e); friend const ExpressionSinh& to_sinh(const Expression& e); friend const ExpressionCosh& to_cosh(const Expression& e); friend const ExpressionTanh& to_tanh(const Expression& e); friend const ExpressionMin& to_min(const Expression& e); friend const ExpressionMax& to_max(const Expression& e); friend const ExpressionCeiling& to_ceil(const Expression& e); friend const ExpressionFloor& to_floor(const Expression& e); friend const ExpressionIfThenElse& to_if_then_else(const Expression& e); friend const ExpressionUninterpretedFunction& to_uninterpreted_function( const Expression& e); // Cast functions which takes a pointer to a non-const Expression. friend ExpressionVar& to_variable(Expression* e); friend UnaryExpressionCell& to_unary(Expression* e); friend BinaryExpressionCell& to_binary(Expression* e); friend ExpressionAdd& to_addition(Expression* e); friend ExpressionMul& to_multiplication(Expression* e); friend ExpressionDiv& to_division(Expression* e); friend ExpressionLog& to_log(Expression* e); friend ExpressionAbs& to_abs(Expression* e); friend ExpressionExp& to_exp(Expression* e); friend ExpressionSqrt& to_sqrt(Expression* e); friend ExpressionPow& to_pow(Expression* e); friend ExpressionSin& to_sin(Expression* e); friend ExpressionCos& to_cos(Expression* e); friend ExpressionTan& to_tan(Expression* e); friend ExpressionAsin& to_asin(Expression* e); friend ExpressionAcos& to_acos(Expression* e); friend ExpressionAtan& to_atan(Expression* e); friend ExpressionAtan2& to_atan2(Expression* e); friend ExpressionSinh& to_sinh(Expression* e); friend ExpressionCosh& to_cosh(Expression* e); friend ExpressionTanh& to_tanh(Expression* e); friend ExpressionMin& to_min(Expression* e); friend ExpressionMax& to_max(Expression* e); friend ExpressionCeiling& to_ceil(Expression* e); friend ExpressionFloor& to_floor(Expression* e); friend ExpressionIfThenElse& to_if_then_else(Expression* e); friend ExpressionUninterpretedFunction& to_uninterpreted_function( Expression* e); friend class ExpressionAddFactory; friend class ExpressionMulFactory; template <bool> friend struct internal::Gemm; private: explicit Expression(std::unique_ptr<ExpressionCell> cell); void ConstructExpressionCellNaN(); void HashAppend(DelegatingHasher* hasher) const; void AddImpl(const Expression& rhs); void SubImpl(const Expression& rhs); void MulImpl(const Expression& rhs); void DivImpl(const Expression& rhs); // Returns a const reference to the owned cell. // @pre This expression is not a Constant. const ExpressionCell& cell() const { return boxed_.cell(); } // Returns a mutable reference to the owned cell. This function may only be // called when this object is the sole owner of the cell (use_count == 1). // @pre This expression is not an ExpressionKind::Constant. ExpressionCell& mutable_cell(); internal::BoxedCell boxed_; }; Expression operator+(Expression lhs, const Expression& rhs); // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Expression& operator+=(Expression& lhs, const Expression& rhs); Expression operator+(const Expression& e); Expression operator-(Expression lhs, const Expression& rhs); // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Expression& operator-=(Expression& lhs, const Expression& rhs); Expression operator-(const Expression& e); Expression operator*(Expression lhs, const Expression& rhs); // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Expression& operator*=(Expression& lhs, const Expression& rhs); Expression operator/(Expression lhs, const Expression& rhs); // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Expression& operator/=(Expression& lhs, const Expression& rhs); Expression log(const Expression& e); Expression abs(const Expression& e); Expression exp(const Expression& e); Expression sqrt(const Expression& e); Expression pow(const Expression& e1, const Expression& e2); Expression sin(const Expression& e); Expression cos(const Expression& e); Expression tan(const Expression& e); Expression asin(const Expression& e); Expression acos(const Expression& e); Expression atan(const Expression& e); Expression atan2(const Expression& e1, const Expression& e2); Expression sinh(const Expression& e); Expression cosh(const Expression& e); Expression tanh(const Expression& e); Expression min(const Expression& e1, const Expression& e2); Expression max(const Expression& e1, const Expression& e2); Expression clamp(const Expression& v, const Expression& lo, const Expression& hi); Expression ceil(const Expression& e); Expression floor(const Expression& e); Expression if_then_else(const Formula& f_cond, const Expression& e_then, const Expression& e_else); /** Constructs an uninterpreted-function expression with @p name and @p * arguments. An uninterpreted function is an opaque function that has no other * property than its name and a list of its arguments. This is useful to * applications where it is good enough to provide abstract information of a * function without exposing full details. Declaring sparsity of a system is a * typical example. */ Expression uninterpreted_function(std::string name, std::vector<Expression> arguments); void swap(Expression& a, Expression& b); std::ostream& operator<<(std::ostream& os, const Expression& e); /** Checks if @p e is a constant expression. */ inline bool is_constant(const Expression& e) { return e.boxed_.is_constant(); } /** Checks if @p e is a constant expression representing @p v. */ inline bool is_constant(const Expression& e, double v) { // N.B. This correctly returns `false` even when comparing e's cell against // a `v` value of NaN, because NaN == NaN is false. return e.boxed_.constant_or_nan() == v; } /** Checks if @p e is 0.0. */ inline bool is_zero(const Expression& e) { return is_constant(e, 0.0); } /** Checks if @p e is 1.0. */ inline bool is_one(const Expression& e) { return is_constant(e, 1.0); } /** Checks if @p e is -1.0. */ inline bool is_neg_one(const Expression& e) { return is_constant(e, -1.0); } /** Checks if @p e is 2.0. */ inline bool is_two(const Expression& e) { return is_constant(e, 2.0); } /** Checks if @p e is NaN. */ inline bool is_nan(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::NaN>(); } /** Checks if @p e is a variable expression. */ inline bool is_variable(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Var>(); } /** Checks if @p e is an addition expression. */ inline bool is_addition(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Add>(); } /** Checks if @p e is a multiplication expression. */ inline bool is_multiplication(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Mul>(); } /** Checks if @p e is a division expression. */ inline bool is_division(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Div>(); } /** Checks if @p e is a log expression. */ inline bool is_log(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Log>(); } /** Checks if @p e is an abs expression. */ inline bool is_abs(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Abs>(); } /** Checks if @p e is an exp expression. */ inline bool is_exp(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Exp>(); } /** Checks if @p e is a square-root expression. */ inline bool is_sqrt(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Sqrt>(); } /** Checks if @p e is a power-function expression. */ inline bool is_pow(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Pow>(); } /** Checks if @p e is a sine expression. */ inline bool is_sin(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Sin>(); } /** Checks if @p e is a cosine expression. */ inline bool is_cos(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Cos>(); } /** Checks if @p e is a tangent expression. */ inline bool is_tan(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Tan>(); } /** Checks if @p e is an arcsine expression. */ inline bool is_asin(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Asin>(); } /** Checks if @p e is an arccosine expression. */ inline bool is_acos(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Acos>(); } /** Checks if @p e is an arctangent expression. */ inline bool is_atan(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Atan>(); } /** Checks if @p e is an arctangent2 expression. */ inline bool is_atan2(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Atan2>(); } /** Checks if @p e is a hyperbolic-sine expression. */ inline bool is_sinh(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Sinh>(); } /** Checks if @p e is a hyperbolic-cosine expression. */ inline bool is_cosh(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Cosh>(); } /** Checks if @p e is a hyperbolic-tangent expression. */ inline bool is_tanh(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Tanh>(); } /** Checks if @p e is a min expression. */ inline bool is_min(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Min>(); } /** Checks if @p e is a max expression. */ inline bool is_max(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Max>(); } /** Checks if @p e is a ceil expression. */ inline bool is_ceil(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Ceil>(); } /** Checks if @p e is a floor expression. */ inline bool is_floor(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::Floor>(); } /** Checks if @p e is an if-then-else expression. */ inline bool is_if_then_else(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::IfThenElse>(); } /** Checks if @p e is an uninterpreted-function expression. */ inline bool is_uninterpreted_function(const Expression& e) { return e.boxed_.is_kind<ExpressionKind::UninterpretedFunction>(); } /** Returns the constant value of the constant expression @p e. * \pre{@p e is a constant expression.} */ inline double get_constant_value(const Expression& e) { return e.boxed_.constant(); } /** Returns the embedded variable in the variable expression @p e. * \pre{@p e is a variable expression.} */ const Variable& get_variable(const Expression& e); /** Returns the argument in the unary expression @p e. * \pre{@p e is a unary expression.} */ const Expression& get_argument(const Expression& e); /** Returns the first argument of the binary expression @p e. * \pre{@p e is a binary expression.} */ const Expression& get_first_argument(const Expression& e); /** Returns the second argument of the binary expression @p e. * \pre{@p e is a binary expression.} */ const Expression& get_second_argument(const Expression& e); /** Returns the constant part of the addition expression @p e. For instance, * given 7 + 2 * x + 3 * y, it returns 7. * \pre{@p e is an addition expression.} */ double get_constant_in_addition(const Expression& e); /** Returns the map from an expression to its coefficient in the addition * expression @p e. For instance, given 7 + 2 * x + 3 * y, the return value * maps 'x' to 2 and 'y' to 3. * \pre{@p e is an addition expression.} */ const std::map<Expression, double>& get_expr_to_coeff_map_in_addition( const Expression& e); /** Returns the constant part of the multiplication expression @p e. For * instance, given 7 * x^2 * y^3, it returns 7. * \pre{@p e is a multiplication expression.} */ double get_constant_in_multiplication(const Expression& e); /** Returns the map from a base expression to its exponent expression in the * multiplication expression @p e. For instance, given 7 * x^2 * y^3 * z^x, the * return value maps 'x' to 2, 'y' to 3, and 'z' to 'x'. * \pre{@p e is a multiplication expression.} */ const std::map<Expression, Expression>& get_base_to_exponent_map_in_multiplication(const Expression& e); /** Returns the name of an uninterpreted-function expression @p e. * \pre @p e is an uninterpreted-function expression. */ const std::string& get_uninterpreted_function_name(const Expression& e); /** Returns the arguments of an uninterpreted-function expression @p e. * \pre @p e is an uninterpreted-function expression. */ const std::vector<Expression>& get_uninterpreted_function_arguments( const Expression& e); /** Returns the conditional formula in the if-then-else expression @p e. * @pre @p e is an if-then-else expression. */ const Formula& get_conditional_formula(const Expression& e); /** Returns the 'then' expression in the if-then-else expression @p e. * @pre @p e is an if-then-else expression. */ const Expression& get_then_expression(const Expression& e); /** Returns the 'else' expression in the if-then-else expression @p e. * @pre @p e is an if-then-else expression. */ const Expression& get_else_expression(const Expression& e); Expression operator+(const Variable& var); Expression operator-(const Variable& var); /// Returns the Taylor series expansion of `f` around `a` of order `order`. /// /// @param[in] f Symbolic expression to approximate using Taylor series /// expansion. /// @param[in] a Symbolic environment which specifies the point of /// approximation. If a partial environment is provided, /// the unspecified variables are treated as symbolic /// variables (e.g. decision variable). /// @param[in] order Positive integer which specifies the maximum order of the /// resulting polynomial approximating `f` around `a`. Expression TaylorExpand(const Expression& f, const Environment& a, int order); } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::Expression>. */ template <> struct hash<drake::symbolic::Expression> : public drake::DefaultHash {}; #if defined(__GLIBCXX__) // https://gcc.gnu.org/onlinedocs/libstdc++/manual/unordered_associative.html template <> struct __is_fast_hash<hash<drake::symbolic::Expression>> : std::false_type {}; #endif /* Provides std::less<drake::symbolic::Expression>. */ template <> struct less<drake::symbolic::Expression> { bool operator()(const drake::symbolic::Expression& lhs, const drake::symbolic::Expression& rhs) const { return lhs.Less(rhs); } }; /* Provides std::equal_to<drake::symbolic::Expression>. */ template <> struct equal_to<drake::symbolic::Expression> { bool operator()(const drake::symbolic::Expression& lhs, const drake::symbolic::Expression& rhs) const { return lhs.EqualTo(rhs); } }; /* Provides std::numeric_limits<drake::symbolic::Expression>. */ template <> struct numeric_limits<drake::symbolic::Expression> : public std::numeric_limits<double> {}; /// Provides std::uniform_real_distribution, U(a, b), for symbolic expressions. /// /// When operator() is called, it returns a symbolic expression `a + (b - a) * /// v` where v is a symbolic random variable associated with the standard /// uniform distribution. /// /// @see std::normal_distribution<drake::symbolic::Expression> for the internal /// representation of this implementation. template <> class uniform_real_distribution<drake::symbolic::Expression> { public: using RealType = drake::symbolic::Expression; using result_type = RealType; /// Constructs a new distribution object with a minimum value @p a and a /// maximum value @p b. /// /// @throws std::exception if a and b are constant expressions but a > b. explicit uniform_real_distribution(RealType a, RealType b = 1.0) : a_{std::move(a)}, b_{std::move(b)}, random_variables_{std::make_shared<std::vector<Variable>>()} { if (is_constant(a_) && is_constant(b_) && get_constant_value(a_) > get_constant_value(b_)) { throw std::runtime_error( "In constructing a uniform_real_distribution<Expression>, we " "detected that the minimum distribution parameter " + a_.to_string() + " is greater than the maximum distribution parameter " + b_.to_string() + "."); } } /// Constructs a new distribution object with a = 0.0 and b = 1.0. uniform_real_distribution() : uniform_real_distribution{0.0} {} DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(uniform_real_distribution); /// Resets the internal state of the distribution object. void reset() { index_ = 0; } /// Generates a symbolic expression representing a random value that is /// distributed according to the associated probability function. result_type operator()() { if (random_variables_->size() == index_) { random_variables_->emplace_back( "random_uniform_" + std::to_string(index_), drake::symbolic::Variable::Type::RANDOM_UNIFORM); } const drake::symbolic::Variable& v{(*random_variables_)[index_++]}; return a_ + (b_ - a_) * v; } /// Generates a symbolic expression representing a random value that is /// distributed according to the associated probability function. /// /// @note We provide this method, which takes a random generator, for /// compatibility with the std::uniform_real_distribution::operator(). template <class Generator> result_type operator()(Generator&) { return (*this)(); } /// Returns the minimum value a. [[nodiscard]] RealType a() const { return a_; } /// Returns the maximum value b. [[nodiscard]] RealType b() const { return b_; } /// Returns the minimum potentially generated value. [[nodiscard]] result_type min() const { return a_; } /// Returns the maximum potentially generated value. [[nodiscard]] result_type max() const { return b_; } private: using Variable = drake::symbolic::Variable; RealType a_; RealType b_; std::shared_ptr<std::vector<Variable>> random_variables_; std::vector<Variable>::size_type index_{0}; friend bool operator==( const uniform_real_distribution<drake::symbolic::Expression>& lhs, const uniform_real_distribution<drake::symbolic::Expression>& rhs) { return lhs.a().EqualTo(rhs.a()) && lhs.b().EqualTo(rhs.b()) && (lhs.index_ == rhs.index_) && (lhs.random_variables_ == rhs.random_variables_); } }; inline bool operator!=( const uniform_real_distribution<drake::symbolic::Expression>& lhs, const uniform_real_distribution<drake::symbolic::Expression>& rhs) { return !(lhs == rhs); } // TODO(jwnimmer-tri) Rewrite this as a fmt::formatter specialization. inline std::ostream& operator<<( std::ostream& os, const uniform_real_distribution<drake::symbolic::Expression>& d) { return os << d.a() << " " << d.b(); } /// Provides std::normal_distribution, N(μ, σ), for symbolic expressions. /// /// When operator() is called, it returns a symbolic expression `μ + σ * v` /// where v is a symbolic random variable associated with the standard normal /// (Gaussian) distribution. /// /// It keeps a shared pointer to the vector of symbolic random variables that /// has been created for the following purposes: /// /// - When `reset()` is called, it rewinds `index_` to zero so that the next /// operator (re)-uses the first symbolic random variable. /// @code /// random_device rd; /// RandomGenerator g{rd()}; /// std::normal_distribution<Expression> d(0.0, 1.0); /// /// const Expression e1{d(g)}; /// const Expression e2{d(g)}; /// d.reset(); /// const Expression e3{d(g)}; /// /// EXPECT_FALSE(e1.EqualTo(e2)); /// EXPECT_TRUE(e1.EqualTo(e3)); /// @endcode /// /// - When an instance of this class is copied, the original and copied /// distributions share the vector of symbolic random variables. We want to /// make sure that the two generate identical sequences of elements. /// @code /// random_device rd; /// RandomGenerator g{rd()}; /// /// std::normal_distribution<Expression> d1(0.0, 1.0); /// std::normal_distribution<Expression> d2(d1); /// const Expression e1_1{d1(g)}; /// const Expression e1_2{d1(g)}; /// /// const Expression e2_1{d2(g)}; /// const Expression e2_2{d2(g)}; /// /// EXPECT_TRUE(e1_1.EqualTo(e2_1)); /// EXPECT_TRUE(e1_2.EqualTo(e2_2)); /// @endcode template <> class normal_distribution<drake::symbolic::Expression> { public: using RealType = drake::symbolic::Expression; using result_type = RealType; /// Constructs a new distribution object with @p mean and @p stddev. /// /// @throws std::exception if stddev is a non-positive constant expression. explicit normal_distribution(RealType mean, RealType stddev = 1.0) : mean_{std::move(mean)}, stddev_{std::move(stddev)}, random_variables_{std::make_shared<std::vector<Variable>>()} { if (is_constant(stddev_) && get_constant_value(stddev_) <= 0) { throw std::runtime_error( "In constructing a normal_distribution<Expression>, we " "detected that the stddev distribution parameter " + stddev_.to_string() + " is non-positive."); } } /// Constructs a new distribution object with mean = 0.0 and stddev = 1.0. normal_distribution() : normal_distribution{0.0} {} DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(normal_distribution); /// Resets the internal state of the distribution object. void reset() { index_ = 0; } /// Generates a symbolic expression representing a random value that is /// distributed according to the associated probability function. result_type operator()() { if (random_variables_->size() == index_) { random_variables_->emplace_back( "random_gaussian_" + std::to_string(index_), drake::symbolic::Variable::Type::RANDOM_GAUSSIAN); } const drake::symbolic::Variable& v{(*random_variables_)[index_++]}; return mean_ + stddev_ * v; } /// Generates a symbolic expression representing a random value that is /// distributed according to the associated probability function. /// /// @note We provide this method, which takes a random generator, for /// compatibility with the std::normal_distribution::operator(). template <class Generator> result_type operator()(Generator&) { return (*this)(); } /// Returns the mean μ distribution parameter. [[nodiscard]] RealType mean() const { return mean_; } /// Returns the deviation σ distribution parameter. [[nodiscard]] RealType stddev() const { return stddev_; } /// Returns the minimum potentially generated value. /// /// @note In libstdc++ std::normal_distribution<> defines min() and max() to /// return -DBL_MAX and DBL_MAX while the one in libc++ returns -INFINITY and /// INFINITY. We follows libc++ and return -INFINITY and INFINITY. [[nodiscard]] result_type min() const { return -std::numeric_limits<double>::infinity(); } /// Returns the maximum potentially generated value.o [[nodiscard]] result_type max() const { return std::numeric_limits<double>::infinity(); } private: using Variable = drake::symbolic::Variable; RealType mean_; RealType stddev_; std::shared_ptr<std::vector<Variable>> random_variables_; std::vector<Variable>::size_type index_{0}; friend bool operator==( const normal_distribution<drake::symbolic::Expression>& lhs, const normal_distribution<drake::symbolic::Expression>& rhs) { return lhs.mean().EqualTo(rhs.mean()) && lhs.stddev().EqualTo(rhs.stddev()) && (lhs.index_ == rhs.index_) && (lhs.random_variables_ == rhs.random_variables_); } }; inline bool operator!=( const normal_distribution<drake::symbolic::Expression>& lhs, const normal_distribution<drake::symbolic::Expression>& rhs) { return !(lhs == rhs); } // TODO(jwnimmer-tri) Rewrite this as a fmt::formatter specialization. inline std::ostream& operator<<( std::ostream& os, const normal_distribution<drake::symbolic::Expression>& d) { return os << d.mean() << " " << d.stddev(); } /// Provides std::exponential_distribution, Exp(λ), for symbolic expressions. /// /// When operator() is called, it returns a symbolic expression `v / λ` where v /// is a symbolic random variable associated with the standard exponential /// distribution (λ = 1). /// /// @see std::normal_distribution<drake::symbolic::Expression> for the internal /// representation of this implementation. template <> class exponential_distribution<drake::symbolic::Expression> { public: using RealType = drake::symbolic::Expression; using result_type = RealType; /// Constructs a new distribution object with @p lambda. /// /// @throws std::exception if lambda is a non-positive constant expression. explicit exponential_distribution(RealType lambda) : lambda_{std::move(lambda)}, random_variables_{std::make_shared<std::vector<Variable>>()} { if (is_constant(lambda_) && get_constant_value(lambda_) <= 0) { throw std::runtime_error( "In constructing an exponential_distribution<Expression>, we " "detected that the lambda distribution parameter " + lambda_.to_string() + " is non-positive."); } } /// Constructs a new distribution object with lambda = 1.0. exponential_distribution() : exponential_distribution{1.0} {} DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(exponential_distribution); /// Resets the internal state of the distribution object. void reset() { index_ = 0; } /// Generates a symbolic expression representing a random value that is /// distributed according to the associated probability function. result_type operator()() { if (random_variables_->size() == index_) { random_variables_->emplace_back( "random_exponential_" + std::to_string(index_), drake::symbolic::Variable::Type::RANDOM_EXPONENTIAL); } const drake::symbolic::Variable& v{(*random_variables_)[index_++]}; return v / lambda_; } /// Generates a symbolic expression representing a random value that is /// distributed according to the associated probability function. /// /// @note We provide this method, which takes a random generator, for /// compatibility with the std::exponential_distribution::operator(). template <class Generator> result_type operator()(Generator&) { return (*this)(); } /// Returns the lambda λ distribution parameter. [[nodiscard]] RealType lambda() const { return lambda_; } /// Returns the minimum potentially generated value. [[nodiscard]] result_type min() const { return 0.0; } /// Returns the maximum potentially generated value. /// @note that in libstdc++ exponential_distribution<>::max() returns DBL_MAX /// while the one in libc++ returns INFINITY. We follows libc++ and return /// INFINITY. [[nodiscard]] result_type max() const { return std::numeric_limits<double>::infinity(); } private: using Variable = drake::symbolic::Variable; RealType lambda_; std::shared_ptr<std::vector<Variable>> random_variables_; std::vector<Variable>::size_type index_{0}; friend bool operator==( const exponential_distribution<drake::symbolic::Expression>& lhs, const exponential_distribution<drake::symbolic::Expression>& rhs) { return lhs.lambda().EqualTo(rhs.lambda()) && (lhs.index_ == rhs.index_) && (lhs.random_variables_ == rhs.random_variables_); } }; inline bool operator!=( const exponential_distribution<drake::symbolic::Expression>& lhs, const exponential_distribution<drake::symbolic::Expression>& rhs) { return !(lhs == rhs); } // TODO(jwnimmer-tri) Rewrite this as a fmt::formatter specialization. inline std::ostream& operator<<( std::ostream& os, const exponential_distribution<drake::symbolic::Expression>& d) { return os << d.lambda(); } } // namespace std #if !defined(DRAKE_DOXYGEN_CXX) // Define Eigen traits needed for Matrix<drake::symbolic::Expression>. namespace Eigen { // Eigen scalar type traits for Matrix<drake::symbolic::Expression>. template <> struct NumTraits<drake::symbolic::Expression> : GenericNumTraits<drake::symbolic::Expression> { static inline int digits10() { return 0; } }; // Informs Eigen that Variable op Variable gets Expression. template <typename BinaryOp> struct ScalarBinaryOpTraits<drake::symbolic::Variable, drake::symbolic::Variable, BinaryOp> { enum { Defined = 1 }; typedef drake::symbolic::Expression ReturnType; }; // Informs Eigen that Variable op Expression gets Expression. template <typename BinaryOp> struct ScalarBinaryOpTraits<drake::symbolic::Variable, drake::symbolic::Expression, BinaryOp> { enum { Defined = 1 }; typedef drake::symbolic::Expression ReturnType; }; // Informs Eigen that Expression op Variable gets Expression. template <typename BinaryOp> struct ScalarBinaryOpTraits<drake::symbolic::Expression, drake::symbolic::Variable, BinaryOp> { enum { Defined = 1 }; typedef drake::symbolic::Expression ReturnType; }; // Informs Eigen that Variable op double gets Expression. template <typename BinaryOp> struct ScalarBinaryOpTraits<drake::symbolic::Variable, double, BinaryOp> { enum { Defined = 1 }; typedef drake::symbolic::Expression ReturnType; }; // Informs Eigen that double op Variable gets Expression. template <typename BinaryOp> struct ScalarBinaryOpTraits<double, drake::symbolic::Variable, BinaryOp> { enum { Defined = 1 }; typedef drake::symbolic::Expression ReturnType; }; // Informs Eigen that Expression op double gets Expression. template <typename BinaryOp> struct ScalarBinaryOpTraits<drake::symbolic::Expression, double, BinaryOp> { enum { Defined = 1 }; typedef drake::symbolic::Expression ReturnType; }; // Informs Eigen that double op Expression gets Expression. template <typename BinaryOp> struct ScalarBinaryOpTraits<double, drake::symbolic::Expression, BinaryOp> { enum { Defined = 1 }; typedef drake::symbolic::Expression ReturnType; }; } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX) namespace drake { namespace symbolic { namespace internal { /* Optimized implementations of BLAS GEMM for symbolic types to take advantage of scalar type specializations. With our current mechanism for hooking this into Eigen, we only need to support the simplified form C ⇐ A@B rather than the more general C ⇐ αA@B+βC of typical GEMM; if we figure out how to hook into Eigen's expression templates, we could expand to the more general form. We group these functions using a struct so that the friendship declaration with Expression can be straightforward. @tparam reverse When true, calculates B@A instead of A@B. */ template <bool reverse> struct Gemm { Gemm() = delete; // Allow for passing numpy.ndarray without copies. template <typename T> using MatrixRef = Eigen::Ref<const MatrixX<T>, 0, StrideX>; // Matrix product for double, Variable. // When reverse == false, sets result to D * V. // When reverse == true, sets result to V * D. static void CalcDV(const MatrixRef<double>& D, const MatrixRef<Variable>& V, EigenPtr<MatrixX<Expression>> result); // Matrix product for Variable, Variable. // When reverse == false, sets result to A * B. // When reverse == true, sets result to B * A. static void CalcVV(const MatrixRef<Variable>& A, const MatrixRef<Variable>& B, EigenPtr<MatrixX<Expression>> result); // Matrix product for double, Expression. // When reverse == false, sets result to D * E. // When reverse == true, sets result to E * D. static void CalcDE(const MatrixRef<double>& D, const MatrixRef<Expression>& E, EigenPtr<MatrixX<Expression>> result); // Matrix product for Variable, Expression. // When reverse == false, sets result to V * E. // When reverse == true, sets result to E * V. static void CalcVE(const MatrixRef<Variable>& V, const MatrixRef<Expression>& E, EigenPtr<MatrixX<Expression>> result); // Matrix product for Expression, Expression. // When reverse == false, sets result to A * B. // When reverse == true, sets result to B * A. static void CalcEE(const MatrixRef<Expression>& A, const MatrixRef<Expression>& B, EigenPtr<MatrixX<Expression>> result); }; /* Eigen promises "automatic conversion of the inner product to a scalar", so when we calculate an inner product we need to return this magic type that acts like both a Matrix1<Expression> and an Expression. There does not appear to be any practical way to mimic what Eigen does, other than multiple inheritance. */ class ExpressionInnerProduct : public Expression, public Eigen::Map<Eigen::Matrix<Expression, 1, 1>> { public: ExpressionInnerProduct() : Map(this) {} void resize(int rows, int cols) { DRAKE_ASSERT(rows == 1 && cols == 1); } }; /* Helper to look up the return type we'll use for an Expression matmul. */ template <typename MatrixL, typename MatrixR> using ExpressionMatMulResult = std::conditional_t<MatrixL::RowsAtCompileTime == 1 && MatrixR::ColsAtCompileTime == 1, ExpressionInnerProduct, Eigen::Matrix<Expression, MatrixL::RowsAtCompileTime, MatrixR::ColsAtCompileTime>>; } // namespace internal // Matrix<Expression> * Matrix<double> => Matrix<Expression> template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && std::is_same_v<typename MatrixL::Scalar, Expression> && std::is_same_v<typename MatrixR::Scalar, double>, internal::ExpressionMatMulResult<MatrixL, MatrixR>> operator*(const MatrixL& lhs, const MatrixR& rhs) { DRAKE_THROW_UNLESS(lhs.cols() == rhs.rows()); internal::ExpressionMatMulResult<MatrixL, MatrixR> result; result.resize(lhs.rows(), rhs.cols()); constexpr bool reverse = true; internal::Gemm<reverse>::CalcDE(rhs, lhs, &result); return result; } // Matrix<double> * Matrix<Expression> => Matrix<Expression> template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && std::is_same_v<typename MatrixL::Scalar, double> && std::is_same_v<typename MatrixR::Scalar, Expression>, internal::ExpressionMatMulResult<MatrixL, MatrixR>> operator*(const MatrixL& lhs, const MatrixR& rhs) { DRAKE_THROW_UNLESS(lhs.cols() == rhs.rows()); internal::ExpressionMatMulResult<MatrixL, MatrixR> result; result.resize(lhs.rows(), rhs.cols()); constexpr bool reverse = false; internal::Gemm<reverse>::CalcDE(lhs, rhs, &result); return result; } // Matrix<Expression> * Matrix<Variable> => Matrix<Expression> template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && std::is_same_v<typename MatrixL::Scalar, Expression> && std::is_same_v<typename MatrixR::Scalar, Variable>, internal::ExpressionMatMulResult<MatrixL, MatrixR>> operator*(const MatrixL& lhs, const MatrixR& rhs) { DRAKE_THROW_UNLESS(lhs.cols() == rhs.rows()); internal::ExpressionMatMulResult<MatrixL, MatrixR> result; result.resize(lhs.rows(), rhs.cols()); constexpr bool reverse = true; internal::Gemm<reverse>::CalcVE(rhs, lhs, &result); return result; } // Matrix<Variable> * Matrix<Expression> => Matrix<Expression> template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && std::is_same_v<typename MatrixL::Scalar, Variable> && std::is_same_v<typename MatrixR::Scalar, Expression>, internal::ExpressionMatMulResult<MatrixL, MatrixR>> operator*(const MatrixL& lhs, const MatrixR& rhs) { DRAKE_THROW_UNLESS(lhs.cols() == rhs.rows()); internal::ExpressionMatMulResult<MatrixL, MatrixR> result; result.resize(lhs.rows(), rhs.cols()); constexpr bool reverse = false; internal::Gemm<reverse>::CalcVE(lhs, rhs, &result); return result; } // Matrix<Variable> * Matrix<double> => Matrix<Expression> template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && std::is_same_v<typename MatrixL::Scalar, Variable> && std::is_same_v<typename MatrixR::Scalar, double>, internal::ExpressionMatMulResult<MatrixL, MatrixR>> operator*(const MatrixL& lhs, const MatrixR& rhs) { DRAKE_THROW_UNLESS(lhs.cols() == rhs.rows()); internal::ExpressionMatMulResult<MatrixL, MatrixR> result; result.resize(lhs.rows(), rhs.cols()); constexpr bool reverse = true; internal::Gemm<reverse>::CalcDV(rhs, lhs, &result); return result; } // Matrix<double> * Matrix<Variable> => Matrix<Expression> template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && std::is_same_v<typename MatrixL::Scalar, double> && std::is_same_v<typename MatrixR::Scalar, Variable>, internal::ExpressionMatMulResult<MatrixL, MatrixR>> operator*(const MatrixL& lhs, const MatrixR& rhs) { DRAKE_THROW_UNLESS(lhs.cols() == rhs.rows()); internal::ExpressionMatMulResult<MatrixL, MatrixR> result; result.resize(lhs.rows(), rhs.cols()); constexpr bool reverse = false; internal::Gemm<reverse>::CalcDV(lhs, rhs, &result); return result; } // Matrix<Variable> * Matrix<Variable> => Matrix<Expression> template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && std::is_same_v<typename MatrixL::Scalar, Variable> && std::is_same_v<typename MatrixR::Scalar, Variable>, internal::ExpressionMatMulResult<MatrixL, MatrixR>> operator*(const MatrixL& lhs, const MatrixR& rhs) { DRAKE_THROW_UNLESS(lhs.cols() == rhs.rows()); internal::ExpressionMatMulResult<MatrixL, MatrixR> result; result.resize(lhs.rows(), rhs.cols()); constexpr bool reverse = false; internal::Gemm<reverse>::CalcVV(lhs, rhs, &result); return result; } // Matrix<Expression> * Matrix<Expression> => Matrix<Expression> template <typename MatrixL, typename MatrixR> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<MatrixL>, MatrixL> && std::is_base_of_v<Eigen::MatrixBase<MatrixR>, MatrixR> && std::is_same_v<typename MatrixL::Scalar, Expression> && std::is_same_v<typename MatrixR::Scalar, Expression>, internal::ExpressionMatMulResult<MatrixL, MatrixR>> operator*(const MatrixL& lhs, const MatrixR& rhs) { internal::ExpressionMatMulResult<MatrixL, MatrixR> result; DRAKE_THROW_UNLESS(lhs.cols() == rhs.rows()); result.resize(lhs.rows(), rhs.cols()); constexpr bool reverse = false; internal::Gemm<reverse>::CalcEE(lhs, rhs, &result); return result; } /// Transform<double> * Transform<Expression> => Transform<Expression> template <int Dim, int LhsMode, int RhsMode, int LhsOptions, int RhsOptions> auto operator*(const Eigen::Transform<Expression, Dim, LhsMode, LhsOptions>& t1, const Eigen::Transform<double, Dim, RhsMode, RhsOptions>& t2) { return t1 * t2.template cast<Expression>(); } /// Transform<Expression> * Transform<double> => Transform<Expression> template <int Dim, int LhsMode, int RhsMode, int LhsOptions, int RhsOptions> auto operator*( const Eigen::Transform<double, Dim, LhsMode, LhsOptions>& t1, const Eigen::Transform<Expression, Dim, RhsMode, RhsOptions>& t2) { return t1.template cast<Expression>() * t2; } /// Evaluates a symbolic matrix @p m using @p env and @p random_generator. /// /// If there is a random variable in @p m which is unassigned in @p env, this /// function uses @p random_generator to sample a value and use the value to /// substitute all occurrences of the random variable in @p m. /// /// @returns a matrix of double whose size is the size of @p m. /// @throws std::exception if NaN is detected during evaluation. /// @throws std::exception if @p m includes unassigned random variables but /// @p random_generator is `nullptr`. /// @pydrake_mkdoc_identifier{expression} template <typename Derived> std::enable_if_t<std::is_same_v<typename Derived::Scalar, Expression>, MatrixLikewise<double, Derived>> Evaluate(const Eigen::MatrixBase<Derived>& m, const Environment& env = Environment{}, RandomGenerator* random_generator = nullptr) { // Note that the return type is written out explicitly to help gcc 5 (on // ubuntu). Previously the implementation used `auto`, and placed an ` // .eval()` at the end to prevent lazy evaluation. if (random_generator == nullptr) { return m.unaryExpr([&env](const Expression& e) { return e.Evaluate(env); }); } else { // Construct an environment by extending `env` by sampling values for the // random variables in `m` which are unassigned in `env`. const Environment env_with_random_variables{PopulateRandomVariables( env, GetDistinctVariables(m), random_generator)}; return m.unaryExpr([&env_with_random_variables](const Expression& e) { return e.Evaluate(env_with_random_variables); }); } } /** Evaluates @p m using a given environment (by default, an empty environment). * * @throws std::exception if there exists a variable in @p m whose value is * not provided by @p env. * @throws std::exception if NaN is detected during evaluation. */ Eigen::SparseMatrix<double> Evaluate( const Eigen::Ref<const Eigen::SparseMatrix<Expression>>& m, const Environment& env = Environment{}); /// Substitutes a symbolic matrix @p m using a given substitution @p subst. /// /// @returns a matrix of symbolic expressions whose size is the size of @p m. /// @throws std::exception if NaN is detected during substitution. template <typename Derived> MatrixLikewise<Expression, Derived> Substitute( const Eigen::MatrixBase<Derived>& m, const Substitution& subst) { static_assert(std::is_same_v<typename Derived::Scalar, Expression>, "Substitute only accepts a symbolic matrix."); // Note that the return type is written out explicitly to help gcc 5 (on // ubuntu). return m.unaryExpr([&subst](const Expression& e) { return e.Substitute(subst); }); } /// Substitutes @p var with @p e in a symbolic matrix @p m. /// /// @returns a matrix of symbolic expressions whose size is the size of @p m. /// @throws std::exception if NaN is detected during substitution. template <typename Derived> MatrixLikewise<Expression, Derived> Substitute( const Eigen::MatrixBase<Derived>& m, const Variable& var, const Expression& e) { static_assert(std::is_same_v<typename Derived::Scalar, Expression>, "Substitute only accepts a symbolic matrix."); // Note that the return type is written out explicitly to help gcc 5 (on // ubuntu). return Substitute(m, Substitution{{var, e}}); } /// Constructs a vector of variables from the vector of variable expressions. /// @throws std::exception if there is an expression in @p vec which is not a /// variable. VectorX<Variable> GetVariableVector( const Eigen::Ref<const VectorX<Expression>>& expressions); /// Computes the Jacobian matrix J of the vector function @p f with respect to /// @p vars. J(i,j) contains ∂f(i)/∂vars(j). /// /// For example, Jacobian([x * cos(y), x * sin(y), x^2], {x, y}) returns the /// following 3x2 matrix: /// <pre> /// = |cos(y) -x * sin(y)| /// |sin(y) x * cos(y)| /// | 2 * x 0| /// </pre> /// /// @pre {@p vars is non-empty}. MatrixX<Expression> Jacobian(const Eigen::Ref<const VectorX<Expression>>& f, const std::vector<Variable>& vars); /// Computes the Jacobian matrix J of the vector function @p f with respect to /// @p vars. J(i,j) contains ∂f(i)/∂vars(j). /// /// @pre {@p vars is non-empty}. /// @pydrake_mkdoc_identifier{expression} MatrixX<Expression> Jacobian(const Eigen::Ref<const VectorX<Expression>>& f, const Eigen::Ref<const VectorX<Variable>>& vars); /// Returns the distinct variables in the matrix of expressions. Variables GetDistinctVariables(const Eigen::Ref<const MatrixX<Expression>>& v); /// Checks if two Eigen::Matrix<Expression> @p m1 and @p m2 are structurally /// equal. That is, it returns true if and only if `m1(i, j)` is structurally /// equal to `m2(i, j)` for all `i`, `j`. template <typename DerivedA, typename DerivedB> typename std::enable_if_t< std::is_base_of_v<Eigen::MatrixBase<DerivedA>, DerivedA> && std::is_base_of_v<Eigen::MatrixBase<DerivedB>, DerivedB> && std::is_same_v<typename DerivedA::Scalar, Expression> && std::is_same_v<typename DerivedB::Scalar, Expression>, bool> CheckStructuralEquality(const DerivedA& m1, const DerivedB& m2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(m1.rows() == m2.rows() && m1.cols() == m2.cols()); // Note that std::equal_to<Expression> calls Expression::EqualTo which checks // structural equality between two expressions. return m1.binaryExpr(m2, std::equal_to<Expression>{}).all(); } } // namespace symbolic /** Provides specialization of @c cond function defined in drake/common/cond.h * file. This specialization is required to handle @c double to @c * symbolic::Expression conversion so that we can write one such as <tt>cond(x > * 0.0, 1.0, -1.0)</tt>. */ template <typename... Rest> symbolic::Expression cond(const symbolic::Formula& f_cond, double v_then, Rest... rest) { return if_then_else(f_cond, symbolic::Expression{v_then}, cond(rest...)); } /// Specializes common/dummy_value.h. template <> struct dummy_value<symbolic::Expression> { static symbolic::Expression get() { return symbolic::Expression::NaN(); } }; /// Returns the symbolic expression's value() as a double. /// /// @throws std::exception if it is not possible to evaluate the symbolic /// expression with an empty environment. double ExtractDoubleOrThrow(const symbolic::Expression& e); /// Returns @p matrix as an Eigen::Matrix<double, ...> with the same size /// allocation as @p matrix. Calls ExtractDoubleOrThrow on each element of the /// matrix, and therefore throws if any one of the extractions fail. template <typename Derived> typename std::enable_if_t< std::is_same_v<typename Derived::Scalar, symbolic::Expression>, MatrixLikewise<double, Derived>> ExtractDoubleOrThrow(const Eigen::MatrixBase<Derived>& matrix) { return matrix .unaryExpr([](const typename Derived::Scalar& value) { return ExtractDoubleOrThrow(value); }) .eval(); } /* * Determine if two EigenBase<> types are matrices (non-column-vectors) of * Expressions and doubles, to then form an implicit formulas. */ template <typename DerivedV, typename DerivedB> struct is_eigen_nonvector_expression_double_pair : std::bool_constant< is_eigen_nonvector_of<DerivedV, symbolic::Expression>::value && is_eigen_nonvector_of<DerivedB, double>::value> {}; /* * Determine if two EigenBase<> types are vectors of Expressions and doubles * that could make a formula. */ template <typename DerivedV, typename DerivedB> struct is_eigen_vector_expression_double_pair : std::bool_constant< is_eigen_vector_of<DerivedV, symbolic::Expression>::value && is_eigen_vector_of<DerivedB, double>::value> {}; } // namespace drake DRAKE_FORMATTER_AS(, drake::symbolic, Expression, e, e.to_string())
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/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:private"]) drake_cc_package_library( name = "expression", visibility = ["//common/symbolic:__pkg__"], deps = [ ":everything", ], ) drake_cc_library( name = "everything", srcs = [ "all.cc", "boxed_cell.cc", "environment.cc", "expression.cc", "expression_cell.cc", "formula.cc", "formula_cell.cc", "ldlt.cc", "variable.cc", "variables.cc", ], hdrs = [ "all.h", "boxed_cell.h", "environment.h", "expression.h", "expression_cell.h", "expression_kind.h", "expression_visitor.h", "formula.h", "formula_cell.h", "formula_visitor.h", "ldlt.h", "variable.h", "variables.h", ], interface_deps = [ "//common:drake_bool", "//common:essential", "//common:hash", "//common:random", "//common:reset_after_move", ], deps = [ "@abseil_cpp_internal//absl/container:flat_hash_set", "@abseil_cpp_internal//absl/container:inlined_vector", "@fmt", ], ) drake_cc_googletest( name = "boxed_cell_test", deps = [ ":expression", ], ) drake_cc_googletest( name = "environment_test", deps = [ ":expression", ], ) drake_cc_googletest( name = "expression_test", deps = [ ":expression", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:is_memcpy_movable", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "expression_array_test", deps = [ ":expression", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "expression_cell_test", deps = [ ":expression", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "expression_differentiation_test", deps = [ ":expression", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "expression_expansion_test", deps = [ ":expression", "//common/test_utilities:limit_malloc", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "expression_jacobian_test", deps = [ ":expression", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "expression_matrix_test", deps = [ ":expression", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "expression_transform_test", deps = [ ":expression", "//common/test_utilities:eigen_matrix_compare", "//math:geometric_transform", ], ) drake_cc_googletest( name = "formula_test", deps = [ ":expression", "//common/test_utilities:expect_no_throw", "//common/test_utilities:is_memcpy_movable", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "formula_visitor_test", deps = [ ":expression", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "ldlt_test", deps = [ ":expression", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", ], ) drake_cc_googletest( name = "mixing_scalar_types_test", deps = [ ":expression", "//common/test_utilities:limit_malloc", ], ) drake_cc_googletest( name = "ostream_test", deps = [ ":expression", ], ) drake_cc_googletest( name = "sparse_test", deps = [ ":expression", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "substitution_test", deps = [ ":expression", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "variable_test", deps = [ ":expression", "//common/test_utilities:is_memcpy_movable", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "variable_overloading_test", deps = [ ":expression", "//common/test_utilities:expect_no_throw", "//common/test_utilities:symbolic_test_util", ], ) drake_cc_googletest( name = "variables_test", deps = [ ":expression", ], ) add_lint_tests()
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/environment.cc
/* clang-format off to disable clang-format-includes */ // NOLINTNEXTLINE(build/include): Our header file is included by all.h. #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <cmath> #include <initializer_list> #include <ostream> #include <random> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <fmt/format.h> namespace drake { namespace symbolic { using std::endl; using std::initializer_list; using std::ostream; using std::ostringstream; using std::runtime_error; using std::string; namespace { void throw_if_nan(const double v) { if (std::isnan(v)) { ostringstream oss; oss << "NaN is detected in the initialization of an environment."; throw runtime_error(oss.str()); } } // Given a list of variables, @p vars, builds an Environment::map which maps a // Variable to its double value. All values are set to 0.0. Environment::map BuildMap(const initializer_list<Environment::key_type> vars) { Environment::map m; for (const Environment::key_type& var : vars) { m.emplace(var, 0.0); } return m; } } // namespace Environment::Environment(const std::initializer_list<value_type> init) : Environment{map(init)} {} Environment::Environment(const std::initializer_list<key_type> vars) : Environment{BuildMap(vars)} {} Environment::Environment(map m) : map_{std::move(m)} { for (const auto& p : map_) { throw_if_nan(p.second); } } void Environment::insert(const key_type& key, const mapped_type& elem) { throw_if_nan(elem); map_.emplace(key, elem); } void Environment::insert( const Eigen::Ref<const MatrixX<key_type>>& keys, const Eigen::Ref<const MatrixX<mapped_type>>& elements) { if (keys.rows() != elements.rows() || keys.cols() != elements.cols()) { throw runtime_error(fmt::format( "symbolic::Environment::insert: The size of keys ({} x {}) " "does not match the size of elements ({} x {}).", keys.rows(), keys.cols(), elements.rows(), elements.cols())); } for (Eigen::Index i = 0; i < keys.cols(); ++i) { for (Eigen::Index j = 0; j < keys.rows(); ++j) { insert(keys(j, i), elements(j, i)); } } } Variables Environment::domain() const { Variables dom; for (const auto& p : map_) { dom += p.first; } return dom; } string Environment::to_string() const { ostringstream oss; oss << *this; return oss.str(); } Environment::mapped_type& Environment::operator[](const key_type& key) { return map_[key]; } const Environment::mapped_type& Environment::operator[]( const key_type& key) const { if (!map_.contains(key)) { ostringstream oss; oss << "Environment::operator[] was called on a const Environment " << "with a missing key \"" << key << "\"."; throw runtime_error(oss.str()); } return map_.at(key); } ostream& operator<<(ostream& os, const Environment& env) { for (const auto& p : env) { os << p.first << " -> " << p.second << endl; } return os; } Environment PopulateRandomVariables(Environment env, const Variables& variables, RandomGenerator* const random_generator) { DRAKE_DEMAND(random_generator != nullptr); for (const Variable& var : variables) { const auto it = env.find(var); if (it != env.end()) { // The variable is already assigned by env, no need to sample. continue; } switch (var.get_type()) { case Variable::Type::CONTINUOUS: case Variable::Type::BINARY: case Variable::Type::BOOLEAN: case Variable::Type::INTEGER: // Do nothing for non-random variables. break; case Variable::Type::RANDOM_UNIFORM: env.insert(var, std::uniform_real_distribution<double>{ 0.0, 1.0}(*random_generator)); break; case Variable::Type::RANDOM_GAUSSIAN: env.insert( var, std::normal_distribution<double>{0.0, 1.0}(*random_generator)); break; case Variable::Type::RANDOM_EXPONENTIAL: env.insert( var, std::exponential_distribution<double>{1.0}(*random_generator)); break; } } return env; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/formula.cc
/* clang-format off to disable clang-format-includes */ // NOLINTNEXTLINE(build/include): Our header file is included by all.h. #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <cstddef> #include <limits> #include <memory> #include <ostream> #include <set> #include <sstream> #include "drake/common/drake_assert.h" #define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/expression/formula_cell.h" #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER namespace drake { namespace symbolic { using std::make_shared; using std::numeric_limits; using std::ostream; using std::ostringstream; using std::set; using std::shared_ptr; using std::string; bool operator<(FormulaKind k1, FormulaKind k2) { return static_cast<int>(k1) < static_cast<int>(k2); } Formula::Formula(std::shared_ptr<const FormulaCell> ptr) : ptr_{std::move(ptr)} {} Formula::Formula(const Variable& var) : ptr_{make_shared<const FormulaVar>(var)} {} FormulaKind Formula::get_kind() const { DRAKE_ASSERT(ptr_ != nullptr); return ptr_->get_kind(); } void Formula::HashAppend(DelegatingHasher* hasher) const { using drake::hash_append; hash_append(*hasher, get_kind()); ptr_->HashAppendDetail(hasher); } Variables Formula::GetFreeVariables() const { DRAKE_ASSERT(ptr_ != nullptr); return ptr_->GetFreeVariables(); } bool Formula::EqualTo(const Formula& f) const { DRAKE_ASSERT(ptr_ != nullptr); DRAKE_ASSERT(f.ptr_ != nullptr); if (ptr_ == f.ptr_) { // pointer equality return true; } if (get_kind() != f.get_kind()) { return false; } // Same kind/hash, but it could be the result of hash collision, // check structural equality. return ptr_->EqualTo(*(f.ptr_)); } bool Formula::Less(const Formula& f) const { const FormulaKind k1{get_kind()}; const FormulaKind k2{f.get_kind()}; if (k1 < k2) { return true; } if (k2 < k1) { return false; } return ptr_->Less(*(f.ptr_)); } bool Formula::Evaluate(const Environment& env, RandomGenerator* const random_generator) const { DRAKE_ASSERT(ptr_ != nullptr); if (random_generator == nullptr) { return ptr_->Evaluate(env); } else { return ptr_->Evaluate( PopulateRandomVariables(env, GetFreeVariables(), random_generator)); } } bool Formula::Evaluate(RandomGenerator* const random_generator) const { DRAKE_ASSERT(ptr_ != nullptr); return Evaluate(Environment{}, random_generator); } Formula Formula::Substitute(const Variable& var, const Expression& e) const { DRAKE_ASSERT(ptr_ != nullptr); return Formula{ptr_->Substitute({{var, e}})}; } Formula Formula::Substitute(const Substitution& s) const { DRAKE_ASSERT(ptr_ != nullptr); if (!s.empty()) { return Formula{ptr_->Substitute(s)}; } return *this; } string Formula::to_string() const { ostringstream oss; oss << *this; return oss.str(); } Formula Formula::True() { static Formula tt{make_shared<const FormulaTrue>()}; return tt; } Formula Formula::False() { static Formula ff{make_shared<const FormulaFalse>()}; return ff; } Formula forall(const Variables& vars, const Formula& f) { return Formula{make_shared<const FormulaForall>(vars, f)}; } Formula make_conjunction(const set<Formula>& formulas) { set<Formula> operands; for (const Formula& f : formulas) { if (is_false(f)) { // Short-circuits to False. // f₁ ∧ ... ∧ False ∧ ... ∧ fₙ => False return Formula::False(); } if (is_true(f)) { // Drop redundant True. // f₁ ∧ ... ∧ True ∧ ... ∧ fₙ => f₁ ∧ ... ∧ fₙ continue; } if (is_conjunction(f)) { // Flattening. // f₁ ∧ ... ∧ (fᵢ₁ ∧ ... ∧ fᵢₘ) ∧ ... ∧ fₙ // => f₁ ∧ ... ∧ fᵢ₁ ∧ ... ∧ fᵢₘ ∧ ... ∧ fₙ const auto& operands_in_f = get_operands(f); operands.insert(operands_in_f.cbegin(), operands_in_f.cend()); } else { operands.insert(f); } } if (operands.empty()) { // ⋀{} = True return Formula::True(); } if (operands.size() == 1) { return *(operands.begin()); } // TODO(soonho-tri): Returns False if both f and ¬f appear in operands. return Formula{make_shared<const FormulaAnd>(operands)}; } Formula operator&&(const Formula& f1, const Formula& f2) { return make_conjunction({f1, f2}); } Formula operator&&(const Variable& v, const Formula& f) { return Formula(v) && f; } Formula operator&&(const Formula& f, const Variable& v) { return f && Formula(v); } Formula operator&&(const Variable& v1, const Variable& v2) { return Formula(v1) && Formula(v2); } Formula make_disjunction(const set<Formula>& formulas) { set<Formula> operands; for (const Formula& f : formulas) { if (is_true(f)) { // Short-circuits to True. // f₁ ∨ ... ∨ True ∨ ... ∨ fₙ => True return Formula::True(); } if (is_false(f)) { // Drop redundant False. // f₁ ∨ ... ∨ False ∨ ... ∨ fₙ => f₁ ∨ ... ∨ fₙ continue; } if (is_disjunction(f)) { // Flattening. // f₁ ∨ ... ∨ (fᵢ₁ ∨ ... ∨ fᵢₘ) ∨ ... ∨ fₙ // => f₁ ∨ ... ∨ fᵢ₁ ∨ ... ∨ fᵢₘ ∨ ... ∨ fₙ const auto& operands_in_f = get_operands(f); operands.insert(operands_in_f.cbegin(), operands_in_f.cend()); } else { operands.insert(f); } } if (operands.empty()) { // ⋁{} = False return Formula::False(); } if (operands.size() == 1) { return *(operands.begin()); } // TODO(soonho-tri): Returns True if both f and ¬f appear in operands. return Formula{make_shared<const FormulaOr>(operands)}; } Formula operator||(const Formula& f1, const Formula& f2) { return make_disjunction({f1, f2}); } Formula operator||(const Variable& v, const Formula& f) { return Formula(v) || f; } Formula operator||(const Formula& f, const Variable& v) { return f || Formula(v); } Formula operator||(const Variable& v1, const Variable& v2) { return Formula(v1) || Formula(v2); } Formula operator!(const Formula& f) { if (f.EqualTo(Formula::True())) { return Formula::False(); } if (f.EqualTo(Formula::False())) { return Formula::True(); } // Simplification: ¬(¬f₁) => f₁ if (is_negation(f)) { return get_operand(f); } return Formula{make_shared<const FormulaNot>(f)}; } Formula operator!(const Variable& v) { return !Formula(v); } ostream& operator<<(ostream& os, const Formula& f) { DRAKE_ASSERT(f.ptr_ != nullptr); return f.ptr_->Display(os); } Formula operator==(const Expression& e1, const Expression& e2) { // Simplification: E1 - E2 == 0 => True const Expression diff{e1 - e2}; if (diff.get_kind() == ExpressionKind::Constant) { return diff.Evaluate() == 0.0 ? Formula::True() : Formula::False(); } return Formula{make_shared<const FormulaEq>(e1, e2)}; } Formula operator!=(const Expression& e1, const Expression& e2) { // Simplification: E1 - E2 != 0 => True const Expression diff{e1 - e2}; if (diff.get_kind() == ExpressionKind::Constant) { return diff.Evaluate() != 0.0 ? Formula::True() : Formula::False(); } return Formula{make_shared<const FormulaNeq>(e1, e2)}; } Formula operator<(const Expression& e1, const Expression& e2) { // Simplification: E1 - E2 < 0 => True const Expression diff{e1 - e2}; if (diff.get_kind() == ExpressionKind::Constant) { return diff.Evaluate() < 0 ? Formula::True() : Formula::False(); } return Formula{make_shared<const FormulaLt>(e1, e2)}; } Formula operator<=(const Expression& e1, const Expression& e2) { // Simplification: E1 - E2 <= 0 => True const Expression diff{e1 - e2}; if (diff.get_kind() == ExpressionKind::Constant) { return diff.Evaluate() <= 0 ? Formula::True() : Formula::False(); } return Formula{make_shared<const FormulaLeq>(e1, e2)}; } Formula operator>(const Expression& e1, const Expression& e2) { // Simplification: E1 - E2 > 0 => True const Expression diff{e1 - e2}; if (diff.get_kind() == ExpressionKind::Constant) { return diff.Evaluate() > 0 ? Formula::True() : Formula::False(); } return Formula{make_shared<const FormulaGt>(e1, e2)}; } Formula operator>=(const Expression& e1, const Expression& e2) { // Simplification: E1 - E2 >= 0 => True const Expression diff{e1 - e2}; if (diff.get_kind() == ExpressionKind::Constant) { return diff.Evaluate() >= 0 ? Formula::True() : Formula::False(); } return Formula{make_shared<const FormulaGeq>(e1, e2)}; } Formula isnan(const Expression& e) { return Formula{make_shared<const FormulaIsnan>(e)}; } Formula isinf(const Expression& e) { const double inf{numeric_limits<double>::infinity()}; return (-inf == e) || (e == inf); } Formula isfinite(const Expression& e) { const double inf{numeric_limits<double>::infinity()}; return (-inf < e) && (e < inf); } Formula positive_semidefinite(const Eigen::Ref<const MatrixX<Expression>>& m) { return Formula{make_shared<const FormulaPositiveSemidefinite>(m)}; } Formula positive_semidefinite(const MatrixX<Expression>& m, const Eigen::UpLoType mode) { switch (mode) { case Eigen::Lower: return Formula{make_shared<const FormulaPositiveSemidefinite>( m.triangularView<Eigen::Lower>())}; case Eigen::Upper: return Formula{make_shared<const FormulaPositiveSemidefinite>( m.triangularView<Eigen::Upper>())}; default: throw std::runtime_error( "positive_semidefinite is called with a mode which is neither " "Eigen::Lower nor Eigen::Upper."); } } bool is_false(const Formula& f) { return is_false(*f.ptr_); } bool is_true(const Formula& f) { return is_true(*f.ptr_); } bool is_variable(const Formula& f) { return is_variable(*f.ptr_); } bool is_equal_to(const Formula& f) { return is_equal_to(*f.ptr_); } bool is_not_equal_to(const Formula& f) { return is_not_equal_to(*f.ptr_); } bool is_greater_than(const Formula& f) { return is_greater_than(*f.ptr_); } bool is_greater_than_or_equal_to(const Formula& f) { return is_greater_than_or_equal_to(*f.ptr_); } bool is_less_than(const Formula& f) { return is_less_than(*f.ptr_); } bool is_less_than_or_equal_to(const Formula& f) { return is_less_than_or_equal_to(*f.ptr_); } bool is_relational(const Formula& f) { return is_equal_to(f) || is_not_equal_to(f) || is_greater_than(f) || is_greater_than_or_equal_to(f) || is_less_than(f) || is_less_than_or_equal_to(f); } bool is_conjunction(const Formula& f) { return is_conjunction(*f.ptr_); } bool is_disjunction(const Formula& f) { return is_disjunction(*f.ptr_); } bool is_nary(const Formula& f) { return is_conjunction(f) || is_disjunction(f); } bool is_negation(const Formula& f) { return is_negation(*f.ptr_); } bool is_forall(const Formula& f) { return is_forall(*f.ptr_); } bool is_isnan(const Formula& f) { return is_isnan(*f.ptr_); } bool is_positive_semidefinite(const Formula& f) { return is_positive_semidefinite(*f.ptr_); } const Variable& get_variable(const Formula& f) { DRAKE_ASSERT(is_variable(f)); return to_variable(f)->get_variable(); } const Expression& get_lhs_expression(const Formula& f) { DRAKE_ASSERT(is_relational(f)); return to_relational(f)->get_lhs_expression(); } const Expression& get_rhs_expression(const Formula& f) { DRAKE_ASSERT(is_relational(f)); return to_relational(f)->get_rhs_expression(); } const Expression& get_unary_expression(const Formula& f) { DRAKE_ASSERT(is_isnan(f)); return to_isnan(f)->get_unary_expression(); } const set<Formula>& get_operands(const Formula& f) { return to_nary(f)->get_operands(); } const Formula& get_operand(const Formula& f) { return to_negation(f)->get_operand(); } const Variables& get_quantified_variables(const Formula& f) { return to_forall(f)->get_quantified_variables(); } const Formula& get_quantified_formula(const Formula& f) { return to_forall(f)->get_quantified_formula(); } const MatrixX<Expression>& get_matrix_in_positive_semidefinite( const Formula& f) { return to_positive_semidefinite(f)->get_matrix(); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/variables.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <cstddef> #include <functional> #include <initializer_list> #include <ostream> #include <set> #include <string> #include "drake/common/eigen_types.h" #include "drake/common/fmt.h" #include "drake/common/hash.h" namespace drake { namespace symbolic { /** Represents a set of variables. * * This class is based on std::set<Variable>. The intent is to add things that * we need including set-union (Variables::insert, operator+, operator+=), * set-minus (Variables::erase, operator-, operator-=), and subset/superset * checking functions (Variables::IsSubsetOf, Variables::IsSupersetOf, * Variables::IsStrictSubsetOf, Variables::IsStrictSupersetOf). */ class Variables { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Variables) typedef typename std::set<Variable>::size_type size_type; typedef typename std::set<Variable>::iterator iterator; typedef typename std::set<Variable>::const_iterator const_iterator; typedef typename std::set<Variable>::reverse_iterator reverse_iterator; typedef typename std::set<Variable>::const_reverse_iterator const_reverse_iterator; /** Default constructor. */ Variables() = default; /** List constructor. */ Variables(std::initializer_list<Variable> init); /** Constructs from an Eigen vector of variables. */ explicit Variables(const Eigen::Ref<const VectorX<Variable>>& vec); /** Returns the number of elements. */ [[nodiscard]] size_type size() const { return vars_.size(); } /** Checks if this set is empty or not. */ [[nodiscard]] bool empty() const { return vars_.empty(); } /** Returns string representation of Variables. */ [[nodiscard]] std::string to_string() const; /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const Variables& item) noexcept { using drake::hash_append; hash_append(hasher, item.vars_); } /** Returns an iterator to the beginning. */ iterator begin() { return vars_.begin(); } /** Returns an iterator to the end. */ iterator end() { return vars_.end(); } /** Returns an iterator to the beginning. */ [[nodiscard]] const_iterator begin() const { return vars_.cbegin(); } /** Returns an iterator to the end. */ [[nodiscard]] const_iterator end() const { return vars_.cend(); } /** Returns a const iterator to the beginning. */ [[nodiscard]] const_iterator cbegin() const { return vars_.cbegin(); } /** Returns a const iterator to the end. */ [[nodiscard]] const_iterator cend() const { return vars_.cend(); } /** Returns a reverse iterator to the beginning. */ reverse_iterator rbegin() { return vars_.rbegin(); } /** Returns a reverse iterator to the end. */ reverse_iterator rend() { return vars_.rend(); } /** Returns a reverse iterator to the beginning. */ [[nodiscard]] const_reverse_iterator rbegin() const { return vars_.crbegin(); } /** Returns a reverse iterator to the end. */ [[nodiscard]] const_reverse_iterator rend() const { return vars_.crend(); } /** Returns a const reverse-iterator to the beginning. */ [[nodiscard]] const_reverse_iterator crbegin() const { return vars_.crbegin(); } /** Returns a const reverse-iterator to the end. */ [[nodiscard]] const_reverse_iterator crend() const { return vars_.crend(); } /** Inserts a variable @p var into a set. */ void insert(const Variable& var) { vars_.insert(var); } /** Inserts variables in [@p first, @p last) into a set. */ template <class InputIt> void insert(InputIt first, InputIt last) { vars_.insert(first, last); } /** Inserts variables in @p vars into a set. */ void insert(const Variables& vars) { vars_.insert(vars.begin(), vars.end()); } /** Erases @p key from a set. Return number of erased elements (0 or 1). */ size_type erase(const Variable& key) { return vars_.erase(key); } /** Erases variables in @p vars from a set. Return number of erased elements ([0, vars.size()]). */ size_type erase(const Variables& vars); /** Finds element with specific key. */ iterator find(const Variable& key) { return vars_.find(key); } [[nodiscard]] const_iterator find(const Variable& key) const { return vars_.find(key); } /** Return true if @p key is included in the Variables. */ [[nodiscard]] bool include(const Variable& key) const { return find(key) != end(); } /** Return true if @p vars is a subset of the Variables. */ [[nodiscard]] bool IsSubsetOf(const Variables& vars) const; /** Return true if @p vars is a superset of the Variables. */ [[nodiscard]] bool IsSupersetOf(const Variables& vars) const; /** Return true if @p vars is a strict subset of the Variables. */ [[nodiscard]] bool IsStrictSubsetOf(const Variables& vars) const; /** Return true if @p vars is a strict superset of the Variables. */ [[nodiscard]] bool IsStrictSupersetOf(const Variables& vars) const; friend bool operator==(const Variables& vars1, const Variables& vars2); friend bool operator<(const Variables& vars1, const Variables& vars2); friend std::ostream& operator<<(std::ostream&, const Variables& vars); friend Variables intersect(const Variables& vars1, const Variables& vars2); private: /* Constructs from std::set<Variable>. */ explicit Variables(std::set<Variable> vars); std::set<Variable> vars_; }; /** Updates @p var1 with the result of set-union(@p var1, @p var2). */ // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Variables& operator+=(Variables& vars1, const Variables& vars2); /** Updates @p vars with the result of set-union(@p vars, { @p var }). */ // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Variables& operator+=(Variables& vars, const Variable& var); /** Returns set-union of @p var1 and @p var2. */ Variables operator+(Variables vars1, const Variables& vars2); /** Returns set-union of @p vars and {@p var}. */ Variables operator+(Variables vars, const Variable& var); /** Returns set-union of {@p var} and @p vars. */ Variables operator+(const Variable& var, Variables vars); /** Updates @p var1 with the result of set-minus(@p var1, @p var2). */ // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Variables& operator-=(Variables& vars1, const Variables& vars2); /** Updates @p vars with the result of set-minus(@p vars, {@p var}). */ // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Variables& operator-=(Variables& vars, const Variable& var); /** Returns set-minus(@p var1, @p vars2). */ Variables operator-(Variables vars1, const Variables& vars2); /** Returns set-minus(@p vars, { @p var }). */ Variables operator-(Variables vars, const Variable& var); /** Returns the intersection of @p vars1 and @p vars2. * * This function has a time complexity of `O(N₁ + N₂)` where `N₁` and `N₂` are * the size of @p vars1 and @p vars2 respectively. */ Variables intersect(const Variables& vars1, const Variables& vars2); } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::Variables>. */ template <> struct hash<drake::symbolic::Variables> : public drake::DefaultHash {}; } // namespace std DRAKE_FORMATTER_AS(, drake::symbolic, Variables, vs, vs.to_string())
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/expression.cc
/* clang-format off to disable clang-format-includes */ // NOLINTNEXTLINE(build/include): Our header file is included by all.h. #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <algorithm> #include <ios> #include <stdexcept> #include "absl/container/flat_hash_set.h" #include "absl/container/inlined_vector.h" #include <fmt/format.h> #include "drake/common/drake_assert.h" #include "drake/common/never_destroyed.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 { using std::logic_error; using std::make_unique; using std::map; using std::numeric_limits; using std::ostream; using std::ostringstream; using std::pair; using std::runtime_error; using std::streamsize; using std::string; using std::unique_ptr; using std::vector; namespace { // Negates an addition expression. // - (E_1 + ... + E_n) => (-E_1 + ... + -E_n) Expression NegateAddition(const Expression& e) { DRAKE_ASSERT(is_addition(e)); return ExpressionAddFactory{to_addition(e)}.Negate().GetExpression(); } // Negates a multiplication expression. // - (c0 * E_1 * ... * E_n) => (-c0 * E_1 * ... * E_n) Expression NegateMultiplication(const Expression& e) { DRAKE_ASSERT(is_multiplication(e)); return ExpressionMulFactory{to_multiplication(e)}.Negate().GetExpression(); } } // namespace Expression::Expression(const Variable& var) : Expression{make_unique<ExpressionVar>(var)} {} // Constructs this taking ownership of the given call. Expression::Expression(std::unique_ptr<ExpressionCell> cell) { boxed_.SetSharedCell(cell.release()); } // Implements the Expression(double) constructor when the constant is NaN. // Note that this uses the ExpressionNaN cell type to denote NaN, not a // constant NaN value in an ExpressionKind::Constant. void Expression::ConstructExpressionCellNaN() { *this = NaN(); } ExpressionCell& Expression::mutable_cell() { ExpressionCell& result = const_cast<ExpressionCell&>(cell()); // This is an invariant of Drake's symbolic library. If this ever trips, // that indicates an implementation defect within Drake; please file a bug. DRAKE_DEMAND(result.use_count() == 1); return result; } void Expression::HashAppend(DelegatingHasher* hasher) const { using drake::hash_append; if (is_constant(*this)) { hash_append(*hasher, ExpressionKind::Constant); hash_append(*hasher, get_constant_value(*this)); } else { hash_append(*hasher, get_kind()); cell().HashAppendDetail(hasher); } } Expression Expression::NaN() { // This global cell is initialized upon first use and never destroyed. static const ExpressionNaN* const flyweight = []() { ExpressionNaN* initial_value = new ExpressionNaN; ++initial_value->use_count(); return initial_value; }(); Expression result; result.boxed_.SetSharedCell(flyweight); return result; } Variables Expression::GetVariables() const { if (is_constant(*this)) { return {}; } return cell().GetVariables(); } bool Expression::EqualTo(const Expression& e) const { if (boxed_.trivially_equals(e.boxed_)) { return true; } const ExpressionKind k1{get_kind()}; const ExpressionKind k2{e.get_kind()}; if (k1 != k2) { return false; } if (k1 == ExpressionKind::Constant) { return get_constant_value(*this) == get_constant_value(e); } // Check structural equality. return cell().EqualTo(e.cell()); } bool Expression::Less(const Expression& e) const { if (boxed_.trivially_equals(e.boxed_)) { return false; } const ExpressionKind k1{get_kind()}; const ExpressionKind k2{e.get_kind()}; if (k1 < k2) { return true; } if (k2 < k1) { return false; } // k1 == k2 if (k1 == ExpressionKind::Constant) { return get_constant_value(*this) < get_constant_value(e); } return cell().Less(e.cell()); } bool Expression::is_polynomial() const { if (is_constant(*this)) { return true; } return cell().is_polynomial(); } bool Expression::is_expanded() const { if (is_constant(*this)) { return true; } return cell().is_expanded(); } double Expression::Evaluate(const Environment& env, RandomGenerator* const random_generator) const { if (is_constant(*this)) { return get_constant_value(*this); } if (random_generator == nullptr) { return cell().Evaluate(env); } else { return cell().Evaluate( PopulateRandomVariables(env, GetVariables(), random_generator)); } } double Expression::Evaluate(RandomGenerator* const random_generator) const { if (is_constant(*this)) { return get_constant_value(*this); } return Evaluate(Environment{}, random_generator); } Eigen::SparseMatrix<double> Evaluate( const Eigen::Ref<const Eigen::SparseMatrix<Expression>>& m, const Environment& env) { return m.unaryExpr([&env](const Expression& e) { return e.Evaluate(env); }); } Expression Expression::EvaluatePartial(const Environment& env) const { if (is_constant(*this) || env.empty()) { return *this; } return cell().EvaluatePartial(env); } Expression Expression::Expand() const { if (is_constant(*this)) { return *this; } if (cell().is_expanded()) { // If it is already expanded, return the current expression without calling // Expand() on the cell. return *this; } Expression result = cell().Expand(); if (!result.is_expanded()) { result.mutable_cell().set_expanded(); } return result; } Expression Expression::Substitute(const Variable& var, const Expression& e) const { if (is_constant(*this)) { return *this; } return cell().Substitute({{var, e}}); } Expression Expression::Substitute(const Substitution& s) const { if (is_constant(*this) || s.empty()) { return *this; } return cell().Substitute(s); } Expression Expression::Differentiate(const Variable& x) const { if (is_constant(*this)) { return 0.0; } return cell().Differentiate(x); } RowVectorX<Expression> Expression::Jacobian( const Eigen::Ref<const VectorX<Variable>>& vars) const { RowVectorX<Expression> J(vars.size()); for (VectorX<Variable>::Index i = 0; i < vars.size(); ++i) { J(i) = Differentiate(vars(i)); } return J; } string Expression::to_string() const { ostringstream oss; oss << *this; return oss.str(); } void Expression::AddImpl(const Expression& rhs) { Expression& lhs = *this; // Simplification: 0 + x => x if (is_zero(lhs)) { lhs = rhs; return; } // Simplification: x + 0 => x if (is_zero(rhs)) { return; } // If both terms were constants, our header file `operator+=` function would // have already tried to add them, but got a speculative_result of NaN. If // we reach here, that means the floating-point result really was NaN. if (is_constant(lhs) && is_constant(rhs)) { ConstructExpressionCellNaN(); return; } // Simplification: flattening. To build a new expression, we use // ExpressionAddFactory which holds intermediate terms and does // simplifications internally. ExpressionAddFactory add_factory{}; if (is_addition(lhs)) { // 1. (e_1 + ... + e_n) + rhs add_factory = to_addition(lhs); // Note: AddExpression method takes care of the special case where `rhs` is // of ExpressionAdd. add_factory.AddExpression(rhs); } else { if (is_addition(rhs)) { // 2. lhs + (e_1 + ... + e_n) add_factory = to_addition(rhs); add_factory.AddExpression(lhs); } else { // nothing to flatten: return lhs + rhs add_factory.AddExpression(lhs); add_factory.AddExpression(rhs); } } // Extract an expression from factory lhs = std::move(add_factory).GetExpression(); } Expression& Expression::operator++() { *this += Expression::One(); return *this; } Expression Expression::operator++(int) { Expression copy(*this); ++*this; return copy; } Expression operator+(const Expression& e) { return e; } void Expression::SubImpl(const Expression& rhs) { Expression& lhs = *this; // Simplification: E - E => 0 // TODO(soonho-tri): This simplification is not sound since it cancels `E` // which might cause 0/0 during evaluation. if (lhs.EqualTo(rhs)) { lhs = Expression::Zero(); return; } // Simplification: x - 0 => x if (is_zero(rhs)) { return; } // If both terms were constants, our header file `operator-=` function would // have already tried to subtract them, but got a speculative_result of NaN. // If we reach here, that means the floating-point result really was NaN. // However, that should only happen with inf-inf or (-inf)-(-inf), which // we've handled already. DRAKE_ASSERT(!(is_constant(lhs) && is_constant(rhs))); // x - y => x + (-y) lhs += -rhs; } Expression operator-(const Expression& e) { // Simplification: constant folding if (is_constant(e)) { return Expression{-get_constant_value(e)}; } // Simplification: push '-' inside over '+'. // -(E_1 + ... + E_n) => (-E_1 + ... + -E_n) if (is_addition(e)) { return NegateAddition(e); } // Simplification: push '-' inside over '*'. // -(c0 * E_1 * ... * E_n) => (-c0 * E_1 * ... * E_n) if (is_multiplication(e)) { return NegateMultiplication(e); } return -1 * e; } Expression& Expression::operator--() { *this -= Expression::One(); return *this; } Expression Expression::operator--(int) { // Declare as non-const to allow move. Expression copy(*this); --*this; return copy; } void Expression::MulImpl(const Expression& rhs) { Expression& lhs = *this; // Simplification: 1 * x => x if (is_one(lhs)) { lhs = rhs; return; } // Simplification: x * 1 => x if (is_one(rhs)) { return; } // Simplification: (E1 / E2) * (E3 / E4) => (E1 * E3) / (E2 * E4) if (is_division(lhs) && is_division(rhs)) { lhs = (get_first_argument(lhs) * get_first_argument(rhs)) / (get_second_argument(lhs) * get_second_argument(rhs)); return; } // Simplification: lhs * (c / E) => (c * lhs) / E if (is_division(rhs) && is_constant(get_first_argument(rhs))) { lhs = (get_first_argument(rhs) * lhs) / get_second_argument(rhs); return; } // Simplification: (c / E) * rhs => (c * rhs) / E if (is_division(lhs) && is_constant(get_first_argument(lhs))) { lhs = (get_first_argument(lhs) * rhs) / get_second_argument(lhs); return; } if (is_neg_one(lhs)) { if (is_addition(rhs)) { // Simplification: push '-' inside over '+'. // -1 * (E_1 + ... + E_n) => (-E_1 + ... + -E_n) lhs = NegateAddition(rhs); return; } if (is_multiplication(rhs)) { // Simplification: push '-' inside over '*'. // -1 * (c0 * E_1 * ... * E_n) => (-c0 * E_1 * ... * E_n) lhs = NegateMultiplication(rhs); return; } } if (is_neg_one(rhs)) { if (is_addition(lhs)) { // Simplification: push '-' inside over '+'. // (E_1 + ... + E_n) * -1 => (-E_1 + ... + -E_n) lhs = NegateAddition(lhs); return; } if (is_multiplication(lhs)) { // Simplification: push '-' inside over '*'. // (c0 * E_1 * ... * E_n) * -1 => (-c0 * E_1 * ... * E_n) lhs = NegateMultiplication(lhs); return; } } // Simplification: 0 * E => 0 // TODO(soonho-tri): This simplification is not sound since it cancels `E` // which might cause 0/0 during evaluation. if (is_zero(lhs)) { return; } // Simplification: E * 0 => 0 // TODO(soonho-tri): This simplification is not sound since it cancels `E` // which might cause 0/0 during evaluation. if (is_zero(rhs)) { lhs = Expression::Zero(); return; } // Pow-related simplifications. if (is_pow(lhs)) { const Expression& e1{get_first_argument(lhs)}; if (is_pow(rhs)) { const Expression& e3{get_first_argument(rhs)}; if (e1.EqualTo(e3)) { // Simplification: pow(e1, e2) * pow(e1, e4) => pow(e1, e2 + e4) // TODO(soonho-tri): This simplification is not sound. For example, x^4 // * x^(-3) => x. The original expression `x^4 * x^(-3)` is evaluated to // `nan` when x = 0 while the simplified expression `x` is evaluated to // 0. const Expression& e2{get_second_argument(lhs)}; const Expression& e4{get_second_argument(rhs)}; lhs = pow(e1, e2 + e4); return; } } if (e1.EqualTo(rhs)) { // Simplification: pow(e1, e2) * e1 => pow(e1, e2 + 1) // TODO(soonho-tri): This simplification is not sound. const Expression& e2{get_second_argument(lhs)}; lhs = pow(e1, e2 + 1); return; } } else { if (is_pow(rhs)) { const Expression& e1{get_first_argument(rhs)}; if (e1.EqualTo(lhs)) { // Simplification: (lhs * rhs == e1 * pow(e1, e2)) => pow(e1, 1 + e2) // TODO(soonho-tri): This simplification is not sound. const Expression& e2{get_second_argument(rhs)}; lhs = pow(e1, 1 + e2); return; } } } // If both terms were constants, our header file `operator*=` function would // have already tried to multiply them, but got a speculative_result of NaN. // If we reach here, that means the floating-point result really was NaN. // However, that should only happen with 0*inf or inf*0, which we've handled // already. DRAKE_ASSERT(!(is_constant(lhs) && is_constant(rhs))); // Simplification: flattening ExpressionMulFactory mul_factory{}; if (is_multiplication(lhs)) { // (e_1 * ... * e_n) * rhs mul_factory = to_multiplication(lhs); // Note: AddExpression method takes care of the special case where `rhs` is // of ExpressionMul. mul_factory.AddExpression(rhs); } else { if (is_multiplication(rhs)) { // e_1 * (e_2 * ... * e_n) -> (e_2 * ... * e_n * e_1) // // Note that we do not preserve the original ordering because * is // associative. mul_factory = to_multiplication(rhs); mul_factory.AddExpression(lhs); } else { // Simplification: x * x => x^2 (=pow(x,2)) if (lhs.EqualTo(rhs)) { lhs = pow(lhs, 2.0); return; } // nothing to flatten mul_factory.AddExpression(lhs); mul_factory.AddExpression(rhs); } } lhs = std::move(mul_factory).GetExpression(); } void Expression::DivImpl(const Expression& rhs) { Expression& lhs = *this; // Simplification: x / 1 => x if (is_one(rhs)) { return; } // If both terms were constants, our header file `operator/=` function would // have already tried to divide them, but if it wasn't able to commit to a // result that means that either the divisor was zero or else the result // really is NaN. if (is_constant(lhs) && is_constant(rhs)) { if (is_zero(rhs)) { ostringstream oss{}; oss << "Division by zero: " << lhs << "/0"; throw runtime_error(oss.str()); } ConstructExpressionCellNaN(); return; } // Simplification: E / E => 1 // TODO(soonho-tri): This simplification is not sound since it cancels `E` // which might contain 0/0 problems. if (lhs.EqualTo(rhs)) { lhs = Expression::One(); return; } lhs = Expression{make_unique<ExpressionDiv>(lhs, rhs)}; } namespace { // Changes the precision of `os` to be the `new_precision` and saves the // original precision so that it can be reverted when an instance of this class // is destructed. It is used in `operator<<` of symbolic expression. class PrecisionGuard { public: PrecisionGuard(ostream* const os, const streamsize& new_precision) : os_{os}, original_precision_{os->precision()} { os_->precision(new_precision); } DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PrecisionGuard) ~PrecisionGuard() { os_->precision(original_precision_); } private: ostream* const os_; const streamsize original_precision_; }; } // namespace ostream& operator<<(ostream& os, const Expression& e) { const PrecisionGuard precision_guard{&os, numeric_limits<double>::max_digits10}; if (is_constant(e)) { os << get_constant_value(e); } else { e.cell().Display(os); } return os; } Expression log(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { const double v{get_constant_value(e)}; ExpressionLog::check_domain(v); return Expression{std::log(v)}; } return Expression{make_unique<ExpressionLog>(e)}; } Expression abs(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::fabs(get_constant_value(e))}; } return Expression{make_unique<ExpressionAbs>(e)}; } Expression exp(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::exp(get_constant_value(e))}; } return Expression{make_unique<ExpressionExp>(e)}; } Expression sqrt(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { const double v{get_constant_value(e)}; ExpressionSqrt::check_domain(v); return Expression{std::sqrt(v)}; } // Simplification: sqrt(pow(x, 2)) => abs(x) if (is_pow(e)) { if (is_two(get_second_argument(e))) { return abs(get_first_argument(e)); } } return Expression{make_unique<ExpressionSqrt>(e)}; } Expression pow(const Expression& e1, const Expression& e2) { // Simplification if (is_constant(e2)) { const double v2{get_constant_value(e2)}; if (is_constant(e1)) { // Constant folding const double v1{get_constant_value(e1)}; ExpressionPow::check_domain(v1, v2); return Expression{std::pow(v1, v2)}; } // pow(E, 0) => 1 // TODO(soonho-tri): This simplification is not sound since it cancels `E` // which might contain 0/0 problems. if (v2 == 0.0) { return Expression::One(); } // pow(E, 1) => E if (v2 == 1.0) { return e1; } } if (is_pow(e1)) { // pow(base, exponent) ^ e2 => pow(base, exponent * e2) const Expression& base{get_first_argument(e1)}; const Expression& exponent{get_second_argument(e1)}; return Expression{make_unique<ExpressionPow>(base, exponent * e2)}; } return Expression{make_unique<ExpressionPow>(e1, e2)}; } Expression sin(const Expression& e) { // simplification: constant folding. if (is_constant(e)) { return Expression{std::sin(get_constant_value(e))}; } return Expression{make_unique<ExpressionSin>(e)}; } Expression cos(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::cos(get_constant_value(e))}; } return Expression{make_unique<ExpressionCos>(e)}; } Expression tan(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::tan(get_constant_value(e))}; } return Expression{make_unique<ExpressionTan>(e)}; } Expression asin(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { const double v{get_constant_value(e)}; ExpressionAsin::check_domain(v); return Expression{std::asin(v)}; } return Expression{make_unique<ExpressionAsin>(e)}; } Expression acos(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { const double v{get_constant_value(e)}; ExpressionAcos::check_domain(v); return Expression{std::acos(v)}; } return Expression{make_unique<ExpressionAcos>(e)}; } Expression atan(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::atan(get_constant_value(e))}; } return Expression{make_unique<ExpressionAtan>(e)}; } Expression atan2(const Expression& e1, const Expression& e2) { // Simplification: constant folding. if (is_constant(e1) && is_constant(e2)) { return Expression{ std::atan2(get_constant_value(e1), get_constant_value(e2))}; } return Expression{make_unique<ExpressionAtan2>(e1, e2)}; } Expression sinh(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::sinh(get_constant_value(e))}; } return Expression{make_unique<ExpressionSinh>(e)}; } Expression cosh(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::cosh(get_constant_value(e))}; } return Expression{make_unique<ExpressionCosh>(e)}; } Expression tanh(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::tanh(get_constant_value(e))}; } return Expression{make_unique<ExpressionTanh>(e)}; } Expression min(const Expression& e1, const Expression& e2) { // simplification: min(x, x) => x if (e1.EqualTo(e2)) { return e1; } // Simplification: constant folding. if (is_constant(e1) && is_constant(e2)) { return Expression{std::min(get_constant_value(e1), get_constant_value(e2))}; } return Expression{make_unique<ExpressionMin>(e1, e2)}; } Expression max(const Expression& e1, const Expression& e2) { // Simplification: max(x, x) => x if (e1.EqualTo(e2)) { return e1; } // Simplification: constant folding if (is_constant(e1) && is_constant(e2)) { return Expression{std::max(get_constant_value(e1), get_constant_value(e2))}; } return Expression{make_unique<ExpressionMax>(e1, e2)}; } Expression clamp(const Expression& v, const Expression& lo, const Expression& hi) { DRAKE_ASSERT(!is_constant(lo) || !is_constant(hi) || (lo <= hi)); return min(hi, max(lo, v)); } Expression ceil(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::ceil(get_constant_value(e))}; } return Expression{make_unique<ExpressionCeiling>(e)}; } Expression floor(const Expression& e) { // Simplification: constant folding. if (is_constant(e)) { return Expression{std::floor(get_constant_value(e))}; } return Expression{make_unique<ExpressionFloor>(e)}; } Expression if_then_else(const Formula& f_cond, const Expression& e_then, const Expression& e_else) { // simplification:: if(true, e1, e2) => e1 if (f_cond.EqualTo(Formula::True())) { return e_then; } // simplification:: if(false, e1, e2) => e2 if (f_cond.EqualTo(Formula::False())) { return e_else; } return Expression{make_unique<ExpressionIfThenElse>(f_cond, e_then, e_else)}; } Expression uninterpreted_function(string name, vector<Expression> arguments) { return Expression{make_unique<ExpressionUninterpretedFunction>( std::move(name), std::move(arguments))}; } const Variable& get_variable(const Expression& e) { return to_variable(e).get_variable(); } const Expression& get_argument(const Expression& e) { return to_unary(e).get_argument(); } const Expression& get_first_argument(const Expression& e) { return to_binary(e).get_first_argument(); } const Expression& get_second_argument(const Expression& e) { return to_binary(e).get_second_argument(); } double get_constant_in_addition(const Expression& e) { return to_addition(e).get_constant(); } const map<Expression, double>& get_expr_to_coeff_map_in_addition( const Expression& e) { return to_addition(e).get_expr_to_coeff_map(); } double get_constant_in_multiplication(const Expression& e) { return to_multiplication(e).get_constant(); } const map<Expression, Expression>& get_base_to_exponent_map_in_multiplication( const Expression& e) { return to_multiplication(e).get_base_to_exponent_map(); } const string& get_uninterpreted_function_name(const Expression& e) { return to_uninterpreted_function(e).get_name(); } const vector<Expression>& get_uninterpreted_function_arguments( const Expression& e) { return to_uninterpreted_function(e).get_arguments(); } const Formula& get_conditional_formula(const Expression& e) { return to_if_then_else(e).get_conditional_formula(); } const Expression& get_then_expression(const Expression& e) { return to_if_then_else(e).get_then_expression(); } const Expression& get_else_expression(const Expression& e) { return to_if_then_else(e).get_else_expression(); } Expression operator+(const Variable& var) { return Expression{var}; } Expression operator-(const Variable& var) { return -Expression{var}; } VectorX<Variable> GetVariableVector( const Eigen::Ref<const VectorX<Expression>>& evec) { VectorX<Variable> vec(evec.size()); for (int i = 0; i < evec.size(); i++) { const Expression e_i{evec(i)}; if (is_variable(e_i)) { vec(i) = get_variable(e_i); } else { throw logic_error(fmt::format("{} is not a variable.", e_i)); } } return vec; } MatrixX<Expression> Jacobian(const Eigen::Ref<const VectorX<Expression>>& f, const vector<Variable>& vars) { DRAKE_DEMAND(!vars.empty()); const Eigen::Ref<const VectorX<Expression>>::Index n{f.size()}; const size_t m{vars.size()}; MatrixX<Expression> J(n, m); for (int i = 0; i < n; ++i) { for (size_t j = 0; j < m; ++j) { J(i, j) = f[i].Differentiate(vars[j]); } } return J; } MatrixX<Expression> Jacobian(const Eigen::Ref<const VectorX<Expression>>& f, const Eigen::Ref<const VectorX<Variable>>& vars) { return Jacobian(f, vector<Variable>(vars.data(), vars.data() + vars.size())); } namespace { // Helper functions for TaylorExpand. // // We use the multi-index notation. Please read // https://en.wikipedia.org/wiki/Multi-index_notation for more information. // α = (a₁, ..., aₙ) where αᵢ ∈ Z. using MultiIndex = vector<int>; // Generates multi-indices of order `order` whose size is `num_vars` and append // to `vec`. It generates the indices by increasing the elements of the given // `base`. It only changes the i-th dimension which is greater than or equal to // `start_dim` to avoid duplicates. void DoEnumerateMultiIndex(const int order, const int num_vars, const int start_dim, const MultiIndex& base, vector<MultiIndex>* const vec) { DRAKE_ASSERT(order > 0); DRAKE_ASSERT(start_dim >= 0); DRAKE_ASSERT(base.size() == static_cast<size_t>(num_vars)); if (order == 0) { return; } if (order == 1) { for (int i = start_dim; i < num_vars; ++i) { MultiIndex alpha = base; ++alpha[i]; vec->push_back(std::move(alpha)); } return; } else { for (int i = start_dim; i < num_vars; ++i) { MultiIndex alpha = base; ++alpha[i]; DoEnumerateMultiIndex(order - 1, num_vars, i, alpha, vec); } } } // Returns the set of multi-indices of order `order` whose size is `num-vars`. vector<MultiIndex> EnumerateMultiIndex(const int order, const int num_vars) { DRAKE_ASSERT(order > 0); DRAKE_ASSERT(num_vars >= 1); vector<MultiIndex> vec; MultiIndex base(num_vars, 0); // base = (0, ..., 0) DoEnumerateMultiIndex(order, num_vars, 0, base, &vec); return vec; } // Computes the factorial of n. int Factorial(const int n) { DRAKE_ASSERT(n >= 0); int f = 1; for (int i = 2; i <= n; ++i) { f *= i; } return f; } // Given a multi index α = (α₁, ..., αₙ), returns α₁! * ... * αₙ!. int FactorialProduct(const MultiIndex& alpha) { int ret = 1; for (const int i : alpha) { ret *= Factorial(i); } return ret; } // Computes ∂fᵅ(a) = ∂ᵅ¹...∂ᵅⁿf(a). Expression Derivative(Expression f, const MultiIndex& alpha, const Environment& a) { int i = 0; for (const pair<const Variable, double>& p : a) { const Variable& v = p.first; for (int j = 0; j < alpha[i]; ++j) { f = f.Differentiate(v); } ++i; } return f.EvaluatePartial(a); } // Given terms = [e₁, ..., eₙ] and alpha = (α₁, ..., αₙ), returns // pow(e₁,α₁) * ... * pow(eₙ,αₙ) Expression Exp(const vector<Expression>& terms, const MultiIndex& alpha) { DRAKE_ASSERT(terms.size() == alpha.size()); ExpressionMulFactory factory; for (size_t i = 0; i < terms.size(); ++i) { factory.AddExpression(pow(terms[i], alpha[i])); } return std::move(factory).GetExpression(); } // Computes ∑_{|α| = order} ∂fᵅ(a) / α! * (x - a)ᵅ. void DoTaylorExpand(const Expression& f, const Environment& a, const vector<Expression>& terms, const int order, const int num_vars, ExpressionAddFactory* const factory) { DRAKE_ASSERT(order > 0); DRAKE_ASSERT(terms.size() == static_cast<size_t>(num_vars)); const vector<MultiIndex> multi_indices{EnumerateMultiIndex(order, num_vars)}; for (const MultiIndex& alpha : multi_indices) { factory->AddExpression(Derivative(f, alpha, a) * Exp(terms, alpha) / FactorialProduct(alpha)); } } } // namespace Expression TaylorExpand(const Expression& f, const Environment& a, const int order) { // The implementation uses the formulation: // Taylor(f, a, order) = ∑_{|α| ≤ order} ∂fᵅ(a) / α! * (x - a)ᵅ. DRAKE_DEMAND(order >= 1); ExpressionAddFactory factory; factory.AddExpression(f.EvaluatePartial(a)); const int num_vars = a.size(); if (num_vars == 0) { return f; } vector<Expression> terms; // (x - a) for (const pair<const Variable, double>& p : a) { const Variable& var = p.first; const double v = p.second; terms.push_back(var - v); } for (int i = 1; i <= order; ++i) { DoTaylorExpand(f, a, terms, i, num_vars, &factory); } return std::move(factory).GetExpression(); } namespace { // Visitor used in the implementation of the GetDistinctVariables function // defined below. struct GetDistinctVariablesVisitor { // called for the first coefficient void init(const Expression& value, Eigen::Index, Eigen::Index) { variables += value.GetVariables(); } // called for all other coefficients void operator()(const Expression& value, Eigen::Index, Eigen::Index) { variables += value.GetVariables(); } Variables variables; }; } // namespace Variables GetDistinctVariables(const Eigen::Ref<const MatrixX<Expression>>& v) { GetDistinctVariablesVisitor visitor; v.visit(visitor); return visitor.variables; } } // namespace symbolic double ExtractDoubleOrThrow(const symbolic::Expression& e) { if (is_nan(e)) { // If this was a literal NaN provided by the user or a dummy_value<T>, then // it is sound to promote it as the "extracted value" during scalar // conversion. (In contrast, if an expression tree includes a NaN term, // then it's still desirable to throw an exception and we should NOT return // NaN in that case.) return std::numeric_limits<double>::quiet_NaN(); } return e.Evaluate(); } namespace symbolic { namespace internal { template <bool reverse> void Gemm<reverse>::CalcDV(const MatrixRef<double>& D, const MatrixRef<Variable>& V, EigenPtr<MatrixX<Expression>> result) { // These checks are guaranteed by our header file functions that call us. DRAKE_ASSERT(result != nullptr); if constexpr (!reverse) { // Calculating D * V. DRAKE_ASSERT(result->rows() == D.rows()); DRAKE_ASSERT(result->cols() == V.cols()); DRAKE_ASSERT(D.cols() == V.rows()); } else { // Calculating V * D. DRAKE_ASSERT(result->rows() == V.rows()); DRAKE_ASSERT(result->cols() == D.cols()); DRAKE_ASSERT(V.cols() == D.rows()); } // Our temporary vectors will use the stack for this number of items or fewer. constexpr size_t kSmallSize = 8; // In the below, we'll use index `i` to refer to a column of the V matrix // (or row, when in reverse mode) and index `j` to refer to a row of the // D matrix (or column, when in reverse mode). const int max_i = !reverse ? V.cols() : V.rows(); const int max_j = !reverse ? D.rows() : D.cols(); // We'll use index `k` to index over the inner dot product. const int max_k = !reverse ? D.cols() : V.cols(); // The four containers below are reused across the outer loop. Each one is // either cleared or fully overwritten at the start of each outer loop. // // We'll use `t` to index over a sorted and unique vector of the variables in // each inner product. When there are no duplicates, `t`'s range will be the // same as `k` but in a different order. With duplicates, `t` will be shorter. // // Each inner product is calculated as Σ inner_coeffs(t) * inner_var(t). In // other words, we directly compute the canonical form of ExpressionAdd for // each inner product, without going through the ExpressionAddFactory. absl::InlinedVector<double, kSmallSize> inner_coeffs; inner_coeffs.reserve(max_k); absl::InlinedVector<Variable, kSmallSize> inner_vars; inner_vars.reserve(max_k); absl::InlinedVector<Expression, kSmallSize> inner_vars_as_expr; inner_vars_as_expr.reserve(max_k); // The unique_ids is used to efficiently de-duplicate vars. absl::flat_hash_set<Variable::Id> unique_ids; unique_ids.reserve(max_k); // The var_index[k] refers to the index in inner_vars[] for that variable. // We have inner_vars[var_index[k]] == V(k, j) during the j'th row loop, // or V(j, k) when in reverse mode. absl::InlinedVector<int, kSmallSize> var_index; var_index.resize(max_k); // The outer loop over `i` steps through each column (or row) of V, so that we // can share the variable de-duplication and sorting needed by the for-j loop. for (int i = 0; i < max_i; ++i) { // Convert each Variable to an Expression, consolidating duplicates. // Sort the variables so that map insertion later will be linear time. inner_vars.clear(); unique_ids.clear(); for (int k = 0; k < max_k; ++k) { const Variable& var = !reverse ? V(k, i) : V(i, k); const Variable::Id var_id = var.get_id(); const bool inserted = unique_ids.insert(var_id).second; if (inserted) { inner_vars.emplace_back(var); } } std::sort(inner_vars.begin(), inner_vars.end(), std::less<Variable>{}); // Compute the var_index that projects this V block into inner_vars. for (int k = 0; k < max_k; ++k) { const Variable& var = !reverse ? V(k, i) : V(i, k); auto iter = std::lower_bound(inner_vars.begin(), inner_vars.end(), var, std::less<Variable>{}); DRAKE_ASSERT(iter != inner_vars.end()); DRAKE_ASSERT(iter->get_id() == var.get_id()); const int index = std::distance(inner_vars.begin(), iter); var_index[k] = index; } // Convert the vars to expression cells. We want these to all be shared for // faster comparisons downtream after the Gemm. inner_vars_as_expr.clear(); for (size_t t = 0; t < inner_vars.size(); ++t) { inner_vars_as_expr.push_back(inner_vars[t]); } // Now that the V block is precomputed in a useful format, we can quickly // loop through each block of double coeffs in turn. for (int j = 0; j < max_j; ++j) { // Prepare storage for the summed-up coeffs. inner_coeffs.clear(); inner_coeffs.resize(inner_vars.size(), 0.0); // Sum up D(j, k) * V(k, i) or in reverse mode V(j, i) * D(k, j). for (int k = 0; k < max_k; ++k) { inner_coeffs[var_index[k]] += !reverse ? D(j, k) : D(k, j); } // Convert the sum to the ExpressionAdd representation, skipping zeros, // but for now in vector-pair form instead of map form. using TermsMap = map<Expression, double>; using TermsVec = absl::InlinedVector<TermsMap::value_type, kSmallSize>; TermsVec terms_vec; for (size_t t = 0; t < inner_coeffs.size(); ++t) { const double coeff = inner_coeffs[t]; if (coeff == 0.0) { continue; } terms_vec.emplace_back(inner_vars_as_expr[t], coeff); } // Convert the ExpressionAdd representation to an Expression cell. Expression inner_product; if (!terms_vec.empty()) { if ((terms_vec.size() == 1) && (terms_vec.front().second == 1.0)) { // Special case for `1.0 * v`, use a Var cell (not an Add cell). inner_product = std::move(terms_vec.front().first); } else { // This is carefully crafted to be a linear time insertion because the // vector is already sorted, and to avoid unnecessary copying because // both collections have the same value_type. TermsMap terms_map(std::make_move_iterator(terms_vec.begin()), std::make_move_iterator(terms_vec.end())); auto cell = make_unique<ExpressionAdd>(0.0, std::move(terms_map)); cell->set_expanded(); inner_product = Expression{std::move(cell)}; } } if constexpr (!reverse) { (*result)(j, i) = std::move(inner_product); } else { (*result)(i, j) = std::move(inner_product); } } } } namespace { template <typename T1, typename T2> Expression GenericGevv(const Eigen::Ref<const VectorX<T1>, 0, StrideX>& a, const Eigen::Ref<const VectorX<T2>, 0, StrideX>& b) { DRAKE_ASSERT(a.size() == b.size()); ExpressionAddFactory fac; for (int k = 0; k < a.size(); ++k) { fac.AddExpression(a[k] * b[k]); } return std::move(fac).GetExpression(); } template <typename T1, typename T2> void GenericGemm(const Eigen::Ref<const MatrixX<T1>, 0, StrideX>& left, const Eigen::Ref<const MatrixX<T2>, 0, StrideX>& right, EigenPtr<MatrixX<Expression>> result) { // These checks are guaranteed by our header file functions that call us. DRAKE_ASSERT(result != nullptr); DRAKE_ASSERT(result->rows() == left.rows()); DRAKE_ASSERT(result->cols() == right.cols()); DRAKE_ASSERT(left.cols() == right.rows()); // Delegate to Gevv. for (int i = 0; i < result->rows(); ++i) { for (int j = 0; j < result->cols(); ++j) { (*result)(i, j) = GenericGevv<T1, T2>(left.row(i), right.col(j)); } } } } // namespace template <bool reverse> void Gemm<reverse>::CalcVV(const MatrixRef<Variable>& A, const MatrixRef<Variable>& B, EigenPtr<MatrixX<Expression>> result) { // We convert Variable => Expression up front, so the ExpressionVar cells get // reused during the computation instead of creating lots of duplicates. // TODO(jwnimmer-tri) If A or B contain duplicate variables (e.g., symmetric), // it's possible that interning the duplicates would improve performance of // subsequent operations. CalcEE(A.template cast<Expression>(), B.template cast<Expression>(), result); } template <bool reverse> void Gemm<reverse>::CalcDE(const MatrixRef<double>& D, const MatrixRef<Expression>& E, EigenPtr<MatrixX<Expression>> result) { if constexpr (!reverse) { GenericGemm<double, Expression>(D, E, result); } else { GenericGemm<Expression, double>(E, D, result); } } template <bool reverse> void Gemm<reverse>::CalcVE(const MatrixRef<Variable>& V, const MatrixRef<Expression>& E, EigenPtr<MatrixX<Expression>> result) { // We convert Variable => Expression up front, so the ExpressionVar cells get // reused during the computation instead of creating lots of duplicates. // TODO(jwnimmer-tri) If V contains duplicate variables (e.g., symmetric), // it's possible that interning the duplicates would improve performance of // subsequent operations. CalcEE(V.template cast<Expression>(), E, result); } template <bool reverse> void Gemm<reverse>::CalcEE(const MatrixRef<Expression>& A, const MatrixRef<Expression>& B, EigenPtr<MatrixX<Expression>> result) { if constexpr (!reverse) { GenericGemm<Expression, Expression>(A, B, result); } else { GenericGemm<Expression, Expression>(B, A, result); } } template struct Gemm<false>; template struct Gemm<true>; } // namespace internal } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/variables.cc
/* clang-format off to disable clang-format-includes */ // NOLINTNEXTLINE(build/include): Our header file is included by all.h. #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <algorithm> #include <functional> #include <iterator> #include <numeric> #include <ostream> #include <sstream> #include <string> #include <utility> #include "drake/common/hash.h" using std::includes; using std::initializer_list; using std::inserter; using std::less; using std::ostream; using std::ostream_iterator; using std::ostringstream; using std::set; using std::set_intersection; using std::string; namespace drake { namespace symbolic { Variables::Variables(std::initializer_list<Variable> init) : vars_(init) {} Variables::Variables(const Eigen::Ref<const VectorX<Variable>>& vec) : vars_{vec.data(), vec.data() + vec.size()} {} string Variables::to_string() const { ostringstream oss; oss << *this; return oss.str(); } Variables::size_type Variables::erase(const Variables& vars) { size_type num_of_erased_elements{0}; for (const Variable& var : vars) { num_of_erased_elements += erase(var); } return num_of_erased_elements; } bool Variables::IsSubsetOf(const Variables& vars) const { return includes(vars.begin(), vars.end(), begin(), end(), std::less<Variable>{}); } bool Variables::IsSupersetOf(const Variables& vars) const { return vars.IsSubsetOf(*this); } bool Variables::IsStrictSubsetOf(const Variables& vars) const { if (*this == vars) { return false; } return IsSubsetOf(vars); } bool Variables::IsStrictSupersetOf(const Variables& vars) const { if (*this == vars) { return false; } return IsSupersetOf(vars); } bool operator==(const Variables& vars1, const Variables& vars2) { return std::equal(vars1.vars_.begin(), vars1.vars_.end(), vars2.vars_.begin(), vars2.vars_.end(), std::equal_to<Variable>{}); } bool operator<(const Variables& vars1, const Variables& vars2) { return std::lexicographical_compare(vars1.vars_.begin(), vars1.vars_.end(), vars2.vars_.begin(), vars2.vars_.end(), std::less<Variable>{}); } // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Variables& operator+=(Variables& vars1, const Variables& vars2) { vars1.insert(vars2); return vars1; } // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Variables& operator+=(Variables& vars, const Variable& var) { vars.insert(var); return vars; } Variables operator+(Variables vars1, const Variables& vars2) { vars1 += vars2; return vars1; } Variables operator+(Variables vars, const Variable& var) { vars += var; return vars; } Variables operator+(const Variable& var, Variables vars) { vars += var; return vars; } // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Variables& operator-=(Variables& vars1, const Variables& vars2) { vars1.erase(vars2); return vars1; } // NOLINTNEXTLINE(runtime/references) per C++ standard signature. Variables& operator-=(Variables& vars, const Variable& var) { vars.erase(var); return vars; } Variables operator-(Variables vars1, const Variables& vars2) { vars1 -= vars2; return vars1; } Variables operator-(Variables vars, const Variable& var) { vars -= var; return vars; } Variables::Variables(set<Variable> vars) : vars_{std::move(vars)} {} Variables intersect(const Variables& vars1, const Variables& vars2) { set<Variable> intersection; set_intersection(vars1.vars_.begin(), vars1.vars_.end(), vars2.vars_.begin(), vars2.vars_.end(), inserter(intersection, intersection.begin()), less<Variable>{}); return Variables{std::move(intersection)}; } ostream& operator<<(ostream& os, const Variables& vars) { os << "{"; if (!vars.vars_.empty()) { // output 1st ... N-1th elements by adding ", " at the end copy(vars.begin(), prev(vars.end()), ostream_iterator<Variable>(os, ", ")); // output the last one (without ","). os << *(vars.rbegin()); } os << "}"; return os; } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/boxed_cell.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <cstdint> #include <cstring> #include <memory> #include <utility> #include "drake/common/drake_assert.h" namespace drake { namespace symbolic { class ExpressionCell; namespace internal { /* BoxedCell is an internal class that provides an extremely efficient storage format for the data inside an Expression. Conceptually, it stores three pieces of information: (1) `ExpressionKind kind` -- the operation (e.g., add, mul, cos, max, ...). (2) `double value` -- the constant value iff `kind == ExpressionKind::Constant`. (3) `shared_ptr<ExpressionCell> cell` -- a copy-on-write, heap-allocated object that stores the details of the expression operation (e.g., the terms to sum). This is only used for expressions with `kind != ExpressionKind::Constant`; for constants, the cell is conceptually nullptr. In a naive implementation, those three fields would consume 2 + 8 + 16 == 26 bytes (which the compiler will often round up to 32). The crux of this class is to represent that information using only 8 bytes (as a `double value_;`), with a trick called "nanboxing". Refer to https://piotrduperas.com/posts/nan-boxing for good overview of the technique. Definitely read the background material before proceeding through the rest of this overview! In the following sections, we'll summarize the reasons we're using nanboxing, recap the highlights of the technique, and discuss the specific implementation choices used within BoxedCell. ===== Speed-ups ===== (1) Information density. We use nanboxing in part for the typical payoff -- packing a lot of information into a tiny space and avoiding pointer-chasing for literal values. (2) Speculative arithmetic. For floating-point arithmetic in particular, representing pointers as NaNs allows us to use _speculative_ arithmetic for even more throughput. Consider the following math: x = a*b + c*d + e*f + g*h. If all of the values are constants (i.e., have no Variables), then ideally we'd like to compute `x` using just 7 flops (and at most 7 machine instructions, or perhaps fewer with SIMD). Naively, we could first check all 8 inputs (a..h) for whether they are constant, and if yes then do the flops, otherwise fall back to the slower, fully-symbolic evaluation. (Or worse, check before every binary operator in which case we'd need 14 checks.) Those 8 or 14 branches (>1 per flop) are not cheap, though! Ideally we would like to see very few branches per flop on average, for best throughput. Since non-constants (cell pointers) are always NaN when interpreted as a double, another way we can implement that math is to first compute the result `x` using 7 flops, and then _afterwards_ check only `x` for NaN instead of all of the the inputs. (Per IEEE754, any operation on NaN input always produces a NaN output.) If `x` ends up non-NaN, that means none of the inputs could have been NaN, which means none of the inputs could have been variables, and we're done! One branch per 7 flops. In case `x` did end up as NaN, then we throw away the speculative result and branch to the fully-symbolic evaluation. Note that with how Expression is implemented today in terms of binary operations that run one by one, this technique is only used to partial effect. We still end up checking for some intermediate NaNs, just not as many. To take full effect, we will need to specialize Eigen's matrix-operation functors. Note that `x` could end up NaN even when a..h were all constants (e.g., when subtracting infinity from itself, or dividing by zero). This is a rare case, so we're satisfied to use the slower symbolic codepath to handle it. (3) Fast pattern matching. The implementation also provides some clever functions such as constant_or_nan() or is_kind<ExpressionKind>() that allow for efficient machine code for the most frequent operations performed on an Expression. In many cases (e.g., std::map), the Expression::Less and Expression::EqualTo are called extremely many times, so it's critically important that they bail out early in case the cell pointer or constant is the same, or the kind is different. ===== The BoxedCell implementation and its representation choices ===== When the BoxedCell kind is a Constant, then its `value_` directly holds the constant value. As bits, an IEEE754 64-bit double looks like SEEEEEEE EEEEMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM where S is the sign bit, E are the 11 exponent bits, and M are the 52 mantissa bits. When the E bits are all 1's, then the floating-point value is non-finite: - If M are all zero, then the value is ±infinity (based on the sign bit). - Otherwise, the value is NaN (no matter the sign bit). Because Expression does not allow NaN values as a Constant (instead, there is a cell type ExpressionNaN), we have the opportunity to re-purpose the meaning of the NaN bit pattern as: x1111111 1111xxxx PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP where P is a 48-bit pointer value. Because the pointer cannot be null, we know for sure that the value will be not mistaken for an infinity. Note that x86_64 pointers only have 48 significant bits; see https://en.wikipedia.org/wiki/X86-64#Architectural_features or https://www.amd.com/system/files/TechDocs/24593.pdf for details. The same is true of the nominal AArch64 virtual addresses used on macOS (running `sysctl machdep.virtual_address_size` reports 47 on Apple M1), and we don't expect to ever compile with "pointer authentication" (i.e., "PAC") enabled. (PAC lays claim to the upper bits of the pointer). With more tricks, we can also store the 16-bit ExpressionKind inline: KKKKKKKK KKKKKKKK PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP PPPPPPPP as long as the definition of ExpressionKind has the NaN bits set: x1111111 1111xxxx Indeed, we've set up ExpressionKind in just such a way. The upper 16 bits are called the "pointer tag" or just "tag". We have one final trick up our sleeve. Recall what an infinity looks like: S1111111 11110000 00000000 00000000 00000000 00000000 00000000 00000000 When Expression holds infinity, we need to have e.get_kind() == Constant. We _could_ check all 64 bits for this pattern, but the x86_64 instruction for that requires copying it into an xmm register, whereas Expressions are usually manipulated within integer registers (the SystemV ABI passes them as pointers, not in xmm registers). Instead, we'll make an invariant that no ExpressionKind tag value is ever x1111111 11110000 which means that e.get_kind() can be fully determined by looking only at the 16 tag bits, not all 64 bits. Specifically, if the exponent has a zero bit anywhere ... -------- -------- tag_bits() -------- -------- x0xxxxxx xxxxxxxx xx0xxxxx xxxxxxxx xxx0xxxx xxxxxxxx xxxx0xxx xxxxxxxx xxxxx0xx xxxxxxxx xxxxxx0x xxxxxxxx xxxxxxx0 xxxxxxxx xxxxxxxx 0xxxxxxx xxxxxxxx x0xxxxxx xxxxxxxx xx0xxxxx xxxxxxxx xxx0xxxx ... then the get_kind() is Constant (and finite). Otherwise, if the lower four bits of the tag are all zero ... xxxxxxxx xxxx0000 ... then the get_kind() is Constant (and infinite). Note that in this case the exponent will necessarily have been all 1s ... x1111111 11110000 ... but we don't need to check for that in the matching predicate, the zero nibble is sufficient on its own. (This is actually a meaningful speed-up!) Otherwise, the get_kind() is exactly the tag bits (and isn't Constant) ... KKKKKKKK KKKKKKKK ... keeping in mind that the middle bits are necessarily all 1s ... K1111111 1111KKKK ... but we don't need to check for that in the matching predicate. Note that with this bit layout, we have used ~27 of the 31 available kinds that fit within this design. In case we ever need more than 31, note that the lower 3 bits of the pointer are always zero (because heap allocations always happen on >= 8 bytes boundaries), so we could store more tag bits in the lower 48-bit "pointer" value, either in the low-order bits directly, or by right-shifting the pointer to make more room at the top. A final note: the high-order bit of a NaN's mantissa is the "quiet" bit. When set to 0, the value is a "signaling NaN" and in theory might raise a floating-point trap when operated on. In practice, our supported platforms ignore the signaling vs quiet distinction, so we haven't bothered trying to keep it set to 1. */ class BoxedCell { public: /* Default constructor constructs zero. */ BoxedCell() : BoxedCell(0.0) {} /* Constructs a constant. */ explicit BoxedCell(double constant) : value_(constant) { DRAKE_ASSERT(!std::isnan(constant)); } /* Copyable-constructible. */ BoxedCell(const BoxedCell& other) { if (other.is_constant()) { value_ = other.value_; } else { ConstructCopy(other); } } /* Copyable-assignable. */ BoxedCell& operator=(const BoxedCell& other) { if (is_constant() && other.is_constant()) { value_ = other.value_; } else { AssignCopy(other); } return *this; } /* Move-constructible. After the move, `other` will be zero. */ BoxedCell(BoxedCell&& other) noexcept { // When other is not a Constant, transfers ownership of other.cell() to // this with no change to the cell's use_count. value_ = other.value_; other.value_ = 0; } /* Move-assignable. After the move, `other` will be zero. */ BoxedCell& operator=(BoxedCell&& other) noexcept { if (!is_constant()) { // Decrement the use_count of our currently-managed cell. Release(); } // When other is not a Constant, transfers ownership of other.cell() to // this with no change to the cell's use_count. value_ = other.value_; other.value_ = 0; return *this; } ~BoxedCell() { // This is required in order to decrement the use_count of our cell. Release(); } friend void swap(BoxedCell& a, BoxedCell& b) { std::swap(a.value_, b.value_); } /* Returns the contained ExpressionKind. */ [[nodiscard]] ExpressionKind get_kind() const { const std::uint16_t tag = tag_bits(); // When the floating-point exponent is all 1's, then the floating-point // value is non-finite: either ±infinity, or NaN (which in our case is a // tagged pointer). When the exponent is something _other than_ all 1's, // then the floating-point value is finite, i.e., a Constant. constexpr std::uint16_t non_finite_mask = 0x7FF0; if ((tag & non_finite_mask) != non_finite_mask) { return ExpressionKind::Constant; } // To distinguish ±infinity, it's sufficient to check the lower four bits. // The ExpressionKind tagging constants were carefully assigned to never // use a zero there. constexpr std::uint16_t infinity_mask = 0x000F; if ((tag & infinity_mask) == 0) { return ExpressionKind::Constant; } // We're a NaN (i.e., a tagged pointer). Our tag is the ExpressionKind. return static_cast<ExpressionKind>(tag); } /* Returns true iff get_kind() == ExpressionKind::Constant. */ [[nodiscard]] bool is_constant() const { return !std::isnan(value_); } /* Returns true iff get_kind() == kind. @pre kind is not ExpressionKind::Constant (use is_constant() instead) */ template <ExpressionKind kind> [[nodiscard]] bool is_kind() const { static_assert(kind != ExpressionKind::Constant); return tag_bits() == static_cast<std::uint16_t>(kind); } /* Returns the Constant value. @pre This expression is a Constant. */ [[nodiscard]] double constant() const { DRAKE_ASSERT(is_constant()); return value_; } /* If this is a Constant, then returns the value; otherwise, returns NaN. */ [[nodiscard]] double constant_or_nan() const { return value_; } /* Returns true iff this and other are "trivially" equal, i.e., they are either the both same Constant value, or else both point to the same cell. */ [[nodiscard]] bool trivially_equals(const BoxedCell& other) const { return value_bits() == other.value_bits(); } /* Sets this to a new Constant value. @pre This expression is already a Constant. @pre The new_value is not NaN. */ void update_constant(double new_value) { DRAKE_ASSERT(is_constant()); DRAKE_ASSERT(!std::isnan(new_value)); value_ = new_value; } /* Returns a const reference to the owned cell. @pre This expression is not a Constant. */ [[nodiscard]] const ExpressionCell& cell() const { DRAKE_ASSERT(!is_constant()); // Convert the bit pattern back to the `owned` pointer. // https://en.cppreference.com/w/cpp/language/reinterpret_cast (case 3) return *reinterpret_cast<ExpressionCell*>(pointer_bits()); } /* Sets this to point at the given cell_to_share, incrementing its use_count. @pre This is a Constant (i.e., does currently not own any cell). @pre cell_to_share is not null. */ void SetSharedCell(const ExpressionCell* cell_to_share) noexcept; private: explicit BoxedCell(std::unique_ptr<ExpressionCell> cell); /* Implements copy construction when other is not a constant. */ void ConstructCopy(const BoxedCell& other); /* Implements copy-assignment when either this or other are not constants. */ void AssignCopy(const BoxedCell& other); /* Assigns the Constant value 0.0 to this cell. If our current value was not already a Constant, then decrements the use_count of our currently-owned cell beforehand and also deletes the cell in case the use_count reached zero. */ void Release() noexcept; /* Returns our value_ as an unsigned integer. If this is not a Constant, then the upper 16 bits are the kind and the lower 48 bits are the pointer to the shared ExpressionCell. Refer to the BoxedCell class overview comment for additional details. */ std::uintptr_t value_bits() const { std::uintptr_t result; std::memcpy(&result, &value_, sizeof(result)); return result; } /* Returns the tag portion of our value_. If this is not a Constant, then the result will be our ExpressionKind. Refer to the BoxedCell class overview comment for additional details. */ std::uint16_t tag_bits() const { return value_bits() >> 48; } /* Returns the pointer portion of our value_. If this is not a Constant, then the result will be the pointer to the shared ExpressionCell. Refer to the BoxedCell class overview for additional details. */ std::uintptr_t pointer_bits() const { return value_bits() & ~(0xFFFFull << 48); } #ifdef DRAKE_ASSERT_IS_ARMED double value_{}; #else // N.B. We are careful that every constructor always sets this. // Leaving it non-redundantly initialized here is slightly faster. double value_; #endif }; } // namespace internal } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/variable.cc
/* clang-format off to disable clang-format-includes */ // NOLINTNEXTLINE(build/include): Our header file is included by all.h. #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <atomic> #include <memory> #include <ostream> #include <sstream> #include <string> #include <utility> #include "drake/common/drake_assert.h" #include "drake/common/never_destroyed.h" using std::atomic; using std::make_shared; using std::ostream; using std::ostringstream; using std::string; using std::to_string; namespace drake { namespace symbolic { namespace { /* Produces a unique ID for a variable. */ size_t get_next_id(const Variable::Type type) { static_assert(std::is_same_v<Variable::Id, size_t>); // Note that id 0 is reserved for anonymous variable which is created by the // default constructor, Variable(). As a result, we have an invariant // "get_next_id() > 0". static never_destroyed<atomic<size_t>> next_id(1); const size_t counter = next_id.access()++; // We'll assume that size_t is at least 8 bytes wide, so that we can pack the // counter into the lower 7 bytes of `id_` and the `Type` into the upper byte. static_assert(sizeof(size_t) >= 8); return counter | (static_cast<size_t>(type) << (7 * 8)); } } // namespace Variable::Variable(string name, const Type type) : id_{get_next_id(type)}, name_{make_shared<const string>(std::move(name))} { DRAKE_ASSERT(id_ > 0); } string Variable::get_name() const { return name_ != nullptr ? *name_ : string{"𝑥"}; } string Variable::to_string() const { ostringstream oss; oss << *this; return oss.str(); } ostream& operator<<(ostream& os, const Variable& var) { os << var.get_name(); return os; } ostream& operator<<(ostream& os, Variable::Type type) { switch (type) { case Variable::Type::CONTINUOUS: return os << "Continuous"; case Variable::Type::BINARY: return os << "Binary"; case Variable::Type::INTEGER: return os << "Integer"; case Variable::Type::BOOLEAN: return os << "Boolean"; case Variable::Type::RANDOM_UNIFORM: return os << "Random Uniform"; case Variable::Type::RANDOM_GAUSSIAN: return os << "Random Gaussian"; case Variable::Type::RANDOM_EXPONENTIAL: return os << "Random Exponential"; } DRAKE_UNREACHABLE(); } MatrixX<Variable> MakeMatrixVariable(const int rows, const int cols, const string& name, const Variable::Type type) { MatrixX<Variable> m{rows, cols}; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { m(i, j) = Variable{name + "(" + to_string(i) + ", " + to_string(j) + ")", type}; } } return m; } MatrixX<Variable> MakeMatrixBooleanVariable(const int rows, const int cols, const string& name) { return MakeMatrixVariable(rows, cols, name, Variable::Type::BOOLEAN); } MatrixX<Variable> MakeMatrixBinaryVariable(const int rows, const int cols, const string& name) { return MakeMatrixVariable(rows, cols, name, Variable::Type::BINARY); } MatrixX<Variable> MakeMatrixContinuousVariable(const int rows, const int cols, const string& name) { return MakeMatrixVariable(rows, cols, name, Variable::Type::CONTINUOUS); } MatrixX<Variable> MakeMatrixIntegerVariable(const int rows, const int cols, const string& name) { return MakeMatrixVariable(rows, cols, name, Variable::Type::INTEGER); } VectorX<Variable> MakeVectorVariable(const int rows, const string& name, const Variable::Type type) { VectorX<Variable> vec{rows}; for (int i = 0; i < rows; ++i) { vec[i] = Variable{name + "(" + to_string(i) + ")", type}; } return vec; } VectorX<Variable> MakeVectorBooleanVariable(const int rows, const string& name) { return MakeVectorVariable(rows, name, Variable::Type::BOOLEAN); } VectorX<Variable> MakeVectorBinaryVariable(const int rows, const string& name) { return MakeVectorVariable(rows, name, Variable::Type::BINARY); } VectorX<Variable> MakeVectorContinuousVariable(const int rows, const string& name) { return MakeVectorVariable(rows, name, Variable::Type::CONTINUOUS); } VectorX<Variable> MakeVectorIntegerVariable(const int rows, const string& name) { return MakeVectorVariable(rows, name, Variable::Type::INTEGER); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/formula_visitor.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <utility> #include "drake/common/drake_assert.h" namespace drake { namespace symbolic { /// Calls visitor object @p v with a symbolic formula @p f, and arguments @p /// args. Visitor object is expected to implement the following methods which /// take @p f and @p args: `VisitFalse`, `VisitTrue`, `VisitVariable`, /// `VisitEqualTo`, VisitNotEqualTo, VisitGreaterThan, /// `VisitGreaterThanOrEqualTo`, `VisitLessThan`, `VisitLessThanOrEqualTo`, /// `VisitConjunction`, `VisitDisjunction`, `VisitNegation`, `VisitForall`, /// `VisitIsnan`, `VisitPositiveSemidefinite`. /// /// Check the implementation of @c NegationNormalFormConverter class in /// drake/common/test/symbolic_formula_visitor_test.cc file to find an example. template <typename Result, typename Visitor, typename... Args> Result VisitFormula(Visitor* v, const Formula& f, Args&&... args) { switch (f.get_kind()) { case FormulaKind::False: return v->VisitFalse(f, std::forward<Args>(args)...); case FormulaKind::True: return v->VisitTrue(f, std::forward<Args>(args)...); case FormulaKind::Var: return v->VisitVariable(f, std::forward<Args>(args)...); case FormulaKind::Eq: return v->VisitEqualTo(f, std::forward<Args>(args)...); case FormulaKind::Neq: return v->VisitNotEqualTo(f, std::forward<Args>(args)...); case FormulaKind::Gt: return v->VisitGreaterThan(f, std::forward<Args>(args)...); case FormulaKind::Geq: return v->VisitGreaterThanOrEqualTo(f, std::forward<Args>(args)...); case FormulaKind::Lt: return v->VisitLessThan(f, std::forward<Args>(args)...); case FormulaKind::Leq: return v->VisitLessThanOrEqualTo(f, std::forward<Args>(args)...); case FormulaKind::And: return v->VisitConjunction(f, std::forward<Args>(args)...); case FormulaKind::Or: return v->VisitDisjunction(f, std::forward<Args>(args)...); case FormulaKind::Not: return v->VisitNegation(f, std::forward<Args>(args)...); case FormulaKind::Forall: return v->VisitForall(f, std::forward<Args>(args)...); case FormulaKind::Isnan: return v->VisitIsnan(f, std::forward<Args>(args)...); case FormulaKind::PositiveSemidefinite: return v->VisitPositiveSemidefinite(f, std::forward<Args>(args)...); } DRAKE_UNREACHABLE(); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/boxed_cell.cc
/* clang-format off to disable clang-format-includes */ // NOLINTNEXTLINE(build/include): Our header file is included by all.h. #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #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 { namespace internal { void BoxedCell::ConstructCopy(const BoxedCell& other) { DRAKE_ASSERT(!other.is_constant()); SetSharedCell(&other.cell()); } void BoxedCell::AssignCopy(const BoxedCell& other) { if (this == &other) { return; } // Decrement the use_count of our currently-managed cell. Release(); if (other.is_constant()) { value_ = other.value_; } else { SetSharedCell(&other.cell()); } } void BoxedCell::SetSharedCell(const ExpressionCell* cell) noexcept { DRAKE_ASSERT(cell != nullptr); DRAKE_ASSERT(is_constant()); // Convert the `cell` pointer to a bit pattern. // https://en.cppreference.com/w/cpp/language/reinterpret_cast (case 2) uintptr_t bit_buffer = reinterpret_cast<uintptr_t>(cell); // Compute (and check) the tag. const uint16_t tag = static_cast<uint16_t>(cell->get_kind()); // It must have the NaN bits set. DRAKE_ASSERT((tag & 0x7FF0) == 0x7FF0); // It must NOT have a zero in the low nibble. Otherwise, we could confuse // the tag with +Infinity (0x7FF0...) or -Infinity (0x8FF0...). DRAKE_ASSERT((tag & 0x000F) != 0); // Set the upper 16 bits of the point to the tag (i.e., the kind). They // must have already been zero (due the limit of 48-bit addressable physical // address space on our supported platforms). DRAKE_ASSERT((bit_buffer & (0xFFFFull << 48)) == 0); bit_buffer |= static_cast<uintptr_t>(tag) << 48; // Bit-cast it into a double. static_assert(sizeof(value_) == sizeof(bit_buffer)); std::memcpy(&value_, &bit_buffer, sizeof(value_)); DRAKE_ASSERT(std::isnan(value_)); // Claim a use of the cell. ++(cell->use_count()); } void BoxedCell::Release() noexcept { if (!is_constant()) { const auto& owned = cell(); const int new_use_count = --owned.use_count(); if (new_use_count == 0) { delete &owned; } } value_ = 0.0; } } // namespace internal } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/formula_cell.cc
#define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/expression/formula_cell.h" #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include <algorithm> #include <memory> #include <ostream> #include <set> #include <sstream> #include <stdexcept> #include <utility> #include <fmt/format.h> #include <fmt/ostream.h> #include "drake/common/drake_assert.h" #include "drake/common/fmt_eigen.h" namespace drake { namespace symbolic { using std::equal; using std::lexicographical_compare; using std::ostream; using std::ostringstream; using std::runtime_error; using std::set; using std::shared_ptr; using std::static_pointer_cast; using std::string; FormulaCell::FormulaCell(const FormulaKind k) : kind_{k} {} RelationalFormulaCell::RelationalFormulaCell(const FormulaKind k, Expression lhs, Expression rhs) : FormulaCell{k}, e_lhs_{std::move(lhs)}, e_rhs_{std::move(rhs)} {} void RelationalFormulaCell::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, e_lhs_); hash_append(*hasher, e_rhs_); } Variables RelationalFormulaCell::GetFreeVariables() const { Variables ret{e_lhs_.GetVariables()}; ret.insert(e_rhs_.GetVariables()); return ret; } bool RelationalFormulaCell::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const auto& rel_f = static_cast<const RelationalFormulaCell&>(f); return e_lhs_.EqualTo(rel_f.e_lhs_) && e_rhs_.EqualTo(rel_f.e_rhs_); } bool RelationalFormulaCell::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const auto& rel_f = static_cast<const RelationalFormulaCell&>(f); if (e_lhs_.Less(rel_f.e_lhs_)) { return true; } if (rel_f.e_lhs_.Less(e_lhs_)) { return false; } return e_rhs_.Less(rel_f.e_rhs_); } NaryFormulaCell::NaryFormulaCell(const FormulaKind k, set<Formula> formulas) : FormulaCell{k}, formulas_{std::move(formulas)} {} void NaryFormulaCell::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, formulas_); } Variables NaryFormulaCell::GetFreeVariables() const { Variables ret{}; for (const auto& f : formulas_) { ret.insert(f.GetFreeVariables()); } return ret; } bool NaryFormulaCell::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const auto& nary_f = static_cast<const NaryFormulaCell&>(f); return equal(formulas_.cbegin(), formulas_.cend(), nary_f.formulas_.cbegin(), nary_f.formulas_.cend(), [](const Formula& f1, const Formula& f2) { return f1.EqualTo(f2); }); } bool NaryFormulaCell::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const auto& nary_f = static_cast<const NaryFormulaCell&>(f); return lexicographical_compare( formulas_.cbegin(), formulas_.cend(), nary_f.formulas_.cbegin(), nary_f.formulas_.cend(), [](const Formula& f1, const Formula& f2) { return f1.Less(f2); }); } ostream& NaryFormulaCell::DisplayWithOp(ostream& os, const string& op) const { const set<Formula>& formulas{get_operands()}; auto it(formulas.cbegin()); DRAKE_ASSERT(formulas.size() > 1U); os << "("; os << *it; ++it; while (it != formulas.cend()) { os << " " << op << " " << *it; ++it; } os << ")"; return os; } FormulaTrue::FormulaTrue() : FormulaCell{FormulaKind::True} {} void FormulaTrue::HashAppendDetail(DelegatingHasher*) const {} Variables FormulaTrue::GetFreeVariables() const { return Variables{}; } bool FormulaTrue::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); return true; // There is only one instance of this kind. } bool FormulaTrue::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); // True < True ==> false return false; } bool FormulaTrue::Evaluate(const Environment&) const { return true; } Formula FormulaTrue::Substitute(const Substitution&) const { return Formula::True(); } ostream& FormulaTrue::Display(ostream& os) const { return os << "True"; } FormulaFalse::FormulaFalse() : FormulaCell{FormulaKind::False} {} void FormulaFalse::HashAppendDetail(DelegatingHasher*) const {} Variables FormulaFalse::GetFreeVariables() const { return Variables{}; } bool FormulaFalse::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); return true; // There is only one instance of this kind. } bool FormulaFalse::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); // False < False ==> false return false; } bool FormulaFalse::Evaluate(const Environment&) const { return false; } Formula FormulaFalse::Substitute(const Substitution&) const { return Formula::False(); } ostream& FormulaFalse::Display(ostream& os) const { return os << "False"; } FormulaVar::FormulaVar(Variable v) : FormulaCell{FormulaKind::Var}, var_{std::move(v)} { DRAKE_DEMAND(var_.get_type() == Variable::Type::BOOLEAN); } void FormulaVar::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, var_); } Variables FormulaVar::GetFreeVariables() const { return Variables{var_}; } bool FormulaVar::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaVar& f_var{static_cast<const FormulaVar&>(f)}; return var_.equal_to(f_var.var_); } bool FormulaVar::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaVar& f_var{static_cast<const FormulaVar&>(f)}; return var_.less(f_var.var_); } bool FormulaVar::Evaluate(const Environment& env) const { const Environment::const_iterator it{env.find(var_)}; if (it != env.cend()) { return static_cast<bool>(it->second); } else { ostringstream oss; oss << "The following environment does not have an entry for the " "variable " << var_ << "\n"; oss << env << "\n"; throw runtime_error(oss.str()); } } Formula FormulaVar::Substitute(const Substitution&) const { // TODO(soonho-tri): Add a substitution (Variable -> Formula) and use it // here. For now, `Substitute` does nothing for Boolean variables. return Formula{var_}; } ostream& FormulaVar::Display(ostream& os) const { return os << var_; } const Variable& FormulaVar::get_variable() const { return var_; } FormulaEq::FormulaEq(const Expression& e1, const Expression& e2) : RelationalFormulaCell{FormulaKind::Eq, e1, e2} {} bool FormulaEq::Evaluate(const Environment& env) const { return get_lhs_expression().Evaluate(env) == get_rhs_expression().Evaluate(env); } Formula FormulaEq::Substitute(const Substitution& s) const { return get_lhs_expression().Substitute(s) == get_rhs_expression().Substitute(s); } ostream& FormulaEq::Display(ostream& os) const { return os << "(" << get_lhs_expression() << " == " << get_rhs_expression() << ")"; } FormulaNeq::FormulaNeq(const Expression& e1, const Expression& e2) : RelationalFormulaCell{FormulaKind::Neq, e1, e2} {} bool FormulaNeq::Evaluate(const Environment& env) const { return get_lhs_expression().Evaluate(env) != get_rhs_expression().Evaluate(env); } Formula FormulaNeq::Substitute(const Substitution& s) const { return get_lhs_expression().Substitute(s) != get_rhs_expression().Substitute(s); } ostream& FormulaNeq::Display(ostream& os) const { return os << "(" << get_lhs_expression() << " != " << get_rhs_expression() << ")"; } FormulaGt::FormulaGt(const Expression& e1, const Expression& e2) : RelationalFormulaCell{FormulaKind::Gt, e1, e2} {} bool FormulaGt::Evaluate(const Environment& env) const { return get_lhs_expression().Evaluate(env) > get_rhs_expression().Evaluate(env); } Formula FormulaGt::Substitute(const Substitution& s) const { return get_lhs_expression().Substitute(s) > get_rhs_expression().Substitute(s); } ostream& FormulaGt::Display(ostream& os) const { return os << "(" << get_lhs_expression() << " > " << get_rhs_expression() << ")"; } FormulaGeq::FormulaGeq(const Expression& e1, const Expression& e2) : RelationalFormulaCell{FormulaKind::Geq, e1, e2} {} bool FormulaGeq::Evaluate(const Environment& env) const { return get_lhs_expression().Evaluate(env) >= get_rhs_expression().Evaluate(env); } Formula FormulaGeq::Substitute(const Substitution& s) const { return get_lhs_expression().Substitute(s) >= get_rhs_expression().Substitute(s); } ostream& FormulaGeq::Display(ostream& os) const { return os << "(" << get_lhs_expression() << " >= " << get_rhs_expression() << ")"; } FormulaLt::FormulaLt(const Expression& e1, const Expression& e2) : RelationalFormulaCell{FormulaKind::Lt, e1, e2} {} bool FormulaLt::Evaluate(const Environment& env) const { return get_lhs_expression().Evaluate(env) < get_rhs_expression().Evaluate(env); } Formula FormulaLt::Substitute(const Substitution& s) const { return get_lhs_expression().Substitute(s) < get_rhs_expression().Substitute(s); } ostream& FormulaLt::Display(ostream& os) const { return os << "(" << get_lhs_expression() << " < " << get_rhs_expression() << ")"; } FormulaLeq::FormulaLeq(const Expression& e1, const Expression& e2) : RelationalFormulaCell{FormulaKind::Leq, e1, e2} {} bool FormulaLeq::Evaluate(const Environment& env) const { return get_lhs_expression().Evaluate(env) <= get_rhs_expression().Evaluate(env); } Formula FormulaLeq::Substitute(const Substitution& s) const { return get_lhs_expression().Substitute(s) <= get_rhs_expression().Substitute(s); } ostream& FormulaLeq::Display(ostream& os) const { return os << "(" << get_lhs_expression() << " <= " << get_rhs_expression() << ")"; } FormulaAnd::FormulaAnd(const set<Formula>& formulas) : NaryFormulaCell{FormulaKind::And, formulas} { DRAKE_ASSERT(get_operands().size() > 1U); } FormulaAnd::FormulaAnd(const Formula& f1, const Formula& f2) : NaryFormulaCell{FormulaKind::And, set<Formula>{f1, f2}} {} bool FormulaAnd::Evaluate(const Environment& env) const { for (const auto& f : get_operands()) { if (!f.Evaluate(env)) { return false; } } return true; } Formula FormulaAnd::Substitute(const Substitution& s) const { Formula ret{Formula::True()}; for (const auto& f : get_operands()) { ret = ret && f.Substitute(s); // short-circuiting if (is_false(ret)) { return ret; } } return ret; } ostream& FormulaAnd::Display(ostream& os) const { return DisplayWithOp(os, "and"); } FormulaOr::FormulaOr(const set<Formula>& formulas) : NaryFormulaCell{FormulaKind::Or, formulas} { DRAKE_ASSERT(get_operands().size() > 1U); } FormulaOr::FormulaOr(const Formula& f1, const Formula& f2) : NaryFormulaCell{FormulaKind::Or, set<Formula>{f1, f2}} {} bool FormulaOr::Evaluate(const Environment& env) const { for (const auto& f : get_operands()) { if (f.Evaluate(env)) { return true; } } return false; } Formula FormulaOr::Substitute(const Substitution& s) const { Formula ret{Formula::False()}; for (const auto& f : get_operands()) { ret = ret || f.Substitute(s); // short-circuiting if (is_true(ret)) { return ret; } } return ret; } ostream& FormulaOr::Display(ostream& os) const { return DisplayWithOp(os, "or"); } FormulaNot::FormulaNot(Formula f) : FormulaCell{FormulaKind::Not}, f_{std::move(f)} {} void FormulaNot::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, f_); } Variables FormulaNot::GetFreeVariables() const { return f_.GetFreeVariables(); } bool FormulaNot::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaNot& f_not{static_cast<const FormulaNot&>(f)}; return f_.EqualTo(f_not.f_); } bool FormulaNot::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaNot& not_f{static_cast<const FormulaNot&>(f)}; return f_.Less(not_f.f_); } bool FormulaNot::Evaluate(const Environment& env) const { return !f_.Evaluate(env); } Formula FormulaNot::Substitute(const Substitution& s) const { return !f_.Substitute(s); } ostream& FormulaNot::Display(ostream& os) const { return os << "!(" << f_ << ")"; } FormulaForall::FormulaForall(Variables vars, Formula f) : FormulaCell{FormulaKind::Forall}, vars_{std::move(vars)}, f_{std::move(f)} {} void FormulaForall::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, vars_); hash_append(*hasher, f_); } Variables FormulaForall::GetFreeVariables() const { return f_.GetFreeVariables() - vars_; } bool FormulaForall::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaForall& f_forall{static_cast<const FormulaForall&>(f)}; return vars_ == f_forall.vars_ && f_.EqualTo(f_forall.f_); } bool FormulaForall::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaForall& forall_f{static_cast<const FormulaForall&>(f)}; if (vars_ < forall_f.vars_) { return true; } if (forall_f.vars_ < vars_) { return false; } return this->f_.Less(forall_f.f_); } bool FormulaForall::Evaluate(const Environment&) const { // Given ∀ x1, ..., xn. F, check if there is a counterexample satisfying // ¬F. If exists, it returns false. Otherwise, return true. // That is, it returns !check(∃ x1, ..., xn. ¬F) throw runtime_error("not implemented yet"); } Formula FormulaForall::Substitute(const Substitution& s) const { // Quantified variables are already bound and should not be substituted by s. // We construct a new substitution new_s from s by removing the entries of // bound variables. Substitution new_s{s}; for (const Variable& var : vars_) { new_s.erase(var); } return forall(vars_, f_.Substitute(new_s)); } ostream& FormulaForall::Display(ostream& os) const { return os << "forall(" << vars_ << ". " << f_ << ")"; } FormulaIsnan::FormulaIsnan(Expression e) : FormulaCell{FormulaKind::Isnan}, e_{std::move(e)} {} void FormulaIsnan::HashAppendDetail(DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; hash_append(*hasher, e_); } Variables FormulaIsnan::GetFreeVariables() const { return e_.GetVariables(); } bool FormulaIsnan::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaIsnan& f_isnan{static_cast<const FormulaIsnan&>(f)}; return e_.EqualTo(f_isnan.e_); } bool FormulaIsnan::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaIsnan& f_isnan{static_cast<const FormulaIsnan&>(f)}; return e_.Less(f_isnan.e_); } bool FormulaIsnan::Evaluate(const Environment& env) const { // Note that it throws std::runtime_error if it detects NaN during evaluation. return std::isnan(e_.Evaluate(env)); } Formula FormulaIsnan::Substitute(const Substitution& s) const { return isnan(e_.Substitute(s)); } ostream& FormulaIsnan::Display(ostream& os) const { return os << "isnan(" << e_ << ")"; } namespace { bool IsSymmetric(const Eigen::Ref<const MatrixX<Expression>>& m) { const int dim = m.rows(); if (m.cols() != dim) { return false; } for (int i = 0; i < dim; ++i) { for (int j = i + 1; j < dim; ++j) { if (!m(i, j).EqualTo(m(j, i))) { return false; } } } return true; } } // namespace FormulaPositiveSemidefinite::FormulaPositiveSemidefinite( const Eigen::Ref<const MatrixX<Expression>>& m) : FormulaCell{FormulaKind::PositiveSemidefinite}, m_{m} { if (!IsSymmetric(m)) { throw std::runtime_error(fmt::format( "The following matrix is not symmetric and cannot be used to " "construct drake::symbolic::FormulaPositiveSemidefinite:\n{}", fmt_eigen(m))); } } namespace { // Helper Eigen-visitor class that we use to implement // FormulaPositiveSemidefinite::GetFreeVariables(). struct VariablesCollector { using Index = Eigen::Index; // Called for the first coefficient. void init(const Expression& e, Index i, Index j) { DRAKE_ASSERT(vars_.empty()); return operator()(e, i, j); } // Called for all other coefficients. void operator()(const Expression& e, Index /* i */, Index /* j */) { vars_ += e.GetVariables(); } Variables vars_; }; } // namespace void FormulaPositiveSemidefinite::HashAppendDetail( DelegatingHasher* hasher) const { DRAKE_ASSERT(hasher != nullptr); using drake::hash_append; // Computes a hash of a matrix only using its lower-triangular part. for (int i = 0; i < m_.rows(); ++i) { for (int j = 0; j <= i; ++j) { hash_append(*hasher, m_(i, j)); } } hash_append(*hasher, m_.size()); } Variables FormulaPositiveSemidefinite::GetFreeVariables() const { VariablesCollector vc; m_.visit(vc); return vc.vars_; } bool FormulaPositiveSemidefinite::EqualTo(const FormulaCell& f) const { // Formula::EqualTo guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaPositiveSemidefinite& f_psd{ static_cast<const FormulaPositiveSemidefinite&>(f)}; return (m_.rows() == f_psd.m_.rows()) && (m_.cols() == f_psd.m_.cols()) && CheckStructuralEquality(m_, f_psd.m_); } bool FormulaPositiveSemidefinite::Less(const FormulaCell& f) const { // Formula::Less guarantees the following assertion. DRAKE_ASSERT(get_kind() == f.get_kind()); const FormulaPositiveSemidefinite& f_psd{ static_cast<const FormulaPositiveSemidefinite&>(f)}; // Compare rows. if (m_.rows() < f_psd.m_.rows()) { return true; } if (f_psd.m_.rows() < m_.rows()) { return false; } // No need to compare cols since m_ and f_psd.m_ are square matrices. DRAKE_ASSERT(m_.rows() == f_psd.m_.rows() && m_.cols() == f_psd.m_.cols()); // Element-wise comparison. const int num_of_elements = m_.rows() * m_.cols(); // clang-format off return lexicographical_compare( m_.data(), m_.data() + num_of_elements, f_psd.m_.data(), f_psd.m_.data() + num_of_elements, [](const Expression& e1, const Expression& e2) { return e1.Less(e2); }); // clang-format on } bool FormulaPositiveSemidefinite::Evaluate(const Environment&) const { // Need to check if xᵀ m x ≥ * 0 for all vector x ∈ ℝⁿ. // TODO(Soonho): implement this when we have SMT/delta-SMT support. throw runtime_error( "Checking positive_semidefinite(M) is not yet implemented."); } Formula FormulaPositiveSemidefinite::Substitute(const Substitution& s) const { return positive_semidefinite(m_.unaryExpr([&s](const Expression& e) { return e.Substitute(s); })); } ostream& FormulaPositiveSemidefinite::Display(ostream& os) const { fmt::print(os, "positive_semidefinite({})", fmt_eigen(m_)); return os; } bool is_false(const FormulaCell& f) { return f.get_kind() == FormulaKind::False; } bool is_true(const FormulaCell& f) { return f.get_kind() == FormulaKind::True; } bool is_variable(const FormulaCell& f) { return f.get_kind() == FormulaKind::Var; } bool is_equal_to(const FormulaCell& f) { return f.get_kind() == FormulaKind::Eq; } bool is_not_equal_to(const FormulaCell& f) { return f.get_kind() == FormulaKind::Neq; } bool is_greater_than(const FormulaCell& f) { return f.get_kind() == FormulaKind::Gt; } bool is_greater_than_or_equal_to(const FormulaCell& f) { return f.get_kind() == FormulaKind::Geq; } bool is_less_than(const FormulaCell& f) { return f.get_kind() == FormulaKind::Lt; } bool is_less_than_or_equal_to(const FormulaCell& f) { return f.get_kind() == FormulaKind::Leq; } bool is_relational(const FormulaCell& f) { return is_equal_to(f) || is_not_equal_to(f) || is_greater_than(f) || is_greater_than_or_equal_to(f) || is_less_than(f) || is_less_than_or_equal_to(f); } bool is_conjunction(const FormulaCell& f) { return f.get_kind() == FormulaKind::And; } bool is_disjunction(const FormulaCell& f) { return f.get_kind() == FormulaKind::Or; } bool is_nary(const FormulaCell& f) { return is_conjunction(f) || is_disjunction(f); } bool is_negation(const FormulaCell& f) { return f.get_kind() == FormulaKind::Not; } bool is_forall(const FormulaCell& f) { return f.get_kind() == FormulaKind::Forall; } bool is_isnan(const FormulaCell& f) { return f.get_kind() == FormulaKind::Isnan; } bool is_positive_semidefinite(const FormulaCell& f) { return f.get_kind() == FormulaKind::PositiveSemidefinite; } shared_ptr<const FormulaFalse> to_false( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_false(*f_ptr)); return static_pointer_cast<const FormulaFalse>(f_ptr); } shared_ptr<const FormulaFalse> to_false(const Formula& f) { return to_false(f.ptr_); } shared_ptr<const FormulaTrue> to_true( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_true(*f_ptr)); return static_pointer_cast<const FormulaTrue>(f_ptr); } shared_ptr<const FormulaTrue> to_true(const Formula& f) { return to_true(f.ptr_); } shared_ptr<const FormulaVar> to_variable( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_variable(*f_ptr)); return static_pointer_cast<const FormulaVar>(f_ptr); } shared_ptr<const FormulaVar> to_variable(const Formula& f) { return to_variable(f.ptr_); } shared_ptr<const RelationalFormulaCell> to_relational( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_relational(*f_ptr)); return static_pointer_cast<const RelationalFormulaCell>(f_ptr); } shared_ptr<const RelationalFormulaCell> to_relational(const Formula& f) { return to_relational(f.ptr_); } shared_ptr<const FormulaEq> to_equal_to( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_equal_to(*f_ptr)); return static_pointer_cast<const FormulaEq>(f_ptr); } shared_ptr<const FormulaEq> to_equal_to(const Formula& f) { return to_equal_to(f.ptr_); } shared_ptr<const FormulaNeq> to_not_equal_to( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_not_equal_to(*f_ptr)); return static_pointer_cast<const FormulaNeq>(f_ptr); } shared_ptr<const FormulaNeq> to_not_equal_to(const Formula& f) { return to_not_equal_to(f.ptr_); } shared_ptr<const FormulaGt> to_greater_than( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_greater_than(*f_ptr)); return static_pointer_cast<const FormulaGt>(f_ptr); } shared_ptr<const FormulaGt> to_greater_than(const Formula& f) { return to_greater_than(f.ptr_); } shared_ptr<const FormulaGeq> to_greater_than_or_equal_to( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_greater_than_or_equal_to(*f_ptr)); return static_pointer_cast<const FormulaGeq>(f_ptr); } shared_ptr<const FormulaGeq> to_greater_than_or_equal_to(const Formula& f) { return to_greater_than_or_equal_to(f.ptr_); } shared_ptr<const FormulaLt> to_less_than( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_less_than(*f_ptr)); return static_pointer_cast<const FormulaLt>(f_ptr); } shared_ptr<const FormulaLt> to_less_than(const Formula& f) { return to_less_than(f.ptr_); } shared_ptr<const FormulaLeq> to_less_than_or_equal_to( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_less_than_or_equal_to(*f_ptr)); return static_pointer_cast<const FormulaLeq>(f_ptr); } shared_ptr<const FormulaLeq> to_less_than_or_equal_to(const Formula& f) { return to_less_than_or_equal_to(f.ptr_); } shared_ptr<const NaryFormulaCell> to_nary( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_nary(*f_ptr)); return static_pointer_cast<const NaryFormulaCell>(f_ptr); } shared_ptr<const NaryFormulaCell> to_nary(const Formula& f) { return to_nary(f.ptr_); } shared_ptr<const FormulaAnd> to_conjunction( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_conjunction(*f_ptr)); return static_pointer_cast<const FormulaAnd>(f_ptr); } shared_ptr<const FormulaAnd> to_conjunction(const Formula& f) { return to_conjunction(f.ptr_); } shared_ptr<const FormulaOr> to_disjunction( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_disjunction(*f_ptr)); return static_pointer_cast<const FormulaOr>(f_ptr); } shared_ptr<const FormulaOr> to_disjunction(const Formula& f) { return to_disjunction(f.ptr_); } shared_ptr<const FormulaNot> to_negation( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_negation(*f_ptr)); return static_pointer_cast<const FormulaNot>(f_ptr); } shared_ptr<const FormulaNot> to_negation(const Formula& f) { return to_negation(f.ptr_); } shared_ptr<const FormulaForall> to_forall( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_forall(*f_ptr)); return static_pointer_cast<const FormulaForall>(f_ptr); } shared_ptr<const FormulaForall> to_forall(const Formula& f) { return to_forall(f.ptr_); } shared_ptr<const FormulaIsnan> to_isnan( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_isnan(*f_ptr)); return static_pointer_cast<const FormulaIsnan>(f_ptr); } shared_ptr<const FormulaIsnan> to_isnan(const Formula& f) { return to_isnan(f.ptr_); } shared_ptr<const FormulaPositiveSemidefinite> to_positive_semidefinite( const shared_ptr<const FormulaCell>& f_ptr) { DRAKE_ASSERT(is_positive_semidefinite(*f_ptr)); return static_pointer_cast<const FormulaPositiveSemidefinite>(f_ptr); } shared_ptr<const FormulaPositiveSemidefinite> to_positive_semidefinite( const Formula& f) { return to_positive_semidefinite(f.ptr_); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/environment.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <initializer_list> #include <ostream> #include <string> #include <unordered_map> #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/common/fmt.h" #include "drake/common/random.h" namespace drake { namespace symbolic { /** Represents a symbolic environment (mapping from a variable to a value). * * This class is used when we evaluate symbolic expressions or formulas which * include unquantified (free) variables. Here are examples: * * \code{.cpp} * const Variable var_x{"x"}; * const Variable var_y{"y"}; * const Expression x{var_x}; * const Expression y{var_x}; * const Expression e1{x + y}; * const Expression e2{x - y}; * const Formula f{e1 > e2}; * * // env maps var_x to 2.0 and var_y to 3.0 * const Environment env{{var_x, 2.0}, {var_y, 3.0}}; * * const double res1 = e1.Evaluate(env); // x + y => 2.0 + 3.0 => 5.0 * const double res2 = e2.Evaluate(env); // x - y => 2.0 - 3.0 => -1.0 * const bool res = f.Evaluate(env); // x + y > x - y => 5.0 >= -1.0 => True * \endcode */ class Environment { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Environment) typedef Variable key_type; typedef double mapped_type; typedef typename std::unordered_map<key_type, mapped_type> map; /** std::pair<key_type, mapped_type> */ typedef typename map::value_type value_type; typedef typename map::iterator iterator; typedef typename map::const_iterator const_iterator; /** Default constructor. */ Environment() = default; /** List constructor. Constructs an environment from a list of (Variable * * double). * * @throws std::exception if @p init include a dummy variable or a NaN * value. */ Environment(std::initializer_list<value_type> init); /** List constructor. Constructs an environment from a list of * Variable. Initializes the variables with 0.0. * * @throws std::exception if @p vars include a dummy variable. */ Environment(std::initializer_list<key_type> vars); /** Constructs an environment from @p m (of `map` type, which is * `std::unordered_map`). * * @throws std::exception if @p m include a dummy variable or a NaN value. */ explicit Environment(map m); /** Returns an iterator to the beginning. */ iterator begin() { return map_.begin(); } /** Returns an iterator to the end. */ iterator end() { return map_.end(); } /** Returns a const iterator to the beginning. */ [[nodiscard]] const_iterator begin() const { return map_.cbegin(); } /** Returns a const iterator to the end. */ [[nodiscard]] const_iterator end() const { return map_.cend(); } /** Returns a const iterator to the beginning. */ [[nodiscard]] const_iterator cbegin() const { return map_.cbegin(); } /** Returns a const iterator to the end. */ [[nodiscard]] const_iterator cend() const { return map_.cend(); } /** Inserts a pair (@p key, @p elem) if this environment doesn't contain @p * key. Similar to insert function in map, if the key already * exists in this environment, then calling insert(key, elem) doesn't change * the existing key-value in this environment. */ void insert(const key_type& key, const mapped_type& elem); /** Given a matrix of symbolic variables @p keys and a matrix of values @p * elements, inserts each pair (keys(i, j), elements(i, j)) into the * environment if this environment doesn't contain keys(i, j) . Similar to * insert function in map, if keys(i, j) already exists in this * environment, then this function doesn't change the its existing value in * this environment. * * @throws std::exception if the size of @p keys is different from the size * of @p elements. */ void insert(const Eigen::Ref<const MatrixX<key_type>>& keys, const Eigen::Ref<const MatrixX<mapped_type>>& elements); /** Checks whether the container is empty. */ [[nodiscard]] bool empty() const { return map_.empty(); } /** Returns the number of elements. */ [[nodiscard]] size_t size() const { return map_.size(); } /** Finds element with specific key. */ iterator find(const key_type& key) { return map_.find(key); } /** Finds element with specific key. */ [[nodiscard]] const_iterator find(const key_type& key) const { return map_.find(key); } /** Returns the domain of this environment. */ [[nodiscard]] Variables domain() const; /** Returns string representation. */ [[nodiscard]] std::string to_string() const; /** Returns a reference to the value that is mapped to a key equivalent to * @p key, performing an insertion if such key does not already exist. */ mapped_type& operator[](const key_type& key); /** As above, but returns a constref and does not perform an insertion * (throwing a runtime error instead) if the key does not exist. */ const mapped_type& operator[](const key_type& key) const; friend std::ostream& operator<<(std::ostream& os, const Environment& env); private: map map_; }; /** Populates the environment @p env by sampling values for the unassigned * random variables in @p variables using @p random_generator. */ Environment PopulateRandomVariables(Environment env, const Variables& variables, RandomGenerator* random_generator); } // namespace symbolic } // namespace drake DRAKE_FORMATTER_AS(, drake::symbolic, Environment, env, env.to_string())
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/formula_cell.h
#pragma once /// @file /// /// Internal use only. /// Provides implementation-details of symbolic formulas. #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #error Do not include this file unless you implement symbolic libraries. #endif #include <memory> #include <ostream> #include <set> #include <string> #include "drake/common/drake_assert.h" #include "drake/common/hash.h" #include "drake/common/random.h" #include "drake/common/symbolic/expression/all.h" namespace drake { namespace symbolic { /** Represents an abstract class which is the base of concrete symbolic-formula * classes (i.e. symbolic::FormulaAnd, symbolic::FormulaEq). * * \note It provides virtual function, FormulaCell::Display, * because operator<< is not allowed to be a virtual function. */ class FormulaCell { public: /** Returns kind of formula. */ [[nodiscard]] FormulaKind get_kind() const { return kind_; } /** Sends all hash-relevant bytes for this FormulaCell type into the given * hasher, per the @ref hash_append concept -- except for get_kind(), because * Formula already sends that. */ virtual void HashAppendDetail(DelegatingHasher*) const = 0; /** Returns set of free variables in formula. */ [[nodiscard]] virtual Variables GetFreeVariables() const = 0; /** Checks structural equality. */ [[nodiscard]] virtual bool EqualTo(const FormulaCell& c) const = 0; /** Checks ordering. */ [[nodiscard]] virtual bool Less(const FormulaCell& c) const = 0; /** Evaluates under a given environment. */ [[nodiscard]] virtual bool Evaluate(const Environment& env) const = 0; /** Returns a Formula obtained by replacing all occurrences of the * variables in @p s in the current formula cell with the corresponding * expressions in @p s. */ [[nodiscard]] virtual Formula Substitute(const Substitution& s) const = 0; /** Outputs string representation of formula into output stream @p os. */ virtual std::ostream& Display(std::ostream& os) const = 0; /** Default constructor (deleted). */ FormulaCell() = delete; /** Move-assign (deleted). */ FormulaCell& operator=(FormulaCell&& f) = delete; /** Copy-assign (deleted). */ FormulaCell& operator=(const FormulaCell& f) = delete; protected: /** Move-construct a formula from an rvalue. */ FormulaCell(FormulaCell&& f) = default; /** Copy-construct a formula from an lvalue. */ FormulaCell(const FormulaCell& f) = default; /** Construct FormulaCell of kind @p k. */ explicit FormulaCell(FormulaKind k); /** Default destructor. */ virtual ~FormulaCell() = default; private: const FormulaKind kind_{}; }; /** Represents the base class for relational operators (==, !=, <, <=, >, >=). */ class RelationalFormulaCell : public FormulaCell { public: /** Default constructor (deleted). */ RelationalFormulaCell() = delete; /** Move-construct a formula from an rvalue. */ RelationalFormulaCell(RelationalFormulaCell&& f) = default; /** Copy-construct a formula from an lvalue. */ RelationalFormulaCell(const RelationalFormulaCell& f) = default; /** Move-assign (DELETED). */ RelationalFormulaCell& operator=(RelationalFormulaCell&& f) = delete; /** Copy-assign (DELETED). */ RelationalFormulaCell& operator=(const RelationalFormulaCell& f) = delete; /** Construct RelationalFormulaCell of kind @p k with @p lhs and @p rhs. */ RelationalFormulaCell(FormulaKind k, Expression lhs, Expression rhs); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; [[nodiscard]] bool Less(const FormulaCell& f) const override; /** Returns the expression on left-hand-side. */ [[nodiscard]] const Expression& get_lhs_expression() const { return e_lhs_; } /** Returns the expression on right-hand-side. */ [[nodiscard]] const Expression& get_rhs_expression() const { return e_rhs_; } private: const Expression e_lhs_; const Expression e_rhs_; }; /** Represents the base class for N-ary logic operators (∧ and ∨). * * @note Internally this class maintains a set of symbolic formulas to avoid * duplicated elements (i.e. f1 ∧ ... ∧ f1). */ class NaryFormulaCell : public FormulaCell { public: /** Default constructor (deleted). */ NaryFormulaCell() = delete; /** Move-construct a formula from an rvalue. */ NaryFormulaCell(NaryFormulaCell&& f) = default; /** Copy-construct a formula from an lvalue. */ NaryFormulaCell(const NaryFormulaCell& f) = default; /** Move-assign (DELETED). */ NaryFormulaCell& operator=(NaryFormulaCell&& f) = delete; /** Copy-assign (DELETED). */ NaryFormulaCell& operator=(const NaryFormulaCell& f) = delete; /** Construct NaryFormulaCell of kind @p k with @p formulas. */ NaryFormulaCell(FormulaKind k, std::set<Formula> formulas); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; [[nodiscard]] bool Less(const FormulaCell& f) const override; /** Returns the formulas. */ [[nodiscard]] const std::set<Formula>& get_operands() const { return formulas_; } protected: std::ostream& DisplayWithOp(std::ostream& os, const std::string& op) const; private: const std::set<Formula> formulas_; }; /** Symbolic formula representing true. */ class FormulaTrue : public FormulaCell { public: /** Default Constructor. */ FormulaTrue(); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; [[nodiscard]] bool Less(const FormulaCell& f) const override; [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing false. */ class FormulaFalse : public FormulaCell { public: /** Default Constructor. */ FormulaFalse(); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; [[nodiscard]] bool Less(const FormulaCell& f) const override; [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing a Boolean variable. */ class FormulaVar : public FormulaCell { public: /** Constructs a formula from @p var. * @pre @p var is of BOOLEAN type. */ explicit FormulaVar(Variable v); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; [[nodiscard]] bool Less(const FormulaCell& f) const override; [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& subst) const override; std::ostream& Display(std::ostream& os) const override; [[nodiscard]] const Variable& get_variable() const; private: const Variable var_; }; /** Symbolic formula representing equality (e1 = e2). */ class FormulaEq : public RelationalFormulaCell { public: /** Constructs from @p e1 and @p e2. */ FormulaEq(const Expression& e1, const Expression& e2); [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing disequality (e1 ≠ e2). */ class FormulaNeq : public RelationalFormulaCell { public: /** Constructs from @p e1 and @p e2. */ FormulaNeq(const Expression& e1, const Expression& e2); [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing 'greater-than' (e1 > e2). */ class FormulaGt : public RelationalFormulaCell { public: /** Constructs from @p e1 and @p e2. */ FormulaGt(const Expression& e1, const Expression& e2); [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing 'greater-than-or-equal-to' (e1 ≥ e2). */ class FormulaGeq : public RelationalFormulaCell { public: /** Constructs from @p e1 and @p e2. */ FormulaGeq(const Expression& e1, const Expression& e2); [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing 'less-than' (e1 < e2). */ class FormulaLt : public RelationalFormulaCell { public: /** Constructs from @p e1 and @p e2. */ FormulaLt(const Expression& e1, const Expression& e2); [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing 'less-than-or-equal-to' (e1 ≤ e2). */ class FormulaLeq : public RelationalFormulaCell { public: /** Constructs from @p e1 and @p e2. */ FormulaLeq(const Expression& e1, const Expression& e2); [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing conjunctions (f1 ∧ ... ∧ fn). */ class FormulaAnd : public NaryFormulaCell { public: /** Constructs from @p formulas. */ explicit FormulaAnd(const std::set<Formula>& formulas); /** Constructs @p f1 ∧ @p f2. */ FormulaAnd(const Formula& f1, const Formula& f2); [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing disjunctions (f1 ∨ ... ∨ fn). */ class FormulaOr : public NaryFormulaCell { public: /** Constructs from @p formulas. */ explicit FormulaOr(const std::set<Formula>& formulas); /** Constructs @p f1 ∨ @p f2. */ FormulaOr(const Formula& f1, const Formula& f2); [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic formula representing negations (¬f). */ class FormulaNot : public FormulaCell { public: /** Constructs from @p f. */ explicit FormulaNot(Formula f); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; [[nodiscard]] bool Less(const FormulaCell& f) const override; [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; /** Returns the operand. */ [[nodiscard]] const Formula& get_operand() const { return f_; } private: const Formula f_; }; /** Symbolic formula representing universal quantifications * (∀ x₁, ..., * xn. F). */ class FormulaForall : public FormulaCell { public: /** Constructs from @p vars and @p f. */ FormulaForall(Variables vars, Formula f); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; [[nodiscard]] bool Less(const FormulaCell& f) const override; [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; /** Returns the quantified variables. */ [[nodiscard]] const Variables& get_quantified_variables() const { return vars_; } /** Returns the quantified formula. */ [[nodiscard]] const Formula& get_quantified_formula() const { return f_; } private: const Variables vars_; // Quantified variables. const Formula f_; // Quantified formula. }; /** Symbolic formula representing isnan predicate. */ class FormulaIsnan : public FormulaCell { public: explicit FormulaIsnan(Expression e); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; [[nodiscard]] bool Less(const FormulaCell& f) const override; [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; /** Returns the operand expression. */ [[nodiscard]] const Expression& get_unary_expression() const { return e_; } private: const Expression e_; }; /** Symbolic formula representing positive-semidefinite (PSD) constraint. */ class FormulaPositiveSemidefinite : public FormulaCell { public: /** Constructs a positive-semidefinite formula from a symmetric matrix @p m. * * @throws std::exception if @p m is not symmetric. * * @note This constructor checks if @p m is symmetric, which can be costly. */ explicit FormulaPositiveSemidefinite( const Eigen::Ref<const MatrixX<Expression>>& m); /** Constructs a symbolic positive-semidefinite formula from a * lower triangular-view @p l. */ template <typename Derived> explicit FormulaPositiveSemidefinite( const Eigen::TriangularView<Derived, Eigen::Lower>& l) : FormulaCell{FormulaKind::PositiveSemidefinite}, m_{BuildSymmetricMatrixFromLowerTringularView(l)} {} /** Constructs a symbolic positive-semidefinite formula from an * upper triangular-view @p u. */ template <typename Derived> explicit FormulaPositiveSemidefinite( const Eigen::TriangularView<Derived, Eigen::Upper>& u) : FormulaCell{FormulaKind::PositiveSemidefinite}, m_{BuildSymmetricMatrixFromUpperTriangularView(u)} {} void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetFreeVariables() const override; [[nodiscard]] bool EqualTo(const FormulaCell& f) const override; /** Checks ordering between this PSD formula and @p f. The ordering between * two PSD formulas `psd1` and `psd2` are determined by the ordering between * the two matrices `m1` in `psd1` and `m2` in `psd2`. * * First, we compare the size of `m1` and `m2`: * * - If `m1` is smaller than `m2`, `psd1.Less(psd2)` is true. * - If `m2` is smaller than `m1`, `psd1.Less(psd2)` is false. * * If `m1` and `m2` are of the same size, we perform element-wise comparison * by following column-major order. See the following example: * * @code * m1 << x + y, -3.14, * -3.14, y; * m2 << x + y, 3.14, * 3.14, y; * const Formula psd1{positive_semidefinite(m1)}; * const Formula psd2{positive_semidefinite(m2)}; * * EXPECT_TRUE(psd1.Less(psd2)); * @endcode * * @note In the code above, `psd1.Less(psd2)` holds because we have * * - m1 in column-major ordering : (x + y) -3.14 -3.14 y_ * - m2 in column-major ordering : (x + y) 3.14 3.14 y_. */ [[nodiscard]] bool Less(const FormulaCell& f) const override; [[nodiscard]] bool Evaluate(const Environment& env) const override; [[nodiscard]] Formula Substitute(const Substitution& s) const override; std::ostream& Display(std::ostream& os) const override; /** Returns the corresponding matrix in this PSD formula. */ [[nodiscard]] const MatrixX<symbolic::Expression>& get_matrix() const { return m_; } private: // Builds a symmetric matrix from a lower triangular-view. template <typename Derived> static MatrixX<Expression> BuildSymmetricMatrixFromLowerTringularView( const Eigen::TriangularView<Derived, Eigen::Lower>& l) { MatrixX<Expression> m(l.rows(), l.cols()); m.triangularView<Eigen::Lower>() = l; m.triangularView<Eigen::StrictlyUpper>() = m.transpose().triangularView<Eigen::StrictlyUpper>(); return m; } // Builds a symmetric matrix from an upper triangular-view. template <typename Derived> static MatrixX<Expression> BuildSymmetricMatrixFromUpperTriangularView( const Eigen::TriangularView<Derived, Eigen::Upper>& u) { MatrixX<Expression> m(u.rows(), u.cols()); m.triangularView<Eigen::Upper>() = u; m.triangularView<Eigen::StrictlyLower>() = m.transpose().triangularView<Eigen::StrictlyLower>(); return m; } const MatrixX<Expression> m_; }; /** Checks if @p f is structurally equal to False formula. */ bool is_false(const FormulaCell& f); /** Checks if @p f is structurally equal to True formula. */ bool is_true(const FormulaCell& f); /** Checks if @p f is a variable formula. */ bool is_variable(const FormulaCell& f); /** Checks if @p f is a formula representing equality (==). */ bool is_equal_to(const FormulaCell& f); /** Checks if @p f is a formula representing disequality (!=). */ bool is_not_equal_to(const FormulaCell& f); /** Checks if @p f is a formula representing greater-than (>). */ bool is_greater_than(const FormulaCell& f); /** Checks if @p f is a formula representing greater-than-or-equal-to (>=). */ bool is_greater_than_or_equal_to(const FormulaCell& f); /** Checks if @p f is a formula representing less-than (<). */ bool is_less_than(const FormulaCell& f); /** Checks if @p f is a formula representing less-than-or-equal-to (<=). */ bool is_less_than_or_equal_to(const FormulaCell& f); /** Checks if @p f is a relational formula ({==, !=, >, >=, <, <=}). */ bool is_relational(const FormulaCell& f); /** Checks if @p f is a conjunction (∧). */ bool is_conjunction(const FormulaCell& f); /** Checks if @p f is a disjunction (∨). */ bool is_disjunction(const FormulaCell& f); /** Checks if @p f is a negation (¬). */ bool is_negation(const FormulaCell& f); /** Checks if @p f is a Forall formula (∀). */ bool is_forall(const FormulaCell& f); /** Checks if @p f is an isnan formula. */ bool is_isnan(const FormulaCell& f); /** Checks if @p f is a positive semidefinite formula. */ bool is_positive_semidefinite(const FormulaCell& f); /** Casts @p f_ptr to @c shared_ptr<const FormulaFalse>. * @pre @c is_false(*f_ptr) is true. */ std::shared_ptr<const FormulaFalse> to_false( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaTrue>. * @pre @c is_true(*f_ptr) is true. */ std::shared_ptr<const FormulaTrue> to_true( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaVar>. * @pre @c is_variable(*f_ptr) is true. */ std::shared_ptr<const FormulaVar> to_variable( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const RelationalFormulaCell>. * @pre @c is_relational(*f_ptr) is true. */ std::shared_ptr<const RelationalFormulaCell> to_relational( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaEq>. * @pre @c is_equal_to(*f_ptr) is true. */ std::shared_ptr<const FormulaEq> to_equal_to( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaNeq>. * @pre @c is_not_equal_to(*f_ptr) is true. */ std::shared_ptr<const FormulaNeq> to_not_equal_to( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaGt>. * @pre @c is_greater_than(*f_ptr) is true. */ std::shared_ptr<const FormulaGt> to_greater_than( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaGeq>. * @pre @c is_greater_than_or_equal_to(*f_ptr) is true. */ std::shared_ptr<const FormulaGeq> to_greater_than_or_equal_to( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaLt>. * @pre @c is_less_than(*f_ptr) is true. */ std::shared_ptr<const FormulaLt> to_less_than( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaLeq>. * @pre @c is_less_than_or_equal_to(*f_ptr) is true. */ std::shared_ptr<const FormulaLeq> to_less_than_or_equal_to( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaAnd>. * @pre @c is_conjunction(*f_ptr) is true. */ std::shared_ptr<const FormulaAnd> to_conjunction( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaOr>. * @pre @c is_disjunction(*f_ptr) is true. */ std::shared_ptr<const FormulaOr> to_disjunction( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const NaryFormulaCell>. * @pre @c is_nary(*f_ptr) is true. */ std::shared_ptr<const NaryFormulaCell> to_nary( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaNot>. * @pre @c is_negation(*f_ptr) is true. */ std::shared_ptr<const FormulaNot> to_negation( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaForall>. * @pre @c is_forall(*f_ptr) is true. */ std::shared_ptr<const FormulaForall> to_forall( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaIsnan>. * @pre @c is_isnan(*f_ptr) is true. */ std::shared_ptr<const FormulaIsnan> to_isnan( const std::shared_ptr<const FormulaCell>& f_ptr); /** Casts @p f_ptr to @c shared_ptr<const FormulaPositiveSemidefinite>. * @pre @c is_positive_semidefinite(*f_ptr) is true. */ std::shared_ptr<const FormulaPositiveSemidefinite> to_positive_semidefinite( const std::shared_ptr<const FormulaCell>& f_ptr); } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/variable.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <cstddef> #include <functional> #include <memory> #include <ostream> #include <string> #include <Eigen/Core> #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/common/fmt_ostream.h" #include "drake/common/hash.h" #include "drake/common/reset_after_move.h" namespace drake { namespace symbolic { /** Represents a symbolic variable. * * @note Expression::Evaluate and Formula::Evaluate methods take a symbolic * environment (Variable → double) and a random number generator. When an * expression or a formula includes random variables, `Evaluate` methods use the * random number generator to draw a number for a random variable from the given * distribution. Then this numeric value is used to substitute all the * occurrences of the corresponding random variable in an expression or a * formula. */ class Variable { public: typedef size_t Id; /** Supported types of symbolic variables. */ enum class Type : uint8_t { CONTINUOUS, ///< A CONTINUOUS variable takes a `double` value. INTEGER, ///< An INTEGER variable takes an `int` value. BINARY, ///< A BINARY variable takes an integer value from {0, 1}. BOOLEAN, ///< A BOOLEAN variable takes a `bool` value. RANDOM_UNIFORM, ///< A random variable whose value will be drawn from ///< uniform real distributed ∈ [0,1). RANDOM_GAUSSIAN, ///< A random variable whose value will be drawn from ///< mean-zero, unit-variance normal. RANDOM_EXPONENTIAL, ///< A random variable whose value will be drawn from ///< exponential distribution with λ=1. }; DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Variable) /** Constructs a default variable of type CONTINUOUS with an `Id` of zero. * All default-constructed variables are considered the same variable by the * equality operator (==). Similarly, a moved-from variable is also identical * to a default-constructed variable (in both its `name` and its `Id`). */ Variable() = default; /** Constructs a default value. This overload is used by Eigen when * EIGEN_INITIALIZE_MATRICES_BY_ZERO is enabled. */ explicit Variable(std::nullptr_t) : Variable() {} /** Constructs a variable with a string. If not specified, it has CONTINUOUS * type by default.*/ explicit Variable(std::string name, Type type = Type::CONTINUOUS); /** Checks if this is the variable created by the default constructor. */ [[nodiscard]] bool is_dummy() const { return get_id() == 0; } [[nodiscard]] Id get_id() const { return id_; } [[nodiscard]] Type get_type() const { // We store the 1-byte Type enum in the upper byte of id_. // See get_next_id() in the cc file for more details. return static_cast<Type>(Id{id_} >> (7 * 8)); } [[nodiscard]] std::string get_name() const; [[nodiscard]] std::string to_string() const; /// Checks the equality of two variables based on their ID values. [[nodiscard]] bool equal_to(const Variable& v) const { return get_id() == v.get_id(); } /// Compares two variables based on their ID values. [[nodiscard]] bool less(const Variable& v) const { return get_id() < v.get_id(); } /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const Variable& item) noexcept { using drake::hash_append; hash_append(hasher, Id{item.id_}); // We do not send the name_ to the hasher, because the id_ is already unique // across all instances, so two Variable instances with matching id_ will // always have identical names. } friend std::ostream& operator<<(std::ostream& os, const Variable& var); private: // Unique identifier for this Variable. The high-order byte stores the Type. // See get_next_id() in the cc file for more details. reset_after_move<Id> id_; // Variable class has shared_ptr<const string> instead of string to be // drake::test::IsMemcpyMovable. // Please check https://github.com/RobotLocomotion/drake/issues/5974 // for more information. std::shared_ptr<const std::string> name_; // Name of variable. }; std::ostream& operator<<(std::ostream& os, Variable::Type type); /// Creates a dynamically-sized Eigen matrix of symbolic variables. /// @param rows The number of rows in the new matrix. /// @param cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. /// @param type The type of variables in the matrix. MatrixX<Variable> MakeMatrixVariable( int rows, int cols, const std::string& name, Variable::Type type = Variable::Type::CONTINUOUS); /// Creates a dynamically-sized Eigen matrix of symbolic Boolean variables. /// @param rows The number of rows in the new matrix. /// @param cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. MatrixX<Variable> MakeMatrixBooleanVariable(int rows, int cols, const std::string& name); /// Creates a dynamically-sized Eigen matrix of symbolic binary variables. /// @param rows The number of rows in the new matrix. /// @param cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. MatrixX<Variable> MakeMatrixBinaryVariable(int rows, int cols, const std::string& name); /// Creates a dynamically-sized Eigen matrix of symbolic continuous variables. /// @param rows The number of rows in the new matrix. /// @param cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. MatrixX<Variable> MakeMatrixContinuousVariable(int rows, int cols, const std::string& name); /// Creates a dynamically-sized Eigen matrix of symbolic integer variables. /// @param rows The number of rows in the new matrix. /// @param cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. MatrixX<Variable> MakeMatrixIntegerVariable(int rows, int cols, const std::string& name); /// Creates a static-sized Eigen matrix of symbolic variables. /// @tparam rows The number of rows in the new matrix. /// @tparam cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. /// @param type The type of variables in the matrix. template <int rows, int cols> Eigen::Matrix<Variable, rows, cols> MakeMatrixVariable( const std::string& name, Variable::Type type = Variable::Type::CONTINUOUS) { Eigen::Matrix<Variable, rows, cols> m; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { m(i, j) = Variable{ name + "(" + std::to_string(i) + ", " + std::to_string(j) + ")", type}; } } return m; } /// Creates a static-sized Eigen matrix of symbolic Boolean variables. /// @tparam rows The number of rows in the new matrix. /// @tparam cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. template <int rows, int cols> Eigen::Matrix<Variable, rows, cols> MakeMatrixBooleanVariable( const std::string& name) { return MakeMatrixVariable<rows, cols>(name, Variable::Type::BOOLEAN); } /// Creates a static-sized Eigen matrix of symbolic binary variables. /// @tparam rows The number of rows in the new matrix. /// @tparam cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. template <int rows, int cols> Eigen::Matrix<Variable, rows, cols> MakeMatrixBinaryVariable( const std::string& name) { return MakeMatrixVariable<rows, cols>(name, Variable::Type::BINARY); } /// Creates a static-sized Eigen matrix of symbolic continuous variables. /// @tparam rows The number of rows in the new matrix. /// @tparam cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. template <int rows, int cols> Eigen::Matrix<Variable, rows, cols> MakeMatrixContinuousVariable( const std::string& name) { return MakeMatrixVariable<rows, cols>(name, Variable::Type::CONTINUOUS); } /// Creates a static-sized Eigen matrix of symbolic integer variables. /// @tparam rows The number of rows in the new matrix. /// @tparam cols The number of cols in the new matrix. /// @param name The common prefix for variables. /// The (i, j)-th element will be named as `name(i, j)`. template <int rows, int cols> Eigen::Matrix<Variable, rows, cols> MakeMatrixIntegerVariable( const std::string& name) { return MakeMatrixVariable<rows, cols>(name, Variable::Type::INTEGER); } /// Creates a dynamically-sized Eigen vector of symbolic variables. /// @param rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. /// @param type The type of variables in the vector. VectorX<Variable> MakeVectorVariable( int rows, const std::string& name, Variable::Type type = Variable::Type::CONTINUOUS); /// Creates a dynamically-sized Eigen vector of symbolic Boolean variables. /// @param rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. VectorX<Variable> MakeVectorBooleanVariable(int rows, const std::string& name); /// Creates a dynamically-sized Eigen vector of symbolic binary variables. /// @param rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. VectorX<Variable> MakeVectorBinaryVariable(int rows, const std::string& name); /// Creates a dynamically-sized Eigen vector of symbolic continuous variables. /// @param rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. VectorX<Variable> MakeVectorContinuousVariable(int rows, const std::string& name); /// Creates a dynamically-sized Eigen vector of symbolic integer variables. /// @param rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. VectorX<Variable> MakeVectorIntegerVariable(int rows, const std::string& name); /// Creates a static-sized Eigen vector of symbolic variables. /// @tparam rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. /// @param type The type of variables in the vector. template <int rows> Eigen::Matrix<Variable, rows, 1> MakeVectorVariable( const std::string& name, Variable::Type type = Variable::Type::CONTINUOUS) { Eigen::Matrix<Variable, rows, 1> vec; for (int i = 0; i < rows; ++i) { vec[i] = Variable{name + "(" + std::to_string(i) + ")", type}; } return vec; } /// Creates a static-sized Eigen vector of symbolic Boolean variables. /// @tparam rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. template <int rows> Eigen::Matrix<Variable, rows, 1> MakeVectorBooleanVariable( const std::string& name) { return MakeVectorVariable<rows>(name, Variable::Type::BOOLEAN); } /// Creates a static-sized Eigen vector of symbolic binary variables. /// @tparam rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. template <int rows> Eigen::Matrix<Variable, rows, 1> MakeVectorBinaryVariable( const std::string& name) { return MakeVectorVariable<rows>(name, Variable::Type::BINARY); } /// Creates a static-sized Eigen vector of symbolic continuous variables. /// @tparam rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. template <int rows> Eigen::Matrix<Variable, rows, 1> MakeVectorContinuousVariable( const std::string& name) { return MakeVectorVariable<rows>(name, Variable::Type::CONTINUOUS); } /// Creates a static-sized Eigen vector of symbolic integer variables. /// @tparam rows The size of vector. /// @param name The common prefix for variables. /// The i-th element will be named as `name(i)`. template <int rows> Eigen::Matrix<Variable, rows, 1> MakeVectorIntegerVariable( const std::string& name) { return MakeVectorVariable<rows>(name, Variable::Type::INTEGER); } } // namespace symbolic } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::Variable>. */ template <> struct hash<drake::symbolic::Variable> : public drake::DefaultHash {}; /* Provides std::less<drake::symbolic::Variable>. */ template <> struct less<drake::symbolic::Variable> { bool operator()(const drake::symbolic::Variable& lhs, const drake::symbolic::Variable& rhs) const { return lhs.less(rhs); } }; /* Provides std::equal_to<drake::symbolic::Variable>. */ template <> struct equal_to<drake::symbolic::Variable> { bool operator()(const drake::symbolic::Variable& lhs, const drake::symbolic::Variable& rhs) const { return lhs.equal_to(rhs); } }; } // namespace std #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { // Eigen scalar type traits for Matrix<drake::symbolic::Variable>. template <> struct NumTraits<drake::symbolic::Variable> : GenericNumTraits<drake::symbolic::Variable> { static inline int digits10() { return 0; } }; } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX) namespace drake { namespace symbolic { /// Checks if two Eigen::Matrix<Variable> @p m1 and @p m2 are structurally /// equal. That is, it returns true if and only if `m1(i, j)` is structurally /// equal to `m2(i, j)` for all `i`, `j`. template <typename DerivedA, typename DerivedB> typename std::enable_if_t<is_eigen_scalar_same<DerivedA, Variable>::value && is_eigen_scalar_same<DerivedB, Variable>::value, bool> CheckStructuralEquality(const DerivedA& m1, const DerivedB& m2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(m1.rows() == m2.rows() && m1.cols() == m2.cols()); return m1.binaryExpr(m2, std::equal_to<Variable>{}).all(); } } // namespace symbolic } // namespace drake // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::symbolic::Variable> : drake::ostream_formatter {}; template <> struct formatter<drake::symbolic::Variable::Type> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/expression_visitor.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <stdexcept> #include <utility> #include "drake/common/drake_assert.h" namespace drake { namespace symbolic { /// Calls visitor object @p v with a polynomial symbolic-expression @p e, and /// arguments @p args. Visitor object is expected to implement the following /// methods which take @p f and @p args: `VisitConstant`, `VisitVariable`, /// `VisitAddition`, `VisitMultiplication`, `VisitDivision`, `VisitPow`. /// /// @throws std::exception if NaN is detected during a visit. /// /// See the implementation of @c DegreeVisitor class and @c Degree function in /// drake/common/symbolic_monomial.cc as an example usage. /// /// @pre e.is_polynomial() is true. template <typename Result, typename Visitor, typename... Args> Result VisitPolynomial(Visitor* v, const Expression& e, Args&&... args) { DRAKE_DEMAND(e.is_polynomial()); switch (e.get_kind()) { case ExpressionKind::Constant: return v->VisitConstant(e, std::forward<Args>(args)...); case ExpressionKind::Var: return v->VisitVariable(e, std::forward<Args>(args)...); case ExpressionKind::Add: return v->VisitAddition(e, std::forward<Args>(args)...); case ExpressionKind::Mul: return v->VisitMultiplication(e, std::forward<Args>(args)...); case ExpressionKind::Div: return v->VisitDivision(e, std::forward<Args>(args)...); case ExpressionKind::Pow: return v->VisitPow(e, std::forward<Args>(args)...); case ExpressionKind::NaN: throw std::runtime_error("NaN is detected while visiting an expression."); case ExpressionKind::Log: case ExpressionKind::Abs: case ExpressionKind::Exp: case ExpressionKind::Sqrt: case ExpressionKind::Sin: case ExpressionKind::Cos: case ExpressionKind::Tan: case ExpressionKind::Asin: case ExpressionKind::Acos: case ExpressionKind::Atan: case ExpressionKind::Atan2: case ExpressionKind::Sinh: case ExpressionKind::Cosh: case ExpressionKind::Tanh: case ExpressionKind::Min: case ExpressionKind::Max: case ExpressionKind::Ceil: case ExpressionKind::Floor: case ExpressionKind::IfThenElse: case ExpressionKind::UninterpretedFunction: // Unreachable because of `DRAKE_DEMAND(e.is_polynomial())` at the top. throw std::domain_error( "Unexpected Kind was is_polynomial in VisitPolynomial"); } // Unreachable because all switch cases are accounted for above. DRAKE_UNREACHABLE(); } /// Calls visitor object @p v with a symbolic-expression @p e, and arguments @p /// args. Visitor object is expected to implement the following methods which /// take @p f and @p args: `VisitConstant`, `VisitVariable`, `VisitAddition`, /// `VisitMultiplication`, `VisitDivision`, `VisitLog`, `VisitAbs`, `VisitExp`, /// `VisitSqrt`, `VisitPow`, `VisitSin`, `VisitCos`, `VisitTan`, `VisitAsin`, /// `VisitAtan`, `VisitAtan2`, `VisitSinh`, `VisitCosh`, `VisitTanh`, /// `VisitMin`, `VisitMax`, `VisitCeil`, `VisitFloor`, `VisitIfThenElse`, /// `VisitUninterpretedFunction. /// /// @throws std::exception if NaN is detected during a visit. template <typename Result, typename Visitor, typename... Args> Result VisitExpression(Visitor* v, const Expression& e, Args&&... args) { switch (e.get_kind()) { case ExpressionKind::Constant: return v->VisitConstant(e, std::forward<Args>(args)...); case ExpressionKind::Var: return v->VisitVariable(e, std::forward<Args>(args)...); case ExpressionKind::Add: return v->VisitAddition(e, std::forward<Args>(args)...); case ExpressionKind::Mul: return v->VisitMultiplication(e, std::forward<Args>(args)...); case ExpressionKind::Div: return v->VisitDivision(e, std::forward<Args>(args)...); case ExpressionKind::Log: return v->VisitLog(e, std::forward<Args>(args)...); case ExpressionKind::Abs: return v->VisitAbs(e, std::forward<Args>(args)...); case ExpressionKind::Exp: return v->VisitExp(e, std::forward<Args>(args)...); case ExpressionKind::Sqrt: return v->VisitSqrt(e, std::forward<Args>(args)...); case ExpressionKind::Pow: return v->VisitPow(e, std::forward<Args>(args)...); case ExpressionKind::Sin: return v->VisitSin(e, std::forward<Args>(args)...); case ExpressionKind::Cos: return v->VisitCos(e, std::forward<Args>(args)...); case ExpressionKind::Tan: return v->VisitTan(e, std::forward<Args>(args)...); case ExpressionKind::Asin: return v->VisitAsin(e, std::forward<Args>(args)...); case ExpressionKind::Acos: return v->VisitAcos(e, std::forward<Args>(args)...); case ExpressionKind::Atan: return v->VisitAtan(e, std::forward<Args>(args)...); case ExpressionKind::Atan2: return v->VisitAtan2(e, std::forward<Args>(args)...); case ExpressionKind::Sinh: return v->VisitSinh(e, std::forward<Args>(args)...); case ExpressionKind::Cosh: return v->VisitCosh(e, std::forward<Args>(args)...); case ExpressionKind::Tanh: return v->VisitTanh(e, std::forward<Args>(args)...); case ExpressionKind::Min: return v->VisitMin(e, std::forward<Args>(args)...); case ExpressionKind::Max: return v->VisitMax(e, std::forward<Args>(args)...); case ExpressionKind::Ceil: return v->VisitCeil(e, std::forward<Args>(args)...); case ExpressionKind::Floor: return v->VisitFloor(e, std::forward<Args>(args)...); case ExpressionKind::IfThenElse: return v->VisitIfThenElse(e, std::forward<Args>(args)...); case ExpressionKind::NaN: throw std::runtime_error("NaN is detected while visiting an expression."); case ExpressionKind::UninterpretedFunction: return v->VisitUninterpretedFunction(e, std::forward<Args>(args)...); } DRAKE_UNREACHABLE(); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/ldlt.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <Eigen/Core> /// @file /// Eigen::LDLT is specialized for drake::symbolic::Expression, for certain /// matrix sizes. If the expression matrix is all constants, it returns the /// robust decomposition (as per Eigen's algorithm). If there are unbound /// variables, currently throws an exception (but may support this in the /// future). #if !defined(DRAKE_DOXYGEN_CXX) namespace Eigen { // Provide explicit (full) template specialization for LDLT::compute when the // Scalar is symbolic::Expression. We need to list out all of the different // matrix sizes that Drake uses symbolically, because we cannot partially // specialize a template class template method. #define DRAKE_DECLARE_SPECIALIZE_LDLT(SomeMatrix) \ template <> \ template <> \ Eigen::LDLT<SomeMatrix>& \ Eigen::LDLT<SomeMatrix>::compute<Ref<const SomeMatrix>>( \ const EigenBase<Ref<const SomeMatrix>>&); \ template <> \ template <> \ inline Eigen::LDLT<SomeMatrix>& \ Eigen::LDLT<SomeMatrix>::compute<SomeMatrix>( \ const EigenBase<SomeMatrix>& a) { \ const Ref<const SomeMatrix> ref_a(a.derived()); \ return compute(ref_a); \ } DRAKE_DECLARE_SPECIALIZE_LDLT(drake::MatrixX<drake::symbolic::Expression>) DRAKE_DECLARE_SPECIALIZE_LDLT(drake::MatrixUpTo6<drake::symbolic::Expression>) #undef DRAKE_DECLARE_SPECIALIZE_LDLT } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX)
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/all.cc
#include "drake/common/symbolic/expression/all.h" // This is an empty .cc file that only serves to confirm that all.h is a // stand-alone header.
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/formula.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <functional> #include <memory> #include <ostream> #include <set> #include <string> #include <utility> #include <Eigen/Core> #include "drake/common/drake_assert.h" #include "drake/common/drake_bool.h" #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/common/fmt.h" #include "drake/common/hash.h" #include "drake/common/random.h" namespace drake { namespace symbolic { /** Kinds of symbolic formulas. */ enum class FormulaKind { False, ///< ⊥ True, ///< ⊤ Var, ///< Boolean Variable Eq, ///< = Neq, ///< != Gt, ///< > Geq, ///< >= Lt, ///< < Leq, ///< <= And, ///< Conjunction (∧) Or, ///< Disjunction (∨) Not, ///< Negation (¬) Forall, ///< Universal quantification (∀) Isnan, ///< NaN check predicate PositiveSemidefinite, ///< Positive semidefinite matrix }; // Total ordering between FormulaKinds bool operator<(FormulaKind k1, FormulaKind k2); class FormulaCell; // In drake/common/formula_cell.h class FormulaFalse; // In drake/common/formula_cell.h class FormulaTrue; // In drake/common/formula_cell.h class FormulaVar; // In drake/common/formula_cell.h class RelationalFormulaCell; // In drake/common/formula_cell.h class FormulaEq; // In drake/common/formula_cell.h class FormulaNeq; // In drake/common/formula_cell.h class FormulaGt; // In drake/common/formula_cell.h class FormulaGeq; // In drake/common/formula_cell.h class FormulaLt; // In drake/common/formula_cell.h class FormulaLeq; // In drake/common/formula_cell.h class NaryFormulaCell; // In drake/common/formula_cell.h class FormulaNot; // In drake/common/formula_cell.h class FormulaAnd; // In drake/common/formula_cell.h class FormulaOr; // In drake/common/formula_cell.h class FormulaForall; // In drake/common/formula_cell.h class FormulaIsnan; // In drake/common/formula_cell.h class FormulaPositiveSemidefinite; // In drake/common/formula_cell.h /** Represents a symbolic form of a first-order logic formula. It has the following grammar: \verbatim F := ⊥ | ⊤ | Var | E = E | E ≠ E | E > E | E ≥ E | E < E | E ≤ E | E ∧ ... ∧ E | E ∨ ... ∨ E | ¬F | ∀ x₁, ..., xn. F \endverbatim In the implementation, Formula is a simple wrapper including a shared pointer to FormulaCell class which is a super-class of different kinds of symbolic formulas (i.e. FormulaAnd, FormulaOr, FormulaEq). Note that it includes a shared pointer, not a unique pointer, to allow sharing sub-expressions. \note The sharing of sub-expressions is not yet implemented. The following simple simplifications are implemented: \verbatim E1 = E2 -> True (if E1 and E2 are structurally equal) E1 ≠ E2 -> False (if E1 and E2 are structurally equal) E1 > E2 -> False (if E1 and E2 are structurally equal) E1 ≥ E2 -> True (if E1 and E2 are structurally equal) E1 < E2 -> False (if E1 and E2 are structurally equal) E1 ≤ E2 -> True (if E1 and E2 are structurally equal) F1 ∧ F2 -> False (if either F1 or F2 is False) F1 ∨ F2 -> True (if either F1 or F2 is True) ¬(¬(F)) -> F \endverbatim We flatten nested conjunctions (or disjunctions) at the construction. A conjunction (resp. disjunction) takes a set of conjuncts (resp. disjuncts). Note that any duplicated conjunct/disjunct is removed. For example, both of `f1 && (f2 && f1)` and `(f1 && f2) && f1` are flattened to `f1 && f2 && f1` and simplified into `f1 && f2`. As a result, the two are identified as the same formula. \note Formula class has an explicit conversion operator to bool. It evaluates a symbolic formula under an empty environment. If a symbolic formula includes variables, the conversion operator throws an exception. This operator is only intended for third-party code doing things like `(imag(SymbolicExpression(0)) == SymbolicExpression(0)) { ... };` that we found in Eigen3 codebase. In general, a user of this class should explicitly call `Evaluate` from within Drake for readability. */ class Formula { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Formula) /** Default constructor. Sets the value to Formula::False, to be consistent * with value-initialized `bool`s. */ Formula() : Formula(False()) {} /** Constructs from a `bool`. This overload is also used by Eigen when * EIGEN_INITIALIZE_MATRICES_BY_ZERO is enabled. */ explicit Formula(bool value) : Formula(value ? True() : False()) {} explicit Formula(std::shared_ptr<const FormulaCell> ptr); /** Constructs a formula from @p var. * @pre @p var is of BOOLEAN type. */ explicit Formula(const Variable& var); [[nodiscard]] FormulaKind get_kind() const; /** Gets free variables (unquantified variables). */ [[nodiscard]] Variables GetFreeVariables() const; /** Checks structural equality. */ [[nodiscard]] bool EqualTo(const Formula& f) const; /** Checks lexicographical ordering between this and @p e. * * If the two formulas f1 and f2 have different kinds k1 and k2 respectively, * f1.Less(f2) is equal to k1 < k2. If f1 and f2 are expressions of the same * kind, we check the ordering between f1 and f2 by comparing their elements * lexicographically. * * For example, in case of And, let f1 and f2 be * * f1 = f_1,1 ∧ ... ∧ f_1,n * f2 = f_2,1 ∧ ... ∧ f_2,m * * f1.Less(f2) is true if there exists an index i (<= n, m) such that * for all j < i, we have * * ¬(f_1_j.Less(f_2_j)) ∧ ¬(f_2_j.Less(f_1_j)) * * and f_1_i.Less(f_2_i) holds. * * This function is used as a compare function in * std::map<symbolic::Formula> and std::set<symbolic::Formula> via * std::less<symbolic::Formula>. */ [[nodiscard]] bool Less(const Formula& f) const; /** Evaluates using a given environment (by default, an empty environment) and * a random number generator. If there is a random variable in this formula * which is unassigned in @p env, it uses @p random_generator to sample a * value and use it to substitute all occurrences of the random variable in * this formula. * * @throws std::exception if a variable `v` is needed for an evaluation * but not provided by @p env. * @throws std::exception if an unassigned random variable is detected * while @p random_generator is `nullptr`. */ bool Evaluate(const Environment& env = Environment{}, RandomGenerator* random_generator = nullptr) const; /** Evaluates using an empty environment and a random number generator. * * See the above overload for the exceptions that it might throw. */ bool Evaluate(RandomGenerator* random_generator) const; /** Returns a copy of this formula replacing all occurrences of @p var * with @p e. * @throws std::exception if NaN is detected during substitution. */ [[nodiscard]] Formula Substitute(const Variable& var, const Expression& e) const; /** Returns a copy of this formula replacing all occurrences of the * variables in @p s with corresponding expressions in @p s. Note that the * substitutions occur simultaneously. For example, (x / y > * 0).Substitute({{x, y}, {y, x}}) gets (y / x > 0). * @throws std::exception if NaN is detected during substitution. */ [[nodiscard]] Formula Substitute(const Substitution& s) const; /** Returns string representation of Formula. */ [[nodiscard]] std::string to_string() const; static Formula True(); static Formula False(); /** Conversion to bool. */ explicit operator bool() const { return Evaluate(); } /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const Formula& item) noexcept { DelegatingHasher delegating_hasher( [&hasher](const void* data, const size_t length) { return hasher(data, length); }); item.HashAppend(&delegating_hasher); } friend std::ostream& operator<<(std::ostream& os, const Formula& f); friend void swap(Formula& a, Formula& b) { std::swap(a.ptr_, b.ptr_); } friend bool is_false(const Formula& f); friend bool is_true(const Formula& f); friend bool is_variable(const Formula& f); friend bool is_equal_to(const Formula& f); friend bool is_not_equal_to(const Formula& f); friend bool is_greater_than(const Formula& f); friend bool is_greater_than_or_equal_to(const Formula& f); friend bool is_less_than(const Formula& f); friend bool is_less_than_or_equal_to(const Formula& f); friend bool is_relational(const Formula& f); friend bool is_conjunction(const Formula& f); friend bool is_disjunction(const Formula& f); friend bool is_negation(const Formula& f); friend bool is_forall(const Formula& f); friend bool is_isnan(const Formula& f); friend bool is_positive_semidefinite(const Formula& f); // Note that the following cast functions are only for low-level operations // and not exposed to the user of drake/common/symbolic/expression.h header. // These functions are declared in the formula_cell.h header. friend std::shared_ptr<const FormulaFalse> to_false(const Formula& f); friend std::shared_ptr<const FormulaTrue> to_true(const Formula& f); friend std::shared_ptr<const FormulaVar> to_variable(const Formula& f); friend std::shared_ptr<const RelationalFormulaCell> to_relational( const Formula& f); friend std::shared_ptr<const FormulaEq> to_equal_to(const Formula& f); friend std::shared_ptr<const FormulaNeq> to_not_equal_to(const Formula& f); friend std::shared_ptr<const FormulaGt> to_greater_than(const Formula& f); friend std::shared_ptr<const FormulaGeq> to_greater_than_or_equal_to( const Formula& f); friend std::shared_ptr<const FormulaLt> to_less_than(const Formula& f); friend std::shared_ptr<const FormulaLeq> to_less_than_or_equal_to( const Formula& f); friend std::shared_ptr<const NaryFormulaCell> to_nary(const Formula& f); friend std::shared_ptr<const FormulaAnd> to_conjunction(const Formula& f); friend std::shared_ptr<const FormulaOr> to_disjunction(const Formula& f); friend std::shared_ptr<const FormulaNot> to_negation(const Formula& f); friend std::shared_ptr<const FormulaForall> to_forall(const Formula& f); friend std::shared_ptr<const FormulaIsnan> to_isnan(const Formula& f); friend std::shared_ptr<const FormulaPositiveSemidefinite> to_positive_semidefinite(const Formula& f); private: void HashAppend(DelegatingHasher* hasher) const; // Note: We use "const" FormulaCell type here because a FormulaCell object can // be shared by multiple formulas, a formula should _not_ be able to change // the cell that it points to. std::shared_ptr<const FormulaCell> ptr_; }; /** Returns a formula @p f, universally quantified by variables @p vars. */ Formula forall(const Variables& vars, const Formula& f); /** Returns a conjunction of @p formulas. It performs the following * simplification: * * - make_conjunction({}) returns True. * - make_conjunction({f₁}) returns f₁. * - If False ∈ @p formulas, it returns False. * - If True ∈ @p formulas, it will not appear in the return value. * - Nested conjunctions will be flattened. For example, make_conjunction({f₁, * f₂ ∧ f₃}) returns f₁ ∧ f₂ ∧ f₃. */ Formula make_conjunction(const std::set<Formula>& formulas); Formula operator&&(const Formula& f1, const Formula& f2); Formula operator&&(const Variable& v, const Formula& f); Formula operator&&(const Formula& f, const Variable& v); Formula operator&&(const Variable& v1, const Variable& v2); /** Returns a disjunction of @p formulas. It performs the following * simplification: * * - make_disjunction({}) returns False. * - make_disjunction({f₁}) returns f₁. * - If True ∈ @p formulas, it returns True. * - If False ∈ @p formulas, it will not appear in the return value. * - Nested disjunctions will be flattened. For example, make_disjunction({f₁, * f₂ ∨ f₃}) returns f₁ ∨ f₂ ∨ f₃. */ Formula make_disjunction(const std::set<Formula>& formulas); Formula operator||(const Formula& f1, const Formula& f2); Formula operator||(const Variable& v, const Formula& f); Formula operator||(const Formula& f, const Variable& v); Formula operator||(const Variable& v1, const Variable& v2); Formula operator!(const Formula& f); Formula operator!(const Variable& v); Formula operator==(const Expression& e1, const Expression& e2); Formula operator!=(const Expression& e1, const Expression& e2); Formula operator<(const Expression& e1, const Expression& e2); Formula operator<=(const Expression& e1, const Expression& e2); Formula operator>(const Expression& e1, const Expression& e2); Formula operator>=(const Expression& e1, const Expression& e2); /** Returns a Formula for the predicate isnan(e) to the given expression. This * serves as the argument-dependent lookup related to std::isnan(double). * * When this formula is evaluated, there are two possible outcomes: * - Returns false if the e.Evaluate() is not NaN. * - Throws std::exception if NaN is detected during evaluation. * Note that the evaluation of `isnan(e)` never returns true. */ Formula isnan(const Expression& e); /** Returns a Formula determining if the given expression @p e is a * positive or negative infinity. * @throws std::exception if NaN is detected during evaluation. */ Formula isinf(const Expression& e); /** Returns a Formula determining if the given expression @p e has a finite * value. * @throws std::exception if NaN is detected during evaluation. */ Formula isfinite(const Expression& e); /** Returns a symbolic formula constraining @p m to be a positive-semidefinite * matrix. By definition, a symmetric matrix @p m is positive-semidefinte if xᵀ * m x ≥ 0 for all vector x ∈ ℝⁿ. * * @throws std::exception if @p m is not symmetric. * * @note This method checks if @p m is symmetric, which can be costly. If you * want to avoid it, please consider using * `positive_semidefinite(m.triangularView<Eigen::Lower>())` or * `positive_semidefinite(m.triangularView<Eigen::Upper>())` instead of * `positive_semidefinite(m)`. * * @pydrake_mkdoc_identifier{1args_m} */ Formula positive_semidefinite(const Eigen::Ref<const MatrixX<Expression>>& m); /** Constructs and returns a symbolic positive-semidefinite formula from @p * m. If @p mode is Eigen::Lower, it's using the lower-triangular part of @p m * to construct a positive-semidefinite formula. If @p mode is Eigen::Upper, the * upper-triangular part of @p m is used. It throws std::exception if @p has * other values. See the following code snippet. * * @code * Eigen::Matrix<Expression, 2, 2> m; * m << 1.0, 2.0, * 3.0, 4.0; * * const Formula psd_l{positive_semidefinite(m, Eigen::Lower)}; * // psd_l includes [1.0 3.0] * // [3.0 4.0]. * * const Formula psd_u{positive_semidefinite(m, Eigen::Upper)}; * // psd_u includes [1.0 2.0] * // [2.0 4.0]. * @endcode * * @exclude_from_pydrake_mkdoc{This overload is not bound.} */ Formula positive_semidefinite(const MatrixX<Expression>& m, Eigen::UpLoType mode); /** Constructs and returns a symbolic positive-semidefinite formula from a lower * triangular-view @p l. See the following code snippet. * * @code * Eigen::Matrix<Expression, 2, 2> m; * m << 1.0, 2.0, * 3.0, 4.0; * * Formula psd{positive_semidefinite(m.triangularView<Eigen::Lower>())}; * // psd includes [1.0 3.0] * // [3.0 4.0]. * @endcode * * @exclude_from_pydrake_mkdoc{This overload is not bound.} */ template <typename Derived> typename std::enable_if_t< std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind, Eigen::MatrixXpr> && std::is_same_v<typename Derived::Scalar, Expression>, Formula> positive_semidefinite(const Eigen::TriangularView<Derived, Eigen::Lower>& l) { return positive_semidefinite(l, Eigen::Lower); } /** Constructs and returns a symbolic positive-semidefinite formula from an * upper triangular-view @p u. See the following code snippet. * * @code * Eigen::Matrix<Expression, 2, 2> m; * m << 1.0, 2.0, * 3.0, 4.0; * * Formula psd{positive_semidefinite(m.triangularView<Eigen::Upper>())}; * // psd includes [1.0 2.0] * // [2.0 4.0]. * @endcode * * @exclude_from_pydrake_mkdoc{This overload is not bound.} */ template <typename Derived> typename std::enable_if_t< std::is_same_v<typename Eigen::internal::traits<Derived>::XprKind, Eigen::MatrixXpr> && std::is_same_v<typename Derived::Scalar, Expression>, Formula> positive_semidefinite(const Eigen::TriangularView<Derived, Eigen::Upper>& u) { return positive_semidefinite(u, Eigen::Upper); } std::ostream& operator<<(std::ostream& os, const Formula& f); /** Checks if @p f is structurally equal to False formula. */ bool is_false(const Formula& f); /** Checks if @p f is structurally equal to True formula. */ bool is_true(const Formula& f); /** Checks if @p f is a variable formula. */ bool is_variable(const Formula& f); /** Checks if @p f is a formula representing equality (==). */ bool is_equal_to(const Formula& f); /** Checks if @p f is a formula representing disequality (!=). */ bool is_not_equal_to(const Formula& f); /** Checks if @p f is a formula representing greater-than (>). */ bool is_greater_than(const Formula& f); /** Checks if @p f is a formula representing greater-than-or-equal-to (>=). */ bool is_greater_than_or_equal_to(const Formula& f); /** Checks if @p f is a formula representing less-than (<). */ bool is_less_than(const Formula& f); /** Checks if @p f is a formula representing less-than-or-equal-to (<=). */ bool is_less_than_or_equal_to(const Formula& f); /** Checks if @p f is a relational formula ({==, !=, >, >=, <, <=}). */ bool is_relational(const Formula& f); /** Checks if @p f is a conjunction (∧). */ bool is_conjunction(const Formula& f); /** Checks if @p f is a disjunction (∨). */ bool is_disjunction(const Formula& f); /** Checks if @p f is a n-ary formula ({∧, ∨}). */ bool is_nary(const Formula& f); /** Checks if @p f is a negation (¬). */ bool is_negation(const Formula& f); /** Checks if @p f is a Forall formula (∀). */ bool is_forall(const Formula& f); /** Checks if @p f is an isnan formula. */ bool is_isnan(const Formula& f); /** Checks if @p f is a positive-semidefinite formula. */ bool is_positive_semidefinite(const Formula& f); /** Returns the embedded variable in the variable formula @p f. * @pre @p f is a variable formula. */ const Variable& get_variable(const Formula& f); /** Returns the lhs-argument of a relational formula @p f. * \pre{@p f is a relational formula.} */ const Expression& get_lhs_expression(const Formula& f); /** Returns the rhs-argument of a relational formula @p f. * \pre{@p f is a relational formula.} */ const Expression& get_rhs_expression(const Formula& f); /** Returns the expression in a unary expression formula @p f. * Currently, an isnan() formula is the only kind of unary expression formula. * \pre{@p f is a unary expression formula.} */ const Expression& get_unary_expression(const Formula& f); /** Returns the set of formulas in a n-ary formula @p f. * \pre{@p f is a n-ary formula.} */ const std::set<Formula>& get_operands(const Formula& f); /** Returns the formula in a negation formula @p f. * \pre{@p f is a negation formula.} */ const Formula& get_operand(const Formula& f); /** Returns the quantified variables in a forall formula @p f. * \pre{@p f is a forall formula.} */ const Variables& get_quantified_variables(const Formula& f); /** Returns the quantified formula in a forall formula @p f. * \pre{@p f is a forall formula.} */ const Formula& get_quantified_formula(const Formula& f); /** Returns the matrix in a positive-semidefinite formula @p f. * \pre{@p f is a positive-semidefinite formula.} */ const MatrixX<Expression>& get_matrix_in_positive_semidefinite( const Formula& f); namespace internal { /// Provides a return type of relational operations (=, ≠, ≤, <, ≥, >) between /// `Eigen::Array`s. /// /// @tparam DerivedA A derived type of Eigen::ArrayBase. /// @tparam DerivedB A derived type of Eigen::ArrayBase. /// @pre The type of (DerivedA::Scalar() == DerivedB::Scalar()) is symbolic /// formula. 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> && std::is_same_v<decltype(typename DerivedA::Scalar() == typename DerivedB::Scalar()), Formula>>> struct RelationalOpTraits { static constexpr auto Dynamic = Eigen::Dynamic; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" static constexpr int Rows = EIGEN_SIZE_MIN_PREFER_FIXED( (DerivedA::RowsAtCompileTime), (DerivedB::RowsAtCompileTime)); static constexpr int Cols = EIGEN_SIZE_MIN_PREFER_FIXED( (DerivedA::ColsAtCompileTime), (DerivedB::ColsAtCompileTime)); #pragma GCC diagnostic pop using ReturnType = Eigen::Array<Formula, Rows, Cols>; }; /// Returns @p f1 ∧ @p f2. /// Note that this function returns a `Formula` while /// `std::logical_and<Formula>{}` returns a bool. inline Formula logic_and(const Formula& f1, const Formula& f2) { return f1 && f2; } /// Returns @p f1 ∨ @p f2. /// Note that this function returns a `Formula` while /// `std::logical_or<Formula>{}` returns a bool. inline Formula logic_or(const Formula& f1, const Formula& f2) { return f1 || f2; } } // namespace internal /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise symbolic-equality of two arrays @p m1 and @p m2. /// /// The following table describes the return type of @p m1 == @p m2. /// /// LHS \ RHS | EA<Expression> | EA<Variable> | EA<double> /// ----------------|----------------|--------------|-------------- /// EA<Expression> | EA<Formula> | EA<Formula> | EA<Formula> /// EA<Variable> | EA<Formula> | EA<Formula> | EA<Formula> /// EA<double> | EA<Formula> | EA<Formula> | EA<bool> /// /// In the table, `EA` is a short-hand of `Eigen::Array`. /// /// Note that this function does *not* provide operator overloading for the /// following case. It returns `Eigen::Array<bool>` and is provided by Eigen. /// /// - Eigen::Array<double> == Eigen::Array<double> /// 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> && std::is_same_v<decltype(typename DerivedA::Scalar() == typename DerivedB::Scalar()), Formula>, typename internal::RelationalOpTraits<DerivedA, DerivedB>::ReturnType> operator==(const DerivedA& a1, const DerivedB& a2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(a1.rows() == a2.rows() && a1.cols() == a2.cols()); return a1.binaryExpr(a2, std::equal_to<void>()); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between an array @p a and a scalar @p v using /// equal-to operator (==). That is, for all i and j, the (i, j)-th entry of `(a /// == v)` has a symbolic formula `a(i, j) == v`. /// /// Here is an example using this operator overloading. /// @code /// Eigen::Array<Variable, 2, 2> a; /// a << Variable{"x"}, Variable{"y"}, /// Variable{"z"}, Variable{"w"}; /// Eigen::Array<Formula, 2, 2> f = (a == 3.5); /// // Here f = |(x == 3.5) (y == 3.5)| /// // |(z == 3.5) (w == 3.5)|. /// @endcode 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator==(const Derived& a, const ScalarType& v) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return x == v; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between a scalar @p v and an array @p using equal-to /// operator (==). That is, for all i and j, the (i, j)-th entry of `(v == a)` /// has a symbolic formula `v == a(i, j)`. /// /// Here is an example using this operator overloading. /// @code /// Eigen::Array<Variable, 2, 2> a; /// a << Variable{"x"}, Variable{"y"}, /// Variable{"z"}, Variable{"w"}; /// Eigen::Array<Formula, 2, 2> f = (3.5 == a); /// // Here f = |(3.5 == x) (3.5 == y)| /// // |(3.5 == z) (3.5 == w)|. /// @endcode 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator==(const ScalarType& v, const Derived& a) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return v == x; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison of two arrays @p a1 and @p a2 using /// less-than-or-equal operator (<=). 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> && std::is_same_v<decltype(typename DerivedA::Scalar() <= typename DerivedB::Scalar()), Formula>, typename internal::RelationalOpTraits<DerivedA, DerivedB>::ReturnType> operator<=(const DerivedA& a1, const DerivedB& a2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(a1.rows() == a2.rows() && a1.cols() == a2.cols()); return a1.binaryExpr(a2, std::less_equal<void>()); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between an array @p a and a scalar @p v using /// less-than-or-equal operator (<=). That is, for all i and j, the (i, j)-th /// entry of `(a <= v)` has a symbolic 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator<=(const Derived& a, const ScalarType& v) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return x <= v; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between a scalar @p v and an array @p using /// less-than-or-equal operator (<=). That is, for all i and j, the (i, j)-th /// entry of `(v <= a)` has a symbolic 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator<=(const ScalarType& v, const Derived& a) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return v <= x; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison of two arrays @p a1 and @p a2 using less-than /// operator (<). 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> && std::is_same_v<decltype(typename DerivedA::Scalar() < typename DerivedB::Scalar()), Formula>, typename internal::RelationalOpTraits<DerivedA, DerivedB>::ReturnType> operator<(const DerivedA& a1, const DerivedB& a2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(a1.rows() == a2.rows() && a1.cols() == a2.cols()); return a1.binaryExpr(a2, std::less<void>()); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between an array @p a and a scalar @p v using /// less-than operator (<). That is, for all i and j, the (i, j)-th /// entry of `(a < v)` has a symbolic 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator<(const Derived& a, const ScalarType& v) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return x < v; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between a scalar @p v and an array @p using /// less-than operator (<). That is, for all i and j, the (i, j)-th /// entry of `(v < a)` has a symbolic 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator<(const ScalarType& v, const Derived& a) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return v < x; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison of two arrays @p a1 and @p a2 using /// greater-than-or-equal operator (>=). 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> && std::is_same_v<decltype(typename DerivedA::Scalar() >= typename DerivedB::Scalar()), Formula>, typename internal::RelationalOpTraits<DerivedA, DerivedB>::ReturnType> operator>=(const DerivedA& a1, const DerivedB& a2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(a1.rows() == a2.rows() && a1.cols() == a2.cols()); return a1.binaryExpr(a2, std::greater_equal<void>()); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between an array @p a and a scalar @p v using /// greater-than-or-equal operator (>=). That is, for all i and j, the (i, j)-th /// entry of `(a >= v)` has a symbolic 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator>=(const Derived& a, const ScalarType& v) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return x >= v; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between a scalar @p v and an array @p using /// less-than-or-equal operator (<=) instead of greater-than-or-equal operator /// (>=). That is, for all i and j, the (i, j)-th entry of `(v >= a)` has a /// symbolic formula `a(i, j) <= v`. /// /// Note that given `v >= a`, this methods returns the result of `a <= v`. First /// of all, this formulation is mathematically equivalent to the original /// formulation. We implement this method in this way to be consistent with /// Eigen's semantics. See the definition of `EIGEN_MAKE_CWISE_COMP_R_OP` in /// ArrayCwiseBinaryOps.h file in Eigen. 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator>=(const ScalarType& v, const Derived& a) { return a <= v; } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison of two arrays @p a1 and @p a2 using greater-than /// operator (>). 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> && std::is_same_v<decltype(typename DerivedA::Scalar() > typename DerivedB::Scalar()), Formula>, typename internal::RelationalOpTraits<DerivedA, DerivedB>::ReturnType> operator>(const DerivedA& a1, const DerivedB& a2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(a1.rows() == a2.rows() && a1.cols() == a2.cols()); return a1.binaryExpr(a2, std::greater<void>()); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between an array @p a and a scalar @p v using /// greater-than operator (>). That is, for all i and j, the (i, j)-th /// entry of `(a > v)` has a symbolic 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator>(const Derived& a, const ScalarType& v) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return x > v; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between a scalar @p v and an array @p using /// less-than operator (<) instead of greater-than operator (>). That is, for /// all i and j, the (i, j)-th entry of `(v > a)` has a symbolic formula `a(i, /// j) < v`. /// /// Note that given `v > a`, this methods returns the result of `a < v`. First /// of all, this formulation is mathematically equivalent to the original /// formulation. We implement this method in this way to be consistent with /// Eigen's semantics. See the definition of `EIGEN_MAKE_CWISE_COMP_R_OP` in /// ArrayCwiseBinaryOps.h file in Eigen. 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator>(const ScalarType& v, const Derived& a) { return a < v; } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison of two arrays @p a1 and @p a2 using not-equal /// operator (!=). 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> && std::is_same_v<decltype(typename DerivedA::Scalar() != typename DerivedB::Scalar()), Formula>, typename internal::RelationalOpTraits<DerivedA, DerivedB>::ReturnType> operator!=(const DerivedA& a1, const DerivedB& a2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(a1.rows() == a2.rows() && a1.cols() == a2.cols()); return a1.binaryExpr(a2, std::not_equal_to<void>()); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between an array @p a and a scalar @p v using /// not-equal operator (!=). That is, for all i and j, the (i, j)-th /// entry of `(a != v)` has a symbolic 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator!=(const Derived& a, const ScalarType& v) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return x != v; }); } /// Returns an Eigen array of symbolic formulas where each element includes /// element-wise comparison between a scalar @p v and an array @p using /// not-equal operator (!=). That is, for all i and j, the (i, j)-th /// entry of `(v != a)` has a symbolic 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>, Eigen::Array<Formula, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>> operator!=(const ScalarType& v, const Derived& a) { return a.unaryExpr([&v](const typename Derived::Scalar& x) { return v != x; }); } /// Returns a symbolic formula checking if two matrices @p m1 and @p m2 are /// equal. /// /// The following table describes the return type of @p m1 == @p m2. /// /// LHS \ RHS | EM<Expression> | EM<Variable> | EM<double> /// ----------------|----------------|--------------|------------ /// EM<Expression> | Formula | Formula | Formula /// EM<Variable> | Formula | Formula | Formula /// EM<double> | Formula | Formula | bool /// /// In the table, `EM` is a short-hand of `Eigen::Matrix`. /// /// Note that this function does *not* provide operator overloading for the /// following case. It returns `bool` and is provided by Eigen. /// /// - Eigen::Matrix<double> == Eigen::Matrix<double> /// /// Note that this method returns a conjunctive formula which keeps its /// conjuncts as `std::set<Formula>` internally. This set is ordered by /// `Formula::Less` and this ordering can be *different* from the one in /// inputs. Also, any duplicated formulas are removed in construction. Please /// check the following example. /// /// @code /// // set up v1 = [y x y] and v2 = [1 2 1] /// VectorX<Expression> v1{3}; /// VectorX<Expression> v2{3}; /// const Variable x{"x"}; /// const Variable y{"y"}; /// v1 << y, x, y; /// v2 << 1, 2, 1; /// // Here v1_eq_v2 = ((x = 2) ∧ (y = 1)) /// const Formula v1_eq_v2{v1 == v2}; /// const std::set<Formula> conjuncts{get_operands(v1_eq_v2)}; /// for (const Formula& f : conjuncts) { /// std::cerr << f << std::endl; /// } /// // The outcome of the above loop is: /// (x = 2) /// (y = 1) /// @endcode 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> && std::is_same_v<decltype(typename DerivedA::Scalar() == typename DerivedB::Scalar()), Formula>, Formula> operator==(const DerivedA& m1, const DerivedB& m2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(m1.rows() == m2.rows() && m1.cols() == m2.cols()); return m1.binaryExpr(m2, std::equal_to<void>()).redux(internal::logic_and); } /// Returns a symbolic formula representing the condition whether @p m1 and @p /// m2 are not the same. /// /// The following table describes the return type of @p m1 != @p m2. /// /// LHS \ RHS | EM<Expression> | EM<Variable> | EM<double> /// ----------------|----------------|--------------|------------ /// EM<Expression> | Formula | Formula | Formula /// EM<Variable> | Formula | Formula | Formula /// EM<double> | Formula | Formula | bool /// /// In the table, `EM` is a short-hand of `Eigen::Matrix`. /// /// Note that this function does *not* provide operator overloading for the /// following case. It returns `bool` and is provided by Eigen. /// /// - Eigen::Matrix<double> != Eigen::Matrix<double> 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> && std::is_same_v<decltype(typename DerivedA::Scalar() != typename DerivedB::Scalar()), Formula>, Formula> operator!=(const DerivedA& m1, const DerivedB& m2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(m1.rows() == m2.rows() && m1.cols() == m2.cols()); return m1.binaryExpr(m2, std::not_equal_to<void>()).redux(internal::logic_or); } /// Returns a symbolic formula representing element-wise comparison between two /// matrices @p m1 and @p m2 using less-than (<) operator. /// /// The following table describes the return type of @p m1 < @p m2. /// /// LHS \ RHS | EM<Expression> | EM<Variable> | EM<double> /// ----------------|----------------|--------------|------------ /// EM<Expression> | Formula | Formula | Formula /// EM<Variable> | Formula | Formula | Formula /// EM<double> | Formula | Formula | N/A /// /// In the table, `EM` is a short-hand of `Eigen::Matrix`. 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> && std::is_same_v<decltype(typename DerivedA::Scalar() < typename DerivedB::Scalar()), Formula>, Formula> operator<(const DerivedA& m1, const DerivedB& m2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(m1.rows() == m2.rows() && m1.cols() == m2.cols()); return m1.binaryExpr(m2, std::less<void>()).redux(internal::logic_and); } /// Returns a symbolic formula representing element-wise comparison between two /// matrices @p m1 and @p m2 using less-than-or-equal operator (<=). /// /// The following table describes the return type of @p m1 <= @p m2. /// /// LHS \ RHS | EM<Expression> | EM<Variable> | EM<double> /// ----------------|----------------|--------------|------------ /// EM<Expression> | Formula | Formula | Formula /// EM<Variable> | Formula | Formula | Formula /// EM<double> | Formula | Formula | N/A /// /// In the table, `EM` is a short-hand of `Eigen::Matrix`. 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> && std::is_same_v<decltype(typename DerivedA::Scalar() <= typename DerivedB::Scalar()), Formula>, Formula> operator<=(const DerivedA& m1, const DerivedB& m2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(m1.rows() == m2.rows() && m1.cols() == m2.cols()); return m1.binaryExpr(m2, std::less_equal<void>()).redux(internal::logic_and); } /// Returns a symbolic formula representing element-wise comparison between two /// matrices @p m1 and @p m2 using greater-than operator (>). /// /// The following table describes the return type of @p m1 > @p m2. /// /// LHS \ RHS | EM<Expression> | EM<Variable> | EM<double> /// ----------------|----------------|--------------|------------ /// EM<Expression> | Formula | Formula | Formula /// EM<Variable> | Formula | Formula | Formula /// EM<double> | Formula | Formula | N/A /// /// In the table, `EM` is a short-hand of `Eigen::Matrix`. 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> && std::is_same_v<decltype(typename DerivedA::Scalar() > typename DerivedB::Scalar()), Formula>, Formula> operator>(const DerivedA& m1, const DerivedB& m2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(m1.rows() == m2.rows() && m1.cols() == m2.cols()); return m1.binaryExpr(m2, std::greater<void>()).redux(internal::logic_and); } /// Returns a symbolic formula representing element-wise comparison between two /// matrices @p m1 and @p m2 using greater-than-or-equal operator (>=). /// /// The following table describes the return type of @p m1 >= @p m2. /// /// LHS \ RHS | EM<Expression> | EM<Variable> | EM<double> /// ----------------|----------------|--------------|------------ /// EM<Expression> | Formula | Formula | Formula /// EM<Variable> | Formula | Formula | Formula /// EM<double> | Formula | Formula | N/A /// /// In the table, `EM` is a short-hand of `Eigen::Matrix`. 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> && std::is_same_v<decltype(typename DerivedA::Scalar() >= typename DerivedB::Scalar()), Formula>, Formula> operator>=(const DerivedA& m1, const DerivedB& m2) { EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(DerivedA, DerivedB); DRAKE_DEMAND(m1.rows() == m2.rows() && m1.cols() == m2.cols()); return m1.binaryExpr(m2, std::greater_equal<void>()) .redux(internal::logic_and); } } // namespace symbolic namespace assert { /* We allow assertion-like statements to receive a Formula. Given the typical * uses of assertions and Formulas, rather than trying to be clever and, e.g., * capture assertion data for later use or partially-solve the Formula to find * counterexamples, instead we've decided to ignore assertions for the purpose * of Formula. They are syntax-checked, but always pass. */ template <> struct ConditionTraits<symbolic::Formula> { static constexpr bool is_valid = true; static bool Evaluate(const symbolic::Formula&) { return true; } }; } // namespace assert } // namespace drake namespace std { /* Provides std::hash<drake::symbolic::Formula>. */ template <> struct hash<drake::symbolic::Formula> : public drake::DefaultHash {}; #if defined(__GLIBCXX__) // https://gcc.gnu.org/onlinedocs/libstdc++/manual/unordered_associative.html template <> struct __is_fast_hash<hash<drake::symbolic::Formula>> : std::false_type {}; #endif /* Provides std::less<drake::symbolic::Formula>. */ template <> struct less<drake::symbolic::Formula> { bool operator()(const drake::symbolic::Formula& lhs, const drake::symbolic::Formula& rhs) const { return lhs.Less(rhs); } }; /* Provides std::equal_to<drake::symbolic::Formula>. */ template <> struct equal_to<drake::symbolic::Formula> { bool operator()(const drake::symbolic::Formula& lhs, const drake::symbolic::Formula& rhs) const { return lhs.EqualTo(rhs); } }; } // namespace std #if !defined(DRAKE_DOXYGEN_CXX) // Define Eigen traits needed for Matrix<drake::symbolic::Formula>. namespace Eigen { // Eigen scalar type traits for Matrix<drake::symbolic::Formula>. template <> struct NumTraits<drake::symbolic::Formula> : GenericNumTraits<drake::symbolic::Formula> { static inline int digits10() { return 0; } }; namespace internal { /// Provides specialization for scalar_cmp_op to handle the case "Expr == Expr" template <> struct scalar_cmp_op<drake::symbolic::Expression, drake::symbolic::Expression, cmp_EQ> : binary_op_base<drake::symbolic::Expression, drake::symbolic::Expression> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Expression& a, const drake::symbolic::Expression& b) const { return a == b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Expr < Expr". template <> struct scalar_cmp_op<drake::symbolic::Expression, drake::symbolic::Expression, cmp_LT> : binary_op_base<drake::symbolic::Expression, drake::symbolic::Expression> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Expression& a, const drake::symbolic::Expression& b) const { return a < b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Expr <= Expr". template <> struct scalar_cmp_op<drake::symbolic::Expression, drake::symbolic::Expression, cmp_LE> : binary_op_base<drake::symbolic::Expression, drake::symbolic::Expression> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Expression& a, const drake::symbolic::Expression& b) const { return a <= b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Expr > Expr". template <> struct scalar_cmp_op<drake::symbolic::Expression, drake::symbolic::Expression, cmp_GT> : binary_op_base<drake::symbolic::Expression, drake::symbolic::Expression> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Expression& a, const drake::symbolic::Expression& b) const { return a > b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Expr >= Expr". template <> struct scalar_cmp_op<drake::symbolic::Expression, drake::symbolic::Expression, cmp_GE> : binary_op_base<drake::symbolic::Expression, drake::symbolic::Expression> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Expression& a, const drake::symbolic::Expression& b) const { return a >= b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Expr != Expr". template <> struct scalar_cmp_op<drake::symbolic::Expression, drake::symbolic::Expression, cmp_NEQ> : binary_op_base<drake::symbolic::Expression, drake::symbolic::Expression> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Expression& a, const drake::symbolic::Expression& b) const { return a != b; } }; #if EIGEN_VERSION_AT_LEAST(3, 4, 90) // Provides specialization for minmax_compare to handle the case "Expr < Expr". // This is needed for the trunk versions of Eigen (i.e., anticipating 3.5.x). template <int NaNPropagation> struct minmax_compare<drake::symbolic::Expression, NaNPropagation, true> { using Scalar = drake::symbolic::Expression; static EIGEN_DEVICE_FUNC inline bool compare(Scalar a, Scalar b) { return static_cast<bool>(a < b); } }; // Provides specialization for minmax_compare to handle the case "Expr > Expr". // This is needed for the trunk versions of Eigen (i.e., anticipating 3.5.x). template <int NaNPropagation> struct minmax_compare<drake::symbolic::Expression, NaNPropagation, false> { using Scalar = drake::symbolic::Expression; static EIGEN_DEVICE_FUNC inline bool compare(Scalar a, Scalar b) { return static_cast<bool>(a > b); } }; #endif // EIGEN_VERSION_AT_LEAST /// Provides specialization for scalar_cmp_op to handle the case "Var == Var". template <> struct scalar_cmp_op<drake::symbolic::Variable, drake::symbolic::Variable, cmp_EQ> : binary_op_base<drake::symbolic::Variable, drake::symbolic::Variable> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Variable& a, const drake::symbolic::Variable& b) const { return a == b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Var < Var". template <> struct scalar_cmp_op<drake::symbolic::Variable, drake::symbolic::Variable, cmp_LT> : binary_op_base<drake::symbolic::Variable, drake::symbolic::Variable> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Variable& a, const drake::symbolic::Variable& b) const { return a < b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Var <= Var". template <> struct scalar_cmp_op<drake::symbolic::Variable, drake::symbolic::Variable, cmp_LE> : binary_op_base<drake::symbolic::Variable, drake::symbolic::Variable> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Variable& a, const drake::symbolic::Variable& b) const { return a <= b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Var > Var". template <> struct scalar_cmp_op<drake::symbolic::Variable, drake::symbolic::Variable, cmp_GT> : binary_op_base<drake::symbolic::Variable, drake::symbolic::Variable> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Variable& a, const drake::symbolic::Variable& b) const { return a > b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Var >= Var". template <> struct scalar_cmp_op<drake::symbolic::Variable, drake::symbolic::Variable, cmp_GE> : binary_op_base<drake::symbolic::Variable, drake::symbolic::Variable> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Variable& a, const drake::symbolic::Variable& b) const { return a >= b; } }; /// Provides specialization for scalar_cmp_op to handle the case "Var != Var". template <> struct scalar_cmp_op<drake::symbolic::Variable, drake::symbolic::Variable, cmp_NEQ> : binary_op_base<drake::symbolic::Variable, drake::symbolic::Variable> { typedef drake::symbolic::Formula result_type; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE result_type operator()(const drake::symbolic::Variable& a, const drake::symbolic::Variable& b) const { return a != b; } }; } // namespace internal namespace numext { // Provides specializations for equal_strict and not_equal_strict with // Expression. As of Eigen 3.4.0, these are called at least as part of // triangular vector solve (though they could also potentially come up // elsewhere). The default template relies on an implicit conversion to // bool but our bool operator is explicit, so we need to specialize. // // Furthermore, various Eigen algorithms will use "short-circuit when zero" // guards as an optimization to skip expensive computation if it can show // that the end result will remain unchanged. If our Expression has any // unbound variables during that guard, we will throw instead of skipping // the optimization. Therefore, we tweak these guards to special-case the // result when either of the operands is a literal zero, with no throwing // even if the other operand has unbound variables. template <> EIGEN_STRONG_INLINE bool equal_strict(const drake::symbolic::Expression& x, const drake::symbolic::Expression& y) { if (is_zero(x)) { return is_zero(y); } if (is_zero(y)) { return is_zero(x); } return static_cast<bool>(x == y); } template <> EIGEN_STRONG_INLINE bool not_equal_strict( const drake::symbolic::Expression& x, const drake::symbolic::Expression& y) { return !Eigen::numext::equal_strict(x, y); } // Provides specialization of Eigen::numext::isfinite, numext::isnan, and // numext::isinf for Expression. The default template relies on an implicit // conversion to bool but our bool operator is explicit, so we need to // specialize. // As of Eigen 3.4.0, this is called at least as part of JacobiSVD (though // it could also potentially come up elsewhere). template <> EIGEN_STRONG_INLINE bool isfinite(const drake::symbolic::Expression& e) { return static_cast<bool>(drake::symbolic::isfinite(e)); } template <> EIGEN_STRONG_INLINE bool isinf(const drake::symbolic::Expression& e) { return static_cast<bool>(drake::symbolic::isinf(e)); } template <> EIGEN_STRONG_INLINE bool isnan(const drake::symbolic::Expression& e) { return static_cast<bool>(drake::symbolic::isnan(e)); } } // namespace numext } // namespace Eigen #endif // !defined(DRAKE_DOXYGEN_CXX) DRAKE_FORMATTER_AS(, drake::symbolic, Formula, f, f.to_string())
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/expression_kind.h
#pragma once #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL #error Do not include this file. Use "drake/common/symbolic/expression.h". #endif #include <cstdint> namespace drake { namespace symbolic { /** Kinds of symbolic expressions. @internal The constants here are carefully chosen to support nanboxing. For all elements except Constant, the bit pattern must have have 0x7FF0 bits set but must not be exactly 0x7FF0 nor 0xFFF0 (reserved for ±infinity). Refer to the details in boxed_cell.h for more information. */ enum class ExpressionKind : std::uint16_t { // clang-format off Constant = 0, ///< constant (double) Var = 0x7FF1u, ///< variable Add, ///< addition (+) Mul, ///< multiplication (*) Div, ///< division (/) Log, ///< logarithms Abs, ///< absolute value function Exp, ///< exponentiation Sqrt, ///< square root Pow, ///< power function Sin, ///< sine Cos, ///< cosine Tan, ///< tangent Asin, ///< arcsine Acos, ///< arccosine Atan, ///< arctangent // Here we have Atan = 0x7FFFu, but we can't overflow to 0x8000 for Atan2 so // restart numbering at the next available value (0xFFF1). Atan2 = 0xFFF1u, ///< arctangent2 (atan2(y,x) = atan(y/x)) Sinh, ///< hyperbolic sine Cosh, ///< hyperbolic cosine Tanh, ///< hyperbolic tangent Min, ///< min Max, ///< max Ceil, ///< ceil Floor, ///< floor IfThenElse, ///< if then else NaN, ///< NaN UninterpretedFunction, ///< Uninterpreted function // TODO(soonho): add Integral // clang-format on }; /** Total ordering between ExpressionKinds. */ inline bool operator<(ExpressionKind k1, ExpressionKind k2) { return static_cast<std::uint16_t>(k1) < static_cast<std::uint16_t>(k2); } } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/expression_cell.h
#pragma once /// @file /// /// Internal use only. /// Provides implementation-details of symbolic expressions. #ifndef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #error Do not include this file unless you implement symbolic libraries. #endif #include <algorithm> // for cpplint only #include <atomic> #include <cstddef> #include <map> #include <ostream> #include <string> #include <vector> #include <Eigen/Core> #include "drake/common/drake_copyable.h" #include "drake/common/hash.h" #include "drake/common/random.h" #include "drake/common/symbolic/expression/all.h" namespace drake { namespace symbolic { // Checks if @p v contains an integer value. bool is_integer(double v); // Checks if @p v contains a positive integer value. bool is_positive_integer(double v); // Checks if @p v contains a non-negative integer value. bool is_non_negative_integer(double v); /** Represents an abstract class which is the base of concrete * symbolic-expression classes. * * @note It provides virtual function, ExpressionCell::Display, because * operator<< is not allowed to be a virtual function. */ class ExpressionCell { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ExpressionCell) virtual ~ExpressionCell(); /** Returns the intrusive use count (ala boost::intrusive_ptr). */ std::atomic<int>& use_count() const { return use_count_; } /** Returns expression kind. */ [[nodiscard]] ExpressionKind get_kind() const { return kind_; } /** Sends all hash-relevant bytes for this ExpressionCell type into the given * hasher, per the @ref hash_append concept -- except for get_kind(), because * Expression already sends that. */ virtual void HashAppendDetail(DelegatingHasher*) const = 0; /** Collects variables in expression. */ [[nodiscard]] virtual Variables GetVariables() const = 0; /** Checks structural equality. */ [[nodiscard]] virtual bool EqualTo(const ExpressionCell& c) const = 0; /** Provides lexicographical ordering between expressions. */ [[nodiscard]] virtual bool Less(const ExpressionCell& c) const = 0; /** Checks if this symbolic expression is convertible to Polynomial. */ [[nodiscard]] bool is_polynomial() const { return is_polynomial_; } /** Checks if this symbolic expression is already expanded. */ [[nodiscard]] bool is_expanded() const { return is_expanded_; } /** Sets this symbolic expression as already expanded. */ void set_expanded() { is_expanded_ = true; } /** Evaluates under a given environment (by default, an empty environment). * @throws std::exception if NaN is detected during evaluation. */ [[nodiscard]] virtual double Evaluate(const Environment& env) const = 0; /** Expands out products and positive integer powers in expression. * @throws std::exception if NaN is detected during expansion. */ [[nodiscard]] virtual Expression Expand() const = 0; /** Returns an Expression obtained by replacing all occurrences of the * variables in @p env in the current expression cell with the corresponding * values in @p env. * @throws std::exception if NaN is detected during substitution. */ [[nodiscard]] virtual Expression EvaluatePartial( const Environment& env) const = 0; /** Returns an Expression obtained by replacing all occurrences of the * variables in @p s in the current expression cell with the corresponding * expressions in @p s. * @throws std::exception if NaN is detected during substitution. */ [[nodiscard]] virtual Expression Substitute(const Substitution& s) const = 0; /** Differentiates this symbolic expression with respect to the variable @p * var. * @throws std::exception if it is not differentiable. */ [[nodiscard]] virtual Expression Differentiate(const Variable& x) const = 0; /** Outputs string representation of expression into output stream @p os. */ virtual std::ostream& Display(std::ostream& os) const = 0; protected: /** Constructs ExpressionCell of kind @p k with @p is_poly and @p is_expanded, with a @p use_count of zero. */ ExpressionCell(ExpressionKind k, bool is_poly, bool is_expanded); private: mutable std::atomic<int> use_count_{0}; const ExpressionKind kind_{}; const bool is_polynomial_{false}; bool is_expanded_{false}; }; /** Represents the base class for unary expressions. */ class UnaryExpressionCell : public ExpressionCell { public: void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetVariables() const override; [[nodiscard]] bool EqualTo(const ExpressionCell& e) const override; [[nodiscard]] bool Less(const ExpressionCell& e) const override; [[nodiscard]] double Evaluate(const Environment& env) const override; /** Returns the argument. */ [[nodiscard]] const Expression& get_argument() const { return e_; } protected: /** Constructs UnaryExpressionCell of kind @p k with @p e, @p is_poly, and @p * is_expanded. */ UnaryExpressionCell(ExpressionKind k, Expression e, bool is_poly, bool is_expanded); /** Returns the evaluation result f(@p v ). */ [[nodiscard]] virtual double DoEvaluate(double v) const = 0; private: const Expression e_; }; /** Represents the base class for binary expressions. */ class BinaryExpressionCell : public ExpressionCell { public: void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetVariables() const override; [[nodiscard]] bool EqualTo(const ExpressionCell& e) const override; [[nodiscard]] bool Less(const ExpressionCell& e) const override; [[nodiscard]] double Evaluate(const Environment& env) const override; /** Returns the first argument. */ [[nodiscard]] const Expression& get_first_argument() const { return e1_; } /** Returns the second argument. */ [[nodiscard]] const Expression& get_second_argument() const { return e2_; } protected: /** Constructs BinaryExpressionCell of kind @p k with @p e1, @p e2, * @p is_poly, and @p is_expanded. */ BinaryExpressionCell(ExpressionKind k, Expression e1, Expression e2, bool is_poly, bool is_expanded); /** Returns the evaluation result f(@p v1, @p v2 ). */ [[nodiscard]] virtual double DoEvaluate(double v1, double v2) const = 0; private: const Expression e1_; const Expression e2_; }; /** Symbolic expression representing a variable. */ class ExpressionVar : public ExpressionCell { public: /** Constructs an expression from @p var. * @pre @p var is not a BOOLEAN variable. */ void HashAppendDetail(DelegatingHasher*) const override; explicit ExpressionVar(Variable v); [[nodiscard]] const Variable& get_variable() const { return var_; } [[nodiscard]] Variables GetVariables() const override; [[nodiscard]] bool EqualTo(const ExpressionCell& e) const override; [[nodiscard]] bool Less(const ExpressionCell& e) const override; [[nodiscard]] double Evaluate(const Environment& env) const override; [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: const Variable var_; }; /** Symbolic expression representing NaN (not-a-number). */ class ExpressionNaN : public ExpressionCell { public: ExpressionNaN(); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetVariables() const override; [[nodiscard]] bool EqualTo(const ExpressionCell& e) const override; [[nodiscard]] bool Less(const ExpressionCell& e) const override; [[nodiscard]] double Evaluate(const Environment& env) const override; [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; }; /** Symbolic expression representing an addition which is a sum of products. * * @f[ * c_0 + \sum c_i * e_i * @f] * * where @f$ c_i @f$ is a constant and @f$ e_i @f$ is a symbolic expression. * * Internally this class maintains a member variable @c constant_ to represent * @f$ c_0 @f$ and another member variable @c expr_to_coeff_map_ to represent a * mapping from an expression @f$ e_i @f$ to its coefficient @f$ c_i @f$ of * double. */ class ExpressionAdd : public ExpressionCell { public: /** Constructs ExpressionAdd from @p constant_term and @p term_to_coeff_map. */ ExpressionAdd(double constant, std::map<Expression, double> expr_to_coeff_map); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetVariables() const override; [[nodiscard]] bool EqualTo(const ExpressionCell& e) const override; [[nodiscard]] bool Less(const ExpressionCell& e) const override; [[nodiscard]] double Evaluate(const Environment& env) const override; [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; /** Returns the constant. */ [[nodiscard]] double get_constant() const { return constant_; } /** Returns map from an expression to its coefficient. */ [[nodiscard]] const std::map<Expression, double>& get_expr_to_coeff_map() const { return expr_to_coeff_map_; } private: std::ostream& DisplayTerm(std::ostream& os, bool print_plus, double coeff, const Expression& term) const; const double constant_{}; const std::map<Expression, double> expr_to_coeff_map_; }; /** Factory class to help build ExpressionAdd expressions. */ class ExpressionAddFactory { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ExpressionAddFactory) /** Default constructor. */ ExpressionAddFactory() = default; /** Constructs ExpressionAddFactory with @p constant and @p * expr_to_coeff_map. */ ExpressionAddFactory(double constant, std::map<Expression, double> expr_to_coeff_map); /** Constructs ExpressionAddFactory from @p add. */ explicit ExpressionAddFactory(const ExpressionAdd& add); /** Adds @p e to this factory. */ void AddExpression(const Expression& e); /** Adds ExpressionAdd pointed by @p ptr to this factory. */ void Add(const ExpressionAdd& add); /** Assigns a factory from a an ExpressionAdd. */ ExpressionAddFactory& operator=(const ExpressionAdd& ptr); /** Negates the expressions in factory. * If it represents c0 + c1 * t1 + ... + * cn * tn, * this method flips it into -c0 - c1 * t1 - ... - cn * tn. * @returns *this. */ ExpressionAddFactory&& Negate() &&; /** Returns a symbolic expression. */ [[nodiscard]] Expression GetExpression() &&; private: /* Adds a constant @p constant to this factory. * Adding constant into an add factory representing * * c0 + c1 * t1 + ... + cn * tn * * results in (c0 + constant) + c1 * t1 + ... + cn * tn. */ void AddConstant(double constant); /* Adds coeff * term to this factory. * * Adding (coeff * term) into an add factory representing * * c0 + c1 * t1 + ... + cn * tn * * results in c0 + c1 * t1 + ... + (coeff * term) + ... + cn * tn. Note that * it also performs simplifications to merge the coefficients of common terms. */ void AddTerm(double coeff, const Expression& term); /* Adds expr_to_coeff_map to this factory. It calls AddConstant and AddTerm * methods. */ void AddMap(const std::map<Expression, double>& expr_to_coeff_map); bool is_expanded_{true}; double constant_{0.0}; std::map<Expression, double> expr_to_coeff_map_; }; /** Symbolic expression representing a multiplication of powers. * * @f[ * c_0 \cdot \prod b_i^{e_i} * @f] * * where @f$ c_0 @f$ is a constant and @f$ b_i @f$ and @f$ e_i @f$ are symbolic * expressions. * * Internally this class maintains a member variable @c constant_ representing * @f$ c_0 @f$ and another member variable @c base_to_exponent_map_ representing * a mapping from a base, @f$ b_i @f$ to its exponentiation @f$ e_i @f$. */ class ExpressionMul : public ExpressionCell { public: /** Constructs ExpressionMul from @p constant and @p base_to_exponent_map. */ ExpressionMul(double constant, std::map<Expression, Expression> base_to_exponent_map); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetVariables() const override; [[nodiscard]] bool EqualTo(const ExpressionCell& e) const override; [[nodiscard]] bool Less(const ExpressionCell& e) const override; [[nodiscard]] double Evaluate(const Environment& env) const override; [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; /** Returns constant term. */ [[nodiscard]] double get_constant() const { return constant_; } /** Returns map from a term to its coefficient. */ [[nodiscard]] const std::map<Expression, Expression>& get_base_to_exponent_map() const { return base_to_exponent_map_; } private: std::ostream& DisplayTerm(std::ostream& os, bool print_mul, const Expression& base, const Expression& exponent) const; double constant_{}; std::map<Expression, Expression> base_to_exponent_map_; }; /** Factory class to help build ExpressionMul expressions. */ class ExpressionMulFactory { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(ExpressionMulFactory) /** Default constructor. */ ExpressionMulFactory() = default; /** Constructs ExpressionMulFactory with @p constant and Expression-valued * @p base_to_exponent_map. Note that this constructor runs in constant-time * because it moves the map into storage; it does not loop over the map. */ ExpressionMulFactory(double constant, std::map<Expression, Expression> base_to_exponent_map); /** Constructs ExpressionMulFactory with a Monomial-like (Variable to integer * power) @p base_to_exponent_map. */ explicit ExpressionMulFactory( const std::map<Variable, int>& base_to_exponent_map); /** Constructs ExpressionMulFactory from @p mul. */ explicit ExpressionMulFactory(const ExpressionMul& mul); /** Adds @p e to this factory. */ void AddExpression(const Expression& e); /** Adds ExpressionMul pointed by @p ptr to this factory. */ void Add(const ExpressionMul& ptr); /** Assigns a factory from an ExpressionMul. */ ExpressionMulFactory& operator=(const ExpressionMul& ptr); /** Negates the expressions in factory. * If it represents c0 * p1 * ... * pn, * this method flips it into -c0 * p1 * ... * pn. * @returns *this. */ ExpressionMulFactory&& Negate() &&; /** Returns a symbolic expression. */ [[nodiscard]] Expression GetExpression() &&; private: /* Adds constant to this factory. Adding constant into an mul factory representing c * b1 ^ e1 * ... * bn ^ en results in (constant * c) * b1 ^ e1 * ... * bn ^ en. */ void AddConstant(double constant); /* Adds pow(base, exponent) to this factory. Adding pow(base, exponent) into an mul factory representing c * b1 ^ e1 * ... * bn ^ en results in c * b1 ^ e1 * ... * base^exponent * ... * bn ^ en. Note that it also performs simplifications to merge the exponents of common bases. */ void AddTerm(const Expression& base, const Expression& exponent); /* Adds base_to_exponent_map to this factory. It calls AddConstant and AddTerm * methods. */ void AddMap(const std::map<Expression, Expression>& base_to_exponent_map); /* Sets to represent a zero expression. */ void SetZero(); bool is_expanded_{true}; double constant_{1.0}; std::map<Expression, Expression> base_to_exponent_map_; }; /** Symbolic expression representing division. */ class ExpressionDiv : public BinaryExpressionCell { public: ExpressionDiv(const Expression& e1, const Expression& e2); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v1, double v2) const override; }; /** Symbolic expression representing logarithms. */ class ExpressionLog : public UnaryExpressionCell { public: explicit ExpressionLog(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; friend Expression log(const Expression& e); private: /* Throws std::exception if v ∉ [0, +oo). */ static void check_domain(double v); [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing absolute value function. */ class ExpressionAbs : public UnaryExpressionCell { public: explicit ExpressionAbs(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; friend Expression abs(const Expression& e); private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing exponentiation using the base of * natural logarithms. */ class ExpressionExp : public UnaryExpressionCell { public: explicit ExpressionExp(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing square-root. */ class ExpressionSqrt : public UnaryExpressionCell { public: explicit ExpressionSqrt(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; friend Expression sqrt(const Expression& e); private: /* Throws std::exception if v ∉ [0, +oo). */ static void check_domain(double v); [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing power function. */ class ExpressionPow : public BinaryExpressionCell { public: ExpressionPow(const Expression& e1, const Expression& e2); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; friend Expression pow(const Expression& e1, const Expression& e2); private: /* Throws std::exception if v1 is finite negative and v2 is finite non-integer. */ static void check_domain(double v1, double v2); [[nodiscard]] double DoEvaluate(double v1, double v2) const override; }; /** Symbolic expression representing sine function. */ class ExpressionSin : public UnaryExpressionCell { public: explicit ExpressionSin(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing cosine function. */ class ExpressionCos : public UnaryExpressionCell { public: explicit ExpressionCos(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing tangent function. */ class ExpressionTan : public UnaryExpressionCell { public: explicit ExpressionTan(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing arcsine function. */ class ExpressionAsin : public UnaryExpressionCell { public: explicit ExpressionAsin(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; friend Expression asin(const Expression& e); private: /* Throws std::exception if v ∉ [-1.0, +1.0]. */ static void check_domain(double v); [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing arccosine function. */ class ExpressionAcos : public UnaryExpressionCell { public: explicit ExpressionAcos(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; friend Expression acos(const Expression& e); private: /* Throws std::exception if v ∉ [-1.0, +1.0]. */ static void check_domain(double v); [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing arctangent function. */ class ExpressionAtan : public UnaryExpressionCell { public: explicit ExpressionAtan(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing atan2 function (arctangent function with * two arguments). atan2(y, x) is defined as atan(y/x). */ class ExpressionAtan2 : public BinaryExpressionCell { public: ExpressionAtan2(const Expression& e1, const Expression& e2); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v1, double v2) const override; }; /** Symbolic expression representing hyperbolic sine function. */ class ExpressionSinh : public UnaryExpressionCell { public: explicit ExpressionSinh(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing hyperbolic cosine function. */ class ExpressionCosh : public UnaryExpressionCell { public: explicit ExpressionCosh(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing hyperbolic tangent function. */ class ExpressionTanh : public UnaryExpressionCell { public: explicit ExpressionTanh(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing min function. */ class ExpressionMin : public BinaryExpressionCell { public: ExpressionMin(const Expression& e1, const Expression& e2); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v1, double v2) const override; }; /** Symbolic expression representing max function. */ class ExpressionMax : public BinaryExpressionCell { public: ExpressionMax(const Expression& e1, const Expression& e2); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v1, double v2) const override; }; /** Symbolic expression representing ceil function. */ class ExpressionCeiling : public UnaryExpressionCell { public: explicit ExpressionCeiling(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing floor function. */ class ExpressionFloor : public UnaryExpressionCell { public: explicit ExpressionFloor(const Expression& e); [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; private: [[nodiscard]] double DoEvaluate(double v) const override; }; /** Symbolic expression representing if-then-else expression. */ class ExpressionIfThenElse : public ExpressionCell { public: /** Constructs if-then-else expression from @p f_cond, @p e_then, and @p * e_else. */ ExpressionIfThenElse(Formula f_cond, Expression e_then, Expression e_else); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetVariables() const override; [[nodiscard]] bool EqualTo(const ExpressionCell& e) const override; [[nodiscard]] bool Less(const ExpressionCell& e) const override; [[nodiscard]] double Evaluate(const Environment& env) const override; [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; /** Returns the conditional formula. */ [[nodiscard]] const Formula& get_conditional_formula() const { return f_cond_; } /** Returns the 'then' expression. */ [[nodiscard]] const Expression& get_then_expression() const { return e_then_; } /** Returns the 'else' expression. */ [[nodiscard]] const Expression& get_else_expression() const { return e_else_; } private: const Formula f_cond_; const Expression e_then_; const Expression e_else_; }; /** Symbolic expression representing an uninterpreted function. */ class ExpressionUninterpretedFunction : public ExpressionCell { public: /** Constructs an uninterpreted-function expression from @p name and @p * arguments. */ ExpressionUninterpretedFunction(std::string name, std::vector<Expression> arguments); void HashAppendDetail(DelegatingHasher*) const override; [[nodiscard]] Variables GetVariables() const override; [[nodiscard]] bool EqualTo(const ExpressionCell& e) const override; [[nodiscard]] bool Less(const ExpressionCell& e) const override; [[nodiscard]] double Evaluate(const Environment& env) const override; [[nodiscard]] Expression Expand() const override; [[nodiscard]] Expression EvaluatePartial( const Environment& env) const override; [[nodiscard]] Expression Substitute(const Substitution& s) const override; [[nodiscard]] Expression Differentiate(const Variable& x) const override; std::ostream& Display(std::ostream& os) const override; /** Returns the name of this expression. */ [[nodiscard]] const std::string& get_name() const { return name_; } /** Returns the arguments of this expression. */ [[nodiscard]] const std::vector<Expression>& get_arguments() const { return arguments_; } private: const std::string name_; const std::vector<Expression> arguments_; }; /** Checks if @p c is a variable expression. */ bool is_variable(const ExpressionCell& c); /** Checks if @p c is a unary expression. */ bool is_unary(const ExpressionCell& c); /** Checks if @p c is a binary expression. */ bool is_binary(const ExpressionCell& c); /** Checks if @p c is an addition expression. */ bool is_addition(const ExpressionCell& c); /** Checks if @p c is an multiplication expression. */ bool is_multiplication(const ExpressionCell& c); /** Checks if @p c is a division expression. */ bool is_division(const ExpressionCell& c); /** Checks if @p c is a log expression. */ bool is_log(const ExpressionCell& c); /** Checks if @p c is an absolute-value-function expression. */ bool is_abs(const ExpressionCell& c); /** Checks if @p c is an exp expression. */ bool is_exp(const ExpressionCell& c); /** Checks if @p c is a square-root expression. */ bool is_sqrt(const ExpressionCell& c); /** Checks if @p c is a power-function expression. */ bool is_pow(const ExpressionCell& c); /** Checks if @p c is a sine expression. */ bool is_sin(const ExpressionCell& c); /** Checks if @p c is a cosine expression. */ bool is_cos(const ExpressionCell& c); /** Checks if @p c is a tangent expression. */ bool is_tan(const ExpressionCell& c); /** Checks if @p c is an arcsine expression. */ bool is_asin(const ExpressionCell& c); /** Checks if @p c is an arccosine expression. */ bool is_acos(const ExpressionCell& c); /** Checks if @p c is an arctangent expression. */ bool is_atan(const ExpressionCell& c); /** Checks if @p c is a arctangent2 expression. */ bool is_atan2(const ExpressionCell& c); /** Checks if @p c is a hyperbolic-sine expression. */ bool is_sinh(const ExpressionCell& c); /** Checks if @p c is a hyperbolic-cosine expression. */ bool is_cosh(const ExpressionCell& c); /** Checks if @p c is a hyperbolic-tangent expression. */ bool is_tanh(const ExpressionCell& c); /** Checks if @p c is a min expression. */ bool is_min(const ExpressionCell& c); /** Checks if @p c is a max expression. */ bool is_max(const ExpressionCell& c); /** Checks if @p c is a ceil expression. */ bool is_ceil(const ExpressionCell& c); /** Checks if @p c is a floor expression. */ bool is_floor(const ExpressionCell& c); /** Checks if @p c is an if-then-else expression. */ bool is_if_then_else(const ExpressionCell& c); /** Checks if @p c is an uninterpreted-function expression. */ bool is_uninterpreted_function(const ExpressionCell& c); } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/ldlt.cc
/* clang-format off to disable clang-format-includes */ // NOLINTNEXTLINE(build/include): Our header file is included by all.h. #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <stdexcept> using E = drake::symbolic::Expression; using MatrixXE = drake::MatrixX<E>; namespace Eigen { namespace { // A free-function implementation of Eigen::LDLT<SomeMatrix>::compute, when // Scalar is symbolic::Expression. The output arguments correspond to the // member fields of the LDLT object. For simplicity, we only offer a single // flavor without templates (i.e., with MaxRowsAtCompileTime == Dynamic). void DoCompute(const Ref<const MatrixXE>& a, MatrixXE* matrix, E* l1_norm, Transpositions<Dynamic>* transpositions, internal::SignMatrix* sign, ComputationInfo* info) { if (!GetDistinctVariables(a).empty()) { throw std::logic_error("Symbolic LDLT is not supported yet"); } const MatrixXd new_a = a.unaryExpr([](const E& e) { return drake::ExtractDoubleOrThrow(e); }); auto ldlt = new_a.ldlt(); *matrix = ldlt.matrixLDLT(); *l1_norm = NAN; // We could recompute this, if we really needed it. *transpositions = ldlt.transpositionsP(); *sign = ldlt.isPositive() ? internal::PositiveSemiDef : ldlt.isNegative() ? internal::NegativeSemiDef : internal::Indefinite; *info = ldlt.info(); } } // namespace #define DRAKE_DEFINE_SPECIALIZE_LDLT(SomeMatrix) \ template <> \ template <> \ Eigen::LDLT<SomeMatrix>& \ Eigen::LDLT<SomeMatrix>::compute<Ref<const SomeMatrix>>( \ const EigenBase<Ref<const SomeMatrix>>& a) { \ MatrixXE matrix; \ Transpositions<Dynamic> transpositions; \ DoCompute(a.derived(), &matrix, &m_l1_norm, &transpositions, &m_sign, \ &m_info); \ m_matrix = matrix; \ m_transpositions = transpositions; \ m_isInitialized = true; \ return *this; \ } DRAKE_DEFINE_SPECIALIZE_LDLT(drake::MatrixX<drake::symbolic::Expression>) DRAKE_DEFINE_SPECIALIZE_LDLT(drake::MatrixUpTo6<drake::symbolic::Expression>) #undef DRAKE_DEFINE_SPECIALIZE_LDLT } // namespace Eigen
0
/home/johnshepherd/drake/common/symbolic
/home/johnshepherd/drake/common/symbolic/expression/all.h
#pragma once // Internal use only. Users should not include this header file directly. // Instead, they should say `#include "drake/common/symbolic/expression.h"`. // Many symbolic types are not closed under their defined operations, e.g., // relational operations (i.e., ``<``) over Expression produce a Formula. // To ensure that this library's definitions are always consistent, we use // this header to define the API as a single, consistent component. This // macro provides a fail-fast that the all.h order is always obeyed. #define DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL // Do not alpha-sort the following block of hard-coded #includes, which is // protected by `clang-format on/off`. // // This particular order ensures that everyone sees the order that respects the // inter-dependencies of the symbolic headers. This shields us from triggering // undefined behaviors due to varying the order of template specializations. // // clang-format off #include "drake/common/symbolic/expression/variable.h" #include "drake/common/symbolic/expression/variables.h" #include "drake/common/symbolic/expression/environment.h" #include "drake/common/symbolic/expression/expression_kind.h" #include "drake/common/symbolic/expression/boxed_cell.h" #include "drake/common/symbolic/expression/expression.h" #include "drake/common/symbolic/expression/expression_visitor.h" #include "drake/common/symbolic/expression/ldlt.h" #include "drake/common/symbolic/expression/formula.h" #include "drake/common/symbolic/expression/formula_visitor.h" // clang-format on #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_ALL
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/formula_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <algorithm> #include <cmath> #include <exception> #include <limits> #include <map> #include <random> #include <set> #include <stdexcept> #include <unordered_map> #include <unordered_set> #include <vector> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/drake_throw.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/is_memcpy_movable.h" #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { using std::numeric_limits; using test::IsMemcpyMovable; namespace symbolic { namespace kcov339_avoidance_magic { namespace { using std::map; using std::runtime_error; using std::set; using std::transform; using std::unordered_map; using std::unordered_set; using std::vector; using test::all_of; using test::any_of; using test::ExprEqual; using test::FormulaEqual; using test::FormulaLess; using test::FormulaNotEqual; using test::FormulaNotLess; using test::VarEqual; // Checks if a given 'formulas' is ordered by Formula::Less. void CheckOrdering(const vector<Formula>& formulas) { for (size_t i{0}; i < formulas.size(); ++i) { for (size_t j{0}; j < formulas.size(); ++j) { if (i < j) { EXPECT_PRED2(FormulaLess, formulas[i], formulas[j]) << "(Formulas[" << i << "] = " << formulas[i] << ")" << " is not less than " << "(Formulas[" << j << "] = " << formulas[j] << ")"; EXPECT_PRED2(FormulaNotLess, formulas[j], formulas[i]) << "(Formulas[" << j << "] = " << formulas[j] << ")" << " is less than " << "(Formulas[" << i << "] = " << formulas[i] << ")"; } else if (i > j) { EXPECT_PRED2(FormulaLess, formulas[j], formulas[i]) << "(Formulas[" << j << "] = " << formulas[j] << ")" << " is not less than " << "(Formulas[" << i << "] = " << formulas[i] << ")"; EXPECT_PRED2(FormulaNotLess, formulas[i], formulas[j]) << "(Formulas[" << i << "] = " << formulas[i] << ")" << " is less than " << "(Formulas[" << j << "] = " << formulas[j] << ")"; } else { // i == j EXPECT_PRED2(FormulaNotLess, formulas[i], formulas[j]) << "(Formulas[" << i << "] = " << formulas[i] << ")" << " is less than " << "(Formulas[" << j << "] = " << formulas[j] << ")"; EXPECT_PRED2(FormulaNotLess, formulas[j], formulas[i]) << "(Formulas[" << j << "] = " << formulas[j] << ")" << " is less than " << "(Formulas[" << i << "] = " << formulas[i] << ")"; } } } } // Provides common variables that are used by the following tests. class SymbolicFormulaTest : public ::testing::Test { protected: const Variable var_x_{"x", Variable::Type::CONTINUOUS}; const Variable var_y_{"y", Variable::Type::CONTINUOUS}; const Variable var_z_{"z", Variable::Type::CONTINUOUS}; const Variable var_b1_{"x", Variable::Type::BOOLEAN}; const Variable var_b2_{"y", Variable::Type::BOOLEAN}; const Expression x_{var_x_}; const Expression y_{var_y_}; const Expression z_{var_z_}; const Expression e1_{x_ + y_}; const Expression e1_prime_{x_ + y_}; const Expression e2_{x_ - y_}; const Expression e3_{x_ + z_}; const Formula b1_{var_b1_}; const Formula b2_{var_b2_}; const Formula tt_{Formula::True()}; const Formula ff_{Formula::False()}; const Formula f1_{x_ + y_ > 0}; const Formula f2_{x_ * y_ < 5}; const Formula f3_{x_ / y_ < 5}; const Formula f4_{x_ - y_ < 5}; const Formula f_eq_{e1_ == 0.0}; const Formula f_neq_{e1_ != 0.0}; const Formula f_lt_{e1_ < 0.0}; const Formula f_lte_{e1_ <= 0.0}; const Formula f_gt_{e1_ > 0.0}; const Formula f_gte_{e1_ >= 0.0}; const Formula f_and_{f1_ && f2_}; const Formula f_or_{f1_ || f2_}; const Formula not_f_or_{!f_or_}; const Formula f_forall_{forall({var_x_, var_y_}, f_or_)}; const Formula f_isnan_{isnan(Expression::NaN())}; const Environment env1_{{var_x_, 1}, {var_y_, 1}}; const Environment env2_{{var_x_, 3}, {var_y_, 4}}; const Environment env3_{{var_x_, -2}, {var_y_, -5}}; const Environment env4_{{var_x_, -1}, {var_y_, -1}}; // The following matrices will be initialized in SetUp(). Eigen::Matrix<Expression, 2, 2> m_static_2x2_; MatrixX<Expression> m_dynamic_2x2_; Eigen::Matrix<Expression, 3, 3> m_static_3x3_; // The following formulas will be initialized in SetUp(). Formula f_psd_static_2x2_; Formula f_psd_dynamic_2x2_; Formula f_psd_static_3x3_; void SetUp() override { // clang-format off m_static_2x2_ << (x_ + y_), -1.0, -1.0, y_; m_dynamic_2x2_.resize(2, 2); m_dynamic_2x2_ << (x_ + y_), 1.0, 1.0, y_; m_static_3x3_ << (x_ + y_), 3.14, z_, 3.14, y_, z_ * z_, z_, z_ * z_, 1.0; // clang-format on f_psd_static_2x2_ = positive_semidefinite(m_static_2x2_); f_psd_dynamic_2x2_ = positive_semidefinite(m_dynamic_2x2_); f_psd_static_3x3_ = positive_semidefinite(m_static_3x3_); } }; TEST_F(SymbolicFormulaTest, LessKind) { // clang-format off CheckOrdering({ Formula::False(), Formula::True(), b1_, b2_, x_ == y_, x_ != y_, x_> y_, x_ >= y_, x_ < y_, x_ <= y_, f1_ && f2_, f1_ || f2_, !f1_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}); // clang-format on } TEST_F(SymbolicFormulaTest, LessTrueFalse) { CheckOrdering({Formula::False(), Formula::True()}); } TEST_F(SymbolicFormulaTest, LessEq) { const Formula f1{x_ == y_}; const Formula f2{x_ == z_}; const Formula f3{y_ == z_}; CheckOrdering({f1, f2, f3}); } TEST_F(SymbolicFormulaTest, LessNeq) { const Formula f1{x_ != y_}; const Formula f2{x_ != z_}; const Formula f3{y_ != z_}; CheckOrdering({f1, f2, f3}); } TEST_F(SymbolicFormulaTest, LessGt) { const Formula f1{x_ > y_}; const Formula f2{x_ > z_}; const Formula f3{y_ > z_}; CheckOrdering({f1, f2, f3}); } TEST_F(SymbolicFormulaTest, LessGeq) { const Formula f1{x_ >= y_}; const Formula f2{x_ >= z_}; const Formula f3{y_ >= z_}; CheckOrdering({f1, f2, f3}); } TEST_F(SymbolicFormulaTest, LessLt) { const Formula f1{x_ < y_}; const Formula f2{x_ < z_}; const Formula f3{y_ < z_}; CheckOrdering({f1, f2, f3}); } TEST_F(SymbolicFormulaTest, LessLeq) { const Formula f1{x_ <= y_}; const Formula f2{x_ <= z_}; const Formula f3{y_ <= z_}; CheckOrdering({f1, f2, f3}); } TEST_F(SymbolicFormulaTest, LessAnd) { const Formula and1{f1_ && f2_ && f3_}; const Formula and2{f1_ && f3_}; const Formula and3{f2_ && f3_}; CheckOrdering({and1, and2, and3}); } TEST_F(SymbolicFormulaTest, LessOr) { const Formula or1{f1_ || f2_ || f3_}; const Formula or2{f1_ || f3_}; const Formula or3{f2_ || f3_}; CheckOrdering({or1, or2, or3}); } TEST_F(SymbolicFormulaTest, LessNot) { const Formula not1{!f1_}; const Formula not2{!f2_}; const Formula not3{!f3_}; CheckOrdering({not1, not2, not3}); } TEST_F(SymbolicFormulaTest, LessForall) { const Formula forall1{forall({var_x_, var_y_}, f1_)}; const Formula forall2{forall({var_x_, var_y_, var_z_}, f1_)}; const Formula forall3{forall({var_x_, var_y_, var_z_}, f2_)}; CheckOrdering({forall1, forall2, forall3}); } TEST_F(SymbolicFormulaTest, True) { EXPECT_PRED2(FormulaEqual, Formula::True(), Formula{tt_}); EXPECT_TRUE(Formula::True().Evaluate()); EXPECT_EQ(Formula::True().GetFreeVariables().size(), 0u); EXPECT_EQ(Formula::True().to_string(), "True"); EXPECT_TRUE(is_true(Formula::True())); } TEST_F(SymbolicFormulaTest, False) { EXPECT_PRED2(FormulaEqual, Formula::False(), Formula{ff_}); EXPECT_FALSE(Formula::False().Evaluate()); EXPECT_EQ(Formula::False().GetFreeVariables().size(), 0u); EXPECT_EQ(Formula::False().to_string(), "False"); EXPECT_TRUE(is_false(Formula::False())); } TEST_F(SymbolicFormulaTest, Variable) { // Tests is_variable and get_variable functions. EXPECT_TRUE(is_variable(b1_)); EXPECT_TRUE(is_variable(b2_)); EXPECT_PRED2(VarEqual, get_variable(b1_), var_b1_); EXPECT_PRED2(VarEqual, get_variable(b2_), var_b2_); } TEST_F(SymbolicFormulaTest, IsNaN) { // Things that aren't NaN are !isnan. const Expression zero{0}; const Formula zero_is_nan{isnan(zero)}; EXPECT_FALSE(zero_is_nan.Evaluate()); // Things that _are_ NaN are exceptions, which is consistent with Expression // disallowing NaNs to be evaluated at runtime. const Expression nan{NAN}; const Formula nan_is_nan{isnan(nan)}; EXPECT_THROW(nan_is_nan.Evaluate(), runtime_error); // Buried NaNs are safe. const Formula ite_nan1{isnan(if_then_else(tt_, zero, nan))}; EXPECT_FALSE(ite_nan1.Evaluate()); // This case will be evaluated to NaN and we will have runtime_error. const Formula ite_nan2{isnan(if_then_else(ff_, zero, nan))}; EXPECT_THROW(ite_nan2.Evaluate(), runtime_error); // Formula isnan(x / y) should throw a runtime_error when evaluated with // an environment mapping both of x and y to zero, because 0.0 / 0.0 = NaN. const Expression x_div_y{x_ / y_}; const Environment env1{{var_x_, 0.0}, {var_y_, 0.0}}; EXPECT_THROW(isnan(x_div_y).Evaluate(env1), runtime_error); // If the included expression `e` is not evaluated to NaN, `isnan(e)` should // return false. const Environment env2{{var_x_, 3.0}, {var_y_, 2.0}}; EXPECT_FALSE(isnan(x_div_y).Evaluate(env2)); } TEST_F(SymbolicFormulaTest, EqualTo1) { const Formula f_eq{x_ == y_}; const Formula f_ne{x_ != y_}; const Formula f_lt{x_ < y_}; const Formula f_le{x_ <= y_}; const Formula f_gt{x_ > y_}; const Formula f_ge{x_ >= y_}; EXPECT_PRED2(FormulaEqual, f_eq, f_eq); EXPECT_PRED2(FormulaEqual, f_eq, x_ == y_); EXPECT_PRED2(FormulaNotEqual, f_eq, x_ == z_); EXPECT_PRED2(FormulaNotEqual, f_eq, f_ne); EXPECT_PRED2(FormulaNotEqual, f_eq, f_lt); EXPECT_PRED2(FormulaNotEqual, f_eq, f_le); EXPECT_PRED2(FormulaNotEqual, f_eq, f_gt); EXPECT_PRED2(FormulaNotEqual, f_eq, f_ge); EXPECT_PRED2(FormulaNotEqual, f_ne, f_eq); EXPECT_PRED2(FormulaEqual, f_ne, f_ne); EXPECT_PRED2(FormulaEqual, f_ne, x_ != y_); EXPECT_PRED2(FormulaNotEqual, f_ne, x_ != z_); EXPECT_PRED2(FormulaNotEqual, f_ne, f_lt); EXPECT_PRED2(FormulaNotEqual, f_ne, f_le); EXPECT_PRED2(FormulaNotEqual, f_ne, f_gt); EXPECT_PRED2(FormulaNotEqual, f_ne, f_ge); EXPECT_PRED2(FormulaNotEqual, f_lt, f_eq); EXPECT_PRED2(FormulaNotEqual, f_lt, f_ne); EXPECT_PRED2(FormulaEqual, f_lt, f_lt); EXPECT_PRED2(FormulaEqual, f_lt, x_ < y_); EXPECT_PRED2(FormulaNotEqual, f_lt, x_ < z_); EXPECT_PRED2(FormulaNotEqual, f_lt, f_le); EXPECT_PRED2(FormulaNotEqual, f_lt, f_gt); EXPECT_PRED2(FormulaNotEqual, f_lt, f_ge); EXPECT_PRED2(FormulaNotEqual, f_le, f_eq); EXPECT_PRED2(FormulaNotEqual, f_le, f_ne); EXPECT_PRED2(FormulaNotEqual, f_le, f_lt); EXPECT_PRED2(FormulaEqual, f_le, f_le); EXPECT_PRED2(FormulaEqual, f_le, x_ <= y_); EXPECT_PRED2(FormulaNotEqual, f_le, x_ <= z_); EXPECT_PRED2(FormulaNotEqual, f_le, f_gt); EXPECT_PRED2(FormulaNotEqual, f_le, f_ge); EXPECT_PRED2(FormulaNotEqual, f_gt, f_eq); EXPECT_PRED2(FormulaNotEqual, f_gt, f_ne); EXPECT_PRED2(FormulaNotEqual, f_gt, f_lt); EXPECT_PRED2(FormulaNotEqual, f_gt, f_le); EXPECT_PRED2(FormulaEqual, f_gt, f_gt); EXPECT_PRED2(FormulaEqual, f_gt, x_ > y_); EXPECT_PRED2(FormulaNotEqual, f_gt, x_ > z_); EXPECT_PRED2(FormulaNotEqual, f_gt, f_ge); EXPECT_PRED2(FormulaNotEqual, f_ge, f_eq); EXPECT_PRED2(FormulaNotEqual, f_ge, f_ne); EXPECT_PRED2(FormulaNotEqual, f_ge, f_lt); EXPECT_PRED2(FormulaNotEqual, f_ge, f_le); EXPECT_PRED2(FormulaNotEqual, f_ge, f_gt); EXPECT_PRED2(FormulaEqual, f_ge, f_ge); EXPECT_PRED2(FormulaEqual, f_ge, x_ >= y_); EXPECT_PRED2(FormulaNotEqual, f_ge, x_ >= z_); } TEST_F(SymbolicFormulaTest, EqualTo2) { const Formula f1{x_ == y_}; const Formula f2{y_ > z_}; const Formula f_and{f1 && f2}; const Formula f_or{f1 || f2}; const Formula f_not{!f1}; EXPECT_PRED2(FormulaEqual, f_and, f_and); EXPECT_PRED2(FormulaNotEqual, f_and, f_or); EXPECT_PRED2(FormulaNotEqual, f_and, f_not); EXPECT_PRED2(FormulaNotEqual, f_or, f_and); EXPECT_PRED2(FormulaEqual, f_or, f_or); EXPECT_PRED2(FormulaNotEqual, f_or, f_not); EXPECT_PRED2(FormulaNotEqual, f_not, f_and); EXPECT_PRED2(FormulaNotEqual, f_not, f_or); EXPECT_PRED2(FormulaEqual, f_not, f_not); } TEST_F(SymbolicFormulaTest, EqualTo3) { const Formula f_forall1{forall({var_x_, var_y_}, f_or_)}; const Formula f_forall2{forall({var_x_, var_y_, var_z_}, f_or_)}; const Formula f_forall3{forall({var_x_, var_y_}, f_and_)}; const Formula f_forall4{forall({var_x_, var_y_, var_z_}, f_and_)}; EXPECT_PRED2(FormulaEqual, f_forall1, f_forall1); EXPECT_PRED2(FormulaNotEqual, f_forall1, f_forall2); EXPECT_PRED2(FormulaNotEqual, f_forall1, f_forall3); EXPECT_PRED2(FormulaNotEqual, f_forall1, f_forall4); EXPECT_PRED2(FormulaNotEqual, f_forall2, f_forall1); EXPECT_PRED2(FormulaEqual, f_forall2, f_forall2); EXPECT_PRED2(FormulaNotEqual, f_forall2, f_forall3); EXPECT_PRED2(FormulaNotEqual, f_forall2, f_forall4); EXPECT_PRED2(FormulaNotEqual, f_forall3, f_forall1); EXPECT_PRED2(FormulaNotEqual, f_forall3, f_forall2); EXPECT_PRED2(FormulaEqual, f_forall3, f_forall3); EXPECT_PRED2(FormulaNotEqual, f_forall3, f_forall4); EXPECT_PRED2(FormulaNotEqual, f_forall4, f_forall1); EXPECT_PRED2(FormulaNotEqual, f_forall4, f_forall2); EXPECT_PRED2(FormulaNotEqual, f_forall4, f_forall3); EXPECT_PRED2(FormulaEqual, f_forall4, f_forall4); } TEST_F(SymbolicFormulaTest, Eq) { const Formula f1{e1_ == e1_}; // true EXPECT_PRED2(FormulaEqual, f1, Formula::True()); EXPECT_PRED2(FormulaNotEqual, f1, Formula::False()); const Formula f2{e1_ == e1_prime_}; // true EXPECT_PRED2(FormulaEqual, f2, Formula::True()); EXPECT_PRED2(FormulaNotEqual, f2, Formula::False()); const Formula f3{e1_ == e3_}; EXPECT_PRED2(FormulaNotEqual, f3, Formula::True()); const Formula f4{e2_ == e3_}; EXPECT_PRED2(FormulaNotEqual, f4, Formula::True()); const Formula f5{x_ == x_ + 5}; // false EXPECT_PRED2(FormulaEqual, f5, Formula::False()); EXPECT_TRUE(all_of({f3, f4}, is_equal_to)); EXPECT_FALSE(any_of({f1, f2, f5}, is_equal_to)); const Environment env{{var_x_, 2}, {var_y_, 3}, {var_z_, 3}}; EXPECT_EQ(f3.Evaluate(env), (2 + 3) == (2 + 3)); EXPECT_EQ(f4.Evaluate(env), (2 - 3) == (2 + 3)); EXPECT_EQ((5 + x_ == 3 + y_).to_string(), "((5 + x) == (3 + y))"); } TEST_F(SymbolicFormulaTest, Neq) { const Formula f1{e1_ != e1_}; // false EXPECT_PRED2(FormulaEqual, f1, Formula::False()); EXPECT_PRED2(FormulaNotEqual, f1, Formula::True()); const Formula f2{e1_ != e1_prime_}; // false EXPECT_PRED2(FormulaEqual, f2, Formula::False()); EXPECT_PRED2(FormulaNotEqual, f2, Formula::True()); const Formula f3{e1_ != e3_}; EXPECT_PRED2(FormulaNotEqual, f3, Formula::False()); const Formula f4{e2_ != e3_}; EXPECT_PRED2(FormulaNotEqual, f4, Formula::False()); const Formula f5{x_ != x_ + 5}; // true EXPECT_PRED2(FormulaEqual, f5, Formula::True()); EXPECT_TRUE(all_of({f3, f4}, is_not_equal_to)); EXPECT_FALSE(any_of({f1, f2, f5}, is_not_equal_to)); const Environment env{{var_x_, 2}, {var_y_, 3}, {var_z_, 3}}; EXPECT_EQ(f3.Evaluate(env), (2 + 3) != (2 + 3)); EXPECT_EQ(f4.Evaluate(env), (2 - 3) != (2 + 3)); EXPECT_EQ((5 + x_ != 3 + y_).to_string(), "((5 + x) != (3 + y))"); } TEST_F(SymbolicFormulaTest, Lt) { const Formula f1{e1_ < e1_}; // false EXPECT_PRED2(FormulaEqual, f1, Formula::False()); EXPECT_PRED2(FormulaNotEqual, f1, Formula::True()); const Formula f2{e1_ < e1_prime_}; // false EXPECT_PRED2(FormulaEqual, f2, Formula::False()); EXPECT_PRED2(FormulaNotEqual, f2, Formula::True()); const Formula f3{e1_ < e3_}; EXPECT_PRED2(FormulaNotEqual, f3, Formula::True()); const Formula f4{e2_ < e3_}; EXPECT_PRED2(FormulaNotEqual, f4, Formula::True()); const Formula f5{x_ < x_ + 5}; // true EXPECT_PRED2(FormulaEqual, f5, Formula::True()); EXPECT_TRUE(all_of({f3, f4}, is_less_than)); EXPECT_FALSE(any_of({f1, f2, f5}, is_less_than)); const Environment env{{var_x_, 2}, {var_y_, 3}, {var_z_, 3}}; EXPECT_EQ(f3.Evaluate(env), (2 + 3) < (2 + 3)); EXPECT_EQ(f4.Evaluate(env), (2 - 3) < (2 + 3)); EXPECT_EQ((5 + x_ < 3 + y_).to_string(), "((5 + x) < (3 + y))"); } TEST_F(SymbolicFormulaTest, Gt) { const Formula f1{e1_ > e1_}; // false EXPECT_PRED2(FormulaEqual, f1, Formula::False()); EXPECT_PRED2(FormulaNotEqual, f1, Formula::True()); const Formula f2{e1_ > e1_prime_}; // false EXPECT_PRED2(FormulaEqual, f2, Formula::False()); EXPECT_PRED2(FormulaNotEqual, f2, Formula::True()); const Formula f3{e1_ > e3_}; EXPECT_PRED2(FormulaNotEqual, f3, Formula::True()); const Formula f4{e2_ > e3_}; EXPECT_PRED2(FormulaNotEqual, f4, Formula::True()); const Formula f5{x_ > x_ + 5}; // false EXPECT_PRED2(FormulaEqual, f5, Formula::False()); EXPECT_TRUE(all_of({f3, f4}, is_greater_than)); EXPECT_FALSE(any_of({f1, f2, f5}, is_greater_than)); const Environment env{{var_x_, 2}, {var_y_, 3}, {var_z_, 3}}; EXPECT_EQ(f3.Evaluate(env), (2 + 3) > (2 + 3)); EXPECT_EQ(f4.Evaluate(env), (2 - 3) > (2 + 3)); EXPECT_EQ((5 + x_ > 3 + y_).to_string(), "((5 + x) > (3 + y))"); } TEST_F(SymbolicFormulaTest, Leq) { const Formula f1{e1_ <= e1_}; // true EXPECT_PRED2(FormulaEqual, f1, Formula::True()); EXPECT_PRED2(FormulaNotEqual, f1, Formula::False()); const Formula f2{e1_ <= e1_prime_}; // true EXPECT_PRED2(FormulaEqual, f2, Formula::True()); EXPECT_PRED2(FormulaNotEqual, f2, Formula::False()); const Formula f3{e1_ <= e3_}; EXPECT_PRED2(FormulaNotEqual, f3, Formula::True()); const Formula f4{e2_ <= e3_}; EXPECT_PRED2(FormulaNotEqual, f4, Formula::True()); const Formula f5{x_ <= x_ + 5}; // true EXPECT_PRED2(FormulaEqual, f5, Formula::True()); EXPECT_TRUE(all_of({f3, f4}, is_less_than_or_equal_to)); EXPECT_FALSE(any_of({f1, f2, f5}, is_less_than_or_equal_to)); const Environment env{{var_x_, 2}, {var_y_, 3}, {var_z_, 3}}; EXPECT_EQ(f3.Evaluate(env), (2 + 3) <= (2 + 3)); EXPECT_EQ(f4.Evaluate(env), (2 - 3) <= (2 + 3)); EXPECT_EQ((5 + x_ <= 3 + y_).to_string(), "((5 + x) <= (3 + y))"); } TEST_F(SymbolicFormulaTest, Geq) { const Formula f1{e1_ >= e1_}; // true EXPECT_PRED2(FormulaEqual, f1, Formula::True()); EXPECT_PRED2(FormulaNotEqual, f1, Formula::False()); const Formula f2{e1_ >= e1_prime_}; // true EXPECT_PRED2(FormulaEqual, f2, Formula::True()); EXPECT_PRED2(FormulaNotEqual, f2, Formula::False()); const Formula f3{e1_ >= e3_}; EXPECT_PRED2(FormulaNotEqual, f3, Formula::True()); const Formula f4{e2_ >= e3_}; EXPECT_PRED2(FormulaNotEqual, f4, Formula::True()); const Formula f5{x_ >= x_ + 5}; // false EXPECT_PRED2(FormulaEqual, f5, Formula::False()); EXPECT_TRUE(all_of({f3, f4}, is_greater_than_or_equal_to)); EXPECT_FALSE(any_of({f1, f2, f5}, is_greater_than_or_equal_to)); const Environment env{{var_x_, 2}, {var_y_, 3}, {var_z_, 3}}; EXPECT_EQ(f3.Evaluate(env), (2 + 3) >= (2 + 3)); EXPECT_EQ(f4.Evaluate(env), (2 - 3) >= (2 + 3)); EXPECT_EQ((5 + x_ >= 3 + y_).to_string(), "((5 + x) >= (3 + y))"); } TEST_F(SymbolicFormulaTest, And1) { EXPECT_PRED2(FormulaEqual, tt_, tt_ && tt_); EXPECT_PRED2(FormulaEqual, ff_, ff_ && tt_); EXPECT_PRED2(FormulaEqual, ff_, tt_ && ff_); EXPECT_PRED2(FormulaEqual, ff_, ff_ && ff_); EXPECT_PRED2(FormulaEqual, f1_, tt_ && f1_); EXPECT_PRED2(FormulaEqual, f1_, f1_ && tt_); EXPECT_PRED2(FormulaEqual, make_conjunction({tt_, f1_, tt_}), f1_); EXPECT_PRED2(FormulaEqual, make_conjunction({tt_, tt_, ff_}), ff_); // Checks if flattening works: (f₁ ∧ f₂) ∧ (f₃ ∧ f₄) => f₁ ∧ f₂ ∧ f₃ ∧ f₄. EXPECT_PRED2(FormulaEqual, make_conjunction({f1_ && f2_, f3_ && f4_}), make_conjunction({f1_, f2_, f3_, f4_})); // Empty conjunction = True. EXPECT_PRED2(FormulaEqual, make_conjunction({}), Formula::True()); } TEST_F(SymbolicFormulaTest, And2) { EXPECT_EQ(f_and_.Evaluate(env1_), (1 + 1 > 0) && (1 * 1 < 5)); EXPECT_EQ(f_and_.Evaluate(env2_), (3 + 4 > 0) && (3 * 4 < 5)); EXPECT_EQ(f_and_.Evaluate(env3_), (-2 + -5 > 0) && (-2 * -5 < 5)); EXPECT_EQ(f_and_.Evaluate(env4_), (-1 + -1 > 0) && (-1 * -1 < 5)); EXPECT_EQ((x_ == 3 && y_ == 5).to_string(), "((x == 3) and (y == 5))"); EXPECT_TRUE(is_conjunction(x_ == 3 && y_ == 5)); EXPECT_TRUE(is_nary(x_ == 3 && y_ == 5)); } TEST_F(SymbolicFormulaTest, And3) { // Flattening EXPECT_PRED2(FormulaEqual, f1_ && f2_ && f3_ && f4_, f1_ && f2_ && f3_ && f4_); EXPECT_PRED2(FormulaEqual, (f1_ && f2_) && (f3_ && f4_), f1_ && f2_ && f3_ && f4_); EXPECT_PRED2(FormulaEqual, f1_ && (f2_ && f3_) && f4_, f1_ && f2_ && f3_ && f4_); EXPECT_PRED2(FormulaEqual, f1_ && ((f2_ && f3_) && f4_), f1_ && f2_ && f3_ && f4_); // Remove duplicate EXPECT_PRED2(FormulaEqual, f1_ && f2_ && f1_, f1_ && f2_); } TEST_F(SymbolicFormulaTest, And4) { // Simplification: f && f => f. for (const Formula& f : {b1_, b2_, tt_, ff_, f1_, f2_, f3_, f4_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_}) { EXPECT_PRED2(FormulaEqual, f && f, f); } } TEST_F(SymbolicFormulaTest, And5) { // Flatten and removing duplicates. This is the example mentioned in // symbolic_formula.h file: // (f1 && f2) && f1 => f1 && f2 // f1 && (f2 && f1) => f1 && f2 EXPECT_PRED2(FormulaEqual, (f1_ && f2_) && f1_, f1_ && f2_); EXPECT_PRED2(FormulaEqual, f1_ && (f2_ && f1_), f1_ && f2_); EXPECT_PRED2(FormulaEqual, (f1_ && f2_) && f1_, f1_ && (f2_ && f1_)); } TEST_F(SymbolicFormulaTest, AndWithBooleanVariableOperator) { // Checks if operator&& works Boolean variables as expected. const Formula f1{var_b1_ && var_b2_}; ASSERT_TRUE(is_conjunction(f1)); EXPECT_TRUE(get_operands(f1).contains(b1_)); EXPECT_TRUE(get_operands(f1).contains(b2_)); const Formula f2{var_b1_ && (y_ > 0)}; ASSERT_TRUE(is_conjunction(f2)); EXPECT_TRUE(get_operands(f2).contains(b1_)); const Formula f3{(x_ > 0) && var_b2_}; ASSERT_TRUE(is_conjunction(f3)); EXPECT_TRUE(get_operands(f3).contains(b2_)); } TEST_F(SymbolicFormulaTest, AndWithBooleanVariableEvaluate) { // Checks the evaluations of conjunctive formulas with Boolean variables. const Formula f{b1_ && b2_}; const Environment env1{{var_b1_, true}, {var_b2_, true}}; const Environment env2{{var_b1_, true}, {var_b2_, false}}; const Environment env3{{var_b1_, false}, {var_b2_, true}}; const Environment env4{{var_b1_, false}, {var_b2_, false}}; EXPECT_TRUE(f.Evaluate(env1)); EXPECT_FALSE(f.Evaluate(env2)); EXPECT_FALSE(f.Evaluate(env3)); EXPECT_FALSE(f.Evaluate(env4)); } TEST_F(SymbolicFormulaTest, Or1) { EXPECT_PRED2(FormulaEqual, tt_, tt_ || tt_); EXPECT_PRED2(FormulaEqual, tt_, ff_ || tt_); EXPECT_PRED2(FormulaEqual, tt_, tt_ || ff_); EXPECT_PRED2(FormulaEqual, ff_, ff_ || ff_); EXPECT_PRED2(FormulaEqual, f1_, ff_ || f1_); EXPECT_PRED2(FormulaEqual, f1_, f1_ || ff_); EXPECT_PRED2(FormulaEqual, make_disjunction({ff_, f1_, ff_}), f1_); EXPECT_PRED2(FormulaEqual, make_disjunction({ff_, ff_, tt_}), tt_); // Checks if flattening works: (f₁ ∨ f₂) ∨ (f₃ ∨ f₄) => f₁ ∨ f₂ ∨ f₃ ∨ f₄. EXPECT_PRED2(FormulaEqual, make_disjunction({f1_ || f2_, f3_ || f4_}), make_disjunction({f1_, f2_, f3_, f4_})); // Empty disjunction = False. EXPECT_PRED2(FormulaEqual, make_disjunction({}), Formula::False()); } TEST_F(SymbolicFormulaTest, Or2) { EXPECT_EQ(f_or_.Evaluate(env1_), (1 + 1 > 0) || (1 * 1 < 5)); EXPECT_EQ(f_or_.Evaluate(env2_), (3 + 4 > 0) || (3 * 4 < 5)); EXPECT_EQ(f_or_.Evaluate(env3_), (-2 + -5 > 0) || (-2 * -5 < 5)); EXPECT_EQ(f_or_.Evaluate(env4_), (-1 + -1 > 0) || (-1 * -1 < 5)); EXPECT_EQ((x_ == 3 || y_ == 5).to_string(), "((x == 3) or (y == 5))"); EXPECT_TRUE(is_disjunction(x_ == 3 || y_ == 5)); EXPECT_TRUE(is_nary(x_ == 3 || y_ == 5)); } TEST_F(SymbolicFormulaTest, Or3) { // Flattening EXPECT_PRED2(FormulaEqual, f1_ || f2_ || f3_ || f4_, f1_ || f2_ || f3_ || f4_); EXPECT_PRED2(FormulaEqual, (f1_ || f2_) || (f3_ || f4_), f1_ || f2_ || f3_ || f4_); EXPECT_PRED2(FormulaEqual, f1_ || (f2_ || f3_) || f4_, f1_ || f2_ || f3_ || f4_); EXPECT_PRED2(FormulaEqual, f1_ || ((f2_ || f3_) || f4_), f1_ || f2_ || f3_ || f4_); // Remove duplicate EXPECT_PRED2(FormulaEqual, f1_ || f2_ || f1_, f1_ || f2_); } TEST_F(SymbolicFormulaTest, Or4) { // Simplification: f || f => f. for (const Formula& f : {b1_, b2_, tt_, ff_, f1_, f2_, f3_, f4_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_}) { EXPECT_PRED2(FormulaEqual, f || f, f); } } TEST_F(SymbolicFormulaTest, Or5) { // Flatten and removing duplicates. This is a disjunctive version of the // example mentioned in symbolic_formula.h file: // (f1 || f2) || f1 => f1 || f2 // f1 || (f2 || f1) => f1 || f2 EXPECT_PRED2(FormulaEqual, (f1_ || f2_) || f1_, f1_ || f2_); EXPECT_PRED2(FormulaEqual, f1_ || (f2_ || f1_), f1_ || f2_); EXPECT_PRED2(FormulaEqual, (f1_ || f2_) || f1_, f1_ || (f2_ || f1_)); } TEST_F(SymbolicFormulaTest, OrWithBooleanVariableOperator) { // Checks if operator|| works with Boolean variables as expected. const Formula f1{var_b1_ || var_b2_}; ASSERT_TRUE(is_disjunction(f1)); EXPECT_TRUE(get_operands(f1).contains(b1_)); EXPECT_TRUE(get_operands(f1).contains(b2_)); const Formula f2{var_b1_ || (y_ > 0)}; ASSERT_TRUE(is_disjunction(f2)); EXPECT_TRUE(get_operands(f2).contains(b1_)); const Formula f3{(x_ > 0) || var_b2_}; ASSERT_TRUE(is_disjunction(f3)); EXPECT_TRUE(get_operands(f3).contains(b2_)); } TEST_F(SymbolicFormulaTest, OrWithBooleanVariableEvaluate) { // Checks the evaluations of disjunctive formulas with Boolean variables. const Formula f{b1_ || b2_}; const Environment env1{{var_b1_, true}, {var_b2_, true}}; const Environment env2{{var_b1_, true}, {var_b2_, false}}; const Environment env3{{var_b1_, false}, {var_b2_, true}}; const Environment env4{{var_b1_, false}, {var_b2_, false}}; EXPECT_TRUE(f.Evaluate(env1)); EXPECT_TRUE(f.Evaluate(env2)); EXPECT_TRUE(f.Evaluate(env3)); EXPECT_FALSE(f.Evaluate(env4)); } TEST_F(SymbolicFormulaTest, Not1) { EXPECT_PRED2(FormulaEqual, ff_, !tt_); EXPECT_PRED2(FormulaEqual, tt_, !ff_); EXPECT_PRED2(FormulaEqual, tt_, !(!tt_)); EXPECT_PRED2(FormulaEqual, ff_, !(!ff_)); EXPECT_PRED2(FormulaEqual, !(x_ == 5), !(x_ == 5)); EXPECT_PRED2(FormulaNotEqual, !(x_ == 5), !(x_ == 6)); } TEST_F(SymbolicFormulaTest, Not2) { EXPECT_EQ(not_f_or_.Evaluate(env1_), !((1 + 1 > 0) || (1 * 1 < 5))); EXPECT_EQ(not_f_or_.Evaluate(env2_), !((3 + 4 > 0) || (3 * 4 < 5))); EXPECT_EQ(not_f_or_.Evaluate(env3_), !((-2 + -5 > 0) || (-2 * -5 < 5))); EXPECT_EQ(not_f_or_.Evaluate(env4_), !((-1 + -1 > 0) || (-1 * -1 < 5))); EXPECT_EQ((!(x_ == 5)).to_string(), "!((x == 5))"); EXPECT_TRUE(is_negation(!(x_ == 5))); } // Tests if `!(!f)` is simplified into `f` for all formulas in // SymbolicFormulaTest. TEST_F(SymbolicFormulaTest, DoubleNegationSimplification) { const vector<Formula> collection{b1_, b2_, tt_, ff_, f1_, f2_, f3_, f4_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_}; vector<Formula> negated_collection{collection.size()}; transform(collection.cbegin(), collection.cend(), negated_collection.begin(), [](const Formula& f) { return !f; }); for (size_t i = 0; i < collection.size(); ++i) { EXPECT_PRED2(FormulaEqual, collection[i], !(negated_collection[i])); } } TEST_F(SymbolicFormulaTest, NotWithBooleanVariableOperator) { // Checks if operator! works with Boolean variables as expected. const Formula f{!var_b1_}; EXPECT_TRUE(is_negation(f)); ASSERT_TRUE(is_variable(get_operand(f))); EXPECT_PRED2(VarEqual, get_variable(get_operand(f)), var_b1_); } TEST_F(SymbolicFormulaTest, NotWithBooleanVariableEvaluate) { // Checks the evaluations of negation formulas with a Boolean variable. const Formula f{!b1_}; const Environment env1{{var_b1_, true}}; const Environment env2{{var_b1_, false}}; EXPECT_FALSE(f.Evaluate(env1)); EXPECT_TRUE(f.Evaluate(env2)); } TEST_F(SymbolicFormulaTest, Forall1) { const Formula f1{forall({var_x_, var_y_}, x_ == y_)}; const Formula f2{forall({var_x_, var_y_}, x_ == y_)}; const Formula f3{forall({var_x_, var_y_}, x_ > y_)}; EXPECT_PRED2(FormulaEqual, f1, f2); EXPECT_PRED2(FormulaNotEqual, f1, f3); EXPECT_PRED2(FormulaNotEqual, f2, f3); EXPECT_TRUE(all_of({f1, f2, f3}, is_forall)); } TEST_F(SymbolicFormulaTest, Forall2) { const Formula f1{forall({var_x_, var_y_}, x_ == y_)}; EXPECT_THROW(f1.Evaluate(), runtime_error); } TEST_F(SymbolicFormulaTest, PsdException) { auto non_square = Eigen::Matrix<Expression, 2, 3>::Zero().eval(); EXPECT_THROW(positive_semidefinite(non_square), runtime_error); Eigen::Matrix<Expression, 3, 3> m; // clang-format off m << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0; // clang-format on // m is not symmetric. EXPECT_THROW(positive_semidefinite(m), runtime_error); // positive_semidefinite only takes Eigen::Lower and Eigen::Upper. EXPECT_THROW(positive_semidefinite(m, Eigen::UnitDiag), runtime_error); EXPECT_THROW(positive_semidefinite(m, Eigen::ZeroDiag), runtime_error); EXPECT_THROW(positive_semidefinite(m, Eigen::UnitLower), runtime_error); EXPECT_THROW(positive_semidefinite(m, Eigen::UnitUpper), runtime_error); EXPECT_THROW(positive_semidefinite(m, Eigen::StrictlyLower), runtime_error); EXPECT_THROW(positive_semidefinite(m, Eigen::StrictlyUpper), runtime_error); EXPECT_THROW(positive_semidefinite(m, Eigen::SelfAdjoint), runtime_error); EXPECT_THROW(positive_semidefinite(m, Eigen::Symmetric), runtime_error); } TEST_F(SymbolicFormulaTest, PsdGetFreeVariables) { const Variables vars1{f_psd_static_2x2_.GetFreeVariables()}; EXPECT_EQ(vars1.size(), 2); EXPECT_TRUE(vars1.include(var_x_)); EXPECT_TRUE(vars1.include(var_y_)); const Variables vars2{f_psd_dynamic_2x2_.GetFreeVariables()}; EXPECT_EQ(vars2.size(), 2); EXPECT_TRUE(vars2.include(var_x_)); EXPECT_TRUE(vars2.include(var_y_)); const Variables vars3{f_psd_static_3x3_.GetFreeVariables()}; EXPECT_EQ(vars3.size(), 3); EXPECT_TRUE(vars3.include(var_x_)); EXPECT_TRUE(vars3.include(var_y_)); EXPECT_TRUE(vars3.include(var_z_)); } TEST_F(SymbolicFormulaTest, PsdEqualTo) { EXPECT_TRUE(f_psd_static_2x2_.EqualTo(f_psd_static_2x2_)); EXPECT_FALSE(f_psd_static_2x2_.EqualTo(f_psd_dynamic_2x2_)); EXPECT_FALSE(f_psd_static_2x2_.EqualTo(f_psd_static_3x3_)); EXPECT_FALSE(f_psd_dynamic_2x2_.EqualTo(f_psd_static_2x2_)); EXPECT_TRUE(f_psd_dynamic_2x2_.EqualTo(f_psd_dynamic_2x2_)); EXPECT_FALSE(f_psd_dynamic_2x2_.EqualTo(f_psd_static_3x3_)); EXPECT_FALSE(f_psd_static_3x3_.EqualTo(f_psd_static_2x2_)); EXPECT_FALSE(f_psd_static_3x3_.EqualTo(f_psd_dynamic_2x2_)); EXPECT_TRUE(f_psd_static_3x3_.EqualTo(f_psd_static_3x3_)); } TEST_F(SymbolicFormulaTest, PsdEvaluate) { EXPECT_THROW(f_psd_static_2x2_.Evaluate(), runtime_error); EXPECT_THROW(f_psd_dynamic_2x2_.Evaluate(), runtime_error); EXPECT_THROW(f_psd_static_3x3_.Evaluate(), runtime_error); } TEST_F(SymbolicFormulaTest, GetFreeVariables) { const Formula f1{x_ + y_ > 0}; const Formula f2{y_ * z_ < 5}; const Formula f_or{f1 || f2}; const Formula f_forall{forall({var_x_, var_y_}, f_or)}; const Variables vars1{f1.GetFreeVariables()}; // {x_, y_} EXPECT_EQ(vars1.size(), 2u); EXPECT_TRUE(vars1.include(var_x_)); EXPECT_TRUE(vars1.include(var_y_)); const Variables vars2{f2.GetFreeVariables()}; // {y_, z_} EXPECT_EQ(vars2.size(), 2u); EXPECT_TRUE(vars2.include(var_y_)); EXPECT_TRUE(vars2.include(var_z_)); const Variables vars3{f_or.GetFreeVariables()}; // {x_, y_, z_} EXPECT_EQ(vars3.size(), 3u); EXPECT_TRUE(vars3.include(var_x_)); EXPECT_TRUE(vars3.include(var_y_)); EXPECT_TRUE(vars3.include(var_z_)); const Variables vars4{f_forall.GetFreeVariables()}; // {z_} EXPECT_EQ(vars4.size(), 1u); EXPECT_TRUE(vars4.include(var_z_)); const Variables vars5{(!f1).GetFreeVariables()}; // {x_, y_} EXPECT_EQ(vars5.size(), 2u); EXPECT_TRUE(vars5.include(var_x_)); EXPECT_TRUE(vars5.include(var_y_)); } TEST_F(SymbolicFormulaTest, ToString) { EXPECT_EQ(f1_.to_string(), "((x + y) > 0)"); EXPECT_EQ(f2_.to_string(), "((x * y) < 5)"); EXPECT_EQ(f_or_.to_string(), "(((x + y) > 0) or ((x * y) < 5))"); EXPECT_EQ(f_forall_.to_string(), "forall({x, y}. (((x + y) > 0) or ((x * y) < 5)))"); EXPECT_EQ(f_isnan_.to_string(), "isnan(NaN)"); } TEST_F(SymbolicFormulaTest, IsTrue) { EXPECT_TRUE(is_true(tt_)); EXPECT_FALSE(any_of({ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_true)); } TEST_F(SymbolicFormulaTest, IsFalse) { EXPECT_TRUE(is_false(ff_)); EXPECT_FALSE(any_of({tt_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_false)); } TEST_F(SymbolicFormulaTest, IsEqualTo) { EXPECT_TRUE(is_equal_to(f_eq_)); EXPECT_FALSE(any_of({tt_, ff_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_equal_to)); } TEST_F(SymbolicFormulaTest, IsNotEqualTo) { EXPECT_TRUE(is_not_equal_to(f_neq_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_not_equal_to)); } TEST_F(SymbolicFormulaTest, IsLessThan) { EXPECT_TRUE(is_less_than(f_lt_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_less_than)); } TEST_F(SymbolicFormulaTest, IsLessThanOrEqualTo) { EXPECT_TRUE(is_less_than_or_equal_to(f_lte_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_less_than_or_equal_to)); } TEST_F(SymbolicFormulaTest, IsGreaterThan) { EXPECT_TRUE(is_greater_than(f_gt_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_greater_than)); } TEST_F(SymbolicFormulaTest, IsGreaterThanOrEqualTo) { EXPECT_TRUE(is_greater_than_or_equal_to(f_gte_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_greater_than_or_equal_to)); } TEST_F(SymbolicFormulaTest, IsRelational) { EXPECT_TRUE( all_of({f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_}, is_relational)); EXPECT_FALSE( any_of({tt_, ff_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_relational)); } TEST_F(SymbolicFormulaTest, IsConjunction) { EXPECT_TRUE(is_conjunction(f_and_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_conjunction)); } TEST_F(SymbolicFormulaTest, IsDisjunction) { EXPECT_TRUE(is_disjunction(f_or_)); EXPECT_FALSE( any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_disjunction)); } TEST_F(SymbolicFormulaTest, IsNary) { EXPECT_TRUE(all_of({f_and_, f_or_}, is_nary)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_nary)); } TEST_F(SymbolicFormulaTest, IsNegation) { EXPECT_TRUE(is_negation(not_f_or_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_negation)); } TEST_F(SymbolicFormulaTest, IsForall) { EXPECT_TRUE(is_forall(f_forall_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_forall)); } TEST_F(SymbolicFormulaTest, IsIsnan) { EXPECT_TRUE(is_isnan(f_isnan_)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_isnan)); EXPECT_PRED2(ExprEqual, get_unary_expression(isnan(x_)), x_); } TEST_F(SymbolicFormulaTest, IsPositiveSemidefinite) { EXPECT_TRUE(all_of({f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}, is_positive_semidefinite)); EXPECT_FALSE(any_of({tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_}, is_positive_semidefinite)); } TEST_F(SymbolicFormulaTest, GetLhsExpression) { EXPECT_PRED2(ExprEqual, get_lhs_expression(e1_ == 0.0), e1_); EXPECT_PRED2(ExprEqual, get_lhs_expression(e1_ != 0.0), e1_); EXPECT_PRED2(ExprEqual, get_lhs_expression(e1_ < 0.0), e1_); EXPECT_PRED2(ExprEqual, get_lhs_expression(e1_ <= 0.0), e1_); EXPECT_PRED2(ExprEqual, get_lhs_expression(e1_ > 0.0), e1_); EXPECT_PRED2(ExprEqual, get_lhs_expression(e1_ >= 0.0), e1_); } TEST_F(SymbolicFormulaTest, GetRhsExpression) { EXPECT_PRED2(ExprEqual, get_rhs_expression(0.0 == e1_), e1_); EXPECT_PRED2(ExprEqual, get_rhs_expression(0.0 != e1_), e1_); EXPECT_PRED2(ExprEqual, get_rhs_expression(0.0 < e1_), e1_); EXPECT_PRED2(ExprEqual, get_rhs_expression(0.0 <= e1_), e1_); EXPECT_PRED2(ExprEqual, get_rhs_expression(0.0 > e1_), e1_); EXPECT_PRED2(ExprEqual, get_rhs_expression(0.0 >= e1_), e1_); } TEST_F(SymbolicFormulaTest, GetOperandsConjunction) { const set<Formula> formulas{get_operands(f1_ && f2_ && f3_ && f4_)}; EXPECT_EQ(formulas.size(), 4u); EXPECT_TRUE(formulas.contains(f1_)); EXPECT_TRUE(formulas.contains(f2_)); EXPECT_TRUE(formulas.contains(f3_)); EXPECT_TRUE(formulas.contains(f4_)); } TEST_F(SymbolicFormulaTest, GetOperandsDisjunction) { const set<Formula> formulas{get_operands(f1_ || f2_ || f3_ || f4_)}; EXPECT_EQ(formulas.size(), 4u); EXPECT_TRUE(formulas.contains(f1_)); EXPECT_TRUE(formulas.contains(f2_)); EXPECT_TRUE(formulas.contains(f3_)); EXPECT_TRUE(formulas.contains(f4_)); } TEST_F(SymbolicFormulaTest, GetOperand) { EXPECT_PRED2(FormulaEqual, get_operand(!f1_), f1_); } TEST_F(SymbolicFormulaTest, GetQuantifiedVariables) { const Variables vars{var_x_, var_y_}; const Formula f{x_ + y_ > z_}; const Formula f_forall{forall(vars, f)}; EXPECT_EQ(get_quantified_variables(f_forall), vars); } TEST_F(SymbolicFormulaTest, GetQuantifiedFormula) { const Variables vars{var_x_, var_y_}; const Formula f{x_ + y_ > z_}; const Formula f_forall{forall(vars, f)}; EXPECT_PRED2(FormulaEqual, get_quantified_formula(f_forall), f); } TEST_F(SymbolicFormulaTest, GetMatrixInPSD1) { const auto m1 = get_matrix_in_positive_semidefinite(f_psd_static_2x2_); EXPECT_TRUE(CheckStructuralEquality(m_static_2x2_, m1)); EXPECT_FALSE(m1.IsRowMajor); // m1 is column-major. const auto m2 = get_matrix_in_positive_semidefinite(f_psd_dynamic_2x2_); EXPECT_TRUE(CheckStructuralEquality(m_dynamic_2x2_, m2)); EXPECT_FALSE(m2.IsRowMajor); // m2 is column-major. const auto m3 = get_matrix_in_positive_semidefinite(f_psd_static_3x3_); EXPECT_TRUE(CheckStructuralEquality(m_static_3x3_, m3)); EXPECT_FALSE(m3.IsRowMajor); // m3 is column-major. } TEST_F(SymbolicFormulaTest, GetMatrixInPsdNonSymmetricStatic) { MatrixX<Expression> m(3, 3); // clang-format off m << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0; // clang-format on MatrixX<Expression> sym_from_lower(3, 3); // clang-format off sym_from_lower << 1.0, 4.0, 7.0, 4.0, 5.0, 8.0, 7.0, 8.0, 9.0; // clang-format on MatrixX<Expression> sym_from_upper(3, 3); // clang-format off sym_from_upper << 1.0, 2.0, 3.0, 2.0, 5.0, 6.0, 3.0, 6.0, 9.0; // clang-format on EXPECT_TRUE( CheckStructuralEquality(get_matrix_in_positive_semidefinite( positive_semidefinite(m, Eigen::Lower)), sym_from_lower)); EXPECT_TRUE(CheckStructuralEquality( get_matrix_in_positive_semidefinite( positive_semidefinite(m.triangularView<Eigen::Lower>())), sym_from_lower)); EXPECT_TRUE( CheckStructuralEquality(get_matrix_in_positive_semidefinite( positive_semidefinite(m, Eigen::Upper)), sym_from_upper)); EXPECT_TRUE(CheckStructuralEquality( get_matrix_in_positive_semidefinite( positive_semidefinite(m.triangularView<Eigen::Upper>())), sym_from_upper)); } TEST_F(SymbolicFormulaTest, GetMatrixInPsdNonSymmetricDynamic) { Eigen::Matrix<Expression, 3, 3> m; // clang-format off m << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0; // clang-format on MatrixX<Expression> sym_from_lower(3, 3); // clang-format off sym_from_lower << 1.0, 4.0, 7.0, 4.0, 5.0, 8.0, 7.0, 8.0, 9.0; // clang-format on MatrixX<Expression> sym_from_upper(3, 3); // clang-format off sym_from_upper << 1.0, 2.0, 3.0, 2.0, 5.0, 6.0, 3.0, 6.0, 9.0; // clang-format on EXPECT_TRUE( CheckStructuralEquality(get_matrix_in_positive_semidefinite( positive_semidefinite(m, Eigen::Lower)), sym_from_lower)); EXPECT_TRUE(CheckStructuralEquality( get_matrix_in_positive_semidefinite( positive_semidefinite(m.triangularView<Eigen::Lower>())), sym_from_lower)); EXPECT_TRUE( CheckStructuralEquality(get_matrix_in_positive_semidefinite( positive_semidefinite(m, Eigen::Upper)), sym_from_upper)); EXPECT_TRUE(CheckStructuralEquality( get_matrix_in_positive_semidefinite( positive_semidefinite(m.triangularView<Eigen::Upper>())), sym_from_upper)); } TEST_F(SymbolicFormulaTest, Isinf) { // Checks the std::isinf and symbolic isinf agree on non-NaN values. const double inf{numeric_limits<double>::infinity()}; EXPECT_EQ(std::isinf(inf), isinf(Expression(inf)).Evaluate()); EXPECT_EQ(std::isinf(3e18), isinf(Expression(3e18)).Evaluate()); EXPECT_EQ(std::isinf(3.0), isinf(Expression(3.0)).Evaluate()); EXPECT_EQ(std::isinf(0.0), isinf(Expression(0.0)).Evaluate()); EXPECT_EQ(std::isinf(-3.0), isinf(Expression(-3.0)).Evaluate()); EXPECT_EQ(std::isinf(-3e18), isinf(Expression(-3e18)).Evaluate()); EXPECT_EQ(std::isinf(-inf), isinf(Expression(-inf)).Evaluate()); // Note that constructing isinf with an expression including NaN does *not* // throw. DRAKE_EXPECT_NO_THROW(isinf(Expression::NaN())); // For NaN, symbolic::isinf will throw an exception when evaluated while // std::isfinite returns false. EXPECT_THROW(isinf(Expression::NaN()).Evaluate(), std::runtime_error); } TEST_F(SymbolicFormulaTest, Isfinite) { // Checks the std::isfinite and symbolic isfinte agree on non-NaN values. const double inf{numeric_limits<double>::infinity()}; EXPECT_EQ(std::isfinite(inf), isfinite(Expression(inf)).Evaluate()); EXPECT_EQ(std::isfinite(3e18), isfinite(Expression(3e18)).Evaluate()); EXPECT_EQ(std::isfinite(3.0), isfinite(Expression(3.0)).Evaluate()); EXPECT_EQ(std::isfinite(0.0), isfinite(Expression(0.0)).Evaluate()); EXPECT_EQ(std::isfinite(-3.0), isfinite(Expression(-3.0)).Evaluate()); EXPECT_EQ(std::isfinite(-3e18), isfinite(Expression(-3e18)).Evaluate()); EXPECT_EQ(std::isfinite(-inf), isfinite(Expression(-inf)).Evaluate()); // Note that constructing isfinite with an expression including NaN does *not* // throw. DRAKE_EXPECT_NO_THROW(isfinite(Expression::NaN())); // For NaN, symbolic::isfinite will throw an exception when evaluated while // std::isfinite returns false. EXPECT_THROW(isfinite(Expression::NaN()).Evaluate(), std::runtime_error); } // Confirm that formulas compile (and pass) Drake's assert-like checks. TEST_F(SymbolicFormulaTest, DrakeAssert) { Formula mutable_f{x_ > 0}; DRAKE_ASSERT(f1_); DRAKE_ASSERT(f2_); DRAKE_ASSERT(f_and_); DRAKE_ASSERT(f_or_); DRAKE_ASSERT(not_f_or_); DRAKE_ASSERT(f_forall_); DRAKE_ASSERT(f_isnan_); DRAKE_ASSERT(mutable_f); DRAKE_DEMAND(f1_); DRAKE_DEMAND(f2_); DRAKE_DEMAND(f_and_); DRAKE_DEMAND(f_or_); DRAKE_DEMAND(not_f_or_); DRAKE_DEMAND(f_forall_); DRAKE_DEMAND(f_isnan_); DRAKE_DEMAND(mutable_f); DRAKE_THROW_UNLESS(f1_); DRAKE_THROW_UNLESS(f2_); DRAKE_THROW_UNLESS(f_and_); DRAKE_THROW_UNLESS(f_or_); DRAKE_THROW_UNLESS(not_f_or_); DRAKE_THROW_UNLESS(f_forall_); DRAKE_THROW_UNLESS(f_isnan_); DRAKE_THROW_UNLESS(mutable_f); } // Tests that default constructor and EIGEN_INITIALIZE_MATRICES_BY_ZERO // constructor both create the same value. GTEST_TEST(FormulaTest, DefaultConstructors) { const Formula f_default; const Formula f_zero(0); EXPECT_TRUE(is_false(f_default)); EXPECT_TRUE(is_false(f_zero)); } // Tests the `bool`-literal constructor. GTEST_TEST(FormulaTest, CxxBoolLiteralConstructor) { const Formula f_true(true); const Formula f_false(false); EXPECT_TRUE(is_true(f_true)); EXPECT_TRUE(is_false(f_false)); } // Tests the `bool`-variable constructor. GTEST_TEST(FormulaTest, CxxBoolVariableConstructor) { const bool true_variable = true; const bool false_variable = false; const Formula f_true(true_variable); const Formula f_false(false_variable); EXPECT_TRUE(is_true(f_true)); EXPECT_TRUE(is_false(f_false)); } // This test checks whether symbolic::Formula is compatible with // std::unordered_set. GTEST_TEST(FormulaTest, CompatibleWithUnorderedSet) { unordered_set<Formula> uset; uset.emplace(Formula::True()); uset.emplace(Formula::True()); uset.emplace(Formula::False()); uset.emplace(Formula::False()); } // This test checks whether symbolic::Formula is compatible with // std::unordered_map. GTEST_TEST(FormulaTest, CompatibleWithUnorderedMap) { unordered_map<Formula, Formula> umap; umap.emplace(Formula::True(), Formula::False()); umap.emplace(Formula::False(), Formula::True()); } // This test checks whether symbolic::Formula is compatible with // std::set. GTEST_TEST(FormulaTest, CompatibleWithSet) { set<Formula> set; set.emplace(Formula::True()); set.emplace(Formula::True()); set.emplace(Formula::False()); set.emplace(Formula::False()); } // This test checks whether symbolic::Formula is compatible with // std::map. GTEST_TEST(FormulaTest, CompatibleWithMap) { map<Formula, Formula> map; map.emplace(Formula::True(), Formula::False()); } // This test checks whether symbolic::Formula is compatible with // std::vector. GTEST_TEST(FormulaTest, CompatibleWithVector) { vector<Formula> vec; vec.push_back(Formula::True()); } GTEST_TEST(FormulaTest, NoThrowMoveConstructible) { // Make sure that symbolic::Formula is nothrow move-constructible so that // it can be moved (not copied) when a STL container (i.e. vector<Formula>) // is resized. EXPECT_TRUE(std::is_nothrow_move_constructible_v<Formula>); } // Checks for compatibility with a memcpy primitive move operation. // See https://github.com/RobotLocomotion/drake/issues/5974. TEST_F(SymbolicFormulaTest, MemcpyKeepsFomrulaIntact) { for (const Formula& formula : {tt_, ff_, f_eq_, f_neq_, f_lt_, f_lte_, f_gt_, f_gte_, f_and_, f_or_, not_f_or_, f_forall_, f_isnan_, f_psd_static_2x2_, f_psd_dynamic_2x2_, f_psd_static_3x3_}) { EXPECT_TRUE(IsMemcpyMovable(formula)); } } // This function checks if the following commute diagram works for given a // symbolic formula `f`, a symbolic environment `env`, and a `random generator`. // // Substitute Random Variables // +---------------------+ with Sampled Values +--------------------+ // | Formula | | Formula | // |with Random Variables+---------------------------->+w/o Random Variables| // +----------+----------+ +---------+----------+ // | | // v v // Evaluate Evaluate // with a Random Generator w/o a Random Generator // + + // | | // v v // +----------+----------+ +---------+----------+ // | bool value +----------- == ------------+ bool value | // +---------------------+ +--------------------+ ::testing::AssertionResult CheckFormulaWithRandomVariables( const Formula& f, const Environment& env, RandomGenerator* const random_generator) { RandomGenerator random_generator_copy(*random_generator); const bool b1{f.Evaluate(env, random_generator)}; const Environment env_extended{PopulateRandomVariables( env, f.GetFreeVariables(), &random_generator_copy)}; const bool b2{f.Evaluate(env_extended, nullptr)}; if (b1 == b2) { return ::testing::AssertionSuccess(); } else { return ::testing::AssertionFailure() << "Different evaluation results:\n" << "f = " << f << "\n" << "env = " << env << "\n" << "env_extended = " << env_extended << "\n" << "b1 = " << b1 << " and b2 = " << b2; } } TEST_F(SymbolicFormulaTest, EvaluateFormulasIncludingRandomVariables) { const Variable uni1{"uniform1", Variable::Type::RANDOM_UNIFORM}; const Variable uni2{"uniform2", Variable::Type::RANDOM_UNIFORM}; const Variable gau1{"gaussian1", Variable::Type::RANDOM_GAUSSIAN}; const Variable gau2{"gaussian2", Variable::Type::RANDOM_GAUSSIAN}; const Variable exp1{"exponential1", Variable::Type::RANDOM_EXPONENTIAL}; const Variable exp2{"exponential2", Variable::Type::RANDOM_EXPONENTIAL}; const vector<Formula> formulas{ uni1 > uni2, gau1 < gau2, exp1 == exp2, x_ * sin(uni1) >= cos(uni1) * tan(uni1) + y_, exp1 * pow(abs(x_), exp1) <= exp2, x_ / (1 + exp(abs(gau1 * gau2))) != y_ * pow(exp1, 4 + y_), x_ * uni1 + y_ * uni1 + x_ * gau1 == y_ * gau1 + x_ * exp1 + y_ * exp1, }; const vector<Environment> environments{ {{{var_x_, -1.0}, {var_y_, 3.0}}}, {{{var_x_, 1.0}, {var_y_, 1.0}}}, {{{var_x_, 2.0}, {var_y_, 1.0}}}, {{{var_x_, 2.0}, {var_y_, -2.0}}}, }; RandomGenerator generator{}; for (const Formula& f : formulas) { for (const Environment& env : environments) { EXPECT_TRUE(CheckFormulaWithRandomVariables(f, env, &generator)); } } } } // namespace } // namespace kcov339_avoidance_magic } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/ldlt_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/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" namespace drake { namespace symbolic { namespace test { namespace { GTEST_TEST(SymbolicLdlt, DynamicSize) { // An arbitrary positive-definite matrix. MatrixX<double> input_d(3, 3); // clang-format off input_d << 81, -9, 63, -9 , 2, -5, 63, -5, 69; // clang-format on const auto ldlt_d = input_d.ldlt(); // Perform LDLT decomposition, with Scalar = Expression. const MatrixX<Expression> input_e = input_d.template cast<Expression>(); const auto ldlt_e = input_e.ldlt(); // Check that Expression results match double results. EXPECT_TRUE(CompareMatrices(MatrixX<Expression>(ldlt_e.matrixL()), MatrixX<double>(ldlt_d.matrixL()))); EXPECT_TRUE(CompareMatrices(MatrixX<Expression>(ldlt_e.matrixU()), MatrixX<double>(ldlt_d.matrixU()))); EXPECT_TRUE(CompareMatrices(ldlt_e.transpositionsP().indices(), ldlt_d.transpositionsP().indices())); EXPECT_TRUE(CompareMatrices(ldlt_e.vectorD(), ldlt_d.vectorD())); EXPECT_TRUE(ldlt_e.isPositive()); EXPECT_FALSE(ldlt_e.isNegative()); EXPECT_EQ(ldlt_e.info(), ldlt_d.info()); } GTEST_TEST(SymbolicLdlt, Exception) { MatrixX<Expression> dut(1, 1); dut(0, 0) = 0; DRAKE_EXPECT_NO_THROW(dut.ldlt()); dut(0, 0) = Variable("a(0,0)"); EXPECT_THROW(dut.ldlt(), std::exception); } GTEST_TEST(SymbolicLdlt, SizeUpTo6) { drake::MatrixUpTo6<Expression> dut(1, 1); dut.setZero(); DRAKE_EXPECT_NO_THROW(dut.ldlt()); } } // namespace } // namespace test } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/expression_matrix_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/fmt_eigen.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { namespace symbolic { namespace { using test::ExprEqual; using test::FormulaEqual; class SymbolicExpressionMatrixTest : public ::testing::Test { protected: const Variable var_a_{"a"}; const Variable var_x_{"x"}; const Variable var_y_{"y"}; const Variable var_z_{"z"}; const Variable var_w_{"w"}; const Expression a_{var_a_}; const Expression x_{var_x_}; const Expression y_{var_y_}; const Expression z_{var_z_}; const Expression w_{var_w_}; 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::Matrix<Expression, 2, 2, Eigen::DontAlign> matrix_expr_1_; Eigen::Matrix<Expression, 2, 2, Eigen::DontAlign> matrix_expr_2_; Eigen::Matrix<Variable, 2, 2, Eigen::DontAlign> matrix_var_1_; Eigen::Matrix<Variable, 2, 2, Eigen::DontAlign> matrix_var_2_; Eigen::Matrix<double, 2, 2, Eigen::DontAlign> matrix_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] matrix_expr_1_ << x_, y_, z_, x_; matrix_expr_2_ << z_, x_, y_, z_; matrix_var_1_ << var_x_, var_y_, var_z_, var_x_; matrix_var_2_ << var_y_, var_z_, var_x_, var_x_; matrix_double_ << 1.0, 2.0, 3.0, 4.0; // clang-format on } }; TEST_F(SymbolicExpressionMatrixTest, EigenAdd) { auto const M(A_ + A_); Eigen::Matrix<Expression, 3, 2> M_expected; // clang-format off M_expected << (x_ + x_), (one_ + one_), (y_ + y_), (neg_one_ + neg_one_), (z_ + z_), (pi_ + pi_); // clang-format on EXPECT_EQ(M, M_expected); } TEST_F(SymbolicExpressionMatrixTest, GetVariableVector) { const Vector3<Expression> evec(x_, y_, z_); const VectorX<Variable> vec = GetVariableVector(evec); EXPECT_EQ(vec(0), x_); EXPECT_EQ(vec(1), y_); EXPECT_EQ(vec(2), z_); EXPECT_THROW(GetVariableVector(Vector3<Expression>(x_, y_, x_ + y_)), std::logic_error); } TEST_F(SymbolicExpressionMatrixTest, EigenSub1) { auto const M(A_ - A_); Eigen::Matrix<Expression, 3, 2> M_expected; EXPECT_EQ(M, M_expected); // should be all zero. } TEST_F(SymbolicExpressionMatrixTest, EigenSub2) { auto const M(A_ - C_); Eigen::Matrix<Expression, 3, 2> M_expected; // clang-format off M_expected << (x_ - z_), (one_ - two_), (y_ - x_), (neg_one_ - e_), (z_ - y_), (pi_ - pi_); // clang-format on EXPECT_EQ(M, M_expected); // should be all zero. } TEST_F(SymbolicExpressionMatrixTest, EigenMul1) { auto const M(A_ * B_); Eigen::Matrix<Expression, 3, 3> M_expected; // clang-format off M_expected << (x_ * x_ + e_), (x_ * y_ + pi_), (x_ * z_ + two_), (y_ * x_ + -e_), (y_ * y_ + - pi_), (y_ * z_ + - two_), (z_ * x_ + pi_ * e_), (z_ * y_ + pi_ * pi_), (z_ * z_ + pi_ * two_); // clang-format on EXPECT_EQ(M, M_expected); } TEST_F(SymbolicExpressionMatrixTest, EigenMul2) { auto const M(B_ * A_); Eigen::Matrix<Expression, 2, 2> M_expected; // clang-format off M_expected << (x_ * x_ + (y_ * y_ + z_ * z_)), (x_ + (-y_ + z_ * pi_)), (e_ * x_ + (pi_ * y_ + two_ * z_)), (e_ * one_ + pi_ * - one_ + two_ * pi_); // clang-format on EXPECT_EQ(M, M_expected); } TEST_F(SymbolicExpressionMatrixTest, EigenMul3) { auto const M(2.0 * A_); Eigen::Matrix<Expression, 3, 2> M_expected; // clang-format off M_expected << (2 * x_), (2 * one_), (2 * y_), (2 * neg_one_), (2 * z_), (2 * pi_); // clang-format on EXPECT_EQ(M, M_expected); } TEST_F(SymbolicExpressionMatrixTest, EigenMul4) { auto const M(A_ * 2.0); Eigen::Matrix<Expression, 3, 2> M_expected; // clang-format off M_expected << (x_ * 2), (one_ * 2), (y_ * 2), (neg_one_ * 2), (z_ * 2), (pi_ * 2); // clang-format on EXPECT_EQ(M, M_expected); } TEST_F(SymbolicExpressionMatrixTest, EigenMul5) { auto const M(matrix_var_1_ * matrix_var_2_); Eigen::Matrix<Expression, 2, 2> M_expected; // clang-format off M_expected << x_ * y_ + x_ * y_, x_ * y_ + x_ * z_, y_ * z_ + x_ * x_, x_ * x_ + z_ * z_; // clang-format on EXPECT_TRUE(CheckStructuralEquality(M, M_expected)) << fmt::to_string(fmt_eigen(M)); } TEST_F(SymbolicExpressionMatrixTest, EigenDot) { const auto vec = Vector3<Expression>(x_, y_, z_); const Expression expected = (x_ * x_) + (y_ * y_) + (z_ * z_); const Expression dot1 = vec.dot(vec); const Expression dot2 = vec.transpose() * vec; const Eigen::Matrix<Expression, 1, 1> dot3 = vec.transpose() * vec; EXPECT_TRUE(ExprEqual(dot1, expected)); EXPECT_TRUE(ExprEqual(dot2, expected)); EXPECT_TRUE(ExprEqual(dot3(0), expected)); } TEST_F(SymbolicExpressionMatrixTest, EigenDiv) { auto const M(A_ / 2.0); Eigen::Matrix<Expression, 3, 2> M_expected; // clang-format off M_expected << (x_ / 2), (one_ / 2), (y_ / 2), (neg_one_ / 2), (z_ / 2), (pi_ / 2); // clang-format on EXPECT_EQ(M, M_expected); } TEST_F(SymbolicExpressionMatrixTest, CheckStructuralEquality) { EXPECT_TRUE(CheckStructuralEquality(A_, A_)); EXPECT_TRUE(CheckStructuralEquality(B_, B_)); EXPECT_TRUE(CheckStructuralEquality(C_, C_)); EXPECT_FALSE(CheckStructuralEquality(A_, C_)); EXPECT_FALSE(CheckStructuralEquality(B_ * A_, B_ * C_)); } // Checks the following two formulas are identical: // - m1 == m2 // - ⋀ᵢⱼ (m1.array() == m2.array()) bool CheckMatrixOperatorEq(const MatrixX<Expression>& m1, const MatrixX<Expression>& m2) { const Formula f1{m1 == m2}; const Formula f2{(m1.array() == m2.array()).redux(internal::logic_and)}; return f1.EqualTo(f2); } // Checks the following two formulas are identical: // - m1 != m2 // - ⋁ᵢⱼ (m1.array() != m2.array()) bool CheckMatrixOperatorNeq(const MatrixX<Expression>& m1, const MatrixX<Expression>& m2) { const Formula f1{m1 != m2}; const Formula f2{(m1.array() != m2.array()).redux(internal::logic_or)}; return f1.EqualTo(f2); } // Checks the following two formulas are identical: // - m1 < m2 // - ⋀ᵢⱼ (m1.array() < m2.array()) bool CheckMatrixOperatorLt(const MatrixX<Expression>& m1, const MatrixX<Expression>& m2) { const Formula f1{m1 < m2}; const Formula f2{(m1.array() < m2.array()).redux(internal::logic_and)}; return f1.EqualTo(f2); } // Checks the following two formulas are identical: // - m1 <= m2 // - ⋀ᵢⱼ (m1.array() <= m2.array()) bool CheckMatrixOperatorLte(const MatrixX<Expression>& m1, const MatrixX<Expression>& m2) { const Formula f1{m1 <= m2}; const Formula f2{(m1.array() <= m2.array()).redux(internal::logic_and)}; return f1.EqualTo(f2); } // Checks the following two formulas are identical: // - m1 > m2 // - ⋀ᵢⱼ (m1.array() > m2.array()) bool CheckMatrixOperatorGt(const MatrixX<Expression>& m1, const MatrixX<Expression>& m2) { const Formula f1{m1 > m2}; const Formula f2{(m1.array() > m2.array()).redux(internal::logic_and)}; return f1.EqualTo(f2); } // Checks the following two formulas are identical: // - m1 >= m2 // - ⋀ᵢⱼ (m1.array() >= m2.array()) bool CheckMatrixOperatorGte(const MatrixX<Expression>& m1, const MatrixX<Expression>& m2) { const Formula f1{m1 >= m2}; const Formula f2{(m1.array() >= m2.array()).redux(internal::logic_and)}; return f1.EqualTo(f2); } TEST_F(SymbolicExpressionMatrixTest, MatrixOperatorExprEqExpr1) { Eigen::Matrix<Expression, 2, 2> m1; Eigen::Matrix<Expression, 2, 2> m2; m1 << x_, y_, z_, x_; m2 << z_, x_, y_, z_; const Formula f{m1 == m2}; EXPECT_EQ(f.to_string(), "((x == z) and (y == x) and (z == y))"); ASSERT_TRUE(is_conjunction(f)); EXPECT_EQ(get_operands(f).size(), 3); EXPECT_TRUE(CheckMatrixOperatorEq(m1, m2)); EXPECT_TRUE(CheckMatrixOperatorNeq(m1, m2)); EXPECT_TRUE(CheckMatrixOperatorLt(m1, m2)); EXPECT_TRUE(CheckMatrixOperatorLte(m1, m2)); EXPECT_TRUE(CheckMatrixOperatorGt(m1, m2)); EXPECT_TRUE(CheckMatrixOperatorGte(m1, m2)); } TEST_F(SymbolicExpressionMatrixTest, MatrixOperatorExprEqExpr2) { Eigen::Matrix<Expression, 2, 2> m1; Eigen::Matrix<Expression, 2, 2> m2; m1 << x_, 1.0, z_, x_; m2 << z_, 2.0, y_, z_; const Formula f1{m1 == m2}; // Because (1.0 == 2.0) is false, the whole conjunction is reduced // to false. EXPECT_TRUE(is_false(f1)); const Formula f2{m1 == m1}; EXPECT_TRUE(is_true(f2)); } // Checks operator== between Matrix<Expression> and Matrix<Variable> TEST_F(SymbolicExpressionMatrixTest, MatrixOperatorExprEqVar) { Eigen::Matrix<Expression, 2, 2> m1; Eigen::Matrix<Variable, 2, 2> m2; m1 << x_, 1.0, z_, x_; m2 << var_x_, var_y_, var_z_, var_x_; const Formula f1{m1 == m2}; const Formula f2{m2 == m1}; EXPECT_PRED2(FormulaEqual, f1, 1.0 == var_y_); EXPECT_PRED2(FormulaEqual, f2, var_y_ == 1.0); } // Checks operator== between Matrix<Expression> and Matrix<double> TEST_F(SymbolicExpressionMatrixTest, MatrixOperatorExprEqDouble) { Eigen::Matrix<Expression, 2, 2> m1; Eigen::Matrix<double, 2, 2> m2; m1 << x_, 1.0, z_, x_; m2 << 1.0, 1.0, 3.0, 1.0; const Formula f1{m1 == m2}; const Formula f2{m2 == m1}; EXPECT_PRED2(FormulaEqual, f1, (x_ == 1.0) && (z_ == 3.0)); EXPECT_PRED2(FormulaEqual, f2, (1.0 == x_) && (3.0 == z_)); } // Checks operator== between Matrix<Variable> and Matrix<double> TEST_F(SymbolicExpressionMatrixTest, MatrixOperatorVarEqdouble) { Eigen::Matrix<Variable, 2, 2> m1; Eigen::Matrix<double, 2, 2> m2; m1 << var_x_, var_y_, var_z_, var_x_; m2 << 1.0, 2.0, 3.0, 1.0; const Formula f1{m1 == m2}; const Formula f2{m2 == m1}; EXPECT_PRED2(FormulaEqual, f1, (var_x_ == 1.0) && (var_y_ == 2.0) && (var_z_ == 3.0)); EXPECT_PRED2(FormulaEqual, f2, (1.0 == var_x_) && (2.0 == var_y_) && (3.0 == var_z_)); } // Checks operator== between Matrix<Variable> and Matrix<Variable> TEST_F(SymbolicExpressionMatrixTest, MatrixOperatorVarEqVar) { Eigen::Matrix<Variable, 2, 2> m1; Eigen::Matrix<Variable, 2, 2> m2; m1 << var_x_, var_y_, var_z_, var_x_; m2 << var_y_, var_z_, var_x_, var_x_; const Formula f1{m1 == m2}; const Formula f2{m2 == m1}; EXPECT_PRED2(FormulaEqual, f1, (var_x_ == var_y_) && (var_y_ == var_z_) && (var_z_ == var_x_)); EXPECT_PRED2(FormulaEqual, f2, (var_y_ == var_x_) && (var_z_ == var_y_) && (var_x_ == var_z_)); } TEST_F(SymbolicExpressionMatrixTest, ExpressionMatrixSegment) { Eigen::Matrix<Expression, 5, 1> v; v << x_, 1, y_, x_, 1; const auto s1 = v.segment(0, 2); // [x, 1] const auto s2 = v.segment(1, 2); // [1, y] const auto s3 = v.segment<2>(3); // [x, 1] const Formula f1{s1 == s2}; // (x = 1) ∧ (1 = y) const Formula f2{s1 == s3}; // (x = x) ∧ (1 = 1) -> True ASSERT_TRUE(is_conjunction(f1)); EXPECT_EQ(get_operands(f1).size(), 2); EXPECT_TRUE(is_true(f2)); } TEST_F(SymbolicExpressionMatrixTest, ExpressionMatrixBlock) { Eigen::Matrix<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(0, 0, 2, 2); // b2 = [1, 2] // [3, 4] const auto b2 = m.block<2, 2>(1, 1); // (x = 1) ∧ (y = 2) ∧ (y = 3) ∧ (1 = 4) -> False const Formula f{b1 == b2}; EXPECT_TRUE(is_false(f)); } // Checks relational operators (==, !=, <=, <, >=, >) between // Matrix<Expression> and Matrix<Expression>. TEST_F(SymbolicExpressionMatrixTest, MatrixExprRopMatrixExpr) { EXPECT_TRUE(CheckMatrixOperatorEq(A_, C_)); EXPECT_TRUE(CheckMatrixOperatorEq(B_ * A_, B_ * C_)); EXPECT_TRUE(CheckMatrixOperatorLte(A_, C_)); EXPECT_TRUE(CheckMatrixOperatorLte(B_ * A_, B_ * C_)); EXPECT_TRUE(CheckMatrixOperatorLt(A_, C_)); EXPECT_TRUE(CheckMatrixOperatorLt(B_ * A_, B_ * C_)); EXPECT_TRUE(CheckMatrixOperatorGte(A_, C_)); EXPECT_TRUE(CheckMatrixOperatorGte(B_ * A_, B_ * C_)); EXPECT_TRUE(CheckMatrixOperatorGt(A_, C_)); EXPECT_TRUE(CheckMatrixOperatorGt(B_ * A_, B_ * C_)); EXPECT_TRUE(CheckMatrixOperatorNeq(A_, C_)); EXPECT_TRUE(CheckMatrixOperatorNeq(B_ * A_, B_ * C_)); } // Checks relational operators (==, !=, <=, <, >=, >) between // Matrix<Expression> and Matrix<Variable> TEST_F(SymbolicExpressionMatrixTest, MatrixExprRopMatrixVar) { EXPECT_TRUE(CheckMatrixOperatorEq(matrix_expr_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorEq(matrix_var_2_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorLte(matrix_expr_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorLte(matrix_var_2_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorLt(matrix_expr_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorLt(matrix_var_2_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorGte(matrix_expr_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorGte(matrix_var_2_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorGt(matrix_expr_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorGt(matrix_var_2_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorNeq(matrix_expr_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorNeq(matrix_var_2_, matrix_expr_1_)); } // Checks relational operators (==, !=, <=, <, >=, >) between // Matrix<Expression> and Matrix<double> TEST_F(SymbolicExpressionMatrixTest, MatrixExprRopMatrixDouble) { EXPECT_TRUE(CheckMatrixOperatorEq(matrix_expr_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorEq(matrix_double_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorLte(matrix_expr_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorLte(matrix_double_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorLt(matrix_expr_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorLt(matrix_double_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorGte(matrix_expr_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorGte(matrix_double_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorGt(matrix_expr_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorGt(matrix_double_, matrix_expr_1_)); EXPECT_TRUE(CheckMatrixOperatorNeq(matrix_expr_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorNeq(matrix_double_, matrix_expr_1_)); } // Checks relational operators (==, !=, <=, <, >=, >) between // Matrix<Variable> and Matrix<double> TEST_F(SymbolicExpressionMatrixTest, MatrixVarRopMatrixDouble) { EXPECT_TRUE(CheckMatrixOperatorEq(matrix_var_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorEq(matrix_double_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorLte(matrix_var_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorLte(matrix_double_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorLt(matrix_var_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorLt(matrix_double_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorGte(matrix_var_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorGte(matrix_double_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorGt(matrix_var_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorGt(matrix_double_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorNeq(matrix_var_1_, matrix_double_)); EXPECT_TRUE(CheckMatrixOperatorNeq(matrix_double_, matrix_var_1_)); } // Checks relational operators (==, !=, <=, <, >=, >) between // Matrix<Variable> and Matrix<Variable> TEST_F(SymbolicExpressionMatrixTest, MatrixVarRopMatrixVar) { EXPECT_TRUE(CheckMatrixOperatorEq(matrix_var_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorEq(matrix_var_2_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorLte(matrix_var_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorLte(matrix_var_2_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorLt(matrix_var_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorLt(matrix_var_2_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorGte(matrix_var_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorGte(matrix_var_2_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorGt(matrix_var_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorGt(matrix_var_2_, matrix_var_1_)); EXPECT_TRUE(CheckMatrixOperatorNeq(matrix_var_1_, matrix_var_2_)); EXPECT_TRUE(CheckMatrixOperatorNeq(matrix_var_2_, matrix_var_1_)); } TEST_F(SymbolicExpressionMatrixTest, EvaluateDenseMatrix) { const Environment env{{{var_x_, 1.0}, {var_y_, 2.0}, {var_z_, 3.0}}}; // 1. A_ is a fixed-size matrix (3 x 2) = [x 1] // [y -1] // [z 3.141592] Eigen::Matrix<double, 3, 2> A_eval_expected; // clang-format off A_eval_expected << 1.0, 1.0, 2.0, -1.0, 3.0, 3.141592; // clang-format on const Eigen::Matrix<double, 3, 2> A_eval{Evaluate(1.0 * A_, env)}; EXPECT_EQ(A_eval_expected, A_eval); // 2. B is a dynamic-size matrix (2 x 2) = [x-y x] // [y z] MatrixX<Expression> B(2, 2); Eigen::MatrixXd B_eval_expected(2, 2); // clang-format off B << x_ - y_, x_, y_, z_; B_eval_expected << 1.0 - 2.0, 1.0, 2.0, 3.0; // clang-format on const Eigen::MatrixXd B_eval{Evaluate(B, env)}; EXPECT_EQ(B_eval_expected, B_eval); // 3. Check if Evaluate throws if it computes NaN in evaluation. MatrixX<Expression> C(2, 2); // clang-format off C << x_, Expression::NaN(), y_, z_; // clang-format on DRAKE_EXPECT_THROWS_MESSAGE(Evaluate(C, env), "NaN is detected during Symbolic computation."); } TEST_F(SymbolicExpressionMatrixTest, EvaluateSparseMatrix) { const Environment env{{{var_x_, 1.0}, {var_y_, 2.0}, {var_z_, 3.0}}}; Eigen::SparseMatrix<Expression> A{3, 2}; A.insert(0, 0) = x_ + y_; A.insert(2, 1) = 3 + z_; const Eigen::SparseMatrix<double> A_eval{Evaluate(A, env)}; EXPECT_EQ(A.nonZeros(), A_eval.nonZeros()); EXPECT_EQ(A.coeff(0, 0).Evaluate(env), A_eval.coeff(0, 0)); EXPECT_EQ(A.coeff(2, 1).Evaluate(env), A_eval.coeff(2, 1)); } TEST_F(SymbolicExpressionMatrixTest, EvaluateWithRandomGenerator) { RandomGenerator g{}; 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 env{{{var_x_, 1.0}, {var_y_, 2.0}, {var_z_, 3.0}}}; // 1. A_ is a fixed-size matrix (3 x 2) = [x uni * gau + exp] // [uni * gau + exp -1] // [z 3.141592] Eigen::Matrix<Expression, 3, 2> A; // clang-format off A << x_, uni * gau + exp, uni * gau + exp, -1, z_, 3.141592; // clang-format on // A(1,0) and A(0, 1) are the same symbolic expressions. Therefore, they // should be evaluated to the same value regardless of sampled values for the // random variables in A. const Eigen::Matrix<double, 3, 2> A_eval{Evaluate(A, env, &g)}; EXPECT_PRED2(ExprEqual, A(1, 0), A(0, 1)); EXPECT_EQ(A_eval(1, 0), A_eval(0, 1)); // 2. B is a dynamic-size matrix (2 x 2) = [uni + gau + exp x] // [y uni + gau + exp] MatrixX<Expression> B(2, 2); // clang-format off B << uni + gau + exp, x_, y_, uni + gau + exp; // clang-format on // B(0, 0) and B(1, 1) are the same symbolic expressions. Therefore, they // should be evaluated to the same value regardless of sampled values for the // random variables in B. const Eigen::Matrix<double, 2, 2> B_eval{Evaluate(B, env, &g)}; EXPECT_PRED2(ExprEqual, B(0, 0), B(1, 1)); EXPECT_EQ(B_eval(0, 0), B_eval(1, 1)); } MatrixX<Variable> MakeMatrixVariable(int rows, int cols) { MatrixX<Variable> M(rows, cols); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { M(i, j) = Variable(fmt::format("m{}_{}", i, j)); } } return M; } Eigen::MatrixXd MakeSimpleInvertibleMatrix(int N) { Eigen::MatrixXd M(N, N); for (int i = 0; i < N * N; ++i) { M(i) = std::pow(i, N - 1); } return M; } const char* kBadMatrixInversion = R"""(.*does not have an entry for the variable[\s\S]*)"""; // Tests Eigen `.inverse` method works for certain shapes of symbolic matrices. // We demonstrate it by showing that the following two values are matched for // a statically-sized symbolic matrix `M` and a substitution (Variable -> // double) `subst`: // // 1. Substitute(M.inverse(), subst) // 2. Substitute(M, subst).inverse() // // Note that in 1) Matrix<Expression>::inverse() is called while in 2) // Matrix<double>::inverse() is used. // Also show that it fails for matrices larger than 4x4 and any // dynamically-sized matrix. template <int N> void CheckSymbolicMatrixInversion() { drake::log()->debug("CheckSymbolicMatrixInversion<{}>()", N); const Eigen::Matrix<Variable, N, N> Mvar = MakeMatrixVariable(N, N); const Eigen::Matrix<Expression, N, N> M = Mvar; const Eigen::Matrix<Expression, N, N> Minv = M.inverse(); const Eigen::MatrixXd Mvalue = MakeSimpleInvertibleMatrix(N); Substitution subst; for (int i = 0; i < N * N; ++i) { subst[Mvar(i)] = Mvalue(i); } EXPECT_TRUE(CompareMatrices(Substitute(Minv, subst), Substitute(M, subst).inverse(), 1e-10)); // Show that the dynamically-sized variant fails. const MatrixX<Expression> Mdyn = M; DRAKE_EXPECT_THROWS_MESSAGE(Mdyn.inverse().eval(), kBadMatrixInversion); } // Positive tests for symbolic inversion of 1x1, 2x2, 3x3, and 4x4 matrices. // Negative test for 5x5 matrix. TEST_F(SymbolicExpressionMatrixTest, Inverse) { CheckSymbolicMatrixInversion<1>(); CheckSymbolicMatrixInversion<2>(); CheckSymbolicMatrixInversion<3>(); CheckSymbolicMatrixInversion<4>(); DRAKE_EXPECT_THROWS_MESSAGE(CheckSymbolicMatrixInversion<5>(), kBadMatrixInversion); } // Shows that a purely numeric matrix of Expression is invertible. template <int N> void CheckNumericExpressionMatrixInversion() { const Eigen::Matrix<double, N, N> M_f = MakeSimpleInvertibleMatrix(N); const Eigen::Matrix<Expression, N, N> M_sym = M_f; // Statically sized. EXPECT_TRUE(CompareMatrices(M_f.inverse(), M_sym.inverse(), 1e-9)); // Dynamically sized. EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(M_f).inverse(), MatrixX<Expression>(M_sym).inverse(), 1e-9)); } TEST_F(SymbolicExpressionMatrixTest, InverseNumeric) { CheckNumericExpressionMatrixInversion<1>(); CheckNumericExpressionMatrixInversion<2>(); CheckNumericExpressionMatrixInversion<3>(); CheckNumericExpressionMatrixInversion<4>(); CheckNumericExpressionMatrixInversion<5>(); CheckNumericExpressionMatrixInversion<10>(); } // We found that the following example could leak memory. This test makes sure // that we provide a correct work-around. FYI, `--config asan` option is // required to see failures from this test case. // // See https://github.com/RobotLocomotion/drake/issues/12453 for details. TEST_F(SymbolicExpressionMatrixTest, SparseMatrixMultiplicationNoMemoryLeak) { Eigen::SparseMatrix<Expression> M1(2, 2); Eigen::SparseMatrix<Expression> M2(2, 2); (M1 * M2).eval(); } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/formula_visitor_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <algorithm> #include <functional> #include <iterator> #include <memory> #include <set> #include <gtest/gtest.h> #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { namespace symbolic { namespace { using std::function; using std::inserter; using std::make_shared; using std::set; using std::shared_ptr; using std::transform; using test::FormulaEqual; // Given formulas = {f₁, ..., fₙ} and a func : Formula → Formula, // map(formulas, func) returns a set {func(f₁), ... func(fₙ)}. set<Formula> map(const set<Formula>& formulas, const function<Formula(const Formula&)>& func) { set<Formula> result; transform(formulas.cbegin(), formulas.cend(), inserter(result, result.begin()), func); return result; } // A class implementing NNF (Negation Normal Form) conversion. See // https://en.wikipedia.org/wiki/Negation_normal_form for more information on // NNF. // // TODO(soonho-tri): Consider moving this class into a separate file in // `drake/common` directory when we have a use-case of this class in Drake. For // now, we have it here to test `drake/common/symbolic_formula_visitor.h`. class NegationNormalFormConverter { public: // Converts @p f into an equivalent formula @c f' in NNF. Formula Visit(const Formula& f) const { return Visit(f, true); } private: // Converts @p f into an equivalent formula @c f' in NNF. The parameter @p // polarity is to indicate whether it processes @c f (if @p polarity is // true) or @c ¬f (if @p polarity is false). Formula Visit(const Formula& f, const bool polarity) const { return VisitFormula<Formula>(this, f, polarity); } Formula VisitFalse(const Formula& f, const bool polarity) const { // NNF(False) = False // NNF(¬False) = True return polarity ? Formula::False() : Formula::True(); } Formula VisitTrue(const Formula& f, const bool polarity) const { // NNF(True) = True // NNF(¬True) = False return polarity ? Formula::True() : Formula::False(); } Formula VisitVariable(const Formula& f, const bool polarity) const { // NNF(b) = b // NNF(¬b) = ¬b return polarity ? f : !f; } Formula VisitEqualTo(const Formula& f, const bool polarity) const { // NNF(e1 = e2) = (e1 = e2) // NNF(¬(e1 = e2)) = (e1 != e2) return polarity ? f : get_lhs_expression(f) != get_rhs_expression(f); } Formula VisitNotEqualTo(const Formula& f, const bool polarity) const { // NNF(e1 != e2) = (e1 != e2) // NNF(¬(e1 != e2)) = (e1 = e2) return polarity ? f : get_lhs_expression(f) == get_rhs_expression(f); } Formula VisitGreaterThan(const Formula& f, const bool polarity) const { // NNF(e1 > e2) = (e1 > e2) // NNF(¬(e1 > e2)) = (e1 <= e2) return polarity ? f : get_lhs_expression(f) <= get_rhs_expression(f); } Formula VisitGreaterThanOrEqualTo(const Formula& f, const bool polarity) const { // NNF(e1 >= e2) = (e1 >= e2) // NNF(¬(e1 >= e2)) = (e1 < e2) return polarity ? f : get_lhs_expression(f) < get_rhs_expression(f); } Formula VisitLessThan(const Formula& f, const bool polarity) const { // NNF(e1 < e2) = (e1 < e2) // NNF(¬(e1 < e2)) = (e1 >= e2) return polarity ? f : get_lhs_expression(f) >= get_rhs_expression(f); } Formula VisitLessThanOrEqualTo(const Formula& f, const bool polarity) const { // NNF(e1 <= e2) = (e1 <= e2) // NNF(¬(e1 <= e2)) = (e1 > e2) return polarity ? f : get_lhs_expression(f) > get_rhs_expression(f); } Formula VisitConjunction(const Formula& f, const bool polarity) const { // NNF(f₁ ∧ ... ∨ fₙ) = NNF(f₁) ∧ ... ∧ NNF(fₙ) // NNF(¬(f₁ ∧ ... ∨ fₙ)) = NNF(¬f₁) ∨ ... ∨ NNF(¬fₙ) const set<Formula> new_operands{ map(get_operands(f), [this, &polarity](const Formula& formula) { return this->Visit(formula, polarity); })}; return polarity ? make_conjunction(new_operands) : make_disjunction(new_operands); } Formula VisitDisjunction(const Formula& f, const bool polarity) const { // NNF(f₁ ∨ ... ∨ fₙ) = NNF(f₁) ∨ ... ∨ NNF(fₙ) // NNF(¬(f₁ ∨ ... ∨ fₙ)) = NNF(¬f₁) ∧ ... ∧ NNF(¬fₙ) const set<Formula> new_operands{ map(get_operands(f), [this, &polarity](const Formula& formula) { return this->Visit(formula, polarity); })}; return polarity ? make_disjunction(new_operands) : make_conjunction(new_operands); } Formula VisitNegation(const Formula& f, const bool polarity) const { // NNF(¬f, ⊤) = NNF(f, ⊥) // NNF(¬f, ⊥) = NNF(f, ⊤) return Visit(get_operand(f), !polarity); } Formula VisitForall(const Formula& f, const bool polarity) const { // NNF(∀v₁...vₙ. f) = ∀v₁...vₙ. f // NNF(¬(∀v₁...vₙ. f)) = ¬∀v₁...vₙ. f // // TODO(soonho-tri): The second case can be further reduced into // ∃v₁...vₙ. NNF(¬f). However, we do not have a representation // FormulaExists(∃) yet. Revisit this when we add FormulaExists. return polarity ? f : !f; } Formula VisitIsnan(const Formula& f, const bool polarity) const { // NNF(isnan(f)) = isnan(f) // NNF(¬isnan(f)) = ¬isnan(f) return polarity ? f : !f; } Formula VisitPositiveSemidefinite(const Formula& f, const bool polarity) const { // NNF(psd(M)) = psd(M) // NNF(¬psd(M)) = ¬psd(M) return polarity ? f : !f; } // Makes VisitFormula a friend of this class so that it can use private // methods. friend Formula drake::symbolic::VisitFormula<Formula>( const NegationNormalFormConverter*, const Formula&, const bool&); }; class SymbolicFormulaVisitorTest : public ::testing::Test { protected: const Variable x_{"x", Variable::Type::CONTINUOUS}; const Variable y_{"y", Variable::Type::CONTINUOUS}; const Variable z_{"z", Variable::Type::CONTINUOUS}; const Variable b1_{"b1", Variable::Type::BOOLEAN}; const Variable b2_{"b2", Variable::Type::BOOLEAN}; const Variable b3_{"b3", Variable::Type::BOOLEAN}; Eigen::Matrix<Expression, 2, 2, Eigen::DontAlign> M_; const NegationNormalFormConverter converter_{}; void SetUp() override { // clang-format off M_ << (x_ + y_), -1.0, -1.0, y_; // clang-format on } }; TEST_F(SymbolicFormulaVisitorTest, NNFNoChanges) { // No Changes: True EXPECT_PRED2(FormulaEqual, converter_.Visit(Formula::True()), Formula::True()); // No Changes: False EXPECT_PRED2(FormulaEqual, converter_.Visit(Formula::False()), Formula::False()); // No Changes: Variables EXPECT_PRED2(FormulaEqual, converter_.Visit(Formula{b1_}), Formula{b1_}); EXPECT_PRED2(FormulaEqual, converter_.Visit(!b1_), !b1_); // No Changes: x ≥ y ∧ y ≤ z const Formula f1{x_ >= y_ && y_ <= z_}; EXPECT_PRED2(FormulaEqual, converter_.Visit(f1), f1); // No Changes.: x > y ∨ y < z const Formula f2{x_ > y_ || y_ < z_}; EXPECT_PRED2(FormulaEqual, converter_.Visit(f2), f2); // No Changes: isnan(x) const Formula f3{isnan(x_)}; EXPECT_PRED2(FormulaEqual, converter_.Visit(f3), f3); EXPECT_PRED2(FormulaEqual, converter_.Visit(!f3), !f3); // No Changes: ∀x. x + y ≥ x const Formula f4{forall({x_}, x_ + y_ >= x_)}; EXPECT_PRED2(FormulaEqual, converter_.Visit(f4), f4); EXPECT_PRED2(FormulaEqual, converter_.Visit(!f4), !f4); // No Changes: psd(M) const Formula psd{positive_semidefinite(M_)}; EXPECT_PRED2(FormulaEqual, converter_.Visit(psd), psd); EXPECT_PRED2(FormulaEqual, converter_.Visit(!psd), !psd); } TEST_F(SymbolicFormulaVisitorTest, NNFRelational) { // ¬(x ≥ y) ∧ ¬(y ≤ z) ==> x < y ∧ y > z EXPECT_PRED2(FormulaEqual, converter_.Visit(!(x_ >= y_) && !(y_ <= z_)), x_ < y_ && y_ > z_); // ¬(x ≥ y ∧ y ≤ z) ==> x < y ∨ y > z EXPECT_PRED2(FormulaEqual, converter_.Visit(!(x_ >= y_ && y_ <= z_)), x_ < y_ || y_ > z_); // ¬(x > y) ∨ ¬(y < z) ==> x ≤ y ∨ y ≥ z EXPECT_PRED2(FormulaEqual, converter_.Visit(!(x_ > y_) || !(y_ < z_)), x_ <= y_ || y_ >= z_); // ¬(x > y ∨ y < z) ==> x ≤ y ∧ y ≥ z EXPECT_PRED2(FormulaEqual, converter_.Visit(!(x_ > y_ || y_ < z_)), x_ <= y_ && y_ >= z_); // ¬(x ≠ y) ∧ ¬(y = z) ==> x = y ∧ y ≠ z EXPECT_PRED2(FormulaEqual, converter_.Visit(!(x_ != y_) && !(y_ == z_)), x_ == y_ && y_ != z_); // ¬(x ≠ y ∧ y = z) ==> x = y ∨ y ≠ z EXPECT_PRED2(FormulaEqual, converter_.Visit(!(x_ != y_ && y_ == z_)), x_ == y_ || y_ != z_); } TEST_F(SymbolicFormulaVisitorTest, NNFBoolean) { // ¬(b₁ ∨ ¬(b₂ ∧ b₃)) ==> ¬b₁ ∧ b₂ ∧ b₃ EXPECT_PRED2(FormulaEqual, converter_.Visit(!(b1_ || !(b2_ && b3_))), !b1_ && b2_ && b3_); // ¬(b₁ ∨ ¬(b₂ ∨ b₃)) ==> ¬b₁ ∧ (b₂ ∨ b₃) EXPECT_PRED2(FormulaEqual, converter_.Visit(!(b1_ || !(b2_ || b3_))), !b1_ && (b2_ || b3_)); // ¬(b₁ ∧ ¬(b₂ ∨ b₃)) ==> ¬b₁ ∨ b₂ ∨ b₃ EXPECT_PRED2(FormulaEqual, converter_.Visit(!(b1_ && !(b2_ || b3_))), !b1_ || b2_ || b3_); // ¬(b₁ ∧ ¬(b₂ ∧ b₃)) ==> ¬b₁ ∨ (b₂ ∧ b₃) EXPECT_PRED2(FormulaEqual, converter_.Visit(!(b1_ && !(b2_ && b3_))), !b1_ || (b2_ && b3_)); } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/mixing_scalar_types_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <string> #include <gtest/gtest.h> #include "drake/common/fmt_eigen.h" #include "drake/common/test_utilities/limit_malloc.h" namespace drake { namespace symbolic { namespace { using std::string; using test::LimitMalloc; class SymbolicMixingScalarTypesTest : public ::testing::Test { template <typename Scalar> using Matrix2DontAlign = Eigen::Matrix<Scalar, 2, 2, Eigen::DontAlign>; template <typename Scalar> using Vector2DontAlign = Eigen::Matrix<Scalar, 2, 1, Eigen::DontAlign>; protected: const Variable var_x_{"x"}; const Variable var_y_{"y"}; const Variable var_z_{"z"}; const Variable var_w_{"w"}; const Expression x_{var_x_}; const Expression y_{var_y_}; const Expression z_{var_z_}; const Expression w_{var_w_}; Matrix2DontAlign<Expression> M_expr_fixed_; MatrixX<Expression> M_expr_dyn_{2, 2}; Vector2DontAlign<Expression> V_expr_fixed_; VectorX<Expression> V_expr_dyn_{2}; Matrix2DontAlign<Variable> M_var_fixed_; MatrixX<Variable> M_var_dyn_{2, 2}; Vector2DontAlign<Variable> V_var_fixed_; VectorX<Variable> V_var_dyn_{2}; Matrix2DontAlign<double> M_double_fixed_; MatrixX<double> M_double_dyn_{2, 2}; Vector2DontAlign<double> V_double_fixed_; VectorX<double> V_double_dyn_{2}; void SetUp() override { // clang-format off M_expr_fixed_ << x_, y_, z_, w_; M_expr_dyn_ << x_, y_, z_, w_; V_expr_fixed_ << x_, y_; V_expr_dyn_ << x_, y_; // clang-format on // clang-format off M_var_fixed_ << var_x_, var_y_, var_z_, var_w_; M_var_dyn_ << var_x_, var_y_, var_z_, var_w_; V_var_fixed_ << var_x_, var_y_; V_var_dyn_ << var_x_, var_y_; // clang-format on // clang-format off M_double_fixed_ << 1, 2, 3, 4; M_double_dyn_ << 1, 2, 3, 4; V_double_fixed_ << 1, 2; V_double_dyn_ << 1, 2; // clang-format on } template <typename Scalar> string to_string(const Eigen::MatrixBase<Scalar>& m) { return fmt::to_string(fmt_eigen(m)); } }; TEST_F(SymbolicMixingScalarTypesTest, MatrixAdditionExprVar) { const MatrixX<Expression> M1{M_expr_fixed_ + M_var_fixed_}; const MatrixX<Expression> M2{M_expr_fixed_ + M_var_dyn_}; const MatrixX<Expression> M3{M_expr_dyn_ + M_var_fixed_}; const MatrixX<Expression> M4{M_expr_dyn_ + M_var_dyn_}; const string expected{ "(2 * x) (2 * y)\n" "(2 * z) (2 * w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixAdditionExprDouble) { const MatrixX<Expression> M1{M_expr_fixed_ + M_double_fixed_}; const MatrixX<Expression> M2{M_expr_fixed_ + M_double_dyn_}; const MatrixX<Expression> M3{M_expr_dyn_ + M_double_fixed_}; const MatrixX<Expression> M4{M_expr_dyn_ + M_double_dyn_}; const string expected{ "(1 + x) (2 + y)\n" "(3 + z) (4 + w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixAdditionVarExpr) { const MatrixX<Expression> M1{M_var_fixed_ + M_expr_fixed_}; const MatrixX<Expression> M2{M_var_fixed_ + M_expr_dyn_}; const MatrixX<Expression> M3{M_var_dyn_ + M_expr_fixed_}; const MatrixX<Expression> M4{M_var_dyn_ + M_expr_dyn_}; const string expected{ "(2 * x) (2 * y)\n" "(2 * z) (2 * w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixAdditionVarDouble) { const MatrixX<Expression> M1{M_var_fixed_ + M_double_fixed_}; const MatrixX<Expression> M2{M_var_fixed_ + M_double_dyn_}; const MatrixX<Expression> M3{M_var_dyn_ + M_double_fixed_}; const MatrixX<Expression> M4{M_var_dyn_ + M_double_dyn_}; const string expected{ "(1 + x) (2 + y)\n" "(3 + z) (4 + w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixAdditionDoubleExpr) { const MatrixX<Expression> M1{M_double_fixed_ + M_expr_fixed_}; const MatrixX<Expression> M2{M_double_fixed_ + M_expr_dyn_}; const MatrixX<Expression> M3{M_double_dyn_ + M_expr_fixed_}; const MatrixX<Expression> M4{M_double_dyn_ + M_expr_dyn_}; const string expected{ "(1 + x) (2 + y)\n" "(3 + z) (4 + w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixAdditionDoubleVar) { const MatrixX<Expression> M1{M_double_fixed_ + M_var_fixed_}; const MatrixX<Expression> M2{M_double_fixed_ + M_var_dyn_}; const MatrixX<Expression> M3{M_double_dyn_ + M_var_fixed_}; const MatrixX<Expression> M4{M_double_dyn_ + M_var_dyn_}; const string expected{ "(1 + x) (2 + y)\n" "(3 + z) (4 + w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixSubtractionExprVar) { const MatrixX<Expression> M1{M_expr_fixed_ - M_var_fixed_}; const MatrixX<Expression> M2{M_expr_fixed_ - M_var_dyn_}; const MatrixX<Expression> M3{M_expr_dyn_ - M_var_fixed_}; const MatrixX<Expression> M4{M_expr_dyn_ - M_var_dyn_}; const string expected{"0 0\n0 0"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixSubtractionExprDouble) { const MatrixX<Expression> M1{M_expr_fixed_ - M_double_fixed_}; const MatrixX<Expression> M2{M_expr_fixed_ - M_double_dyn_}; const MatrixX<Expression> M3{M_expr_dyn_ - M_double_fixed_}; const MatrixX<Expression> M4{M_expr_dyn_ - M_double_dyn_}; const string expected{ "(-1 + x) (-2 + y)\n" "(-3 + z) (-4 + w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixSubtractionVarExpr) { const MatrixX<Expression> M1{M_var_fixed_ - M_expr_fixed_}; const MatrixX<Expression> M2{M_var_fixed_ - M_expr_dyn_}; const MatrixX<Expression> M3{M_var_dyn_ - M_expr_fixed_}; const MatrixX<Expression> M4{M_var_dyn_ - M_expr_dyn_}; const string expected{"0 0\n0 0"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixSubtractionVarDouble) { const MatrixX<Expression> M1{M_var_fixed_ - M_double_fixed_}; const MatrixX<Expression> M2{M_var_fixed_ - M_double_dyn_}; const MatrixX<Expression> M3{M_var_dyn_ - M_double_fixed_}; const MatrixX<Expression> M4{M_var_dyn_ - M_double_dyn_}; const string expected{ "(-1 + x) (-2 + y)\n" "(-3 + z) (-4 + w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixSubtractionDoubleExpr) { const MatrixX<Expression> M1{M_double_fixed_ - M_expr_fixed_}; const MatrixX<Expression> M2{M_double_fixed_ - M_expr_dyn_}; const MatrixX<Expression> M3{M_double_dyn_ - M_expr_fixed_}; const MatrixX<Expression> M4{M_double_dyn_ - M_expr_dyn_}; const string expected{ "(1 - x) (2 - y)\n" "(3 - z) (4 - w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixSubtractionDoubleVar) { const MatrixX<Expression> M1{M_double_fixed_ - M_var_fixed_}; const MatrixX<Expression> M2{M_double_fixed_ - M_var_dyn_}; const MatrixX<Expression> M3{M_double_dyn_ - M_var_fixed_}; const MatrixX<Expression> M4{M_double_dyn_ - M_var_dyn_}; const string expected{ "(1 - x) (2 - y)\n" "(3 - z) (4 - w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixMatrixMultiplicationExprVar) { const MatrixX<Expression> M1{M_expr_fixed_ * M_var_fixed_}; const MatrixX<Expression> M2{M_expr_fixed_ * M_var_dyn_}; const MatrixX<Expression> M3{M_expr_dyn_ * M_var_fixed_}; const MatrixX<Expression> M4{M_expr_dyn_ * M_var_dyn_}; const string expected{ "((y * z) + pow(x, 2)) ((x * y) + (y * w))\n" " ((x * z) + (z * w)) ((y * z) + pow(w, 2))"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixVectorMultiplicationExprVar) { const MatrixX<Expression> M1{M_expr_fixed_ * V_var_fixed_}; const MatrixX<Expression> M2{M_expr_fixed_ * V_var_dyn_}; const MatrixX<Expression> M3{M_expr_dyn_ * V_var_fixed_}; const MatrixX<Expression> M4{M_expr_dyn_ * V_var_dyn_}; const string expected{ "(pow(x, 2) + pow(y, 2))\n" " ((x * z) + (y * w))"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorMatrixMultiplicationExprVar) { const MatrixX<Expression> M1{V_expr_fixed_.transpose() * M_var_fixed_}; const MatrixX<Expression> M2{V_expr_fixed_.transpose() * M_var_dyn_}; const MatrixX<Expression> M3{V_expr_dyn_.transpose() * M_var_fixed_}; const MatrixX<Expression> M4{V_expr_dyn_.transpose() * M_var_dyn_}; const string expected{"((y * z) + pow(x, 2)) ((x * y) + (y * w))"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorVectorMultiplicationExprVar) { const MatrixX<Expression> M1{V_expr_fixed_.transpose() * V_var_fixed_}; const MatrixX<Expression> M2{V_expr_fixed_.transpose() * V_var_dyn_}; const MatrixX<Expression> M3{V_expr_dyn_.transpose() * V_var_fixed_}; const MatrixX<Expression> M4{V_expr_dyn_.transpose() * V_var_dyn_}; const string expected{"(pow(x, 2) + pow(y, 2))"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixMatrixMultiplicationVarExpr) { const MatrixX<Expression> M1{M_var_fixed_ * M_expr_fixed_}; const MatrixX<Expression> M2{M_var_fixed_ * M_expr_dyn_}; const MatrixX<Expression> M3{M_var_dyn_ * M_expr_fixed_}; const MatrixX<Expression> M4{M_var_dyn_ * M_expr_dyn_}; const string expected{ "((y * z) + pow(x, 2)) ((x * y) + (y * w))\n" " ((x * z) + (z * w)) ((y * z) + pow(w, 2))"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixVectorMultiplicationVarExpr) { const MatrixX<Expression> M1{M_var_fixed_ * V_expr_fixed_}; const MatrixX<Expression> M2{M_var_fixed_ * V_expr_dyn_}; const MatrixX<Expression> M3{M_var_dyn_ * V_expr_fixed_}; const MatrixX<Expression> M4{M_var_dyn_ * V_expr_dyn_}; const string expected{ "(pow(x, 2) + pow(y, 2))\n" " ((x * z) + (y * w))"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorMatrixMultiplicationVarExpr) { const MatrixX<Expression> M1{V_var_fixed_.transpose() * M_expr_fixed_}; const MatrixX<Expression> M2{V_var_fixed_.transpose() * M_expr_dyn_}; const MatrixX<Expression> M3{V_var_dyn_.transpose() * M_expr_fixed_}; const MatrixX<Expression> M4{V_var_dyn_.transpose() * M_expr_dyn_}; const string expected{"((y * z) + pow(x, 2)) ((x * y) + (y * w))"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorVectorMultiplicationVarExpr) { const MatrixX<Expression> M1{V_var_fixed_.transpose() * V_expr_fixed_}; const MatrixX<Expression> M2{V_var_fixed_.transpose() * V_expr_dyn_}; const MatrixX<Expression> M3{V_var_dyn_.transpose() * V_expr_fixed_}; const MatrixX<Expression> M4{V_var_dyn_.transpose() * V_expr_dyn_}; const string expected{"(pow(x, 2) + pow(y, 2))"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixMatrixMultiplicationExprDouble) { const MatrixX<Expression> M1{M_expr_fixed_ * M_double_fixed_}; const MatrixX<Expression> M2{M_expr_fixed_ * M_double_dyn_}; const MatrixX<Expression> M3{M_expr_dyn_ * M_double_fixed_}; const MatrixX<Expression> M4{M_expr_dyn_ * M_double_dyn_}; const string expected{ "(x + 3 * y) (2 * x + 4 * y)\n" "(z + 3 * w) (2 * z + 4 * w)"}; } TEST_F(SymbolicMixingScalarTypesTest, MatrixVectorMultiplicationExprDouble) { const MatrixX<Expression> M1{M_expr_fixed_ * V_double_fixed_}; const MatrixX<Expression> M2{M_expr_fixed_ * V_double_dyn_}; const MatrixX<Expression> M3{M_expr_dyn_ * V_double_fixed_}; const MatrixX<Expression> M4{M_expr_dyn_ * V_double_dyn_}; const string expected{ "(x + 2 * y)\n" "(z + 2 * w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorMatrixMultiplicationExprDouble) { const MatrixX<Expression> M1{V_expr_fixed_.transpose() * M_double_fixed_}; const MatrixX<Expression> M2{V_expr_fixed_.transpose() * M_double_dyn_}; const MatrixX<Expression> M3{V_expr_dyn_.transpose() * M_double_fixed_}; const MatrixX<Expression> M4{V_expr_dyn_.transpose() * M_double_dyn_}; const string expected{" (x + 3 * y) (2 * x + 4 * y)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorVectorMultiplicationExprDouble) { const MatrixX<Expression> M1{V_expr_fixed_.transpose() * V_double_fixed_}; const MatrixX<Expression> M2{V_expr_fixed_.transpose() * V_double_dyn_}; const MatrixX<Expression> M3{V_expr_dyn_.transpose() * V_double_fixed_}; const MatrixX<Expression> M4{V_expr_dyn_.transpose() * V_double_dyn_}; const string expected{"(x + 2 * y)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixMatrixMultiplicationDoubleExpr) { const MatrixX<Expression> M1{M_double_fixed_ * M_expr_fixed_}; const MatrixX<Expression> M2{M_double_fixed_ * M_expr_dyn_}; const MatrixX<Expression> M3{M_double_dyn_ * M_expr_fixed_}; const MatrixX<Expression> M4{M_double_dyn_ * M_expr_dyn_}; const string expected{ " (x + 2 * z) (y + 2 * w)\n" "(3 * x + 4 * z) (3 * y + 4 * w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixVectorMultiplicationDoubleExpr) { const MatrixX<Expression> M1{M_double_fixed_ * V_expr_fixed_}; const MatrixX<Expression> M2{M_double_fixed_ * V_expr_dyn_}; const MatrixX<Expression> M3{M_double_dyn_ * V_expr_fixed_}; const MatrixX<Expression> M4{M_double_dyn_ * V_expr_dyn_}; const string expected{ " (x + 2 * y)\n" "(3 * x + 4 * y)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorMatrixMultiplicationDoubleExpr) { const MatrixX<Expression> M1{V_double_fixed_.transpose() * M_expr_fixed_}; const MatrixX<Expression> M2{V_double_fixed_.transpose() * M_expr_dyn_}; const MatrixX<Expression> M3{V_double_dyn_.transpose() * M_expr_fixed_}; const MatrixX<Expression> M4{V_double_dyn_.transpose() * M_expr_dyn_}; const string expected{"(x + 2 * z) (y + 2 * w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorVectorMultiplicationDoubleExpr) { const MatrixX<Expression> M1{V_double_fixed_.transpose() * V_expr_fixed_}; const MatrixX<Expression> M2{V_double_fixed_.transpose() * V_expr_dyn_}; const MatrixX<Expression> M3{V_double_dyn_.transpose() * V_expr_fixed_}; const MatrixX<Expression> M4{V_double_dyn_.transpose() * V_expr_dyn_}; const string expected{"(x + 2 * y)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixMatrixMultiplicationVarDouble) { const MatrixX<Expression> M1{M_var_fixed_ * M_double_fixed_}; const MatrixX<Expression> M2{M_var_fixed_ * M_double_dyn_}; const MatrixX<Expression> M3{M_var_dyn_ * M_double_fixed_}; const MatrixX<Expression> M4{M_var_dyn_ * M_double_dyn_}; const string expected{ " (x + 3 * y) (2 * x + 4 * y)\n" " (z + 3 * w) (2 * z + 4 * w)"}; } TEST_F(SymbolicMixingScalarTypesTest, MatrixMatrixMultiplicationVarDoubleHeap) { M_double_fixed_ = Eigen::Matrix2d::Identity(); const int expected_alloc = // The temporary flat_hash_set. 1 // One expression cell for each variable. + 4; LimitMalloc guard({.max_num_allocations = expected_alloc}); auto result = (M_var_fixed_ * M_double_fixed_).eval(); } TEST_F(SymbolicMixingScalarTypesTest, MatrixVectorMultiplicationVarDouble) { const MatrixX<Expression> M1{M_var_fixed_ * V_double_fixed_}; const MatrixX<Expression> M2{M_var_fixed_ * V_double_dyn_}; const MatrixX<Expression> M3{M_var_dyn_ * V_double_fixed_}; const MatrixX<Expression> M4{M_var_dyn_ * V_double_dyn_}; const string expected{ "(x + 2 * y)\n" "(z + 2 * w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorMatrixMultiplicationVarDouble) { const MatrixX<Expression> M1{V_var_fixed_.transpose() * M_double_fixed_}; const MatrixX<Expression> M2{V_var_fixed_.transpose() * M_double_dyn_}; const MatrixX<Expression> M3{V_var_dyn_.transpose() * M_double_fixed_}; const MatrixX<Expression> M4{V_var_dyn_.transpose() * M_double_dyn_}; const string expected{" (x + 3 * y) (2 * x + 4 * y)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorVectorMultiplicationVarDouble) { const MatrixX<Expression> M1{V_var_fixed_.transpose() * V_double_fixed_}; const MatrixX<Expression> M2{V_var_fixed_.transpose() * V_double_dyn_}; const MatrixX<Expression> M3{V_var_dyn_.transpose() * V_double_fixed_}; const MatrixX<Expression> M4{V_var_dyn_.transpose() * V_double_dyn_}; const string expected{"(x + 2 * y)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixMatrixMultiplicationDoubleVar) { const MatrixX<Expression> M1{M_double_fixed_ * M_var_fixed_}; const MatrixX<Expression> M2{M_double_fixed_ * M_var_dyn_}; const MatrixX<Expression> M3{M_double_dyn_ * M_var_fixed_}; const MatrixX<Expression> M4{M_double_dyn_ * M_var_dyn_}; const string expected{ " (x + 2 * z) (y + 2 * w)\n" "(3 * x + 4 * z) (3 * y + 4 * w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, MatrixMatrixMultiplicationDoubleVarHeap) { M_double_fixed_ = Eigen::Matrix2d::Identity(); const int expected_alloc = // The temporary flat_hash_set. 1 // One expression cell for each variable. + 4; LimitMalloc guard({.max_num_allocations = expected_alloc}); auto result = (M_double_fixed_ * M_var_fixed_).eval(); } TEST_F(SymbolicMixingScalarTypesTest, MatrixVectorMultiplicationDoubleVar) { const MatrixX<Expression> M1{M_double_fixed_ * V_var_fixed_}; const MatrixX<Expression> M2{M_double_fixed_ * V_var_dyn_}; const MatrixX<Expression> M3{M_double_dyn_ * V_var_fixed_}; const MatrixX<Expression> M4{M_double_dyn_ * V_var_dyn_}; const string expected{ " (x + 2 * y)\n" "(3 * x + 4 * y)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorMatrixMultiplicationDoubleVar) { const MatrixX<Expression> M1{V_double_fixed_.transpose() * M_var_fixed_}; const MatrixX<Expression> M2{V_double_fixed_.transpose() * M_var_dyn_}; const MatrixX<Expression> M3{V_double_dyn_.transpose() * M_var_fixed_}; const MatrixX<Expression> M4{V_double_dyn_.transpose() * M_var_dyn_}; const string expected{"(x + 2 * z) (y + 2 * w)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } TEST_F(SymbolicMixingScalarTypesTest, VectorVectorMultiplicationDoubleVar) { const MatrixX<Expression> M1{V_double_fixed_.transpose() * V_var_fixed_}; const MatrixX<Expression> M2{V_double_fixed_.transpose() * V_var_dyn_}; const MatrixX<Expression> M3{V_double_dyn_.transpose() * V_var_fixed_}; const MatrixX<Expression> M4{V_double_dyn_.transpose() * V_var_dyn_}; const string expected{"(x + 2 * y)"}; EXPECT_EQ(to_string(M1), expected); EXPECT_EQ(to_string(M2), expected); EXPECT_EQ(to_string(M3), expected); EXPECT_EQ(to_string(M4), expected); } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/variable_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <map> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include <Eigen/Core> #include <gtest/gtest.h> #include "drake/common/test_utilities/is_memcpy_movable.h" #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { using test::IsMemcpyMovable; namespace symbolic { namespace { using std::map; using std::unordered_map; using std::unordered_set; using std::vector; using test::VarEqual; using test::VarLess; using test::VarNotEqual; using test::VarNotLess; 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 VariableTest : 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> M_; void SetUp() override { // clang-format off M_ << x_, y_, z_, w_; // clang-format on } }; // Tests that default constructor and EIGEN_INITIALIZE_MATRICES_BY_ZERO // constructor both create the same value. TEST_F(VariableTest, DefaultConstructors) { const Variable v_default; const Variable v_zero(0); EXPECT_TRUE(v_default.is_dummy()); EXPECT_TRUE(v_zero.is_dummy()); // We don't especially care exactly what the name is, just that its non-empty. // For clarity, we'll check for an exact name here but it's OK for us to // change the name as we develop; the API doesn't promise any particular name. EXPECT_EQ(v_default.get_name(), "𝑥"); EXPECT_EQ(v_default.get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(v_default.get_id(), 0); const Variable copy(v_default); EXPECT_EQ(copy.get_name(), "𝑥"); EXPECT_EQ(copy.get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(copy.get_id(), 0); } TEST_F(VariableTest, GetId) { const Variable dummy{}; const Variable x_prime{"x"}; EXPECT_TRUE(dummy.is_dummy()); EXPECT_FALSE(x_.is_dummy()); EXPECT_FALSE(x_prime.is_dummy()); EXPECT_NE(x_.get_id(), x_prime.get_id()); } TEST_F(VariableTest, GetName) { const Variable x_prime{"x"}; EXPECT_EQ(x_.get_name(), x_prime.get_name()); } TEST_F(VariableTest, Copy) { const Variable x{"x"}; const size_t x_id{x.get_id()}; const size_t x_hash{get_std_hash(x)}; const std::string x_name{x.get_name()}; // The copied object has the same value. const Variable x_copied{x}; EXPECT_EQ(x_copied.get_id(), x_id); EXPECT_EQ(get_std_hash(x_copied), x_hash); EXPECT_EQ(x_copied.get_name(), x_name); } TEST_F(VariableTest, Move) { Variable x{"x"}; const size_t x_id{x.get_id()}; const size_t x_hash{get_std_hash(x)}; const std::string x_name{x.get_name()}; // The moved-to object has the same value. const Variable x_moved{std::move(x)}; EXPECT_EQ(x_moved.get_id(), x_id); EXPECT_EQ(get_std_hash(x_moved), x_hash); EXPECT_EQ(x_moved.get_name(), x_name); // The moved-from object matches a default-constructed Variable. const Variable expected; EXPECT_EQ(x.get_id(), expected.get_id()); EXPECT_EQ(get_std_hash(x), get_std_hash(expected)); EXPECT_EQ(x.get_name(), expected.get_name()); } TEST_F(VariableTest, Less) { EXPECT_PRED2(VarNotLess, x_, x_); EXPECT_PRED2(VarLess, x_, y_); EXPECT_PRED2(VarLess, x_, z_); EXPECT_PRED2(VarLess, x_, w_); EXPECT_PRED2(VarNotLess, y_, x_); EXPECT_PRED2(VarNotLess, y_, y_); EXPECT_PRED2(VarLess, y_, z_); EXPECT_PRED2(VarLess, y_, w_); EXPECT_PRED2(VarNotLess, z_, x_); EXPECT_PRED2(VarNotLess, z_, y_); EXPECT_PRED2(VarNotLess, z_, z_); EXPECT_PRED2(VarLess, z_, w_); EXPECT_PRED2(VarNotLess, w_, x_); EXPECT_PRED2(VarNotLess, w_, y_); EXPECT_PRED2(VarNotLess, w_, z_); EXPECT_PRED2(VarNotLess, w_, w_); } TEST_F(VariableTest, EqualTo) { EXPECT_PRED2(VarEqual, x_, x_); EXPECT_PRED2(VarNotEqual, x_, y_); EXPECT_PRED2(VarNotEqual, x_, z_); EXPECT_PRED2(VarNotEqual, x_, w_); EXPECT_PRED2(VarNotEqual, y_, x_); EXPECT_PRED2(VarEqual, y_, y_); EXPECT_PRED2(VarNotEqual, y_, z_); EXPECT_PRED2(VarNotEqual, y_, w_); EXPECT_PRED2(VarNotEqual, z_, x_); EXPECT_PRED2(VarNotEqual, z_, y_); EXPECT_PRED2(VarEqual, z_, z_); EXPECT_PRED2(VarNotEqual, z_, w_); EXPECT_PRED2(VarNotEqual, w_, x_); EXPECT_PRED2(VarNotEqual, w_, y_); EXPECT_PRED2(VarNotEqual, w_, z_); EXPECT_PRED2(VarEqual, w_, w_); } TEST_F(VariableTest, ToString) { EXPECT_EQ(x_.to_string(), "x"); EXPECT_EQ(y_.to_string(), "y"); EXPECT_EQ(z_.to_string(), "z"); EXPECT_EQ(w_.to_string(), "w"); } // This test checks whether Variable is compatible with std::unordered_set. TEST_F(VariableTest, CompatibleWithUnorderedSet) { unordered_set<Variable> uset; uset.emplace(x_); uset.emplace(y_); } // This test checks whether Variable is compatible with std::unordered_map. TEST_F(VariableTest, CompatibleWithUnorderedMap) { unordered_map<Variable, Variable> umap; umap.emplace(x_, y_); } // This test checks whether Variable is compatible with std::vector. TEST_F(VariableTest, CompatibleWithVector) { vector<Variable> vec; vec.push_back(x_); } TEST_F(VariableTest, EigenVariableMatrix) { EXPECT_PRED2(VarEqual, M_(0, 0), x_); EXPECT_PRED2(VarEqual, M_(0, 1), y_); EXPECT_PRED2(VarEqual, M_(1, 0), z_); EXPECT_PRED2(VarEqual, M_(1, 1), w_); } TEST_F(VariableTest, MemcpyKeepsVariableIntact) { // We have it to test that a variable with a long name (>16 chars), which is // not using SSO (Short String Optimization) internally, is memcpy-movable. const Variable long_var("12345678901234567890"); for (const Variable& var : {x_, y_, z_, w_, long_var}) { EXPECT_TRUE(IsMemcpyMovable(var)); } } TEST_F(VariableTest, CheckType) { // By default, a symbolic variable has CONTINUOUS type if not specified at // construction time. const Variable v1("v1"); EXPECT_EQ(v1.get_type(), Variable::Type::CONTINUOUS); // When a type is specified, it should be correctly assigned. const Variable v2("v2", Variable::Type::CONTINUOUS); const Variable v3("v3", Variable::Type::INTEGER); const Variable v4("v4", Variable::Type::BINARY); const Variable v5("v5", Variable::Type::BOOLEAN); EXPECT_EQ(v2.get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(v3.get_type(), Variable::Type::INTEGER); EXPECT_EQ(v4.get_type(), Variable::Type::BINARY); EXPECT_EQ(v5.get_type(), Variable::Type::BOOLEAN); // Dummy variable gets CONTINUOUS type. EXPECT_TRUE(Variable{}.get_type() == Variable::Type::CONTINUOUS); // Variables are identified by their IDs. Names and types are not considered // in the identification process. const Variable v_continuous("v", Variable::Type::CONTINUOUS); const Variable v_int("v", Variable::Type::INTEGER); EXPECT_FALSE(v_continuous.equal_to(v_int)); } TEST_F(VariableTest, MakeVectorVariable) { const VectorX<Variable> vec1{ MakeVectorVariable(2, "x", Variable::Type::CONTINUOUS)}; const Vector2<Variable> vec2{ MakeVectorVariable<2>("x", Variable::Type::CONTINUOUS)}; EXPECT_EQ(vec1.size(), 2); EXPECT_EQ(vec1[0].get_name(), "x(0)"); EXPECT_EQ(vec1[0].get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(vec1[1].get_name(), "x(1)"); EXPECT_EQ(vec1[1].get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(vec2.size(), 2); EXPECT_EQ(vec2[0].get_name(), "x(0)"); EXPECT_EQ(vec2[0].get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(vec2[1].get_name(), "x(1)"); EXPECT_EQ(vec2[1].get_type(), Variable::Type::CONTINUOUS); const VectorX<Variable> vec3{MakeVectorVariable(2, "x")}; const VectorX<Variable> vec4{MakeVectorVariable<2>("x")}; for (int i = 0; i < 2; ++i) { EXPECT_EQ(vec3[i].get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(vec4[i].get_type(), Variable::Type::CONTINUOUS); } } TEST_F(VariableTest, MakeVectorBooleanVariable) { const VectorX<Variable> vec1{MakeVectorBooleanVariable(2, "x")}; const Vector2<Variable> vec2{MakeVectorBooleanVariable<2>("x")}; EXPECT_EQ(vec1.size(), 2); EXPECT_EQ(vec1[0].get_name(), "x(0)"); EXPECT_EQ(vec1[0].get_type(), Variable::Type::BOOLEAN); EXPECT_EQ(vec1[1].get_name(), "x(1)"); EXPECT_EQ(vec1[1].get_type(), Variable::Type::BOOLEAN); EXPECT_EQ(vec2.size(), 2); EXPECT_EQ(vec2[0].get_name(), "x(0)"); EXPECT_EQ(vec2[0].get_type(), Variable::Type::BOOLEAN); EXPECT_EQ(vec2[1].get_name(), "x(1)"); EXPECT_EQ(vec2[1].get_type(), Variable::Type::BOOLEAN); } TEST_F(VariableTest, MakeVectorBinaryVariable) { const VectorX<Variable> vec1{MakeVectorBinaryVariable(2, "x")}; const Vector2<Variable> vec2{MakeVectorBinaryVariable<2>("x")}; EXPECT_EQ(vec1.size(), 2); EXPECT_EQ(vec1[0].get_name(), "x(0)"); EXPECT_EQ(vec1[0].get_type(), Variable::Type::BINARY); EXPECT_EQ(vec1[1].get_name(), "x(1)"); EXPECT_EQ(vec1[1].get_type(), Variable::Type::BINARY); EXPECT_EQ(vec2.size(), 2); EXPECT_EQ(vec2[0].get_name(), "x(0)"); EXPECT_EQ(vec2[0].get_type(), Variable::Type::BINARY); EXPECT_EQ(vec2[1].get_name(), "x(1)"); EXPECT_EQ(vec2[1].get_type(), Variable::Type::BINARY); } TEST_F(VariableTest, MakeVectorContinuousVariable) { const VectorX<Variable> vec1{MakeVectorContinuousVariable(2, "x")}; const Vector2<Variable> vec2{MakeVectorContinuousVariable<2>("x")}; EXPECT_EQ(vec1.size(), 2); EXPECT_EQ(vec1[0].get_name(), "x(0)"); EXPECT_EQ(vec1[0].get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(vec1[1].get_name(), "x(1)"); EXPECT_EQ(vec1[1].get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(vec2.size(), 2); EXPECT_EQ(vec2[0].get_name(), "x(0)"); EXPECT_EQ(vec2[0].get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(vec2[1].get_name(), "x(1)"); EXPECT_EQ(vec2[1].get_type(), Variable::Type::CONTINUOUS); } TEST_F(VariableTest, MakeVectorIntegerVariable) { const VectorX<Variable> vec1{MakeVectorIntegerVariable(2, "x")}; const Vector2<Variable> vec2{MakeVectorIntegerVariable<2>("x")}; EXPECT_EQ(vec1.size(), 2); EXPECT_EQ(vec1[0].get_name(), "x(0)"); EXPECT_EQ(vec1[0].get_type(), Variable::Type::INTEGER); EXPECT_EQ(vec1[1].get_name(), "x(1)"); EXPECT_EQ(vec1[1].get_type(), Variable::Type::INTEGER); EXPECT_EQ(vec2.size(), 2); EXPECT_EQ(vec2[0].get_name(), "x(0)"); EXPECT_EQ(vec2[0].get_type(), Variable::Type::INTEGER); EXPECT_EQ(vec2[1].get_name(), "x(1)"); EXPECT_EQ(vec2[1].get_type(), Variable::Type::INTEGER); } TEST_F(VariableTest, MakeMatrixVariable) { const MatrixX<Variable> m1{ MakeMatrixVariable(1, 2, "x", Variable::Type::CONTINUOUS)}; const auto m2 = MakeMatrixVariable<1, 2>("x", Variable::Type::CONTINUOUS); EXPECT_EQ(m1.rows(), 1); EXPECT_EQ(m1.cols(), 2); EXPECT_EQ(m1(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m1(0, 0).get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(m1(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m1(0, 1).get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(m2.rows(), 1); EXPECT_EQ(m2.cols(), 2); EXPECT_EQ(m2(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m2(0, 0).get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(m2(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m2(0, 1).get_type(), Variable::Type::CONTINUOUS); const MatrixX<Variable> m3{MakeMatrixVariable(1, 2, "x")}; const MatrixX<Variable> m4{MakeMatrixVariable<1, 2>("x")}; for (int i = 0; i < 2; ++i) { EXPECT_EQ(m3(0, i).get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(m4(0, i).get_type(), Variable::Type::CONTINUOUS); } } TEST_F(VariableTest, MakeMatrixBooleanVariable) { const MatrixX<Variable> m1{MakeMatrixBooleanVariable(1, 2, "x")}; const auto m2 = MakeMatrixBooleanVariable<1, 2>("x"); EXPECT_EQ(m1.rows(), 1); EXPECT_EQ(m1.cols(), 2); EXPECT_EQ(m1(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m1(0, 0).get_type(), Variable::Type::BOOLEAN); EXPECT_EQ(m1(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m1(0, 1).get_type(), Variable::Type::BOOLEAN); EXPECT_EQ(m2.rows(), 1); EXPECT_EQ(m2.cols(), 2); EXPECT_EQ(m2(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m2(0, 0).get_type(), Variable::Type::BOOLEAN); EXPECT_EQ(m2(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m2(0, 1).get_type(), Variable::Type::BOOLEAN); } TEST_F(VariableTest, MakeMatrixBinaryVariable) { const MatrixX<Variable> m1{MakeMatrixBinaryVariable(1, 2, "x")}; const auto m2 = MakeMatrixBinaryVariable<1, 2>("x"); EXPECT_EQ(m1.rows(), 1); EXPECT_EQ(m1.cols(), 2); EXPECT_EQ(m1(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m1(0, 0).get_type(), Variable::Type::BINARY); EXPECT_EQ(m1(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m1(0, 1).get_type(), Variable::Type::BINARY); EXPECT_EQ(m2.rows(), 1); EXPECT_EQ(m2.cols(), 2); EXPECT_EQ(m2(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m2(0, 0).get_type(), Variable::Type::BINARY); EXPECT_EQ(m2(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m2(0, 1).get_type(), Variable::Type::BINARY); } TEST_F(VariableTest, MakeMatrixContinuousVariable) { const MatrixX<Variable> m1{MakeMatrixContinuousVariable(1, 2, "x")}; const auto m2 = MakeMatrixContinuousVariable<1, 2>("x"); EXPECT_EQ(m1.rows(), 1); EXPECT_EQ(m1.cols(), 2); EXPECT_EQ(m1(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m1(0, 0).get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(m1(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m1(0, 1).get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(m2.rows(), 1); EXPECT_EQ(m2.cols(), 2); EXPECT_EQ(m2(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m2(0, 0).get_type(), Variable::Type::CONTINUOUS); EXPECT_EQ(m2(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m2(0, 1).get_type(), Variable::Type::CONTINUOUS); } TEST_F(VariableTest, MakeMatrixIntegerVariable) { const MatrixX<Variable> m1{MakeMatrixIntegerVariable(1, 2, "x")}; const auto m2 = MakeMatrixIntegerVariable<1, 2>("x"); EXPECT_EQ(m1.rows(), 1); EXPECT_EQ(m1.cols(), 2); EXPECT_EQ(m1(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m1(0, 0).get_type(), Variable::Type::INTEGER); EXPECT_EQ(m1(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m1(0, 1).get_type(), Variable::Type::INTEGER); EXPECT_EQ(m2.rows(), 1); EXPECT_EQ(m2.cols(), 2); EXPECT_EQ(m2(0, 0).get_name(), "x(0, 0)"); EXPECT_EQ(m2(0, 0).get_type(), Variable::Type::INTEGER); EXPECT_EQ(m2(0, 1).get_name(), "x(0, 1)"); EXPECT_EQ(m2(0, 1).get_type(), Variable::Type::INTEGER); } // Shows that a random uniform variable and std::uniform_real_distribution with // [0, 1) show the same behavior when the same random number generator is // passed. TEST_F(VariableTest, RandomUniform) { RandomGenerator generator{}; RandomGenerator generator_copy{generator}; const Variable v{"v", Variable::Type::RANDOM_UNIFORM}; const double sample{Expression{v}.Evaluate(&generator)}; std::uniform_real_distribution<double> d(0.0, 1.0); // [0, 1). const double expected{d(generator_copy)}; EXPECT_EQ(sample, expected); } // Shows that a random Gaussian variable and std::normal_distribution with (mean // = 0.0, stddev = 1.0) show the same behavior when the same random number // generator is passed. TEST_F(VariableTest, RandomGaussian) { RandomGenerator generator{}; RandomGenerator generator_copy{generator}; const Variable v{"v", Variable::Type::RANDOM_GAUSSIAN}; const double sample{Expression{v}.Evaluate(&generator)}; std::normal_distribution<double> d(0.0, 1.0); // mean = 0, stddev = 1.0. const double expected{d(generator_copy)}; EXPECT_EQ(sample, expected); } // Shows that a random exponential variable and std::exponential_distribution // with lambda = 1.0 show the same behavior when the same random number // generator is passed. TEST_F(VariableTest, RandomExponential) { RandomGenerator generator{}; RandomGenerator generator_copy{generator}; const Variable v{"v", Variable::Type::RANDOM_EXPONENTIAL}; const double sample{Expression{v}.Evaluate(&generator)}; std::exponential_distribution<double> d(1.0); // lambda = 1.0. const double expected{d(generator_copy)}; EXPECT_EQ(sample, expected); } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/expression_cell_test.cc
#define DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include "drake/common/symbolic/expression/expression_cell.h" #undef DRAKE_COMMON_SYMBOLIC_EXPRESSION_DETAIL_HEADER #include <gtest/gtest.h> #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { namespace symbolic { namespace { using test::ExprEqual; using test::FormulaEqual; // Provides common variables and expressions that are used by the following // tests. class SymbolicExpressionCellTest : 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 e_constant_{1.0}; const Expression e_var_{var_x_}; const Expression e_add_{x_ + y_}; const Expression e_mul_{x_ * y_}; const Expression e_div_{x_ / y_}; const Expression e_log_{log(x_)}; const Expression e_abs_{abs(x_)}; const Expression e_exp_{exp(x_)}; const Expression e_sqrt_{sqrt(x_)}; const Expression e_pow_{pow(x_, y_)}; const Expression e_sin_{sin(x_)}; const Expression e_cos_{cos(x_)}; const Expression e_tan_{tan(x_)}; const Expression e_asin_{asin(x_)}; const Expression e_acos_{acos(x_)}; const Expression e_atan_{atan(x_)}; const Expression e_atan2_{atan2(x_, y_)}; const Expression e_sinh_{sinh(x_)}; const Expression e_cosh_{cosh(x_)}; const Expression e_tanh_{tanh(x_)}; const Expression e_min_{min(x_, y_)}; const Expression e_max_{max(x_, y_)}; const Expression e_ceil_{ceil(x_)}; const Expression e_floor_{floor(x_)}; const Expression e_ite_{if_then_else(x_ < y_, x_, y_)}; const Expression e_uf_{uninterpreted_function("uf", {var_x_, var_y_})}; }; TEST_F(SymbolicExpressionCellTest, CastFunctionsConst) { EXPECT_EQ(to_variable(e_var_).get_variable(), get_variable(e_var_)); EXPECT_EQ(to_addition(e_add_).get_constant(), get_constant_in_addition(e_add_)); EXPECT_EQ(to_addition(e_add_).get_expr_to_coeff_map(), get_expr_to_coeff_map_in_addition(e_add_)); EXPECT_EQ(to_multiplication(e_mul_).get_constant(), get_constant_in_multiplication(e_mul_)); EXPECT_EQ(to_multiplication(e_mul_).get_base_to_exponent_map().size(), get_base_to_exponent_map_in_multiplication(e_mul_).size()); EXPECT_EQ(to_multiplication(e_mul_).get_base_to_exponent_map().size(), 2); EXPECT_PRED2(ExprEqual, to_multiplication(e_mul_).get_base_to_exponent_map().at(var_x_), get_base_to_exponent_map_in_multiplication(e_mul_).at(var_x_)); EXPECT_PRED2(ExprEqual, to_multiplication(e_mul_).get_base_to_exponent_map().at(var_y_), get_base_to_exponent_map_in_multiplication(e_mul_).at(var_y_)); EXPECT_EQ(to_division(e_div_).get_second_argument(), get_second_argument(e_div_)); EXPECT_EQ(to_division(e_div_).get_second_argument(), get_second_argument(e_div_)); EXPECT_EQ(to_log(e_log_).get_argument(), get_argument(e_log_)); EXPECT_EQ(to_abs(e_abs_).get_argument(), get_argument(e_abs_)); EXPECT_EQ(to_exp(e_exp_).get_argument(), get_argument(e_exp_)); EXPECT_EQ(to_sqrt(e_sqrt_).get_argument(), get_argument(e_sqrt_)); EXPECT_EQ(to_pow(e_pow_).get_first_argument(), get_first_argument(e_pow_)); EXPECT_EQ(to_pow(e_pow_).get_second_argument(), get_second_argument(e_pow_)); EXPECT_EQ(to_sin(e_sin_).get_argument(), get_argument(e_sin_)); EXPECT_EQ(to_cos(e_cos_).get_argument(), get_argument(e_cos_)); EXPECT_EQ(to_tan(e_tan_).get_argument(), get_argument(e_tan_)); EXPECT_EQ(to_asin(e_asin_).get_argument(), get_argument(e_asin_)); EXPECT_EQ(to_acos(e_acos_).get_argument(), get_argument(e_acos_)); EXPECT_EQ(to_atan(e_atan_).get_argument(), get_argument(e_atan_)); EXPECT_EQ(to_atan2(e_atan2_).get_first_argument(), get_first_argument(e_atan2_)); EXPECT_EQ(to_atan2(e_atan2_).get_second_argument(), get_second_argument(e_atan2_)); EXPECT_EQ(to_sinh(e_sinh_).get_argument(), get_argument(e_sinh_)); EXPECT_EQ(to_cosh(e_cosh_).get_argument(), get_argument(e_cosh_)); EXPECT_EQ(to_tanh(e_tanh_).get_argument(), get_argument(e_tanh_)); EXPECT_EQ(to_min(e_min_).get_first_argument(), get_first_argument(e_min_)); EXPECT_EQ(to_min(e_min_).get_second_argument(), get_second_argument(e_min_)); EXPECT_EQ(to_max(e_max_).get_first_argument(), get_first_argument(e_max_)); EXPECT_EQ(to_max(e_max_).get_second_argument(), get_second_argument(e_max_)); EXPECT_EQ(to_ceil(e_ceil_).get_argument(), get_argument(e_ceil_)); EXPECT_EQ(to_floor(e_floor_).get_argument(), get_argument(e_floor_)); EXPECT_PRED2(FormulaEqual, to_if_then_else(e_ite_).get_conditional_formula(), get_conditional_formula(e_ite_)); EXPECT_PRED2(ExprEqual, to_if_then_else(e_ite_).get_then_expression(), get_then_expression(e_ite_)); EXPECT_PRED2(ExprEqual, to_if_then_else(e_ite_).get_else_expression(), get_else_expression(e_ite_)); EXPECT_EQ(to_uninterpreted_function(e_uf_).get_name(), get_uninterpreted_function_name(e_uf_)); EXPECT_EQ(to_uninterpreted_function(e_uf_).get_arguments().size(), 2); EXPECT_EQ(to_uninterpreted_function(e_uf_).get_arguments().size(), get_uninterpreted_function_arguments(e_uf_).size()); EXPECT_EQ(to_uninterpreted_function(e_uf_).get_arguments()[0], get_uninterpreted_function_arguments(e_uf_)[0]); EXPECT_EQ(to_uninterpreted_function(e_uf_).get_arguments()[1], get_uninterpreted_function_arguments(e_uf_)[1]); } TEST_F(SymbolicExpressionCellTest, CastFunctionsNonConst) { EXPECT_EQ(to_variable(Expression{e_var_}).get_variable(), get_variable(e_var_)); EXPECT_EQ(to_addition(Expression{e_add_}).get_constant(), get_constant_in_addition(e_add_)); EXPECT_EQ(to_addition(Expression{e_add_}).get_expr_to_coeff_map(), get_expr_to_coeff_map_in_addition(e_add_)); EXPECT_EQ(to_multiplication(Expression{e_mul_}).get_constant(), get_constant_in_multiplication(e_mul_)); EXPECT_EQ( to_multiplication(Expression{e_mul_}).get_base_to_exponent_map().size(), get_base_to_exponent_map_in_multiplication(e_mul_).size()); EXPECT_EQ( to_multiplication(Expression{e_mul_}).get_base_to_exponent_map().size(), 2); EXPECT_PRED2(ExprEqual, to_multiplication(Expression{e_mul_}) .get_base_to_exponent_map() .at(var_x_), get_base_to_exponent_map_in_multiplication(e_mul_).at(var_x_)); EXPECT_PRED2(ExprEqual, to_multiplication(Expression{e_mul_}) .get_base_to_exponent_map() .at(var_y_), get_base_to_exponent_map_in_multiplication(e_mul_).at(var_y_)); EXPECT_EQ(to_division(Expression{e_div_}).get_second_argument(), get_second_argument(e_div_)); EXPECT_EQ(to_division(Expression{e_div_}).get_second_argument(), get_second_argument(e_div_)); EXPECT_EQ(to_log(Expression{e_log_}).get_argument(), get_argument(e_log_)); EXPECT_EQ(to_abs(Expression{e_abs_}).get_argument(), get_argument(e_abs_)); EXPECT_EQ(to_exp(Expression{e_exp_}).get_argument(), get_argument(e_exp_)); EXPECT_EQ(to_sqrt(Expression{e_sqrt_}).get_argument(), get_argument(e_sqrt_)); EXPECT_EQ(to_pow(Expression{e_pow_}).get_first_argument(), get_first_argument(e_pow_)); EXPECT_EQ(to_pow(Expression{e_pow_}).get_second_argument(), get_second_argument(e_pow_)); EXPECT_EQ(to_sin(Expression{e_sin_}).get_argument(), get_argument(e_sin_)); EXPECT_EQ(to_cos(Expression{e_cos_}).get_argument(), get_argument(e_cos_)); EXPECT_EQ(to_tan(Expression{e_tan_}).get_argument(), get_argument(e_tan_)); EXPECT_EQ(to_asin(Expression{e_asin_}).get_argument(), get_argument(e_asin_)); EXPECT_EQ(to_acos(Expression{e_acos_}).get_argument(), get_argument(e_acos_)); EXPECT_EQ(to_atan(Expression{e_atan_}).get_argument(), get_argument(e_atan_)); EXPECT_EQ(to_atan2(Expression{e_atan2_}).get_first_argument(), get_first_argument(e_atan2_)); EXPECT_EQ(to_atan2(Expression{e_atan2_}).get_second_argument(), get_second_argument(e_atan2_)); EXPECT_EQ(to_sinh(Expression{e_sinh_}).get_argument(), get_argument(e_sinh_)); EXPECT_EQ(to_cosh(Expression{e_cosh_}).get_argument(), get_argument(e_cosh_)); EXPECT_EQ(to_tanh(Expression{e_tanh_}).get_argument(), get_argument(e_tanh_)); EXPECT_EQ(to_min(Expression{e_min_}).get_first_argument(), get_first_argument(e_min_)); EXPECT_EQ(to_min(Expression{e_min_}).get_second_argument(), get_second_argument(e_min_)); EXPECT_EQ(to_max(Expression{e_max_}).get_first_argument(), get_first_argument(e_max_)); EXPECT_EQ(to_max(Expression{e_max_}).get_second_argument(), get_second_argument(e_max_)); EXPECT_EQ(to_ceil(Expression{e_ceil_}).get_argument(), get_argument(e_ceil_)); EXPECT_EQ(to_floor(Expression{e_floor_}).get_argument(), get_argument(e_floor_)); EXPECT_PRED2(FormulaEqual, to_if_then_else(Expression{e_ite_}).get_conditional_formula(), get_conditional_formula(e_ite_)); EXPECT_PRED2(ExprEqual, to_if_then_else(Expression{e_ite_}).get_then_expression(), get_then_expression(e_ite_)); EXPECT_PRED2(ExprEqual, to_if_then_else(Expression{e_ite_}).get_else_expression(), get_else_expression(e_ite_)); EXPECT_EQ(to_uninterpreted_function(Expression{e_uf_}).get_name(), get_uninterpreted_function_name(e_uf_)); EXPECT_EQ(to_uninterpreted_function(Expression{e_uf_}).get_arguments().size(), 2); EXPECT_EQ(to_uninterpreted_function(Expression{e_uf_}).get_arguments().size(), get_uninterpreted_function_arguments(e_uf_).size()); EXPECT_EQ(to_uninterpreted_function(Expression{e_uf_}).get_arguments()[0], get_uninterpreted_function_arguments(e_uf_)[0]); EXPECT_EQ(to_uninterpreted_function(Expression{e_uf_}).get_arguments()[1], get_uninterpreted_function_arguments(e_uf_)[1]); } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/variable_overloading_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <sstream> #include <gtest/gtest.h> #include "drake/common/fmt_eigen.h" #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { namespace symbolic { namespace { using std::ostringstream; using symbolic::Expression; using symbolic::test::ExprEqual; // 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<double, 2, 2, Eigen::DontAlign> double_mat_; Eigen::Matrix<Variable, 2, 2, Eigen::DontAlign> var_mat_; Eigen::Matrix<Expression, 2, 2, Eigen::DontAlign> expr_mat_; void SetUp() override { // clang-format off double_mat_ << 1.0, 2.0, 3.0, 4.0; var_mat_ << x_, y_, z_, w_; expr_mat_ << (x_ + z_), (x_ + w_), (y_ + z_), (y_ + w_); // clang-format on } }; TEST_F(VariableOverloadingTest, OperatorOverloadingArithmetic) { // Variable op Variable. const Expression e1{x_ + y_}; const Expression e2{x_ - y_}; const Expression e3{x_ * y_}; const Expression e4{x_ / y_}; EXPECT_EQ(e1.to_string(), "(x + y)"); EXPECT_EQ(e2.to_string(), "(x - y)"); EXPECT_EQ(e3.to_string(), "(x * y)"); EXPECT_EQ(e4.to_string(), "(x / y)"); // Expression op Variable. const Expression e5{e1 + z_}; // (x + y) + z const Expression e6{e2 - z_}; // (x - y) - z const Expression e7{e3 * z_}; // (x * y) * z const Expression e8{e4 / z_}; // (x / y) / z EXPECT_EQ(e5.to_string(), "(x + y + z)"); EXPECT_EQ(e6.to_string(), "(x - y - z)"); EXPECT_EQ(e7.to_string(), "(x * y * z)"); EXPECT_EQ(e8.to_string(), "((x / y) / z)"); // Variable op Expression. const Expression e9{w_ + e1}; // w + (x + y) -> x + y + w const Expression e10{w_ - e2}; // w - (x - y) -> w -x + y -> -x + y + w const Expression e11{w_ * e3}; // w * (x * y) -> x * y * w const Expression e12{w_ / e4}; // w / (x / y) EXPECT_EQ(e9.to_string(), "(x + y + w)"); EXPECT_EQ(e10.to_string(), "( - x + y + w)"); EXPECT_EQ(e11.to_string(), "(x * y * w)"); EXPECT_EQ(e12.to_string(), "(w / (x / y))"); // Variable op double. const Expression e13{x_ + 5.0}; // x + 5 -> 5 + x const Expression e14{x_ - 5.0}; // x - 5 -> -5 + x const Expression e15{x_ * 5.0}; // x * 5 -> 5 * x const Expression e16{x_ / 5.0}; EXPECT_EQ(e13.to_string(), "(5 + x)"); EXPECT_EQ(e14.to_string(), "(-5 + x)"); EXPECT_EQ(e15.to_string(), "(5 * x)"); EXPECT_EQ(e16.to_string(), "(x / 5)"); // double op Variable. const Expression e17{5.0 + y_}; const Expression e18{5.0 - y_}; const Expression e19{5.0 * y_}; const Expression e20{5.0 / y_}; EXPECT_EQ(e17.to_string(), "(5 + y)"); EXPECT_EQ(e18.to_string(), "(5 - y)"); EXPECT_EQ(e19.to_string(), "(5 * y)"); EXPECT_EQ(e20.to_string(), "(5 / y)"); } TEST_F(VariableOverloadingTest, OperatorOverloadingArithmeticAssignment) { Expression e{x_ + y_}; e += z_; // x + y + z EXPECT_EQ(e.to_string(), "(x + y + z)"); e -= x_; // y + z EXPECT_EQ(e.to_string(), "(y + z)"); e *= w_; // w * (y + z) EXPECT_EQ(e.to_string(), "(w * (y + z))"); e /= y_; // (w * (y + z)) / y EXPECT_EQ(e.to_string(), "((w * (y + z)) / y)"); } TEST_F(VariableOverloadingTest, OperatorOverloadingEigenTestSanityCheck) { // [1.0 2.0] // [3.0 4.0] EXPECT_EQ(double_mat_(0, 0), 1.0); EXPECT_EQ(double_mat_(0, 1), 2.0); EXPECT_EQ(double_mat_(1, 0), 3.0); EXPECT_EQ(double_mat_(1, 1), 4.0); // [x y] // [z w] EXPECT_EQ(var_mat_(0, 0), x_); EXPECT_EQ(var_mat_(0, 1), y_); EXPECT_EQ(var_mat_(1, 0), z_); EXPECT_EQ(var_mat_(1, 1), w_); // [x + z x + w] // [y + z y + w] EXPECT_PRED2(ExprEqual, expr_mat_(0, 0), x_ + z_); EXPECT_PRED2(ExprEqual, expr_mat_(0, 1), x_ + w_); EXPECT_PRED2(ExprEqual, expr_mat_(1, 0), y_ + z_); EXPECT_PRED2(ExprEqual, expr_mat_(1, 1), y_ + w_); } TEST_F(VariableOverloadingTest, OperatorOverloadingEigenVariableOpVariable) { const Eigen::Matrix<Expression, 2, 2> m1{var_mat_ + var_mat_}; const Eigen::Matrix<Expression, 2, 2> m2{var_mat_ - var_mat_}; const Eigen::Matrix<Expression, 2, 2> m3{var_mat_ * var_mat_}; // [x y] + [x y] = [x + x y + y] // [z w] [z w] [z + z w + w] EXPECT_PRED2(ExprEqual, m1(0, 0), x_ + x_); EXPECT_PRED2(ExprEqual, m1(0, 1), y_ + y_); EXPECT_PRED2(ExprEqual, m1(1, 0), z_ + z_); EXPECT_PRED2(ExprEqual, m1(1, 1), w_ + w_); // [x y] - [x y] = [x - x y - y] = [0 0] // [z w] [z w] [z - z w - w] [0 0] EXPECT_PRED2(ExprEqual, m2(0, 0), 0.0); EXPECT_PRED2(ExprEqual, m2(0, 1), 0.0); EXPECT_PRED2(ExprEqual, m2(1, 0), 0.0); EXPECT_PRED2(ExprEqual, m2(1, 1), 0.0); // [x y] * [x y] = [x * x + y * z x * y + y * w] // [z w] [z w] [z * x + w * z z * y + w * w] EXPECT_PRED2(ExprEqual, m3(0, 0), x_ * x_ + y_ * z_); EXPECT_PRED2(ExprEqual, m3(0, 1), x_ * y_ + y_ * w_); EXPECT_PRED2(ExprEqual, m3(1, 0), z_ * x_ + w_ * z_); EXPECT_PRED2(ExprEqual, m3(1, 1), z_ * y_ + w_ * w_); } TEST_F(VariableOverloadingTest, OperatorOverloadingEigenVariableOpExpression) { const Eigen::Matrix<Expression, 2, 2> m1{var_mat_ + expr_mat_}; const Eigen::Matrix<Expression, 2, 2> m2{var_mat_ - expr_mat_}; const Eigen::Matrix<Expression, 2, 2> m3{var_mat_ * expr_mat_}; // [x y] + [x + z x + w] = [x + x + z y + x + w] // [z w] [y + z y + w] [z + y + z w + y + w] EXPECT_PRED2(ExprEqual, m1(0, 0), x_ + x_ + z_); EXPECT_PRED2(ExprEqual, m1(0, 1), y_ + x_ + w_); EXPECT_PRED2(ExprEqual, m1(1, 0), z_ + y_ + z_); EXPECT_PRED2(ExprEqual, m1(1, 1), w_ + y_ + w_); // [x y] - [x + z x + w] = [x - (x + z) y - (x + w)] // [z w] [y + z y + w] [z - (y + z) w - (y + w)] EXPECT_PRED2(ExprEqual, m2(0, 0), x_ - (x_ + z_)); EXPECT_PRED2(ExprEqual, m2(0, 1), y_ - (x_ + w_)); EXPECT_PRED2(ExprEqual, m2(1, 0), z_ - (y_ + z_)); EXPECT_PRED2(ExprEqual, m2(1, 1), w_ - (y_ + w_)); // [x y] * [x + z x + w] // [z w] [y + z y + w] // = [x * (x + z) + y * (y + z) x * (x + w) + y * (y + w)] // [z * (x + z) + w * (y + z) z * (x + w) + w * (y + w)] EXPECT_PRED2(ExprEqual, m3(0, 0), x_ * (x_ + z_) + y_ * (y_ + z_)); EXPECT_PRED2(ExprEqual, m3(0, 1), x_ * (x_ + w_) + y_ * (y_ + w_)); EXPECT_PRED2(ExprEqual, m3(1, 0), z_ * (x_ + z_) + w_ * (y_ + z_)); EXPECT_PRED2(ExprEqual, m3(1, 1), z_ * (x_ + w_) + w_ * (y_ + w_)); } TEST_F(VariableOverloadingTest, OperatorOverloadingEigenExpressionOpVariable) { const Eigen::Matrix<Expression, 2, 2> m1{expr_mat_ + var_mat_}; const Eigen::Matrix<Expression, 2, 2> m2{expr_mat_ - var_mat_}; const Eigen::Matrix<Expression, 2, 2> m3{expr_mat_ * var_mat_}; // [x + z x + w] + [x y] = [x + z + x x + w + y] // [y + z y + w] [z w] [y + z + z y + w + w] EXPECT_PRED2(ExprEqual, m1(0, 0), x_ + z_ + x_); EXPECT_PRED2(ExprEqual, m1(0, 1), x_ + w_ + y_); EXPECT_PRED2(ExprEqual, m1(1, 0), y_ + z_ + z_); EXPECT_PRED2(ExprEqual, m1(1, 1), y_ + w_ + w_); // [x + z x + w] - [x y] = [x + z - x x + w - y] // [y + z y + w] [z w] [y + z - z y + w - w] EXPECT_PRED2(ExprEqual, m2(0, 0), x_ + z_ - x_); EXPECT_PRED2(ExprEqual, m2(0, 1), x_ + w_ - y_); EXPECT_PRED2(ExprEqual, m2(1, 0), y_ + z_ - z_); EXPECT_PRED2(ExprEqual, m2(1, 1), y_ + w_ - w_); // [x + z x + w] * [x y] // [y + z y + w] [z w] // // = [(x + z) * x + (x + w) * z (x + z) * y + (x + w) * w] // [(y + z) * x + (y + w) * z (y + z) * y + (y + w) * w] EXPECT_PRED2(ExprEqual, m3(0, 0), (x_ + z_) * x_ + (x_ + w_) * z_); EXPECT_PRED2(ExprEqual, m3(0, 1), (x_ + z_) * y_ + (x_ + w_) * w_); EXPECT_PRED2(ExprEqual, m3(1, 0), (y_ + z_) * x_ + (y_ + w_) * z_); EXPECT_PRED2(ExprEqual, m3(1, 1), (y_ + z_) * y_ + (y_ + w_) * w_); } TEST_F(VariableOverloadingTest, OperatorOverloadingEigenVariableOpDouble) { const Eigen::Matrix<Expression, 2, 2> m1{var_mat_ + double_mat_}; const Eigen::Matrix<Expression, 2, 2> m2{var_mat_ - double_mat_}; const Eigen::Matrix<Expression, 2, 2> m3{var_mat_ * double_mat_}; // [x y] + [1.0 2.0] = [x + 1.0 y + 2.0] // [z w] [3.0 4.0] [z + 3.0 w + 4.0] EXPECT_PRED2(ExprEqual, m1(0, 0), x_ + 1.0); EXPECT_PRED2(ExprEqual, m1(0, 1), y_ + 2.0); EXPECT_PRED2(ExprEqual, m1(1, 0), z_ + 3.0); EXPECT_PRED2(ExprEqual, m1(1, 1), w_ + 4.0); // [x y] - [1.0 2.0] = [x - 1.0 y - 2.0] // [z w] [3.0 4.0] [z - 3.0 w - 4.0] EXPECT_PRED2(ExprEqual, m2(0, 0), x_ - 1.0); EXPECT_PRED2(ExprEqual, m2(0, 1), y_ - 2.0); EXPECT_PRED2(ExprEqual, m2(1, 0), z_ - 3.0); EXPECT_PRED2(ExprEqual, m2(1, 1), w_ - 4.0); // [x y] * [1.0 2.0] = [x * 1.0 + y * 3.0 x * 2.0 + y * 4.0] // [z w] [3.0 4.0] [z * 1.0 + w * 3.0 z * 2.0 + y * 4.0] EXPECT_PRED2(ExprEqual, m3(0, 0), x_ * 1.0 + y_ * 3.0); EXPECT_PRED2(ExprEqual, m3(0, 1), x_ * 2.0 + y_ * 4.0); EXPECT_PRED2(ExprEqual, m3(1, 0), z_ * 1.0 + w_ * 3.0); EXPECT_PRED2(ExprEqual, m3(1, 1), z_ * 2.0 + w_ * 4.0); } TEST_F(VariableOverloadingTest, OperatorOverloadingEigenDoubleOpVariable) { const Eigen::Matrix<Expression, 2, 2> m1{double_mat_ + var_mat_}; const Eigen::Matrix<Expression, 2, 2> m2{double_mat_ - var_mat_}; const Eigen::Matrix<Expression, 2, 2> m3{double_mat_ * var_mat_}; // [1.0 2.0] + [x y] = [1.0 + x 2.0 + y] // [3.0 4.0] [z w] [3.0 + z 4.0 + w] EXPECT_PRED2(ExprEqual, m1(0, 0), 1.0 + x_); EXPECT_PRED2(ExprEqual, m1(0, 1), 2.0 + y_); EXPECT_PRED2(ExprEqual, m1(1, 0), 3.0 + z_); EXPECT_PRED2(ExprEqual, m1(1, 1), 4.0 + w_); // [1.0 2.0] - [x y] = [1.0 - x 2.0 - y] // [3.0 4.0] [z w] [3.0 - z 4.0 - w] EXPECT_PRED2(ExprEqual, m2(0, 0), 1.0 - x_); EXPECT_PRED2(ExprEqual, m2(0, 1), 2.0 - y_); EXPECT_PRED2(ExprEqual, m2(1, 0), 3.0 - z_); EXPECT_PRED2(ExprEqual, m2(1, 1), 4.0 - w_); // [1.0 2.0] * [x y] = [1.0 * x + 2.0 * z 1.0 * y + 2.0 * w] // [3.0 4.0] [z w] [3.0 * x + 4.0 * z 3.0 * y + 4.0 * w] EXPECT_PRED2(ExprEqual, m3(0, 0), 1.0 * x_ + 2.0 * z_); EXPECT_PRED2(ExprEqual, m3(0, 1), 1.0 * y_ + 2.0 * w_); EXPECT_PRED2(ExprEqual, m3(1, 0), 3.0 * x_ + 4.0 * z_); EXPECT_PRED2(ExprEqual, m3(1, 1), 3.0 * y_ + 4.0 * w_); } TEST_F(VariableOverloadingTest, OperatorOverloadingEigenDivideByVariable) { const Eigen::Matrix<Expression, 2, 2> m1{double_mat_ / x_}; const Eigen::Matrix<Expression, 2, 2> m2{var_mat_ / x_}; const Eigen::Matrix<Expression, 2, 2> m3{expr_mat_ / x_}; // [1.0 2.0] / x = [1.0 / x 2.0 / x] // [3.0 4.0] [3.0 / x 4.0 / x] EXPECT_PRED2(ExprEqual, m1(0, 0), 1.0 / x_); EXPECT_PRED2(ExprEqual, m1(0, 1), 2.0 / x_); EXPECT_PRED2(ExprEqual, m1(1, 0), 3.0 / x_); EXPECT_PRED2(ExprEqual, m1(1, 1), 4.0 / x_); // [x y] / x = [x / x y / x] // [z w] [z / x w / x] EXPECT_PRED2(ExprEqual, m2(0, 0), x_ / x_); EXPECT_PRED2(ExprEqual, m2(0, 1), y_ / x_); EXPECT_PRED2(ExprEqual, m2(1, 0), z_ / x_); EXPECT_PRED2(ExprEqual, m2(1, 1), w_ / x_); // [x + z x + w] / x = [(x + z) / x (x + w) / x] // [y + z y + w] [(y + z) / x (y + w) / x] EXPECT_PRED2(ExprEqual, m3(0, 0), (x_ + z_) / x_); EXPECT_PRED2(ExprEqual, m3(0, 1), (x_ + w_) / x_); EXPECT_PRED2(ExprEqual, m3(1, 0), (y_ + z_) / x_); EXPECT_PRED2(ExprEqual, m3(1, 1), (y_ + w_) / x_); } TEST_F(VariableOverloadingTest, OperatorOverloadingEigenDivideVariable) { const Eigen::Matrix<Expression, 2, 2> m1{var_mat_ / 3.0}; const Eigen::Matrix<Expression, 2, 2> m2{var_mat_ / (x_ + y_)}; // [x y] / 3.0 = [x / 3.0 y / 3.0] // [z w] [z / 3.0 w / 3.0] EXPECT_PRED2(ExprEqual, m1(0, 0), x_ / 3.0); EXPECT_PRED2(ExprEqual, m1(0, 1), y_ / 3.0); EXPECT_PRED2(ExprEqual, m1(1, 0), z_ / 3.0); EXPECT_PRED2(ExprEqual, m1(1, 1), w_ / 3.0); // [x y] / (x + y) = [x / (x + y) y / (x + y)] // [z w] [z / (x + y) w / (x + y)] EXPECT_PRED2(ExprEqual, m2(0, 0), x_ / (x_ + y_)); EXPECT_PRED2(ExprEqual, m2(0, 1), y_ / (x_ + y_)); EXPECT_PRED2(ExprEqual, m2(1, 0), z_ / (x_ + y_)); EXPECT_PRED2(ExprEqual, m2(1, 1), w_ / (x_ + y_)); } TEST_F(VariableOverloadingTest, EigenExpressionMatrixOutputFmt) { EXPECT_EQ(fmt::to_string(fmt_eigen(expr_mat_)), "(x + z) (x + w)\n" "(y + z) (y + w)"); } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/expression_transform_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" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/rotation_matrix.h" namespace drake { namespace symbolic { namespace { using math::RotationMatrixd; class SymbolicExpressionTransformationTest : public ::testing::Test { protected: void SetUp() override { R1_ = RotationMatrixd::MakeXRotation(.25 * M_PI) * RotationMatrixd::MakeYRotation(.5 * M_PI) * RotationMatrixd::MakeZRotation(.33 * M_PI); R2_ = RotationMatrixd::MakeXRotation(M_PI / 2) * RotationMatrixd::MakeYRotation(-M_PI / 2) * RotationMatrixd::MakeZRotation(M_PI / 2); affine_.setIdentity(); affine_.rotate(R1_.matrix()); affine_.translation() << 1.0, 2.0, 3.0; affine_compact_.setIdentity(); affine_compact_.rotate((R1_ * R2_).matrix()); affine_compact_.translation() << -2.0, 1.0, 3.0; isometry_.setIdentity(); isometry_.rotate(-R2_.matrix()); isometry_.translation() << 3.0, -1.0, 2.0; projective_.setIdentity(); projective_.rotate(-(R2_ * R1_).matrix()); projective_.translation() << 2.0, 3.0, -1.0; } // Rotation Matrices. RotationMatrixd R1_; RotationMatrixd R2_; // Transformations. Eigen::Transform<double, 3, Eigen::Affine, Eigen::DontAlign> affine_; Eigen::Transform<double, 3, Eigen::AffineCompact, Eigen::DontAlign> affine_compact_; Eigen::Transform<double, 3, Eigen::Isometry, Eigen::DontAlign> isometry_; Eigen::Transform<double, 3, Eigen::Projective, Eigen::DontAlign> projective_; }; // Checks if `lhs.cast<Expression>() * rhs` and `(lhs * rhs).cast<Expression>()` // produce almost identical output. Also checks the symmetric case. See the // following commutative diagram. // * rhs // lhs --------------------------> lhs * rhs // || || // || cast<Expression>() || cast<Expression>() // \/ || // lhs.cast<Expression>() || // || || // || * rhs || // \/ ? \/ // lhs.cast<Expression>() * rhs == (lhs * rhs).cast<Expression>() // // The exactness is not guaranteed due to the non-associativity of // floating-point arithmetic (+, *). template <typename LhsTransform, typename RhsTransform> ::testing::AssertionResult CheckMultiplication(const LhsTransform& lhs, const RhsTransform& rhs) { const auto expected = (lhs * rhs).template cast<Expression>(); const auto lhs_cast = lhs.template cast<Expression>() * rhs; const auto rhs_cast = lhs * rhs.template cast<Expression>(); // Types should be identical. ::testing::StaticAssertTypeEq<decltype(expected), decltype(lhs_cast)>(); ::testing::StaticAssertTypeEq<decltype(expected), decltype(rhs_cast)>(); // Their matrices should be almost identical. const double absolute_tolerance{1e-15}; EXPECT_TRUE(CompareMatrices(expected.matrix(), lhs_cast.matrix(), absolute_tolerance)); EXPECT_TRUE(CompareMatrices(expected.matrix(), rhs_cast.matrix(), absolute_tolerance)); return ::testing::AssertionSuccess(); } TEST_F(SymbolicExpressionTransformationTest, CheckMultiplication) { EXPECT_TRUE(CheckMultiplication(affine_, affine_)); EXPECT_TRUE(CheckMultiplication(affine_, affine_compact_)); EXPECT_TRUE(CheckMultiplication(affine_, isometry_)); EXPECT_TRUE(CheckMultiplication(affine_, projective_)); EXPECT_TRUE(CheckMultiplication(affine_compact_, affine_)); EXPECT_TRUE(CheckMultiplication(affine_compact_, affine_compact_)); EXPECT_TRUE(CheckMultiplication(affine_compact_, isometry_)); EXPECT_TRUE(CheckMultiplication(affine_compact_, projective_)); EXPECT_TRUE(CheckMultiplication(isometry_, affine_)); EXPECT_TRUE(CheckMultiplication(isometry_, affine_compact_)); EXPECT_TRUE(CheckMultiplication(isometry_, isometry_)); EXPECT_TRUE(CheckMultiplication(isometry_, projective_)); EXPECT_TRUE(CheckMultiplication(projective_, affine_)); EXPECT_TRUE(CheckMultiplication(projective_, affine_compact_)); EXPECT_TRUE(CheckMultiplication(projective_, isometry_)); EXPECT_TRUE(CheckMultiplication(projective_, projective_)); } TEST_F(SymbolicExpressionTransformationTest, ExpectedAnswers) { Isometry3<Expression> isometry_expr; const Variable x{"x"}; const Variable y{"y"}; const Variable z{"z"}; isometry_expr.setIdentity(); isometry_expr.translation().x() = x; isometry_expr.translation().y() = y; isometry_expr.translation().z() = z; Isometry3<double> isometry_double; isometry_double.setIdentity(); isometry_double.translation().x() = 1; isometry_double.translation().y() = 2; isometry_double.translation().z() = 3; Eigen::Matrix3d R; // clang-format off R << 0, 0, -1, 0, 1, 0, 1, 0, 1; // clang-format on isometry_double.rotate(R); // Expected result from Transform<Expression> * Transform<double>. Eigen::Matrix<Expression, 4, 4> expected_expr_double; // clang-format off expected_expr_double << 0, 0, -1, (1 + x), 0, 1, 0, (2 + y), 1, 0, 1, (3 + z), 0, 0, 0, 1; // clang-format on EXPECT_EQ((isometry_expr * isometry_double).matrix(), expected_expr_double); // Expected result from Transform<double> * Transform<Expression>. Eigen::Matrix<Expression, 4, 4> expected_double_expr; // clang-format off expected_double_expr << 0, 0, -1, (1 - z), 0, 1, 0, (2 + y), 1, 0, 1, (3 + x + z), 0, 0, 0, 1; // clang-format on EXPECT_EQ((isometry_double * isometry_expr).matrix(), expected_double_expr); } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/expression_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <algorithm> #include <cmath> #include <functional> #include <map> #include <memory> #include <random> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include <gtest/gtest.h> #include "drake/common/hash.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/is_memcpy_movable.h" #include "drake/common/test_utilities/symbolic_test_util.h" using std::count_if; using std::domain_error; using std::equal_to; using std::map; using std::ostringstream; using std::pair; using std::runtime_error; using std::set; using std::string; using std::unordered_map; using std::unordered_set; using std::vector; namespace drake { using test::IsMemcpyMovable; namespace symbolic { namespace { using test::ExprEqual; using test::ExprLess; using test::ExprNotEqual; using test::ExprNotLess; using test::FormulaEqual; template <typename T> size_t get_std_hash(const T& item) { return std::hash<T>{}(item); } // Checks if a given 'expressions' is ordered by Expression::Less. void CheckOrdering(const vector<Expression>& expressions) { for (size_t i{0}; i < expressions.size(); ++i) { for (size_t j{0}; j < expressions.size(); ++j) { if (i < j) { EXPECT_PRED2(ExprLess, expressions[i], expressions[j]) << "(Expressions[" << i << "] = " << expressions[i] << ")" << " is not less than " << "(Expressions[" << j << "] = " << expressions[j] << ")"; EXPECT_PRED2(ExprNotLess, expressions[j], expressions[i]) << "(Expressions[" << j << "] = " << expressions[j] << ")" << " is less than " << "(Expressions[" << i << "] = " << expressions[i] << ")"; } else if (i > j) { EXPECT_PRED2(ExprLess, expressions[j], expressions[i]) << "(Expressions[" << j << "] = " << expressions[j] << ")" << " is not less than " << "(Expressions[" << i << "] = " << expressions[i] << ")"; EXPECT_PRED2(ExprNotLess, expressions[i], expressions[j]) << "(Expressions[" << i << "] = " << expressions[i] << ")" << " is less than " << "(Expressions[" << j << "] = " << expressions[j] << ")"; } else { EXPECT_PRED2(ExprNotLess, expressions[i], expressions[j]) << "(Expressions[" << i << "] = " << expressions[i] << ")" << " is less than " << "(Expressions[" << j << "] = " << expressions[j] << ")"; EXPECT_PRED2(ExprNotLess, expressions[j], expressions[i]) << "(Expressions[" << j << "] = " << expressions[j] << ")" << " is less than " << "(Expressions[" << i << "] = " << expressions[i] << ")"; } } } } // Provides common variables that are used by the following tests. class SymbolicExpressionTest : public ::testing::Test { protected: const Variable var_a_{"a"}; const Variable var_x_{"x"}; const Variable var_y_{"y"}; const Variable var_z_{"z"}; const Expression a_{var_a_}; const Expression x_{var_x_}; const Expression y_{var_y_}; const Expression z_{var_z_}; const Expression x_plus_y_{x_ + y_}; const Expression x_plus_z_{x_ + 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_{M_PI}; const Expression neg_pi_{-M_PI}; const Expression e_{M_E}; const Expression inf_{std::numeric_limits<double>::infinity()}; const Expression c1_{-10.0}; const Expression c2_{1.0}; const Expression c3_{3.14159}; const Expression c4_{-2.718}; const Expression e_constant_{1.0}; const Expression e_var_{var_x_}; const Expression e_add_{x_ + y_}; const Expression e_neg_{-x_}; // -1 * x_ const Expression e_mul_{x_ * y_}; const Expression e_div_{x_ / y_}; const Expression e_log_{log(x_)}; const Expression e_abs_{abs(x_)}; const Expression e_exp_{exp(x_)}; const Expression e_sqrt_{sqrt(x_)}; const Expression e_pow_{pow(x_, y_)}; const Expression e_sin_{sin(x_)}; const Expression e_cos_{cos(x_)}; const Expression e_tan_{tan(x_)}; const Expression e_asin_{asin(x_)}; const Expression e_acos_{acos(x_)}; const Expression e_atan_{atan(x_)}; const Expression e_atan2_{atan2(x_, y_)}; const Expression e_sinh_{sinh(x_)}; const Expression e_cosh_{cosh(x_)}; const Expression e_tanh_{tanh(x_)}; const Expression e_min_{min(x_, y_)}; const Expression e_max_{max(x_, y_)}; const Expression e_ceil_{ceil(x_)}; const Expression e_floor_{floor(x_)}; const Expression e_ite_{if_then_else(x_ < y_, x_, y_)}; const Expression e_nan_{Expression::NaN()}; const Expression e_uf_{uninterpreted_function("uf", {var_x_, var_y_})}; const vector<Expression> collection_{ e_constant_, e_var_, e_add_, e_neg_, e_mul_, e_div_, e_log_, e_abs_, e_exp_, e_sqrt_, e_pow_, e_sin_, e_cos_, e_tan_, e_asin_, e_acos_, e_atan_, e_atan2_, e_sinh_, e_cosh_, e_tanh_, e_min_, e_max_, e_ceil_, e_floor_, e_ite_, e_nan_, e_uf_}; }; TEST_F(SymbolicExpressionTest, Dummy) { EXPECT_TRUE(is_nan(dummy_value<Expression>::get())); } TEST_F(SymbolicExpressionTest, AssignCopyFromConstant) { Expression e{x_}; e = c2_; EXPECT_TRUE(is_constant(e, 1.0)); } TEST_F(SymbolicExpressionTest, IsConstant1) { EXPECT_TRUE(is_constant(e_constant_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_constant(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsConstant2) { EXPECT_TRUE(is_constant(Expression{}, 0.0)); EXPECT_TRUE(is_constant(Expression::Zero(), 0.0)); EXPECT_TRUE(is_constant(Expression::One(), 1.0)); EXPECT_TRUE(is_constant(Expression::Pi(), M_PI)); EXPECT_TRUE(is_constant(Expression::E(), M_E)); } TEST_F(SymbolicExpressionTest, IsZero) { EXPECT_TRUE(is_zero(Expression{})); EXPECT_TRUE(is_zero(Expression::Zero())); } TEST_F(SymbolicExpressionTest, IsOne) { EXPECT_TRUE(is_one(Expression::One())); } TEST_F(SymbolicExpressionTest, IsNegOne) { EXPECT_TRUE(is_neg_one(neg_one_)); } TEST_F(SymbolicExpressionTest, IsTwo) { EXPECT_TRUE(is_two(two_)); } TEST_F(SymbolicExpressionTest, NaN) { // It's OK to have NaN expression. const Expression nan{NAN}; EXPECT_TRUE(is_nan(nan)); EXPECT_TRUE(nan.EqualTo(Expression::NaN())); // It's OK to have an expression including NaN inside. const Expression e1{1.0 + nan}; // It's OK to display an expression including NaN inside. EXPECT_EQ(e1.to_string(), "(1 + NaN)"); // It throws when we evaluate an expression including NaN. EXPECT_THROW(e1.Evaluate(), runtime_error); } TEST_F(SymbolicExpressionTest, IsVariable) { EXPECT_TRUE(is_variable(e_var_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_variable(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsAddition) { EXPECT_TRUE(is_addition(e_add_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_addition(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsMultiplication) { EXPECT_TRUE(is_multiplication(e_mul_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_multiplication(e); })}; EXPECT_EQ(cnt, 2); } TEST_F(SymbolicExpressionTest, IsDivision) { EXPECT_TRUE(is_division(e_div_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_division(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsLog) { EXPECT_TRUE(is_log(e_log_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_log(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsAbs) { EXPECT_TRUE(is_abs(e_abs_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_abs(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsExp) { EXPECT_TRUE(is_exp(e_exp_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_exp(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsSqrt) { EXPECT_TRUE(is_sqrt(e_sqrt_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_sqrt(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsPow) { EXPECT_TRUE(is_pow(e_pow_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_pow(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsSin) { EXPECT_TRUE(is_sin(e_sin_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_sin(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsCos) { EXPECT_TRUE(is_cos(e_cos_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_cos(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsTan) { EXPECT_TRUE(is_tan(e_tan_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_tan(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsAsin) { EXPECT_TRUE(is_asin(e_asin_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_asin(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsAcos) { EXPECT_TRUE(is_acos(e_acos_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_acos(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsAtan) { EXPECT_TRUE(is_atan(e_atan_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_atan(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsAtan2) { EXPECT_TRUE(is_atan2(e_atan2_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_atan2(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsSinh) { EXPECT_TRUE(is_sinh(e_sinh_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_sinh(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsCosh) { EXPECT_TRUE(is_cosh(e_cosh_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_cosh(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsTanh) { EXPECT_TRUE(is_tanh(e_tanh_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_tanh(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsMin) { EXPECT_TRUE(is_min(e_min_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_min(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsMax) { EXPECT_TRUE(is_max(e_max_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_max(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsCeil) { EXPECT_TRUE(is_ceil(e_ceil_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_ceil(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsFloor) { EXPECT_TRUE(is_floor(e_floor_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_floor(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsIfThenElse) { EXPECT_TRUE(is_if_then_else(e_ite_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_if_then_else(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsNaN) { EXPECT_TRUE(is_nan(e_nan_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_nan(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, IsUninterpretedFunction) { EXPECT_TRUE(is_uninterpreted_function(e_uf_)); const vector<Expression>::difference_type cnt{ count_if(collection_.begin(), collection_.end(), [](const Expression& e) { return is_uninterpreted_function(e); })}; EXPECT_EQ(cnt, 1); } TEST_F(SymbolicExpressionTest, GetConstantValue) { EXPECT_EQ(get_constant_value(c1_), -10.0); EXPECT_EQ(get_constant_value(c2_), 1.0); EXPECT_EQ(get_constant_value(c3_), 3.14159); EXPECT_EQ(get_constant_value(c4_), -2.718); } TEST_F(SymbolicExpressionTest, GetVariable) { EXPECT_EQ(get_variable(x_), var_x_); EXPECT_EQ(get_variable(y_), var_y_); EXPECT_EQ(get_variable(z_), var_z_); } TEST_F(SymbolicExpressionTest, GetArgument) { EXPECT_PRED2(ExprEqual, get_argument(e_log_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_abs_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_exp_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_sqrt_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_sin_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_cos_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_tan_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_asin_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_acos_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_atan_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_sinh_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_cosh_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_tanh_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_ceil_), x_); EXPECT_PRED2(ExprEqual, get_argument(e_floor_), x_); } TEST_F(SymbolicExpressionTest, GetFirstArgument) { EXPECT_PRED2(ExprEqual, get_first_argument(e_div_), x_); EXPECT_PRED2(ExprEqual, get_first_argument(e_pow_), x_); EXPECT_PRED2(ExprEqual, get_first_argument(e_atan2_), x_); EXPECT_PRED2(ExprEqual, get_first_argument(e_min_), x_); EXPECT_PRED2(ExprEqual, get_first_argument(e_max_), x_); } TEST_F(SymbolicExpressionTest, GetSecondArgument) { EXPECT_PRED2(ExprEqual, get_second_argument(e_div_), y_); EXPECT_PRED2(ExprEqual, get_second_argument(e_pow_), y_); EXPECT_PRED2(ExprEqual, get_second_argument(e_atan2_), y_); EXPECT_PRED2(ExprEqual, get_second_argument(e_min_), y_); EXPECT_PRED2(ExprEqual, get_second_argument(e_max_), y_); } TEST_F(SymbolicExpressionTest, GetConstantTermInAddition) { EXPECT_PRED2(ExprEqual, get_constant_in_addition(2 * x_ + 3 * y_), 0.0); EXPECT_PRED2(ExprEqual, get_constant_in_addition(3 + 2 * x_ + 3 * y_), 3); EXPECT_PRED2(ExprEqual, get_constant_in_addition(-2 + 2 * x_ + 3 * y_), -2); } TEST_F(SymbolicExpressionTest, GetTermsInAddition) { const Expression e{3 + 2 * x_ + 3 * y_}; const map<Expression, double> terms{get_expr_to_coeff_map_in_addition(e)}; EXPECT_EQ(terms.at(x_), 2.0); EXPECT_EQ(terms.at(y_), 3.0); } TEST_F(SymbolicExpressionTest, GetConstantFactorInMultiplication) { EXPECT_PRED2(ExprEqual, get_constant_in_multiplication(e_neg_), -1.0); EXPECT_PRED2(ExprEqual, get_constant_in_multiplication(x_ * y_ * y_), 1.0); EXPECT_PRED2(ExprEqual, get_constant_in_multiplication(2 * x_ * y_ * y_), 2.0); EXPECT_PRED2(ExprEqual, get_constant_in_multiplication(-3 * x_ * y_ * y_), -3.0); } TEST_F(SymbolicExpressionTest, GetProductsInMultiplication) { const Expression e{2 * x_ * y_ * y_ * pow(z_, y_)}; const map<Expression, Expression> products{ get_base_to_exponent_map_in_multiplication(e)}; EXPECT_PRED2(ExprEqual, products.at(x_), 1.0); EXPECT_PRED2(ExprEqual, products.at(y_), 2.0); EXPECT_PRED2(ExprEqual, products.at(z_), y_); } TEST_F(SymbolicExpressionTest, GetIfThenElse) { const Formula conditional{x_ > y_}; const Expression e1{x_ + y_}; const Expression e2{x_ - y_}; const Expression e{if_then_else(conditional, e1, e2)}; EXPECT_PRED2(FormulaEqual, get_conditional_formula(e), conditional); EXPECT_PRED2(ExprEqual, get_then_expression(e), e1); EXPECT_PRED2(ExprEqual, get_else_expression(e), e2); } TEST_F(SymbolicExpressionTest, IsPolynomial) { const vector<pair<Expression, bool>> test_vec{ {e_constant_, true}, {e_var_, true}, {e_neg_, true}, {e_add_, true}, {e_mul_, true}, {e_div_, false}, {e_log_, false}, {e_abs_, false}, {e_exp_, false}, {e_sqrt_, false}, {e_pow_, false}, {e_sin_, false}, {e_cos_, false}, {e_tan_, false}, {e_asin_, false}, {e_acos_, false}, {e_atan_, false}, {e_atan2_, false}, {e_sinh_, false}, {e_cosh_, false}, {e_tanh_, false}, {e_min_, false}, {e_max_, false}, {e_ceil_, false}, {e_floor_, false}, {e_ite_, false}, {e_nan_, false}, {e_uf_, false}}; for (const pair<Expression, bool>& p : test_vec) { EXPECT_EQ(p.first.is_polynomial(), p.second); } // x^2 -> polynomial EXPECT_TRUE(pow(x_, 2).is_polynomial()); // 3 + x + y + z -> polynomial EXPECT_TRUE((3 + x_ + y_ + z_).is_polynomial()); // 1 + x^2 + y^2 -> polynomial EXPECT_TRUE((1 + pow(x_, 2) + pow(y_, 2)).is_polynomial()); // x^2 * y^2 -> polynomial EXPECT_TRUE((pow(x_, 2) * pow(y_, 2)).is_polynomial()); // (x + y + z)^3 -> polynomial EXPECT_TRUE(pow(x_ + y_ + z_, 3).is_polynomial()); // (x + y + z)^3 / 10 -> polynomial EXPECT_TRUE((pow(x_ + y_ + z_, 3) / 10).is_polynomial()); // (x^3)^(1/3) -> x -> polynomial EXPECT_TRUE(pow(pow(x_, 3), 1 / 3).is_polynomial()); // x^-1 -> not polynomial EXPECT_FALSE(pow(x_, -1).is_polynomial()); // x^2.1 -> not polynomial EXPECT_FALSE(pow(x_, 2.1).is_polynomial()); // x^y -> not polynomial EXPECT_FALSE(pow(x_, y_).is_polynomial()); // 3 + x^y -> not polynomial EXPECT_FALSE((3 + pow(x_, y_)).is_polynomial()); // 3 + x^2.1 -> not polynomial EXPECT_FALSE((3 + pow(x_, 2.1)).is_polynomial()); // x^y / 10 -> not polynomial EXPECT_FALSE((pow(x_, y_) / 10).is_polynomial()); // x^2 * y^ 2.1 -> not polynomial EXPECT_FALSE((pow(x_, 2) * pow(y_, 2.1)).is_polynomial()); // x^2 * y^ -1 -> not polynomial EXPECT_FALSE((pow(x_, 2) * pow(y_, -1)).is_polynomial()); // x^2 * y^ 2 * x^y / 10 -> not polynomial EXPECT_FALSE((pow(x_, 2) * pow(y_, 2) * pow(x_, y_) / 10).is_polynomial()); // (x + y + z)^3 / x -> not polynomial EXPECT_FALSE((pow(x_ + y_ + z_, 3) / x_).is_polynomial()); // sqrt(x^2) -> |x| -> not polynomial EXPECT_FALSE(sqrt(pow(x_, 2)).is_polynomial()); } TEST_F(SymbolicExpressionTest, LessKind) { CheckOrdering({e_constant_, e_var_, e_add_, e_neg_, e_mul_, e_div_, e_log_, e_abs_, e_exp_, e_sqrt_, e_pow_, e_sin_, e_cos_, e_tan_, e_asin_, e_acos_, e_atan_, e_atan2_, e_sinh_, e_cosh_, e_tanh_, e_min_, e_max_, e_ceil_, e_floor_, e_ite_, e_nan_, e_uf_}); } TEST_F(SymbolicExpressionTest, LessConstant) { CheckOrdering({c1_, c2_, c3_}); } TEST_F(SymbolicExpressionTest, LessVariable) { CheckOrdering({x_, y_, z_}); } TEST_F(SymbolicExpressionTest, LessNeg) { // Defined in the ascending order. const Expression neg1{-c3_}; const Expression neg2{-c1_}; const Expression neg3{-x_}; // note: Constant kind < Variable kind CheckOrdering({neg1, neg2, neg3}); } TEST_F(SymbolicExpressionTest, LessAdd) { const Expression add1{c1_ + x_ + y_}; const Expression add2{c1_ + 2 * x_ + y_}; const Expression add3{c1_ - 2 * y_ + z_}; const Expression add4{c1_ + y_ + z_}; const Expression add5{c1_ + 5 * y_ + z_}; const Expression add6{c3_ - 2 * x_ + y_}; const Expression add7{c3_ + x_ + y_}; const Expression add8{c3_ + y_ + 2 * z_}; const Expression add9{c3_ + y_ + 3 * z_}; CheckOrdering({add1, add2, add3, add4, add5, add6, add7, add8, add9}); } TEST_F(SymbolicExpressionTest, LessSub) { const Expression sub1{c1_ - x_ - y_}; const Expression sub2{c1_ - y_ - z_}; const Expression sub3{c3_ - x_ - y_}; const Expression sub4{c3_ - y_ - z_}; CheckOrdering({sub1, sub2, sub3, sub4}); } TEST_F(SymbolicExpressionTest, LessMul) { const Expression mul1{c1_ * x_ * y_}; const Expression mul2{c1_ * y_ * z_}; const Expression mul3{c3_ * x_ * y_}; const Expression mul4{c3_ * y_ * z_}; CheckOrdering({mul1, mul2, mul3, mul4}); } TEST_F(SymbolicExpressionTest, LessDiv) { const Expression div1{x_ / y_}; const Expression div2{x_ / z_}; const Expression div3{y_ / z_}; CheckOrdering({div1, div2, div3}); } TEST_F(SymbolicExpressionTest, LessLog) { const Expression log1{log(x_)}; const Expression log2{log(y_)}; const Expression log3{log(x_plus_y_)}; const Expression log4{log(x_plus_z_)}; CheckOrdering({log1, log2, log3, log4}); } TEST_F(SymbolicExpressionTest, LessAbs) { const Expression abs1{abs(x_)}; const Expression abs2{abs(y_)}; const Expression abs3{abs(x_plus_y_)}; const Expression abs4{abs(x_plus_z_)}; CheckOrdering({abs1, abs2, abs3, abs4}); } TEST_F(SymbolicExpressionTest, LessExp) { const Expression exp1{exp(x_)}; const Expression exp2{exp(y_)}; const Expression exp3{exp(x_plus_y_)}; const Expression exp4{exp(x_plus_z_)}; CheckOrdering({exp1, exp2, exp3, exp4}); } TEST_F(SymbolicExpressionTest, LessSqrt) { const Expression sqrt1{sqrt(x_)}; const Expression sqrt2{sqrt(y_)}; const Expression sqrt3{sqrt(x_plus_y_)}; const Expression sqrt4{sqrt(x_plus_z_)}; CheckOrdering({sqrt1, sqrt2, sqrt3, sqrt4}); } TEST_F(SymbolicExpressionTest, LessSin) { const Expression sin1{sin(x_)}; const Expression sin2{sin(y_)}; const Expression sin3{sin(x_plus_y_)}; const Expression sin4{sin(x_plus_z_)}; CheckOrdering({sin1, sin2, sin3, sin4}); } TEST_F(SymbolicExpressionTest, LessCos) { const Expression cos1{cos(x_)}; const Expression cos2{cos(y_)}; const Expression cos3{cos(x_plus_y_)}; const Expression cos4{cos(x_plus_z_)}; CheckOrdering({cos1, cos2, cos3, cos4}); } TEST_F(SymbolicExpressionTest, LessTan) { const Expression tan1{tan(x_)}; const Expression tan2{tan(y_)}; const Expression tan3{tan(x_plus_y_)}; const Expression tan4{tan(x_plus_z_)}; CheckOrdering({tan1, tan2, tan3, tan4}); } TEST_F(SymbolicExpressionTest, LessAsin) { const Expression asin1{asin(x_)}; const Expression asin2{asin(y_)}; const Expression asin3{asin(x_plus_y_)}; const Expression asin4{asin(x_plus_z_)}; CheckOrdering({asin1, asin2, asin3, asin4}); } TEST_F(SymbolicExpressionTest, LessAcos) { const Expression acos1{acos(x_)}; const Expression acos2{acos(y_)}; const Expression acos3{acos(x_plus_y_)}; const Expression acos4{acos(x_plus_z_)}; CheckOrdering({acos1, acos2, acos3, acos4}); } TEST_F(SymbolicExpressionTest, LessAtan) { const Expression atan1{atan(x_)}; const Expression atan2{atan(y_)}; const Expression atan3{atan(x_plus_y_)}; const Expression atan4{atan(x_plus_z_)}; CheckOrdering({atan1, atan2, atan3, atan4}); } TEST_F(SymbolicExpressionTest, LessSinh) { const Expression sinh1{sinh(x_)}; const Expression sinh2{sinh(y_)}; const Expression sinh3{sinh(x_plus_y_)}; const Expression sinh4{sinh(x_plus_z_)}; CheckOrdering({sinh1, sinh2, sinh3, sinh4}); } TEST_F(SymbolicExpressionTest, LessCosh) { const Expression cosh1{cosh(x_)}; const Expression cosh2{cosh(y_)}; const Expression cosh3{cosh(x_plus_y_)}; const Expression cosh4{cosh(x_plus_z_)}; CheckOrdering({cosh1, cosh2, cosh3, cosh4}); } TEST_F(SymbolicExpressionTest, LessTanh) { const Expression tanh1{tanh(x_)}; const Expression tanh2{tanh(y_)}; const Expression tanh3{tanh(x_plus_y_)}; const Expression tanh4{tanh(x_plus_z_)}; CheckOrdering({tanh1, tanh2, tanh3, tanh4}); } TEST_F(SymbolicExpressionTest, LessPow) { const Expression pow1{pow(x_, y_)}; const Expression pow2{pow(x_, z_)}; const Expression pow3{pow(y_, z_)}; CheckOrdering({pow1, pow2, pow3}); } TEST_F(SymbolicExpressionTest, LessAtan2) { const Expression atan2_1{atan2(x_, y_)}; const Expression atan2_2{atan2(x_, z_)}; const Expression atan2_3{atan2(y_, z_)}; CheckOrdering({atan2_1, atan2_2, atan2_3}); } TEST_F(SymbolicExpressionTest, LessMin) { const Expression min1{min(x_, y_)}; const Expression min2{min(x_, z_)}; const Expression min3{min(y_, z_)}; CheckOrdering({min1, min2, min3}); } TEST_F(SymbolicExpressionTest, LessMax) { const Expression max1{max(x_, y_)}; const Expression max2{max(x_, z_)}; const Expression max3{max(y_, z_)}; CheckOrdering({max1, max2, max3}); } TEST_F(SymbolicExpressionTest, LessCeil) { const Expression ceil1{ceil(x_)}; const Expression ceil2{ceil(y_)}; const Expression ceil3{ceil(x_plus_y_)}; const Expression ceil4{ceil(x_plus_z_)}; CheckOrdering({ceil1, ceil2, ceil3, ceil4}); } TEST_F(SymbolicExpressionTest, LessFloor) { const Expression floor1{floor(x_)}; const Expression floor2{floor(y_)}; const Expression floor3{floor(x_plus_y_)}; const Expression floor4{floor(x_plus_z_)}; CheckOrdering({floor1, floor2, floor3, floor4}); } TEST_F(SymbolicExpressionTest, LessIfThenElse) { const Formula f1{x_ < y_}; const Formula f2{y_ < z_}; const Expression ite1{if_then_else(f1, x_, y_)}; const Expression ite2{if_then_else(f1, x_, z_)}; const Expression ite3{if_then_else(f1, y_, z_)}; const Expression ite4{if_then_else(f2, y_, z_)}; const Expression ite5{if_then_else(f2, z_, x_)}; CheckOrdering({ite1, ite2, ite3, ite4, ite5}); } TEST_F(SymbolicExpressionTest, LessUninterpretedFunction) { const Expression uf1{uninterpreted_function("name1", {x_, y_ + z_})}; const Expression uf2{uninterpreted_function("name1", {x_, y_ * z_})}; const Expression uf3{uninterpreted_function("name1", {x_, y_ * z_, 3.0})}; const Expression uf4{uninterpreted_function("name2", {})}; const Expression uf5{uninterpreted_function("name2", {0.0, -1.0})}; const Expression uf6{uninterpreted_function("name2", {1.0, 0.0})}; CheckOrdering({uf1, uf2, uf3, uf4, uf5, uf6}); } TEST_F(SymbolicExpressionTest, Variable) { EXPECT_EQ(x_.to_string(), var_x_.get_name()); EXPECT_EQ(y_.to_string(), var_y_.get_name()); EXPECT_EQ(z_.to_string(), var_z_.get_name()); EXPECT_PRED2(ExprEqual, x_, x_); EXPECT_PRED2(ExprNotEqual, x_, y_); EXPECT_PRED2(ExprNotEqual, x_, z_); EXPECT_PRED2(ExprNotEqual, y_, x_); EXPECT_PRED2(ExprEqual, y_, y_); EXPECT_PRED2(ExprNotEqual, y_, z_); EXPECT_PRED2(ExprNotEqual, z_, x_); EXPECT_PRED2(ExprNotEqual, z_, y_); EXPECT_PRED2(ExprEqual, z_, z_); } TEST_F(SymbolicExpressionTest, Evaluate) { EXPECT_THROW(x_plus_y_.Evaluate(), std::runtime_error); } TEST_F(SymbolicExpressionTest, Constant) { EXPECT_EQ(c1_.Evaluate(), -10); EXPECT_EQ(c2_.Evaluate(), 1); EXPECT_EQ(c3_.Evaluate(), 3.14159); EXPECT_EQ(c4_.Evaluate(), -2.718); EXPECT_THROW(Expression{NAN}.Evaluate(), runtime_error); } TEST_F(SymbolicExpressionTest, StaticConstant) { EXPECT_DOUBLE_EQ(Expression::Zero().Evaluate(), 0.0); EXPECT_DOUBLE_EQ(Expression::One().Evaluate(), 1.0); EXPECT_NEAR(Expression::Pi().Evaluate(), M_PI, 0.000001); EXPECT_NEAR(Expression::E().Evaluate(), M_E, 0.000000001); } TEST_F(SymbolicExpressionTest, Hash) { Expression x{var_x_}; const Expression x_prime(x); EXPECT_EQ(get_std_hash(x), get_std_hash(x_prime)); x++; EXPECT_NE(get_std_hash(x), get_std_hash(x_prime)); } TEST_F(SymbolicExpressionTest, HashBinary) { const Expression e1{x_plus_y_ + x_plus_z_}; const Expression e2{x_plus_y_ - x_plus_z_}; const Expression e3{x_plus_y_ * x_plus_z_}; const Expression e4{x_plus_y_ / x_plus_z_}; const Expression e5{pow(x_plus_y_, x_plus_z_)}; const Expression e6{atan2(x_plus_y_, x_plus_z_)}; const Expression e7{min(x_plus_y_, x_plus_z_)}; const Expression e8{max(x_plus_y_, x_plus_z_)}; // e1, ..., e8 share the same sub-expressions, but their hash values should be // distinct. unordered_set<size_t> hash_set; const vector<Expression> exprs{e1, e2, e3, e4, e5, e6, e7, e8}; for (auto const& e : exprs) { hash_set.insert(get_std_hash(e)); } EXPECT_EQ(hash_set.size(), exprs.size()); } TEST_F(SymbolicExpressionTest, HashUnary) { const Expression e0{log(x_plus_y_)}; const Expression e1{abs(x_plus_y_)}; const Expression e2{exp(x_plus_y_)}; const Expression e3{sqrt(x_plus_y_)}; const Expression e4{sin(x_plus_y_)}; const Expression e5{cos(x_plus_y_)}; const Expression e6{tan(x_plus_y_)}; const Expression e7{asin(x_plus_y_)}; const Expression e8{acos(x_plus_y_)}; const Expression e9{atan(x_plus_y_)}; const Expression e10{sinh(x_plus_y_)}; const Expression e11{cosh(x_plus_y_)}; const Expression e12{tanh(x_plus_y_)}; const Expression e13{ceil(x_plus_y_)}; const Expression e14{floor(x_plus_y_)}; // e0, ..., e14 share the same sub-expression, but their hash values should be // distinct. unordered_set<size_t> hash_set; const vector<Expression> exprs{e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14}; for (auto const& e : exprs) { hash_set.insert(get_std_hash(e)); } EXPECT_EQ(hash_set.size(), exprs.size()); } // Confirm that numeric_limits is appropriately specialized for Expression. // We'll just spot-test a few values, since our implementation is trivially // forwarding to numeric_limits<double>. TEST_F(SymbolicExpressionTest, NumericLimits) { using std::numeric_limits; using Limits = numeric_limits<Expression>; const Expression num_eps = Limits::epsilon(); ASSERT_TRUE(is_constant(num_eps)); EXPECT_EQ(get_constant_value(num_eps), numeric_limits<double>::epsilon()); const Expression num_min = Limits::min(); ASSERT_TRUE(is_constant(num_min)); EXPECT_EQ(get_constant_value(num_min), numeric_limits<double>::min()); const Expression num_infinity = Limits::infinity(); EXPECT_EQ(num_infinity.to_string(), "inf"); } TEST_F(SymbolicExpressionTest, UnaryPlus) { EXPECT_PRED2(ExprEqual, c3_, +c3_); EXPECT_PRED2(ExprEqual, Expression(var_x_), +var_x_); } // TODO(jwnimmer-tri) These tests should probably live in symbolic_formula_test. // // Confirm that Eigen::numext::{not_,}equal_strict are appropriately // specialized for Expression. // We only need a limited set of cases because if the specialization doesn't // exist, this would result in a compile error. TEST_F(SymbolicExpressionTest, EigenEqualStrict) { EXPECT_TRUE(Eigen::numext::equal_strict(c3_, c3_)); EXPECT_FALSE(Eigen::numext::equal_strict(c3_, c4_)); // Check our special-case zero handling. EXPECT_TRUE(Eigen::numext::equal_strict(zero_, zero_)); EXPECT_FALSE(Eigen::numext::equal_strict(zero_, one_)); EXPECT_FALSE(Eigen::numext::equal_strict(one_, zero_)); EXPECT_FALSE(Eigen::numext::equal_strict(zero_, x_)); EXPECT_FALSE(Eigen::numext::equal_strict(x_, zero_)); EXPECT_THROW(Eigen::numext::equal_strict(x_, y_), std::exception); } TEST_F(SymbolicExpressionTest, EigenNotEqualStrict) { EXPECT_TRUE(Eigen::numext::not_equal_strict(c3_, c4_)); EXPECT_FALSE(Eigen::numext::not_equal_strict(c3_, c3_)); // Check our special-case zero handling. EXPECT_FALSE(Eigen::numext::not_equal_strict(zero_, zero_)); EXPECT_TRUE(Eigen::numext::not_equal_strict(zero_, one_)); EXPECT_TRUE(Eigen::numext::not_equal_strict(one_, zero_)); EXPECT_TRUE(Eigen::numext::not_equal_strict(zero_, x_)); EXPECT_TRUE(Eigen::numext::not_equal_strict(x_, zero_)); EXPECT_THROW(Eigen::numext::not_equal_strict(x_, y_), std::exception); } // Confirm the other Eigen::numext specializations: // - isfinite // - isnan // - isinf // They all trivially forward to our own functions. TEST_F(SymbolicExpressionTest, EigenNumext) { // isnan is only valid for non-NaN Expressions. Trying to evaluate // a NaN expression will throw an exception. So we can't check that. EXPECT_FALSE(Eigen::numext::isnan(one_)); const Expression num_infinity = std::numeric_limits<Expression>::infinity(); EXPECT_FALSE(Eigen::numext::isinf(one_)); EXPECT_TRUE(Eigen::numext::isinf(num_infinity)); EXPECT_TRUE(Eigen::numext::isfinite(one_)); EXPECT_FALSE(Eigen::numext::isfinite(num_infinity)); } TEST_F(SymbolicExpressionTest, UnaryMinus) { EXPECT_PRED2(ExprEqual, -Expression(var_x_), -var_x_); EXPECT_PRED2(ExprNotEqual, c3_, -c3_); EXPECT_DOUBLE_EQ(c3_.Evaluate(), -(-c3_).Evaluate()); EXPECT_PRED2(ExprEqual, c3_, -(-c3_)); EXPECT_DOUBLE_EQ(c3_.Evaluate(), (-(-c3_)).Evaluate()); const Expression e{x_ + y_}; const Environment env{{var_x_, 1.0}, {var_y_, 2.0}}; EXPECT_EQ((-x_).Evaluate(env), -1.0); EXPECT_PRED2(ExprEqual, x_, -(-x_)); // (x + y) and -(-(x + y)) are structurally equal (after simplification) EXPECT_PRED2(ExprEqual, e, -(-e)); // and their evaluations should be the same. EXPECT_DOUBLE_EQ(e.Evaluate(env), (-(-e)).Evaluate(env)); EXPECT_PRED2(ExprEqual, -(x_plus_y_ + x_plus_z_ + pi_), -x_plus_y_ + (-x_plus_z_) + (-pi_)); EXPECT_EQ((-(x_)).to_string(), "(-1 * x)"); } TEST_F(SymbolicExpressionTest, Add1) { EXPECT_PRED2(ExprEqual, c3_ + zero_, c3_); EXPECT_EQ((c3_ + zero_).to_string(), c3_.to_string()); EXPECT_PRED2(ExprEqual, zero_ + c3_, c3_); EXPECT_EQ((zero_ + c3_).to_string(), c3_.to_string()); EXPECT_PRED2(ExprEqual, 0.0 + c3_, c3_); EXPECT_EQ((0.0 + c3_).to_string(), c3_.to_string()); EXPECT_PRED2(ExprEqual, c3_ + 0.0, c3_); EXPECT_EQ((c3_ + 0.0).to_string(), c3_.to_string()); EXPECT_PRED2(ExprEqual, c3_ + c4_, 3.14159 + -2.718); EXPECT_EQ((c3_ + c4_).to_string(), Expression{3.14159 + -2.718}.to_string()); EXPECT_PRED2(ExprEqual, c3_ + x_, 3.14159 + x_); EXPECT_EQ((c3_ + x_).to_string(), (3.14159 + x_).to_string()); EXPECT_PRED2(ExprEqual, x_ + c3_, x_ + 3.14159); EXPECT_EQ((x_ + c3_).to_string(), (x_ + 3.14159).to_string()); } TEST_F(SymbolicExpressionTest, Add2) { Expression e1{x_ + y_}; Expression e2{e1 + e1}; const auto str_rep_e2(e2.to_string()); EXPECT_EQ(str_rep_e2, "(2 * x + 2 * y)"); EXPECT_PRED2(ExprEqual, e2, 2 * x_ + 2 * y_); e1 += z_; EXPECT_PRED2(ExprEqual, e1, x_ + y_ + z_); EXPECT_EQ(e2.to_string(), str_rep_e2); // e2 doesn't change. } TEST_F(SymbolicExpressionTest, Add3) { const Expression e1{2 + x_ + y_}; const Expression e2{3 + x_ + y_}; EXPECT_PRED2(ExprNotEqual, e1, e2); } TEST_F(SymbolicExpressionTest, Add4) { const Expression e1{-2 - x_ + -3 * y_}; const Expression e2{-2 - x_ - 3 * y_}; EXPECT_EQ(e1.to_string(), "(-2 - x - 3 * y)"); EXPECT_EQ(e2.to_string(), "(-2 - x - 3 * y)"); } TEST_F(SymbolicExpressionTest, Add5) { EXPECT_EQ((inf_ + (-inf_)).to_string(), e_nan_.to_string()); } TEST_F(SymbolicExpressionTest, Inc1) { // Prefix increment Expression x{var_x_}; Expression x_prime{var_x_}; EXPECT_PRED2(ExprEqual, x, x_prime); EXPECT_PRED2(ExprEqual, x++, x_prime); EXPECT_PRED2(ExprNotEqual, x, x_prime); EXPECT_PRED2(ExprNotEqual, x, x_prime++); EXPECT_PRED2(ExprEqual, x, x_prime); } TEST_F(SymbolicExpressionTest, Inc2) { // Postfix increment Expression x{var_x_}; Expression x_prime{var_x_}; EXPECT_PRED2(ExprEqual, x, x_prime); EXPECT_PRED2(ExprNotEqual, ++x, x_prime); EXPECT_PRED2(ExprNotEqual, x, x_prime); EXPECT_PRED2(ExprEqual, x, ++x_prime); EXPECT_PRED2(ExprEqual, x, x_prime); } TEST_F(SymbolicExpressionTest, Inc3) { // Pre/Post increments Expression c1{3.1415}; EXPECT_DOUBLE_EQ((c1++).Evaluate(), 3.1415); EXPECT_DOUBLE_EQ(c1.Evaluate(), 3.1415 + 1.0); Expression c2{3.1415}; EXPECT_DOUBLE_EQ((++c2).Evaluate(), 3.1415 + 1.0); EXPECT_DOUBLE_EQ(c2.Evaluate(), 3.1415 + 1.0); } TEST_F(SymbolicExpressionTest, Sub1) { EXPECT_PRED2(ExprEqual, c3_ - zero_, c3_); EXPECT_EQ((c3_ - zero_).to_string(), c3_.to_string()); EXPECT_PRED2(ExprEqual, zero_ - c3_, -c3_); EXPECT_EQ((zero_ - c3_).to_string(), Expression{-3.14159}.to_string()); EXPECT_PRED2(ExprEqual, 0.0 - c3_, -c3_); EXPECT_EQ((0.0 - c3_).to_string(), Expression{-3.14159}.to_string()); EXPECT_PRED2(ExprEqual, 0.0 - c3_, (-1 * c3_)); EXPECT_EQ((0.0 - c3_).to_string(), (-1 * c3_).to_string()); EXPECT_PRED2(ExprEqual, c3_ - 0.0, c3_); EXPECT_EQ((c3_ - 0.0).to_string(), c3_.to_string()); EXPECT_PRED2(ExprEqual, c3_ - c4_, Expression{3.14159 - -2.718}); EXPECT_EQ((c3_ - c4_).to_string(), Expression{3.14159 - -2.718}.to_string()); EXPECT_PRED2(ExprEqual, c3_ - x_, 3.14159 - x_); EXPECT_EQ((c3_ - x_).to_string(), (3.14159 - x_).to_string()); EXPECT_PRED2(ExprEqual, x_ - c3_, x_ - 3.14159); EXPECT_EQ((x_ - c3_).to_string(), (x_ - 3.14159).to_string()); } TEST_F(SymbolicExpressionTest, Sub2) { Expression e1{x_ - y_}; const Expression e2{x_ - z_}; const Expression e3{e1 - e2}; const auto str_rep_e3(e3.to_string()); EXPECT_EQ(str_rep_e3, "( - y + z)"); e1 -= z_; EXPECT_PRED2(ExprEqual, e1, x_ - y_ - z_); EXPECT_EQ(e3.to_string(), str_rep_e3); // e3 doesn't change. } TEST_F(SymbolicExpressionTest, Sub3) { const Expression e1{x_ - y_}; const Expression e2{x_ - y_}; const Expression e3{e1 - e2}; EXPECT_PRED2(ExprEqual, e1, e2); EXPECT_EQ(e3.to_string(), "0"); // simplified } TEST_F(SymbolicExpressionTest, Dec1) { // Postfix decrement. Expression x{var_x_}; Expression x_prime{var_x_}; EXPECT_PRED2(ExprEqual, x, x_prime); EXPECT_PRED2(ExprEqual, x--, x_prime); EXPECT_PRED2(ExprNotEqual, x, x_prime); EXPECT_PRED2(ExprNotEqual, x, x_prime--); EXPECT_PRED2(ExprEqual, x, x_prime); } TEST_F(SymbolicExpressionTest, Dec2) { // Prefix decrement. Expression x{var_x_}; Expression x_prime{var_x_}; EXPECT_PRED2(ExprEqual, x, x_prime); EXPECT_PRED2(ExprNotEqual, --x, x_prime); EXPECT_PRED2(ExprNotEqual, x, x_prime); EXPECT_PRED2(ExprEqual, x, --x_prime); EXPECT_PRED2(ExprEqual, x, x_prime); } TEST_F(SymbolicExpressionTest, Dec3) { // Pre/Postfix decrements. Expression c1{3.1415}; EXPECT_DOUBLE_EQ((c1--).Evaluate(), 3.1415); EXPECT_DOUBLE_EQ(c1.Evaluate(), 3.1415 - 1.0); Expression c2{3.1415}; EXPECT_DOUBLE_EQ((--c2).Evaluate(), 3.1415 - 1.0); EXPECT_DOUBLE_EQ(c2.Evaluate(), 3.1415 - 1.0); } TEST_F(SymbolicExpressionTest, Mul1) { EXPECT_PRED2(ExprEqual, c3_ * zero_, zero_); EXPECT_PRED2(ExprEqual, zero_ * c3_, zero_); EXPECT_PRED2(ExprEqual, c3_ * 0.0, zero_); EXPECT_PRED2(ExprEqual, 0.0 * c3_, zero_); EXPECT_PRED2(ExprEqual, c3_ * one_, c3_); EXPECT_PRED2(ExprEqual, one_ * c3_, c3_); EXPECT_PRED2(ExprEqual, 1.0 * c3_, c3_); EXPECT_PRED2(ExprEqual, c3_ * 1.0, c3_); EXPECT_PRED2(ExprEqual, c3_ * c4_, 3.14159 * -2.718); EXPECT_PRED2(ExprEqual, c3_ * x_, (3.14159 * x_)); EXPECT_PRED2(ExprEqual, x_ * c3_, (x_ * 3.14159)); } TEST_F(SymbolicExpressionTest, Mul2) { Expression e1{x_ * y_}; Expression e2{e1 * e1}; EXPECT_EQ(e1.to_string(), "(x * y)"); EXPECT_PRED2(ExprEqual, e2, pow(x_, 2) * pow(y_, 2)); e1 *= z_; EXPECT_PRED2(ExprEqual, e1, x_ * y_ * z_); EXPECT_PRED2(ExprEqual, e2, pow(x_, 2) * pow(y_, 2)); // e2 doesn't change. } TEST_F(SymbolicExpressionTest, Mul3) { const Expression e1{x_ * x_ * x_ * x_}; const Expression e2{(x_ * x_) * (x_ * x_)}; const Expression e3{x_ * (x_ * x_ * x_)}; const Expression e4{pow(x_, 4)}; EXPECT_PRED2(ExprEqual, e1, e4); EXPECT_PRED2(ExprEqual, e2, e4); EXPECT_PRED2(ExprEqual, e3, e4); } TEST_F(SymbolicExpressionTest, Mul4) { // x * y * y * x = x^2 * y^2 EXPECT_PRED2(ExprEqual, x_ * y_ * y_ * x_, pow(x_, 2) * pow(y_, 2)); // (x * y * y * x) * (x * y * x * y) = x^4 * y^4 EXPECT_PRED2(ExprEqual, (x_ * y_ * y_ * x_) * (x_ * y_ * x_ * y_), pow(x_, 4) * pow(y_, 4)); EXPECT_PRED2(ExprEqual, 3 * (4 * x_), (3 * 4) * x_); EXPECT_PRED2(ExprEqual, (3 * x_) * 4, (3 * 4) * x_); EXPECT_PRED2(ExprEqual, (3 * x_) * (4 * x_), (3 * 4) * x_ * x_); EXPECT_PRED2(ExprEqual, (x_ * 3) * (x_ * 4), (3 * 4) * x_ * x_); EXPECT_PRED2(ExprEqual, (3 * x_) * (4 * y_), (3 * 4) * x_ * y_); } TEST_F(SymbolicExpressionTest, Mul5) { // x^y * x^z = x^(y + z) EXPECT_PRED2(ExprEqual, pow(x_, y_) * pow(x_, z_), pow(x_, y_ + z_)); // x^y * x = x^(y + 1) EXPECT_PRED2(ExprEqual, pow(x_, y_) * x_, pow(x_, y_ + 1)); // x * pow(x, y) = x^(1 + y) EXPECT_PRED2(ExprEqual, x_ * pow(x_, y_), pow(x_, 1 + y_)); // x * y * y * x = x^2 * y^2 EXPECT_PRED2(ExprEqual, x_ * y_ * y_ * x_, pow(x_, 2) * pow(y_, 2)); // (x * y * y * x) * (x * y * x * y) = x^4 * y^4 EXPECT_PRED2(ExprEqual, (x_ * y_ * y_ * x_) * (x_ * y_ * x_ * y_), pow(x_, 4) * pow(y_, 4)); EXPECT_PRED2(ExprEqual, 3 * (4 * x_), (3 * 4) * x_); EXPECT_PRED2(ExprEqual, (3 * x_) * 4, (3 * 4) * x_); EXPECT_PRED2(ExprEqual, (3 * x_) * (4 * x_), (3 * 4) * x_ * x_); EXPECT_PRED2(ExprEqual, (x_ * 3) * (x_ * 4), (3 * 4) * x_ * x_); EXPECT_PRED2(ExprEqual, (3 * x_) * (4 * y_), (3 * 4) * x_ * y_); } TEST_F(SymbolicExpressionTest, Mul6) { EXPECT_EQ((x_ * x_ * y_ * y_ * y_).to_string(), "(pow(x, 2) * pow(y, 3))"); EXPECT_EQ((2 * x_ * x_ * y_ * y_ * y_).to_string(), "(2 * pow(x, 2) * pow(y, 3))"); EXPECT_EQ((-3 * x_ * x_ * y_ * y_ * y_).to_string(), "(-3 * pow(x, 2) * pow(y, 3))"); } TEST_F(SymbolicExpressionTest, Mul7) { const Expression e1{2 * pow(x_, 2)}; const Expression e2{3 * pow(x_, -2)}; EXPECT_PRED2(ExprEqual, e1 * e2, 6); } TEST_F(SymbolicExpressionTest, AddMul1) { const Expression e1{(x_ * y_ * y_ * x_) + (x_ * y_ * x_ * y_)}; EXPECT_PRED2(ExprEqual, e1, 2 * pow(x_, 2) * pow(y_, 2)); const Expression e2{x_ + y_ + (-x_)}; EXPECT_PRED2(ExprEqual, e2, y_); const Expression e3{(2 * x_) + (3 * x_)}; EXPECT_PRED2(ExprEqual, e3, 5 * x_); const Expression e4{(x_ * 2 * x_) + (x_ * x_ * 3)}; EXPECT_PRED2(ExprEqual, e4, 5 * x_ * x_); EXPECT_PRED2(ExprEqual, e4, 5 * pow(x_, 2)); } TEST_F(SymbolicExpressionTest, Div1) { EXPECT_THROW(c3_ / zero_, runtime_error); EXPECT_EQ((zero_ / c3_).to_string(), zero_.to_string()); EXPECT_THROW(c3_ / 0.0, runtime_error); EXPECT_EQ((0.0 / c3_).to_string(), zero_.to_string()); EXPECT_EQ((c3_ / one_).to_string(), c3_.to_string()); EXPECT_EQ((c3_ / 1.0).to_string(), c3_.to_string()); EXPECT_EQ((c3_ / c4_).to_string(), Expression{3.14159 / -2.718}.to_string()); EXPECT_EQ((c3_ / x_).to_string(), (3.14159 / x_).to_string()); EXPECT_EQ((x_ / c3_).to_string(), (x_ / 3.14159).to_string()); } TEST_F(SymbolicExpressionTest, Div2) { Expression e1{x_ / y_}; const Expression e2{x_ / z_}; const Expression e3{e1 / e2}; EXPECT_EQ(e1.to_string(), "(x / y)"); EXPECT_EQ(e2.to_string(), "(x / z)"); EXPECT_EQ(e3.to_string(), "((x / y) / (x / z))"); e1 /= z_; EXPECT_EQ(e1.to_string(), "((x / y) / z)"); EXPECT_EQ(e3.to_string(), "((x / y) / (x / z))"); // e2 doesn't change. } TEST_F(SymbolicExpressionTest, Div3) { const Expression e1{x_ / y_}; const Expression e2{x_ / y_}; const Expression e3{e1 / e2}; EXPECT_EQ(e1.to_string(), "(x / y)"); EXPECT_EQ(e2.to_string(), "(x / y)"); EXPECT_EQ(e3.to_string(), "1"); // simplified } TEST_F(SymbolicExpressionTest, Div4) { const Expression e{x_ / y_}; const Environment env1{{var_x_, 1.0}, {var_y_, 5.0}}; const Environment env2{{var_x_, 1.0}, {var_y_, 0.0}}; EXPECT_EQ(e.Evaluate(env1), 1.0 / 5.0); EXPECT_THROW(e.Evaluate(env2), std::runtime_error); } TEST_F(SymbolicExpressionTest, Div5) { EXPECT_EQ((inf_ / inf_).to_string(), e_nan_.to_string()); } // This test checks whether symbolic::Expression is compatible with // std::unordered_set. GTEST_TEST(ExpressionTest, CompatibleWithUnorderedSet) { unordered_set<Expression> uset; uset.emplace(Expression{Variable{"a"}}); uset.emplace(Expression{Variable{"b"}}); } // This test checks whether symbolic::Expression is compatible with // std::unordered_map. GTEST_TEST(ExpressionTest, CompatibleWithUnorderedMap) { unordered_map<Expression, Expression> umap; umap.emplace(Expression{Variable{"a"}}, Expression{Variable{"b"}}); } // This test checks whether symbolic::Expression is compatible with // std::set. GTEST_TEST(ExpressionTest, CompatibleWithSet) { set<Expression> set; set.emplace(Expression{Variable{"a"}}); set.emplace(Expression{Variable{"b"}}); } // This test checks whether symbolic::Expression is compatible with // std::map. GTEST_TEST(ExpressionTest, CompatibleWithMap) { map<Expression, Expression> map; map.emplace(Expression{Variable{"a"}}, Expression{Variable{"b"}}); } // This test checks whether symbolic::Expression is compatible with // std::vector. GTEST_TEST(ExpressionTest, CompatibleWithVector) { vector<Expression> vec; vec.push_back(123.0); } GTEST_TEST(ExpressionTest, NoThrowMoveConstructible) { // Make sure that symbolic::Expression is nothrow move-constructible so that // it can be moved (not copied) when a STL container (i.e. vector<Expression>) // is resized. EXPECT_TRUE(std::is_nothrow_move_constructible_v<Expression>); } TEST_F(SymbolicExpressionTest, Log) { EXPECT_DOUBLE_EQ(log(pi_).Evaluate(), std::log(M_PI)); EXPECT_DOUBLE_EQ(log(one_).Evaluate(), std::log(1.0)); EXPECT_DOUBLE_EQ(log(zero_).Evaluate(), std::log(0.0)); EXPECT_THROW(log(neg_one_).Evaluate(), domain_error); EXPECT_THROW(log(neg_pi_).Evaluate(), domain_error); const Expression e{log(x_ * y_ * pi_) + log(x_) + log(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::log(2 * 3.2 * M_PI) + std::log(2) + std::log(3.2)); EXPECT_EQ((log(x_)).to_string(), "log(x)"); } TEST_F(SymbolicExpressionTest, Abs) { EXPECT_DOUBLE_EQ(abs(pi_).Evaluate(), std::fabs(M_PI)); EXPECT_DOUBLE_EQ(abs(one_).Evaluate(), std::fabs(1.0)); EXPECT_DOUBLE_EQ(abs(zero_).Evaluate(), std::fabs(0.0)); EXPECT_DOUBLE_EQ(abs(neg_one_).Evaluate(), std::fabs(-1.0)); EXPECT_DOUBLE_EQ(abs(neg_pi_).Evaluate(), std::fabs(-M_PI)); const Expression e{abs(x_ * y_ * pi_) + abs(x_) + abs(y_)}; const Environment env{{var_x_, -2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::fabs(-2 * 3.2 * M_PI) + std::fabs(-2.0) + std::fabs(3.2)); EXPECT_EQ((abs(x_)).to_string(), "abs(x)"); } TEST_F(SymbolicExpressionTest, Exp) { EXPECT_DOUBLE_EQ(exp(pi_).Evaluate(), std::exp(M_PI)); EXPECT_DOUBLE_EQ(exp(one_).Evaluate(), std::exp(1)); EXPECT_DOUBLE_EQ(exp(zero_).Evaluate(), std::exp(0)); EXPECT_DOUBLE_EQ(exp(neg_one_).Evaluate(), std::exp(-1)); EXPECT_DOUBLE_EQ(exp(neg_pi_).Evaluate(), std::exp(-M_PI)); const Expression e{exp(x_ * y_ * pi_) + exp(x_) + exp(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::exp(2 * 3.2 * M_PI) + std::exp(2.0) + std::exp(3.2)); EXPECT_EQ((exp(x_)).to_string(), "exp(x)"); } TEST_F(SymbolicExpressionTest, Sqrt1) { // sqrt(x * x) => |x| EXPECT_PRED2(ExprEqual, sqrt(x_plus_y_ * x_plus_y_), abs(x_plus_y_)); } TEST_F(SymbolicExpressionTest, Sqrt2) { EXPECT_DOUBLE_EQ(sqrt(pi_).Evaluate(), std::sqrt(M_PI)); EXPECT_DOUBLE_EQ(sqrt(one_).Evaluate(), std::sqrt(1.0)); EXPECT_DOUBLE_EQ(sqrt(zero_).Evaluate(), std::sqrt(0.0)); EXPECT_THROW(sqrt(neg_one_).Evaluate(), domain_error); EXPECT_THROW(sqrt(neg_pi_).Evaluate(), domain_error); const Expression e{sqrt(x_ * y_ * pi_) + sqrt(x_) + sqrt(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::sqrt(2 * 3.2 * M_PI) + std::sqrt(2.0) + std::sqrt(3.2)); EXPECT_EQ((sqrt(x_)).to_string(), "sqrt(x)"); } TEST_F(SymbolicExpressionTest, Pow1) { // pow(x, 0.0) => 1.0 EXPECT_PRED2(ExprEqual, pow(x_plus_y_, Expression::Zero()), Expression::One()); // pow(x, 1.0) => x EXPECT_PRED2(ExprEqual, pow(x_plus_y_, Expression::One()), x_plus_y_); // (x^2)^3 => x^(2*3) EXPECT_PRED2(ExprEqual, pow(pow(x_, 2.0), 3.0), pow(x_, 2.0 * 3.0)); // (x^y)^z => x^(y*z) EXPECT_PRED2(ExprEqual, pow(pow(x_, y_), z_), pow(x_, y_ * z_)); } TEST_F(SymbolicExpressionTest, Pow2) { EXPECT_DOUBLE_EQ(pow(pi_, pi_).Evaluate(), std::pow(M_PI, M_PI)); EXPECT_DOUBLE_EQ(pow(pi_, one_).Evaluate(), std::pow(M_PI, 1)); EXPECT_DOUBLE_EQ(pow(pi_, two_).Evaluate(), std::pow(M_PI, 2)); EXPECT_DOUBLE_EQ(pow(pi_, zero_).Evaluate(), std::pow(M_PI, 0)); EXPECT_DOUBLE_EQ(pow(pi_, neg_one_).Evaluate(), std::pow(M_PI, -1)); EXPECT_DOUBLE_EQ(pow(pi_, neg_pi_).Evaluate(), std::pow(M_PI, -M_PI)); EXPECT_DOUBLE_EQ(pow(one_, pi_).Evaluate(), std::pow(1, M_PI)); EXPECT_DOUBLE_EQ(pow(one_, one_).Evaluate(), std::pow(1, 1)); EXPECT_DOUBLE_EQ(pow(one_, two_).Evaluate(), std::pow(1, 2)); EXPECT_DOUBLE_EQ(pow(one_, zero_).Evaluate(), std::pow(1, 0)); EXPECT_DOUBLE_EQ(pow(one_, neg_one_).Evaluate(), std::pow(1, -1)); EXPECT_DOUBLE_EQ(pow(one_, neg_pi_).Evaluate(), std::pow(1, -M_PI)); EXPECT_DOUBLE_EQ(pow(two_, pi_).Evaluate(), std::pow(2, M_PI)); EXPECT_DOUBLE_EQ(pow(two_, one_).Evaluate(), std::pow(2, 1)); EXPECT_DOUBLE_EQ(pow(two_, two_).Evaluate(), std::pow(2, 2)); EXPECT_DOUBLE_EQ(pow(two_, zero_).Evaluate(), std::pow(2, 0)); EXPECT_DOUBLE_EQ(pow(two_, neg_one_).Evaluate(), std::pow(2, -1)); EXPECT_DOUBLE_EQ(pow(two_, neg_pi_).Evaluate(), std::pow(2, -M_PI)); EXPECT_DOUBLE_EQ(pow(zero_, pi_).Evaluate(), std::pow(0, M_PI)); EXPECT_DOUBLE_EQ(pow(zero_, one_).Evaluate(), std::pow(0, 1)); EXPECT_DOUBLE_EQ(pow(zero_, two_).Evaluate(), std::pow(0, 2)); EXPECT_DOUBLE_EQ(pow(zero_, zero_).Evaluate(), std::pow(0, 0)); EXPECT_DOUBLE_EQ(pow(zero_, neg_one_).Evaluate(), std::pow(0, -1)); EXPECT_DOUBLE_EQ(pow(zero_, neg_pi_).Evaluate(), std::pow(0, -M_PI)); EXPECT_THROW(pow(neg_one_, pi_).Evaluate(), domain_error); EXPECT_DOUBLE_EQ(pow(neg_one_, one_).Evaluate(), std::pow(-1, 1)); EXPECT_DOUBLE_EQ(pow(neg_one_, two_).Evaluate(), std::pow(-1, 2)); EXPECT_DOUBLE_EQ(pow(neg_one_, zero_).Evaluate(), std::pow(-1, 0)); EXPECT_DOUBLE_EQ(pow(neg_one_, neg_one_).Evaluate(), std::pow(-1, -1)); EXPECT_THROW(pow(neg_one_, neg_pi_).Evaluate(), domain_error); EXPECT_THROW(pow(neg_pi_, pi_).Evaluate(), domain_error); EXPECT_DOUBLE_EQ(pow(neg_pi_, one_).Evaluate(), std::pow(-M_PI, 1)); EXPECT_DOUBLE_EQ(pow(neg_pi_, two_).Evaluate(), std::pow(-M_PI, 2)); EXPECT_DOUBLE_EQ(pow(neg_pi_, zero_).Evaluate(), std::pow(-M_PI, 0)); EXPECT_DOUBLE_EQ(pow(neg_pi_, neg_one_).Evaluate(), std::pow(-M_PI, -1)); EXPECT_THROW(pow(neg_pi_, neg_pi_).Evaluate(), domain_error); const Expression e1{pow(x_ * y_ * pi_, x_ + y_ + pi_)}; const Expression e2{(pow(x_, 2) * pow(y_, 2) * pow(x_, y_))}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e1.Evaluate(env), std::pow(2 * 3.2 * M_PI, 2 + 3.2 + M_PI)); EXPECT_DOUBLE_EQ(e2.Evaluate(env), std::pow(2, 2) * std::pow(3.2, 2) * std::pow(2, 3.2)); } TEST_F(SymbolicExpressionTest, Sin) { EXPECT_DOUBLE_EQ(sin(pi_).Evaluate(), std::sin(M_PI)); EXPECT_DOUBLE_EQ(sin(one_).Evaluate(), std::sin(1)); EXPECT_DOUBLE_EQ(sin(two_).Evaluate(), std::sin(2)); EXPECT_DOUBLE_EQ(sin(zero_).Evaluate(), std::sin(0)); EXPECT_DOUBLE_EQ(sin(neg_one_).Evaluate(), std::sin(-1)); EXPECT_DOUBLE_EQ(sin(neg_pi_).Evaluate(), std::sin(-M_PI)); const Expression e{sin(x_ * y_ * pi_) + sin(x_) + sin(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::sin(2 * 3.2 * M_PI) + std::sin(2) + std::sin(3.2)); EXPECT_EQ((sin(x_)).to_string(), "sin(x)"); } TEST_F(SymbolicExpressionTest, Cos) { EXPECT_DOUBLE_EQ(cos(pi_).Evaluate(), std::cos(M_PI)); EXPECT_DOUBLE_EQ(cos(one_).Evaluate(), std::cos(1)); EXPECT_DOUBLE_EQ(cos(two_).Evaluate(), std::cos(2)); EXPECT_DOUBLE_EQ(cos(zero_).Evaluate(), std::cos(0)); EXPECT_DOUBLE_EQ(cos(neg_one_).Evaluate(), std::cos(-1)); EXPECT_DOUBLE_EQ(cos(neg_pi_).Evaluate(), std::cos(-M_PI)); const Expression e{cos(x_ * y_ * pi_) + cos(x_) + cos(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::cos(2 * 3.2 * M_PI) + std::cos(2) + std::cos(3.2)); EXPECT_EQ((cos(x_)).to_string(), "cos(x)"); } TEST_F(SymbolicExpressionTest, Tan) { EXPECT_DOUBLE_EQ(tan(pi_).Evaluate(), std::tan(M_PI)); EXPECT_DOUBLE_EQ(tan(one_).Evaluate(), std::tan(1)); EXPECT_DOUBLE_EQ(tan(two_).Evaluate(), std::tan(2)); EXPECT_DOUBLE_EQ(tan(zero_).Evaluate(), std::tan(0)); EXPECT_DOUBLE_EQ(tan(neg_one_).Evaluate(), std::tan(-1)); EXPECT_DOUBLE_EQ(tan(neg_pi_).Evaluate(), std::tan(-M_PI)); const Expression e{tan(x_ * y_ * pi_) + tan(x_) + tan(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::tan(2 * 3.2 * M_PI) + std::tan(2) + std::tan(3.2)); EXPECT_EQ((tan(x_)).to_string(), "tan(x)"); } TEST_F(SymbolicExpressionTest, Asin) { EXPECT_THROW(asin(pi_).Evaluate(), domain_error); EXPECT_DOUBLE_EQ(asin(one_).Evaluate(), std::asin(1)); EXPECT_THROW(asin(two_).Evaluate(), domain_error); EXPECT_DOUBLE_EQ(asin(zero_).Evaluate(), std::asin(0)); EXPECT_DOUBLE_EQ(asin(neg_one_).Evaluate(), std::asin(-1)); EXPECT_THROW(asin(neg_pi_).Evaluate(), domain_error); const Expression e{asin(x_ * y_ * pi_) + asin(x_) + asin(y_)}; const Environment env{{var_x_, 0.2}, {var_y_, 0.3}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::asin(0.2 * 0.3 * M_PI) + std::asin(0.2) + std::asin(0.3)); EXPECT_EQ((asin(x_)).to_string(), "asin(x)"); } TEST_F(SymbolicExpressionTest, Acos) { EXPECT_THROW(acos(pi_).Evaluate(), domain_error); EXPECT_DOUBLE_EQ(acos(one_).Evaluate(), std::acos(1)); EXPECT_THROW(acos(two_).Evaluate(), domain_error); EXPECT_DOUBLE_EQ(acos(zero_).Evaluate(), std::acos(0)); EXPECT_DOUBLE_EQ(acos(neg_one_).Evaluate(), std::acos(-1)); EXPECT_THROW(acos(neg_pi_).Evaluate(), domain_error); const Expression e{acos(x_ * y_ * pi_) + acos(x_) + acos(y_)}; const Environment env{{var_x_, 0.2}, {var_y_, 0.3}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::acos(0.2 * 0.3 * M_PI) + std::acos(0.2) + std::acos(0.3)); EXPECT_EQ((acos(x_)).to_string(), "acos(x)"); } TEST_F(SymbolicExpressionTest, Atan) { EXPECT_DOUBLE_EQ(atan(pi_).Evaluate(), std::atan(M_PI)); EXPECT_DOUBLE_EQ(atan(one_).Evaluate(), std::atan(1)); EXPECT_DOUBLE_EQ(atan(two_).Evaluate(), std::atan(2)); EXPECT_DOUBLE_EQ(atan(zero_).Evaluate(), std::atan(0)); EXPECT_DOUBLE_EQ(atan(neg_one_).Evaluate(), std::atan(-1)); EXPECT_DOUBLE_EQ(atan(neg_pi_).Evaluate(), std::atan(-M_PI)); const Expression e{atan(x_ * y_ * pi_) + atan(x_) + atan(y_)}; const Environment env{{var_x_, 0.2}, {var_y_, 0.3}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::atan(0.2 * 0.3 * M_PI) + std::atan(0.2) + std::atan(0.3)); EXPECT_EQ((atan(x_)).to_string(), "atan(x)"); } TEST_F(SymbolicExpressionTest, Atan2) { EXPECT_DOUBLE_EQ(atan2(pi_, pi_).Evaluate(), std::atan2(M_PI, M_PI)); EXPECT_DOUBLE_EQ(atan2(pi_, one_).Evaluate(), std::atan2(M_PI, 1)); EXPECT_DOUBLE_EQ(atan2(pi_, two_).Evaluate(), std::atan2(M_PI, 2)); EXPECT_DOUBLE_EQ(atan2(pi_, zero_).Evaluate(), std::atan2(M_PI, 0)); EXPECT_DOUBLE_EQ(atan2(pi_, neg_one_).Evaluate(), std::atan2(M_PI, -1)); EXPECT_DOUBLE_EQ(atan2(pi_, neg_pi_).Evaluate(), std::atan2(M_PI, -M_PI)); EXPECT_DOUBLE_EQ(atan2(one_, pi_).Evaluate(), std::atan2(1, M_PI)); EXPECT_DOUBLE_EQ(atan2(one_, one_).Evaluate(), std::atan2(1, 1)); EXPECT_DOUBLE_EQ(atan2(one_, two_).Evaluate(), std::atan2(1, 2)); EXPECT_DOUBLE_EQ(atan2(one_, zero_).Evaluate(), std::atan2(1, 0)); EXPECT_DOUBLE_EQ(atan2(one_, neg_one_).Evaluate(), std::atan2(1, -1)); EXPECT_DOUBLE_EQ(atan2(one_, neg_pi_).Evaluate(), std::atan2(1, -M_PI)); EXPECT_DOUBLE_EQ(atan2(two_, pi_).Evaluate(), std::atan2(2, M_PI)); EXPECT_DOUBLE_EQ(atan2(two_, one_).Evaluate(), std::atan2(2, 1)); EXPECT_DOUBLE_EQ(atan2(two_, two_).Evaluate(), std::atan2(2, 2)); EXPECT_DOUBLE_EQ(atan2(two_, zero_).Evaluate(), std::atan2(2, 0)); EXPECT_DOUBLE_EQ(atan2(two_, neg_one_).Evaluate(), std::atan2(2, -1)); EXPECT_DOUBLE_EQ(atan2(two_, neg_pi_).Evaluate(), std::atan2(2, -M_PI)); EXPECT_DOUBLE_EQ(atan2(zero_, pi_).Evaluate(), std::atan2(0, M_PI)); EXPECT_DOUBLE_EQ(atan2(zero_, one_).Evaluate(), std::atan2(0, 1)); EXPECT_DOUBLE_EQ(atan2(zero_, two_).Evaluate(), std::atan2(0, 2)); EXPECT_DOUBLE_EQ(atan2(zero_, zero_).Evaluate(), std::atan2(0, 0)); EXPECT_DOUBLE_EQ(atan2(zero_, neg_one_).Evaluate(), std::atan2(0, -1)); EXPECT_DOUBLE_EQ(atan2(zero_, neg_pi_).Evaluate(), std::atan2(0, -M_PI)); EXPECT_DOUBLE_EQ(atan2(neg_one_, pi_).Evaluate(), std::atan2(-1, M_PI)); EXPECT_DOUBLE_EQ(atan2(neg_one_, one_).Evaluate(), std::atan2(-1, 1)); EXPECT_DOUBLE_EQ(atan2(neg_one_, two_).Evaluate(), std::atan2(-1, 2)); EXPECT_DOUBLE_EQ(atan2(neg_one_, zero_).Evaluate(), std::atan2(-1, 0)); EXPECT_DOUBLE_EQ(atan2(neg_one_, neg_one_).Evaluate(), std::atan2(-1, -1)); EXPECT_DOUBLE_EQ(atan2(neg_one_, neg_pi_).Evaluate(), std::atan2(-1, -M_PI)); EXPECT_DOUBLE_EQ(atan2(neg_pi_, pi_).Evaluate(), std::atan2(-M_PI, M_PI)); EXPECT_DOUBLE_EQ(atan2(neg_pi_, one_).Evaluate(), std::atan2(-M_PI, 1)); EXPECT_DOUBLE_EQ(atan2(neg_pi_, two_).Evaluate(), std::atan2(-M_PI, 2)); EXPECT_DOUBLE_EQ(atan2(neg_pi_, zero_).Evaluate(), std::atan2(-M_PI, 0)); EXPECT_DOUBLE_EQ(atan2(neg_pi_, neg_one_).Evaluate(), std::atan2(-M_PI, -1)); EXPECT_DOUBLE_EQ(atan2(neg_pi_, neg_pi_).Evaluate(), std::atan2(-M_PI, -M_PI)); const Expression e{atan2(x_ * y_ * pi_, sin(x_) + sin(y_))}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::atan2(2 * 3.2 * M_PI, std::sin(2) + std::sin(3.2))); EXPECT_EQ((atan2(x_, y_)).to_string(), "atan2(x, y)"); } TEST_F(SymbolicExpressionTest, Sinh) { EXPECT_DOUBLE_EQ(sinh(pi_).Evaluate(), std::sinh(M_PI)); EXPECT_DOUBLE_EQ(sinh(one_).Evaluate(), std::sinh(1)); EXPECT_DOUBLE_EQ(sinh(two_).Evaluate(), std::sinh(2)); EXPECT_DOUBLE_EQ(sinh(zero_).Evaluate(), std::sinh(0)); EXPECT_DOUBLE_EQ(sinh(neg_one_).Evaluate(), std::sinh(-1)); EXPECT_DOUBLE_EQ(sinh(neg_pi_).Evaluate(), std::sinh(-M_PI)); const Expression e{sinh(x_ * y_ * pi_) + sinh(x_) + sinh(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::sinh(2 * 3.2 * M_PI) + std::sinh(2) + std::sinh(3.2)); EXPECT_EQ((sinh(x_)).to_string(), "sinh(x)"); } TEST_F(SymbolicExpressionTest, Cosh) { EXPECT_DOUBLE_EQ(cosh(pi_).Evaluate(), std::cosh(M_PI)); EXPECT_DOUBLE_EQ(cosh(one_).Evaluate(), std::cosh(1)); EXPECT_DOUBLE_EQ(cosh(two_).Evaluate(), std::cosh(2)); EXPECT_DOUBLE_EQ(cosh(zero_).Evaluate(), std::cosh(0)); EXPECT_DOUBLE_EQ(cosh(neg_one_).Evaluate(), std::cosh(-1)); EXPECT_DOUBLE_EQ(cosh(neg_pi_).Evaluate(), std::cosh(-M_PI)); const Expression e{cosh(x_ * y_ * pi_) + cosh(x_) + cosh(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::cosh(2 * 3.2 * M_PI) + std::cosh(2) + std::cosh(3.2)); EXPECT_EQ((cosh(x_)).to_string(), "cosh(x)"); } TEST_F(SymbolicExpressionTest, Tanh) { EXPECT_DOUBLE_EQ(tanh(pi_).Evaluate(), std::tanh(M_PI)); EXPECT_DOUBLE_EQ(tanh(one_).Evaluate(), std::tanh(1)); EXPECT_DOUBLE_EQ(tanh(two_).Evaluate(), std::tanh(2)); EXPECT_DOUBLE_EQ(tanh(zero_).Evaluate(), std::tanh(0)); EXPECT_DOUBLE_EQ(tanh(neg_one_).Evaluate(), std::tanh(-1)); EXPECT_DOUBLE_EQ(tanh(neg_pi_).Evaluate(), std::tanh(-M_PI)); const Expression e{tanh(x_ * y_ * pi_) + tanh(x_) + tanh(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::tanh(2 * 3.2 * M_PI) + std::tanh(2) + std::tanh(3.2)); EXPECT_EQ((tanh(x_)).to_string(), "tanh(x)"); } TEST_F(SymbolicExpressionTest, Min1) { // min(E, E) -> E EXPECT_PRED2(ExprEqual, min(x_plus_y_, x_plus_y_), x_plus_y_); } TEST_F(SymbolicExpressionTest, Min2) { EXPECT_DOUBLE_EQ(min(pi_, pi_).Evaluate(), std::min(M_PI, M_PI)); EXPECT_DOUBLE_EQ(min(pi_, one_).Evaluate(), std::min(M_PI, 1.0)); EXPECT_DOUBLE_EQ(min(pi_, two_).Evaluate(), std::min(M_PI, 2.0)); EXPECT_DOUBLE_EQ(min(pi_, zero_).Evaluate(), std::min(M_PI, 0.0)); EXPECT_DOUBLE_EQ(min(pi_, neg_one_).Evaluate(), std::min(M_PI, -1.0)); EXPECT_DOUBLE_EQ(min(pi_, neg_pi_).Evaluate(), std::min(M_PI, -M_PI)); EXPECT_DOUBLE_EQ(min(one_, pi_).Evaluate(), std::min(1.0, M_PI)); EXPECT_DOUBLE_EQ(min(one_, one_).Evaluate(), std::min(1.0, 1.0)); EXPECT_DOUBLE_EQ(min(one_, two_).Evaluate(), std::min(1.0, 2.0)); EXPECT_DOUBLE_EQ(min(one_, zero_).Evaluate(), std::min(1.0, 0.0)); EXPECT_DOUBLE_EQ(min(one_, neg_one_).Evaluate(), std::min(1.0, -1.0)); EXPECT_DOUBLE_EQ(min(one_, neg_pi_).Evaluate(), std::min(1.0, -M_PI)); EXPECT_DOUBLE_EQ(min(two_, pi_).Evaluate(), std::min(2.0, M_PI)); EXPECT_DOUBLE_EQ(min(two_, one_).Evaluate(), std::min(2.0, 1.0)); EXPECT_DOUBLE_EQ(min(two_, two_).Evaluate(), std::min(2.0, 2.0)); EXPECT_DOUBLE_EQ(min(two_, zero_).Evaluate(), std::min(2.0, 0.0)); EXPECT_DOUBLE_EQ(min(two_, neg_one_).Evaluate(), std::min(2.0, -1.0)); EXPECT_DOUBLE_EQ(min(two_, neg_pi_).Evaluate(), std::min(2.0, -M_PI)); EXPECT_DOUBLE_EQ(min(zero_, pi_).Evaluate(), std::min(0.0, M_PI)); EXPECT_DOUBLE_EQ(min(zero_, one_).Evaluate(), std::min(0.0, 1.0)); EXPECT_DOUBLE_EQ(min(zero_, two_).Evaluate(), std::min(0.0, 2.0)); EXPECT_DOUBLE_EQ(min(zero_, zero_).Evaluate(), std::min(0.0, 0.0)); EXPECT_DOUBLE_EQ(min(zero_, neg_one_).Evaluate(), std::min(0.0, -1.0)); EXPECT_DOUBLE_EQ(min(zero_, neg_pi_).Evaluate(), std::min(0.0, -M_PI)); EXPECT_DOUBLE_EQ(min(neg_one_, pi_).Evaluate(), std::min(-1.0, M_PI)); EXPECT_DOUBLE_EQ(min(neg_one_, one_).Evaluate(), std::min(-1.0, 1.0)); EXPECT_DOUBLE_EQ(min(neg_one_, two_).Evaluate(), std::min(-1.0, 2.0)); EXPECT_DOUBLE_EQ(min(neg_one_, zero_).Evaluate(), std::min(-1.0, 0.0)); EXPECT_DOUBLE_EQ(min(neg_one_, neg_one_).Evaluate(), std::min(-1.0, -1.0)); EXPECT_DOUBLE_EQ(min(neg_one_, neg_pi_).Evaluate(), std::min(-1.0, -M_PI)); EXPECT_DOUBLE_EQ(min(neg_pi_, pi_).Evaluate(), std::min(-M_PI, M_PI)); EXPECT_DOUBLE_EQ(min(neg_pi_, one_).Evaluate(), std::min(-M_PI, 1.0)); EXPECT_DOUBLE_EQ(min(neg_pi_, two_).Evaluate(), std::min(-M_PI, 2.0)); EXPECT_DOUBLE_EQ(min(neg_pi_, zero_).Evaluate(), std::min(-M_PI, 0.0)); EXPECT_DOUBLE_EQ(min(neg_pi_, neg_one_).Evaluate(), std::min(-M_PI, -1.0)); EXPECT_DOUBLE_EQ(min(neg_pi_, neg_pi_).Evaluate(), std::min(-M_PI, -M_PI)); const Expression e{min(x_ * y_ * pi_, sin(x_) + sin(y_))}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::min(2 * 3.2 * M_PI, std::sin(2) + std::sin(3.2))); EXPECT_EQ((min(x_, y_)).to_string(), "min(x, y)"); } TEST_F(SymbolicExpressionTest, Max1) { // max(E, E) -> E EXPECT_PRED2(ExprEqual, max(x_plus_y_, x_plus_y_), x_plus_y_); } TEST_F(SymbolicExpressionTest, Max2) { EXPECT_DOUBLE_EQ(max(pi_, pi_).Evaluate(), std::max(M_PI, M_PI)); EXPECT_DOUBLE_EQ(max(pi_, one_).Evaluate(), std::max(M_PI, 1.0)); EXPECT_DOUBLE_EQ(max(pi_, two_).Evaluate(), std::max(M_PI, 2.0)); EXPECT_DOUBLE_EQ(max(pi_, zero_).Evaluate(), std::max(M_PI, 0.0)); EXPECT_DOUBLE_EQ(max(pi_, neg_one_).Evaluate(), std::max(M_PI, -1.0)); EXPECT_DOUBLE_EQ(max(pi_, neg_pi_).Evaluate(), std::max(M_PI, -M_PI)); EXPECT_DOUBLE_EQ(max(one_, pi_).Evaluate(), std::max(1.0, M_PI)); EXPECT_DOUBLE_EQ(max(one_, one_).Evaluate(), std::max(1.0, 1.0)); EXPECT_DOUBLE_EQ(max(one_, two_).Evaluate(), std::max(1.0, 2.0)); EXPECT_DOUBLE_EQ(max(one_, zero_).Evaluate(), std::max(1.0, 0.0)); EXPECT_DOUBLE_EQ(max(one_, neg_one_).Evaluate(), std::max(1.0, -1.0)); EXPECT_DOUBLE_EQ(max(one_, neg_pi_).Evaluate(), std::max(1.0, -M_PI)); EXPECT_DOUBLE_EQ(max(two_, pi_).Evaluate(), std::max(2.0, M_PI)); EXPECT_DOUBLE_EQ(max(two_, one_).Evaluate(), std::max(2.0, 1.0)); EXPECT_DOUBLE_EQ(max(two_, two_).Evaluate(), std::max(2.0, 2.0)); EXPECT_DOUBLE_EQ(max(two_, zero_).Evaluate(), std::max(2.0, 0.0)); EXPECT_DOUBLE_EQ(max(two_, neg_one_).Evaluate(), std::max(2.0, -1.0)); EXPECT_DOUBLE_EQ(max(two_, neg_pi_).Evaluate(), std::max(2.0, -M_PI)); EXPECT_DOUBLE_EQ(max(zero_, pi_).Evaluate(), std::max(0.0, M_PI)); EXPECT_DOUBLE_EQ(max(zero_, one_).Evaluate(), std::max(0.0, 1.0)); EXPECT_DOUBLE_EQ(max(zero_, two_).Evaluate(), std::max(0.0, 2.0)); EXPECT_DOUBLE_EQ(max(zero_, zero_).Evaluate(), std::max(0.0, 0.0)); EXPECT_DOUBLE_EQ(max(zero_, neg_one_).Evaluate(), std::max(0.0, -1.0)); EXPECT_DOUBLE_EQ(max(zero_, neg_pi_).Evaluate(), std::max(0.0, -M_PI)); EXPECT_DOUBLE_EQ(max(neg_one_, pi_).Evaluate(), std::max(-1.0, M_PI)); EXPECT_DOUBLE_EQ(max(neg_one_, one_).Evaluate(), std::max(-1.0, 1.0)); EXPECT_DOUBLE_EQ(max(neg_one_, two_).Evaluate(), std::max(-1.0, 2.0)); EXPECT_DOUBLE_EQ(max(neg_one_, zero_).Evaluate(), std::max(-1.0, 0.0)); EXPECT_DOUBLE_EQ(max(neg_one_, neg_one_).Evaluate(), std::max(-1.0, -1.0)); EXPECT_DOUBLE_EQ(max(neg_one_, neg_pi_).Evaluate(), std::max(-1.0, -M_PI)); EXPECT_DOUBLE_EQ(max(neg_pi_, pi_).Evaluate(), std::max(-M_PI, M_PI)); EXPECT_DOUBLE_EQ(max(neg_pi_, one_).Evaluate(), std::max(-M_PI, 1.0)); EXPECT_DOUBLE_EQ(max(neg_pi_, two_).Evaluate(), std::max(-M_PI, 2.0)); EXPECT_DOUBLE_EQ(max(neg_pi_, zero_).Evaluate(), std::max(-M_PI, 0.0)); EXPECT_DOUBLE_EQ(max(neg_pi_, neg_one_).Evaluate(), std::max(-M_PI, -1.0)); EXPECT_DOUBLE_EQ(max(neg_pi_, neg_pi_).Evaluate(), std::max(-M_PI, -M_PI)); const Expression e{max(x_ * y_ * pi_, sin(x_) + sin(y_))}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::max(2 * 3.2 * M_PI, std::sin(2) + std::sin(3.2))); EXPECT_EQ((max(x_, y_)).to_string(), "max(x, y)"); } TEST_F(SymbolicExpressionTest, Clamp1) { Expression result; result = clamp(Expression{1.5}, one_, pi_); EXPECT_EQ(result.to_string(), "1.5"); result = clamp(Expression::Zero(), one_, pi_); EXPECT_EQ(result.to_string(), "1"); result = clamp(Expression{5.6}, one_, pi_); const std::string kPi{"3.14"}; EXPECT_EQ(result.to_string().compare(0, kPi.length(), kPi), 0); } TEST_F(SymbolicExpressionTest, Clamp2) { const Variable var_lo{"lo"}; const Variable var_hi{"hi"}; auto e = clamp(x_, var_lo, var_hi); EXPECT_EQ(e.Evaluate({{var_x_, 0}, {var_lo, 3}, {var_hi, 10}}), 3); EXPECT_EQ(e.Evaluate({{var_x_, 5}, {var_lo, 3}, {var_hi, 10}}), 5); EXPECT_EQ(e.Evaluate({{var_x_, 12.3}, {var_lo, 3}, {var_hi, 10}}), 10); } TEST_F(SymbolicExpressionTest, Ceil) { EXPECT_DOUBLE_EQ(ceil(pi_).Evaluate(), std::ceil(M_PI)); EXPECT_DOUBLE_EQ(ceil(one_).Evaluate(), std::ceil(1)); EXPECT_DOUBLE_EQ(ceil(two_).Evaluate(), std::ceil(2)); EXPECT_DOUBLE_EQ(ceil(zero_).Evaluate(), std::ceil(0)); EXPECT_DOUBLE_EQ(ceil(neg_one_).Evaluate(), std::ceil(-1)); EXPECT_DOUBLE_EQ(ceil(neg_pi_).Evaluate(), std::ceil(-M_PI)); const Expression e{ceil(x_ * y_ * pi_) + ceil(x_) + ceil(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::ceil(2 * 3.2 * M_PI) + std::ceil(2) + std::ceil(3.2)); EXPECT_EQ((ceil(x_)).to_string(), "ceil(x)"); } TEST_F(SymbolicExpressionTest, Floor) { EXPECT_DOUBLE_EQ(floor(pi_).Evaluate(), std::floor(M_PI)); EXPECT_DOUBLE_EQ(floor(one_).Evaluate(), std::floor(1)); EXPECT_DOUBLE_EQ(floor(two_).Evaluate(), std::floor(2)); EXPECT_DOUBLE_EQ(floor(zero_).Evaluate(), std::floor(0)); EXPECT_DOUBLE_EQ(floor(neg_one_).Evaluate(), std::floor(-1)); EXPECT_DOUBLE_EQ(floor(neg_pi_).Evaluate(), std::floor(-M_PI)); const Expression e{floor(x_ * y_ * pi_) + floor(x_) + floor(y_)}; const Environment env{{var_x_, 2}, {var_y_, 3.2}}; EXPECT_DOUBLE_EQ(e.Evaluate(env), std::floor(2 * 3.2 * M_PI) + std::floor(2) + std::floor(3.2)); EXPECT_EQ((floor(x_)).to_string(), "floor(x)"); } TEST_F(SymbolicExpressionTest, IfThenElse1) { // should be simplified to 1.0 since (x + 1.0 > x) => true. const Expression ite1{if_then_else(x_ + 1.0 > x_, 1.0, 0.0)}; EXPECT_PRED2(ExprEqual, ite1, 1.0); // should be simplified to 0.0 since (x > x + 1.0) => false. const Expression ite2{if_then_else(x_ > x_ + 1.0, 1.0, 0.0)}; EXPECT_PRED2(ExprEqual, ite2, 0.0); // should not be simplified. const Expression ite3{if_then_else(x_ > y_, 1.0, 0.0)}; EXPECT_PRED2(ExprNotEqual, ite3, 1.0); EXPECT_PRED2(ExprNotEqual, ite3, 0.0); } TEST_F(SymbolicExpressionTest, IfThenElse2) { const Expression max_fn{if_then_else(x_ > y_, x_, y_)}; const Expression min_fn{if_then_else(x_ < y_, x_, y_)}; const Environment env1{{var_x_, 5.0}, {var_y_, 3.0}}; EXPECT_EQ(max_fn.Evaluate(env1), std::max(5.0, 3.0)); EXPECT_EQ(min_fn.Evaluate(env1), std::min(5.0, 3.0)); const Environment env2{{var_x_, 2.0}, {var_y_, 7.0}}; EXPECT_EQ(max_fn.Evaluate(env2), std::max(2.0, 7.0)); EXPECT_EQ(min_fn.Evaluate(env2), std::min(2.0, 7.0)); EXPECT_EQ(max_fn.to_string(), "(if (x > y) then x else y)"); } TEST_F(SymbolicExpressionTest, IfThenElse3) { const Expression max_fn{if_then_else(x_ > 1.0, y_, z_)}; const Variables vars{max_fn.GetVariables()}; EXPECT_EQ(vars.size(), 3u); } TEST_F(SymbolicExpressionTest, Cond1) { const Expression e{cond(x_ >= 10, 10, 0.0)}; EXPECT_PRED2(ExprEqual, e, if_then_else(x_ >= 10, 10, 0.0)); EXPECT_EQ(e.Evaluate({{var_x_, 15}}), 10.0); EXPECT_EQ(e.Evaluate({{var_x_, 10}}), 10.0); EXPECT_EQ(e.Evaluate({{var_x_, 0}}), 0.0); } TEST_F(SymbolicExpressionTest, Cond2) { // clang-format off const Expression e{cond(x_ >= 10, 10.0, x_ >= 5, 5.0, x_ >= 2, 2.0, 0.0)}; EXPECT_PRED2(ExprEqual, e, if_then_else(x_ >= 10, 10, if_then_else(x_ >= 5, 5, if_then_else(x_ >= 2, 2, 0.0)))); // clang-format on EXPECT_EQ(e.Evaluate({{var_x_, 15}}), 10.0); EXPECT_EQ(e.Evaluate({{var_x_, 10}}), 10.0); EXPECT_EQ(e.Evaluate({{var_x_, 9}}), 5.0); EXPECT_EQ(e.Evaluate({{var_x_, 5}}), 5.0); EXPECT_EQ(e.Evaluate({{var_x_, 3}}), 2.0); EXPECT_EQ(e.Evaluate({{var_x_, 2}}), 2.0); EXPECT_EQ(e.Evaluate({{var_x_, 1}}), 0.0); } TEST_F(SymbolicExpressionTest, UninterpretedFunction_GetVariables_GetName_GetArguments) { const Expression uf1{uninterpreted_function("uf1", {})}; EXPECT_TRUE(uf1.GetVariables().empty()); EXPECT_EQ(get_uninterpreted_function_name(uf1), "uf1"); EXPECT_TRUE(get_uninterpreted_function_arguments(uf1).empty()); const Expression uf2{uninterpreted_function("uf2", {var_x_, var_y_})}; EXPECT_EQ(get_uninterpreted_function_name(uf2), "uf2"); const Variables vars_in_uf2{uf2.GetVariables()}; EXPECT_EQ(vars_in_uf2.size(), 2); EXPECT_TRUE(vars_in_uf2.include(var_x_)); EXPECT_TRUE(vars_in_uf2.include(var_y_)); const vector<Expression> arguments{sin(x_), cos(y_)}; const Expression uf3{uninterpreted_function("uf3", arguments)}; const vector<Expression>& the_arguments{ get_uninterpreted_function_arguments(uf3)}; EXPECT_EQ(arguments.size(), the_arguments.size()); EXPECT_PRED2(ExprEqual, arguments[0], the_arguments[0]); EXPECT_PRED2(ExprEqual, arguments[1], the_arguments[1]); } TEST_F(SymbolicExpressionTest, UninterpretedFunctionEvaluate) { const Expression uf1{uninterpreted_function("uf1", {})}; const Expression uf2{uninterpreted_function("uf2", {var_x_, var_y_})}; EXPECT_THROW(uf1.Evaluate(), std::runtime_error); EXPECT_THROW(uf2.Evaluate(), std::runtime_error); } TEST_F(SymbolicExpressionTest, UninterpretedFunctionEqual) { const Expression uf1{uninterpreted_function("name1", {x_, y_ + z_})}; const Expression uf2{uninterpreted_function("name1", {x_, y_ + z_})}; EXPECT_TRUE(uf1.EqualTo(uf2)); const Expression uf3{uninterpreted_function("name2", {x_, y_ + z_})}; EXPECT_FALSE(uf1.EqualTo(uf3)); const Expression uf4{uninterpreted_function("name1", {y_, y_ + z_})}; EXPECT_FALSE(uf1.EqualTo(uf4)); const Expression uf5{uninterpreted_function("name1", {x_, z_})}; EXPECT_FALSE(uf1.EqualTo(uf5)); const Expression uf6{uninterpreted_function("name1", {x_, y_ + z_, 3.0})}; EXPECT_FALSE(uf1.EqualTo(uf6)); } TEST_F(SymbolicExpressionTest, GetVariables) { const Variables vars1{(x_ + y_ * log(x_ + y_)).GetVariables()}; EXPECT_TRUE(vars1.include(var_x_)); EXPECT_TRUE(vars1.include(var_y_)); EXPECT_FALSE(vars1.include(var_z_)); EXPECT_EQ(vars1.size(), 2u); const Variables vars2{(x_ * x_ * z_ - y_ * abs(x_) * log(x_ + y_) + cosh(x_) + cosh(y_) + atan2(x_, y_)) .GetVariables()}; EXPECT_TRUE(vars2.include(var_x_)); EXPECT_TRUE(vars2.include(var_y_)); EXPECT_TRUE(vars2.include(var_z_)); EXPECT_EQ(vars2.size(), 3u); } TEST_F(SymbolicExpressionTest, Swap) { Expression e1{sin(x_ + y_ * z_)}; Expression e2{(x_ * x_ + pow(y_, 2) * z_)}; const Expression e1_copy{e1}; const Expression e2_copy{e2}; // Before Swap. EXPECT_PRED2(ExprEqual, e1, e1_copy); EXPECT_PRED2(ExprEqual, e2, e2_copy); swap(e1, e2); // After Swap. EXPECT_PRED2(ExprEqual, e1, e2_copy); EXPECT_PRED2(ExprEqual, e2, e1_copy); } TEST_F(SymbolicExpressionTest, ToString) { const Expression e1{sin(x_ + y_ * z_)}; const Expression e2{cos(x_ * x_ + pow(y_, 2) * z_)}; const Expression e3{M_PI * x_ * pow(y_, M_E)}; const Expression e4{M_E + x_ + M_PI * y_}; EXPECT_EQ(e1.to_string(), "sin((x + (y * z)))"); EXPECT_EQ(e2.to_string(), "cos(((pow(y, 2) * z) + pow(x, 2)))"); EXPECT_EQ(e3.to_string(), "(3.1415926535897931 * x * pow(y, 2.7182818284590451))"); EXPECT_EQ(e4.to_string(), "(2.7182818284590451 + x + 3.1415926535897931 * y)"); EXPECT_EQ(e_uf_.to_string(), "uf(x, y)"); } TEST_F(SymbolicExpressionTest, EvaluatePartial) { // e = xy - 5yz + 10xz. const Expression e{x_ * y_ - 5 * y_ * z_ + 10 * x_ * z_}; // e1 = e[x ↦ 3] = 3y - 5yz + 30z const Expression e1{e.EvaluatePartial({{var_x_, 3}})}; EXPECT_PRED2(ExprEqual, e1, 3 * y_ - 5 * y_ * z_ + 30 * z_); // e2 = e1[y ↦ 5] = 15 - 25z + 30z = 15 + 5z const Expression e2{e1.EvaluatePartial({{var_y_, 5}})}; EXPECT_PRED2(ExprEqual, e2, 15 + 5 * z_); // e3 = e1[z ↦ -2] = 15 + (-10) = 5 const Expression e3{e2.EvaluatePartial({{var_z_, -2}})}; EXPECT_PRED2(ExprEqual, e3, 5); } // Checks for compatibility with a memcpy primitive move operation. // See https://github.com/RobotLocomotion/drake/issues/5974. TEST_F(SymbolicExpressionTest, MemcpyKeepsExpressionIntact) { for (const Expression& expr : collection_) { EXPECT_TRUE(IsMemcpyMovable(expr)); } } TEST_F(SymbolicExpressionTest, ExtractDoubleTest) { const Expression e1{10.0}; EXPECT_EQ(ExtractDoubleOrThrow(e1), 10.0); // 'x_' can't be converted to a double value. const Expression e2{x_}; EXPECT_THROW(ExtractDoubleOrThrow(e2), std::exception); // 2x - 7 -2x + 2 => -5 const Expression e3{2 * x_ - 7 - 2 * x_ + 2}; EXPECT_EQ(ExtractDoubleOrThrow(e3), -5); // Literal NaN should come through without an exception during Extract. EXPECT_TRUE(std::isnan(ExtractDoubleOrThrow(e_nan_))); // Computed NaN should still throw. const Expression bogus = zero_ / e_nan_; EXPECT_THROW(ExtractDoubleOrThrow(bogus), std::exception); // Eigen variant. const Vector2<Expression> v1{12.0, 13.0}; EXPECT_TRUE( CompareMatrices(ExtractDoubleOrThrow(v1), Eigen::Vector2d{12.0, 13.0})); // Computed NaN should still throw through the Eigen variant. const Vector2<Expression> v2{12.0, bogus}; EXPECT_THROW(ExtractDoubleOrThrow(v2), std::exception); } TEST_F(SymbolicExpressionTest, Jacobian) { // J1 = (x * y + sin(x)).Jacobian([x, y]) // = [y + cos(y), x] const Vector2<Variable> vars{var_x_, var_y_}; const auto J1 = (x_ * y_ + sin(x_)).Jacobian(vars); // This should be matched with the non-member function Jacobian. const auto J2 = Jacobian(Vector1<Expression>(x_ * y_ + sin(x_)), vars); // Checks the sizes. EXPECT_EQ(J1.rows(), 1); EXPECT_EQ(J2.rows(), 1); EXPECT_EQ(J1.cols(), 2); EXPECT_EQ(J2.cols(), 2); // Checks the elements. EXPECT_EQ(J1(0), y_ + cos(x_)); EXPECT_EQ(J1(1), x_); EXPECT_EQ(J2(0), J1(0)); EXPECT_EQ(J2(1), J1(1)); } TEST_F(SymbolicExpressionTest, GetDistinctVariables) { EXPECT_EQ(GetDistinctVariables(Vector1<Expression>{x_plus_y_}), Variables({var_x_, var_y_})); EXPECT_EQ(GetDistinctVariables(Vector1<Expression>{x_plus_z_}), Variables({var_x_, var_z_})); EXPECT_EQ(GetDistinctVariables(Vector2<Expression>{x_plus_y_, x_plus_z_}), Variables({var_x_, var_y_, var_z_})); EXPECT_EQ(GetDistinctVariables(RowVector2<Expression>{x_plus_z_, e_cos_}), Variables({var_x_, var_z_})); } TEST_F(SymbolicExpressionTest, TaylorExpand1) { // Test TaylorExpand(exp(-x²-y²), {x:1, y:2}, 2). const Expression& x{x_}; const Expression& y{y_}; const Expression e{exp(-x * x - y * y)}; const Environment env{{{var_x_, 1}, {var_y_, 2}}}; const Expression expanded{TaylorExpand(e, env, 2)}; // Obtained from Matlab. const Expression expected{std::exp(-5) * (1 - 2 * (x - 1) - 4 * (y - 2) + pow(x - 1, 2) + 8 * (x - 1) * (y - 2) + 7 * pow(y - 2, 2))}; // The difference should be close to zero. We sample a few points around (1, // 2) and test. const vector<Environment> test_envs{{{{var_x_, 0}, {var_y_, 0}}}, {{{var_x_, 2}, {var_y_, 3}}}, {{{var_x_, 0}, {var_y_, 3}}}, {{{var_x_, 2}, {var_y_, 0}}}}; for (const auto& test_env : test_envs) { EXPECT_NEAR((expanded - expected).Evaluate(test_env), 0.0, 1e-10); } } TEST_F(SymbolicExpressionTest, TaylorExpand2) { // Test TaylorExpand(sin(-x² -y²), {x:1, y:2}, 2). const Expression& x{x_}; const Expression& y{y_}; const Expression e{sin(-x * x - y * y)}; const Environment env{{{var_x_, 1}, {var_y_, 2}}}; const Expression expanded{TaylorExpand(e, env, 2)}; // Obtained from Matlab. const Expression expected{8 * sin(5) * (x - 1) * (y - 2) - (cos(5) - 2 * sin(5)) * (x - 1) * (x - 1) - (cos(5) - 8 * sin(5)) * (y - 2) * (y - 2) - 2 * cos(5) * (x - 1) - 4 * cos(5) * (y - 2) - sin(5)}; // The difference should be close to zero. We sample a few points around (1, // 2) and test. const vector<Environment> test_envs{{{{var_x_, 0}, {var_y_, 0}}}, {{{var_x_, 2}, {var_y_, 3}}}, {{{var_x_, 0}, {var_y_, 3}}}, {{{var_x_, 2}, {var_y_, 0}}}}; for (const auto& test_env : test_envs) { EXPECT_NEAR((expanded - expected).Evaluate(test_env), 0.0, 1e-10); } } TEST_F(SymbolicExpressionTest, TaylorExpand3) { // Test TaylorExpand(sin(-x² - y²) + cos(z), {x:1, y:2, z:3}, 3) const Expression& x{x_}; const Expression& y{y_}; const Expression& z{z_}; const Expression e{sin(-pow(x, 2) - pow(y, 2)) + cos(z)}; const Environment env{{{var_x_, 1}, {var_y_, 2}, {var_z_, 3}}}; const Expression expanded{TaylorExpand(e, env, 3)}; // Obtained from Matlab. const Expression expected{ cos(3) - sin(5) + (sin(3) * pow(z - 3, 3)) / 6 - (cos(5) - 2 * sin(5)) * pow(x - 1, 2) - (cos(5) - 8 * sin(5)) * pow(y - 2, 2) + pow(x - 1, 3) * ((4 * cos(5)) / 3 + 2 * sin(5)) + pow(y - 2, 3) * ((32 * cos(5)) / 3 + 4 * sin(5)) - 2 * cos(5) * (x - 1) - 4 * cos(5) * (y - 2) - sin(3) * (z - 3) - (cos(3) * pow(z - 3, 2)) / 2 + pow(x - 1, 2) * (y - 2) * (8 * cos(5) + 4 * sin(5)) + (x - 1) * pow(y - 2, 2) * (16 * cos(5) + 2 * sin(5)) + 8 * sin(5) * (x - 1) * (y - 2)}; // The difference should be close to zero. We sample a few points around (1, // 2) and test. const vector<Environment> test_envs{ {{{var_x_, 0}, {var_y_, 0}, {var_z_, 0}}}, {{{var_x_, 0}, {var_y_, 0}, {var_z_, 3}}}, {{{var_x_, 0}, {var_y_, 3}, {var_z_, 0}}}, {{{var_x_, 3}, {var_y_, 0}, {var_z_, 0}}}, {{{var_x_, 0}, {var_y_, 3}, {var_z_, 3}}}, {{{var_x_, 3}, {var_y_, 3}, {var_z_, 0}}}, {{{var_x_, 3}, {var_y_, 0}, {var_z_, 3}}}, {{{var_x_, 3}, {var_y_, 3}, {var_z_, 3}}}}; for (const auto& test_env : test_envs) { EXPECT_NEAR((expanded - expected).Evaluate(test_env), 0.0, 1e-10); } } TEST_F(SymbolicExpressionTest, TaylorExpand4) { // Test TaylorExpand(7, {}, 2) = 7. const Expression e{7.0}; EXPECT_PRED2(ExprEqual, e, TaylorExpand(e, Environment{}, 2)); } TEST_F(SymbolicExpressionTest, TaylorExpandPartialEnv1) { // Test TaylorExpand(sin(x) + cos(y), {x:1}, 2). // Note that we provide a partial environment, {x:1}. const Expression& x{x_}; const Expression& y{y_}; const Expression e{sin(x) + cos(y)}; const Environment env{{{var_x_, 1}}}; const Expression expanded{TaylorExpand(e, env, 2)}; // We have the following from Wolfram Alpha. // The query was "series sin(x) + cos(y) at x=1 to order 2". const Expression expected{cos(y) + sin(1) + (x - 1) * cos(1) - 0.5 * (x - 1) * (x - 1) * sin(1)}; // To show that the function `expanded` approximates another function // `expected`, we sample a few points around x = 1 and check the evaluation // results over those points. For each point p, the difference between // expanded(p) and expected(p) should be bounded by a tiny number (here, we // picked 1e-10). const vector<Environment> test_envs{{{{var_x_, 0}, {var_y_, 0}}}, {{{var_x_, 2}, {var_y_, 0}}}, {{{var_x_, 0}, {var_y_, 2}}}, {{{var_x_, 2}, {var_y_, 2}}}}; for (const auto& test_env : test_envs) { EXPECT_NEAR((expanded - expected).Evaluate(test_env), 0.0, 1e-10); } } TEST_F(SymbolicExpressionTest, TaylorExpandPartialEnv2) { // Test TaylorExpand(a * sin(x), {x:2}, 3). // Note that we provide a partial environment, {x:2}. const Expression& a{a_}; const Expression& x{x_}; const Expression e{a * sin(x)}; const Environment env{{{var_x_, 2}}}; const Expression expanded{TaylorExpand(e, env, 3)}; // We have the following from Wolfram Alpha. // The query was "series a * sin(x) at x=2 to order 3". const Expression expected{a * sin(2) + a * (x - 2) * cos(2) - 0.5 * (x - 2) * (x - 2) * a * sin(2) - 1.0 / 6.0 * pow((x - 2), 3) * a * cos(2)}; // To show that the function `expanded` approximates another function // `expected`, we sample a few points around x = 2 and check the evaluation // results over those points. For each point p, the difference between // expanded(p) and expected(p) should be bounded by a tiny number (here, we // picked 1e-10). const vector<Environment> test_envs{{{{var_x_, 1}, {var_a_, 0}}}, {{{var_x_, 3}, {var_a_, 0}}}, {{{var_x_, 1}, {var_a_, 2}}}, {{{var_x_, 3}, {var_a_, 2}}}}; for (const auto& test_env : test_envs) { EXPECT_NEAR((expanded - expected).Evaluate(test_env), 0.0, 1e-10); } } // Tests std::uniform_real_distribution<drake::symbolic::Expression>. TEST_F(SymbolicExpressionTest, UniformRealDistribution) { using std::uniform_real_distribution; { // Constructor with zero arguments. uniform_real_distribution<double> double_distribution{}; uniform_real_distribution<Expression> symbolic_distribution{}; EXPECT_EQ(double_distribution.a(), symbolic_distribution.a().Evaluate()); EXPECT_EQ(double_distribution.b(), symbolic_distribution.b().Evaluate()); } { // Constructor with a single argument. uniform_real_distribution<double> double_distribution{-10}; uniform_real_distribution<Expression> symbolic_distribution{-10}; EXPECT_EQ(double_distribution.a(), symbolic_distribution.a().Evaluate()); EXPECT_EQ(double_distribution.b(), symbolic_distribution.b().Evaluate()); } // Constructor with two arguments. uniform_real_distribution<double> double_distribution{-10, 10}; uniform_real_distribution<Expression> symbolic_distribution{-10, 10}; EXPECT_EQ(double_distribution.a(), symbolic_distribution.a().Evaluate()); EXPECT_EQ(double_distribution.b(), symbolic_distribution.b().Evaluate()); // Exceptions at construction. { EXPECT_THROW(uniform_real_distribution<Expression>(1.0, 0.0), runtime_error); } RandomGenerator generator{}; RandomGenerator generator_copy{generator}; // The standard case U(0, 1) should generate an expression `0.0 + (1.0 - 0.0) // * v` which is simplified to `v` where `v` is a random uniform variable. { uniform_real_distribution<Expression> d{0.0, 1.0}; const Expression e{d(generator)}; ASSERT_TRUE(is_variable(e)); const Variable& v{get_variable(e)}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_UNIFORM); } // Checks the same thing, but tests operator() with no arguments. { uniform_real_distribution<Expression> d{0.0, 1.0}; const Expression e{d()}; ASSERT_TRUE(is_variable(e)); const Variable& v{get_variable(e)}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_UNIFORM); } // A general case: X ~ U(-5, 10) should generate a symbolic expression // -5 + 15 * v where v is a random uniform variable. { uniform_real_distribution<Expression> d{-5, 10}; const Expression e{d(generator)}; const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 1); const Variable& v{*(vars.begin())}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_UNIFORM); EXPECT_PRED2(ExprEqual, e, -5 + 15 * v); } // A general case: X ~ U(x, y) should generate a symbolic expression // x + (y - x) * v where v is a random uniform variable. { uniform_real_distribution<Expression> d{x_, y_}; const Expression e{d(generator)}; const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 3); const auto it = find_if(vars.begin(), vars.end(), [](const Variable& v) { return v.get_type() == Variable::Type::RANDOM_UNIFORM; }); ASSERT_TRUE(it != vars.end()); const Variable& v{*it}; EXPECT_PRED2(ExprEqual, e, x_ + (y_ - x_) * v); } // After reset(), it should reuse the symbolic random variables that it has // created. { uniform_real_distribution<Expression> d(0.0, 1.0); const Expression e1{d(generator)}; const Expression e2{d(generator)}; d.reset(); const Expression e3{d(generator)}; const Expression e4{d(generator)}; EXPECT_FALSE(e1.EqualTo(e2)); EXPECT_TRUE(e1.EqualTo(e3)); EXPECT_TRUE(e2.EqualTo(e4)); } // The two distributions show the same behavior when the same random number // generator is passed. const double value{symbolic_distribution(generator).Evaluate(&generator)}; const double expected{double_distribution(generator_copy)}; EXPECT_EQ(value, expected); // min() and max(). EXPECT_EQ(double_distribution.min(), symbolic_distribution.min().Evaluate()); EXPECT_EQ(double_distribution.max(), symbolic_distribution.max().Evaluate()); // operator== and operator!=. { uniform_real_distribution<Expression> d1(0.0, 1.0); uniform_real_distribution<Expression> d2(d1); // d1 and d2 have the same parameters and the same internal states. EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); const Expression e1_1{d1(generator)}; const Expression e1_2{d1(generator)}; // The internal states of d1 has changed. EXPECT_FALSE(d1 == d2); EXPECT_TRUE(d1 != d2); const Expression e2_1{d2(generator)}; const Expression e2_2{d2(generator)}; // Now d1 and d2 have the same internal states. EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); // Note that {e1_1, e1_2} and {e2_1, e2_2} are the same. EXPECT_TRUE(e1_1.EqualTo(e2_1)); EXPECT_TRUE(e1_2.EqualTo(e2_2)); // After resetting d2, d1 and d2 are not the same anymore. d2.reset(); EXPECT_FALSE(d1 == d2); EXPECT_TRUE(d1 != d2); // After resetting d1 as well, d1 and d2 are identical. d1.reset(); EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); // Note that the two newly created distributions have the same parameters, // however, they are considered NOT identical. EXPECT_FALSE(uniform_real_distribution<Expression>(0.0, 1.0) == uniform_real_distribution<Expression>(0.0, 1.0)); EXPECT_TRUE(uniform_real_distribution<Expression>(0.0, 1.0) != uniform_real_distribution<Expression>(0.0, 1.0)); } // operator<< ostringstream oss; oss << symbolic_distribution; EXPECT_EQ(oss.str(), "-10 10"); } // Tests std::normal_distribution<drake::symbolic::Expression>. TEST_F(SymbolicExpressionTest, NormalDistribution) { using std::normal_distribution; { // Constructor with zero arguments. normal_distribution<double> double_distribution{}; normal_distribution<Expression> symbolic_distribution{}; EXPECT_EQ(double_distribution.mean(), symbolic_distribution.mean().Evaluate()); EXPECT_EQ(double_distribution.stddev(), symbolic_distribution.stddev().Evaluate()); } { // Constructor with a single argument. normal_distribution<double> double_distribution{-10}; normal_distribution<Expression> symbolic_distribution{-10}; EXPECT_EQ(double_distribution.mean(), symbolic_distribution.mean().Evaluate()); EXPECT_EQ(double_distribution.stddev(), symbolic_distribution.stddev().Evaluate()); } // Constructor with two arguments. normal_distribution<double> double_distribution{5, 10}; normal_distribution<Expression> symbolic_distribution{5, 10}; EXPECT_EQ(double_distribution.mean(), symbolic_distribution.mean().Evaluate()); EXPECT_EQ(double_distribution.stddev(), symbolic_distribution.stddev().Evaluate()); // Exceptions at construction. { EXPECT_THROW(normal_distribution<Expression>(1.0, -1.0), runtime_error); } RandomGenerator generator{}; RandomGenerator generator_copy{generator}; // The standard case N(0, 1) should generate an expression `0.0 + 1.0 * v` // which is simplified to `v` where `v` is a random Gaussian variable. { normal_distribution<Expression> d{0.0, 1.0}; const Expression e{d(generator)}; ASSERT_TRUE(is_variable(e)); const Variable& v{get_variable(e)}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_GAUSSIAN); } // Checks the same thing, but tests operator() with no arguments. { normal_distribution<Expression> d{0.0, 1.0}; const Expression e{d()}; ASSERT_TRUE(is_variable(e)); const Variable& v{get_variable(e)}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_GAUSSIAN); } // A general case: X ~ N(5, 10) should generate a symbolic expression // 5 + 10 * v where v is a random Gaussian variable. { normal_distribution<Expression> d{5, 10}; const Expression e{d(generator)}; const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 1); const Variable& v{*(vars.begin())}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_GAUSSIAN); EXPECT_PRED2(ExprEqual, e, 5 + 10 * v); } // A general case: X ~ N(x, y) should generate a symbolic expression // x + y * v where v is a random Gaussian variable. { normal_distribution<Expression> d{x_, y_}; const Expression e{d(generator)}; const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 3); const auto it = find_if(vars.begin(), vars.end(), [](const Variable& v) { return v.get_type() == Variable::Type::RANDOM_GAUSSIAN; }); ASSERT_TRUE(it != vars.end()); const Variable& v{*it}; EXPECT_PRED2(ExprEqual, e, x_ + y_ * v); } // After reset(), it should reuse the symbolic random variables that it has // created. { normal_distribution<Expression> d(0.0, 1.0); const Expression e1{d(generator)}; const Expression e2{d(generator)}; d.reset(); const Expression e3{d(generator)}; const Expression e4{d(generator)}; EXPECT_FALSE(e1.EqualTo(e2)); EXPECT_TRUE(e1.EqualTo(e3)); EXPECT_TRUE(e2.EqualTo(e4)); } // The two distributions show the same behavior when the same random number // generator is passed. const double value{symbolic_distribution(generator).Evaluate(&generator)}; const double expected{double_distribution(generator_copy)}; EXPECT_EQ(value, expected); // min() and max(). EXPECT_EQ(symbolic_distribution.min().Evaluate(), -std::numeric_limits<double>::infinity()); EXPECT_EQ(symbolic_distribution.max().Evaluate(), +std::numeric_limits<double>::infinity()); // operator== and operator!=. { normal_distribution<Expression> d1(0.0, 1.0); normal_distribution<Expression> d2(d1); // d1 and d2 have the same parameters and the same internal states. EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); const Expression e1_1{d1(generator)}; const Expression e1_2{d1(generator)}; // The internal states of d1 has changed. EXPECT_FALSE(d1 == d2); EXPECT_TRUE(d1 != d2); const Expression e2_1{d2(generator)}; const Expression e2_2{d2(generator)}; // Now d1 and d2 have the same internal states. EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); // Note that {e1_1, e1_2} and {e2_1, e2_2} are the same. EXPECT_TRUE(e1_1.EqualTo(e2_1)); EXPECT_TRUE(e1_2.EqualTo(e2_2)); // After resetting d2, d1 and d2 are not the same anymore. d2.reset(); EXPECT_FALSE(d1 == d2); EXPECT_TRUE(d1 != d2); // After resetting d1 as well, d1 and d2 are identical. d1.reset(); EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); // Note that the two newly created distributions have the same parameters, // however, they are considered NOT identical. EXPECT_FALSE(normal_distribution<Expression>(0.0, 1.0) == normal_distribution<Expression>(0.0, 1.0)); EXPECT_TRUE(normal_distribution<Expression>(0.0, 1.0) != normal_distribution<Expression>(0.0, 1.0)); } // operator<< ostringstream oss; oss << symbolic_distribution; EXPECT_EQ(oss.str(), "5 10"); } // Tests std::exponential_distribution<drake::symbolic::Expression>. TEST_F(SymbolicExpressionTest, ExponentialDistribution) { using std::exponential_distribution; { // Constructor with zero arguments. exponential_distribution<double> double_distribution{}; exponential_distribution<Expression> symbolic_distribution{}; EXPECT_EQ(double_distribution.lambda(), symbolic_distribution.lambda().Evaluate()); } // Constructor with a single argument. exponential_distribution<double> double_distribution{5.0}; exponential_distribution<Expression> symbolic_distribution{5.0}; EXPECT_EQ(double_distribution.lambda(), symbolic_distribution.lambda().Evaluate()); // Exceptions at construction. { EXPECT_THROW(exponential_distribution<Expression>(-3.0), runtime_error); } RandomGenerator generator{}; RandomGenerator generator_copy{generator}; // The standard case Exp(1) should generate an expression `v / 1` which is // simplified to `v` where `v` is a random exponential variable. { exponential_distribution<Expression> d{1.0}; const Expression e{d(generator)}; ASSERT_TRUE(is_variable(e)); const Variable& v{get_variable(e)}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_EXPONENTIAL); } // Checks the same thing, but tests operator() with no arguments. { exponential_distribution<Expression> d{1.0}; const Expression e{d()}; ASSERT_TRUE(is_variable(e)); const Variable& v{get_variable(e)}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_EXPONENTIAL); } // A general case: X ~ Exp(5) should generate a symbolic expression // v / 5 where v is a random exponential variable. { exponential_distribution<Expression> d{5}; const Expression e{d(generator)}; const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 1); const Variable& v{*(vars.begin())}; EXPECT_EQ(v.get_type(), Variable::Type::RANDOM_EXPONENTIAL); EXPECT_PRED2(ExprEqual, e, v / 5); } // A general case: X ~ EXP(y) should generate a symbolic expression // v / y where v is a random exponential variable. { exponential_distribution<Expression> d{y_}; const Expression e{d(generator)}; const Variables vars{e.GetVariables()}; ASSERT_EQ(vars.size(), 2); const auto it = find_if(vars.begin(), vars.end(), [](const Variable& v) { return v.get_type() == Variable::Type::RANDOM_EXPONENTIAL; }); ASSERT_TRUE(it != vars.end()); const Variable& v{*it}; EXPECT_PRED2(ExprEqual, e, v / y_); } // After reset(), it should reuse the symbolic random variables that it has // created. { exponential_distribution<Expression> d(1.0); const Expression e1{d(generator)}; const Expression e2{d(generator)}; d.reset(); const Expression e3{d(generator)}; const Expression e4{d(generator)}; EXPECT_FALSE(e1.EqualTo(e2)); EXPECT_TRUE(e1.EqualTo(e3)); EXPECT_TRUE(e2.EqualTo(e4)); } // The two distributions show the same behavior when the same random number // generator is passed. const double value{symbolic_distribution(generator).Evaluate(&generator)}; const double expected{double_distribution(generator_copy)}; EXPECT_EQ(value, expected); // min() and max(). EXPECT_EQ(symbolic_distribution.min().Evaluate(), 0.0); EXPECT_EQ(symbolic_distribution.max().Evaluate(), +std::numeric_limits<double>::infinity()); // operator== and operator!=. { exponential_distribution<Expression> d1(2.0); exponential_distribution<Expression> d2(d1); // d1 and d2 have the same parameters and the same internal states. EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); const Expression e1_1{d1(generator)}; const Expression e1_2{d1(generator)}; // The internal states of d1 has changed. EXPECT_FALSE(d1 == d2); EXPECT_TRUE(d1 != d2); const Expression e2_1{d2(generator)}; const Expression e2_2{d2(generator)}; // Now d1 and d2 have the same internal states. EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); // Note that {e1_1, e1_2} and {e2_1, e2_2} are the same. EXPECT_TRUE(e1_1.EqualTo(e2_1)); EXPECT_TRUE(e1_2.EqualTo(e2_2)); // After resetting d2, d1 and d2 are not the same anymore. d2.reset(); EXPECT_FALSE(d1 == d2); EXPECT_TRUE(d1 != d2); // After resetting d1 as well, d1 and d2 are identical. d1.reset(); EXPECT_TRUE(d1 == d2); EXPECT_FALSE(d1 != d2); // Note that the two newly created distributions have the same parameters, // however, they are considered NOT identical. EXPECT_FALSE(exponential_distribution<Expression>(2.0) == exponential_distribution<Expression>(2.0)); EXPECT_TRUE(exponential_distribution<Expression>(2.0) != exponential_distribution<Expression>(2.0)); } // operator<< ostringstream oss; oss << symbolic_distribution; EXPECT_EQ(oss.str(), "5"); } // This function checks if the following commute diagram works for given a // symbolic expression `e`, a symbolic environment `env`, and a `random // generator`. // // Substitute Random Variables // +---------------------+ with Sampled Values +--------------------+ // | Expression | | Expression | // |with Random Variables+---------------------------->+w/o Random Variables| // +----------+----------+ +---------+----------+ // | | // v v // Evaluate Evaluate // with a Random Generator w/o a Random Generator // + + // | | // v v // +----------+----------+ +---------+----------+ // | double value +----------- == ------------+ double value | // +---------------------+ +--------------------+ ::testing::AssertionResult CheckExpressionWithRandomVariables( const Expression& e, const Environment& env, RandomGenerator* const random_generator) { RandomGenerator random_generator_copy(*random_generator); const double v1{e.GetVariables().empty() ? e.Evaluate(random_generator) : e.Evaluate(env, random_generator)}; const Environment env_extended{ PopulateRandomVariables(env, e.GetVariables(), &random_generator_copy)}; const double v2{e.Evaluate(env_extended, nullptr)}; if (v1 == v2) { return ::testing::AssertionSuccess(); } else { return ::testing::AssertionFailure() << "Different evaluation results:\n" << "e = " << e << "\n" << "env = " << env << "\n" << "env_extended = " << env_extended << "\n" << "v1 = " << v1 << " and v2 = " << v2; } } TEST_F(SymbolicExpressionTest, EvaluateExpressionsIncludingRandomVariables) { const Variable uni1{"uniform1", Variable::Type::RANDOM_UNIFORM}; const Variable uni2{"uniform2", Variable::Type::RANDOM_UNIFORM}; const Variable gau1{"gaussian1", Variable::Type::RANDOM_GAUSSIAN}; const Variable gau2{"gaussian2", Variable::Type::RANDOM_GAUSSIAN}; const Variable exp1{"exponential1", Variable::Type::RANDOM_EXPONENTIAL}; const Variable exp2{"exponential2", Variable::Type::RANDOM_EXPONENTIAL}; const vector<Expression> expressions{ c2_, uni1 * uni2, gau1 * gau2, exp1 * exp2, x_ * sin(uni1) * cos(uni1) * tan(uni1) + y_, exp1 * pow(abs(x_), exp1) + exp2, x_ / (1 + exp(abs(gau1 * gau2))) + y_ * pow(exp1, 4 + y_), x_ * uni1 + y_ * uni1 + x_ * gau1 + y_ * gau1 + x_ * exp1 + y_ * exp1, }; const vector<Environment> environments{ {{{var_x_, -1.0}, {var_y_, 3.0}}}, {{{var_x_, 1.0}, {var_y_, 1.0}}}, {{{var_x_, 2.0}, {var_y_, 1.0}}}, {{{var_x_, 2.0}, {var_y_, -2.0}}}, }; RandomGenerator generator{}; for (const Expression& e : expressions) { for (const Environment& env : environments) { EXPECT_TRUE(CheckExpressionWithRandomVariables(e, env, &generator)); } } } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/boxed_cell_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <memory> #include <gtest/gtest.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 { namespace internal { namespace { class BoxedCellTest : public ::testing::Test { protected: // These helper functions return a bare pointer to a newly-allocated cell. // The test case is responsible for deleting the cell. Tests pass the cell to // BoxedCell::SetSharedCell which takes over ownership. When the BoxedCell is // destroyed (typically, at the end of the test case's lexical scope), the // use_count of the cell will reach zero and it will be deleted as part of the // BoxedCell destructor. If BoxedCell has any bugs with its reference counts, // that will show up as leaks in our memory checkers (e.g., LSan or Memcheck). const ExpressionCell* MakeVarCell() { return new ExpressionVar(x_); } const ExpressionCell* MakeSqrtCell() { return new ExpressionSqrt(x_); } const ExpressionCell* MakeNaNCell() { return new ExpressionNaN(); } const BoxedCell zero_; const Variable x_{"x"}; }; TEST_F(BoxedCellTest, DefaultCtor) { const BoxedCell dut; EXPECT_EQ(dut.get_kind(), ExpressionKind::Constant); EXPECT_FALSE(dut.is_kind<ExpressionKind::Add>()); EXPECT_TRUE(dut.is_constant()); EXPECT_EQ(dut.constant(), 0.0); EXPECT_EQ(dut.constant_or_nan(), 0.0); const BoxedCell other; EXPECT_TRUE(dut.trivially_equals(other)); } TEST_F(BoxedCellTest, DoubleCtor) { const BoxedCell dut{0.25}; EXPECT_EQ(dut.get_kind(), ExpressionKind::Constant); EXPECT_FALSE(dut.is_kind<ExpressionKind::Add>()); EXPECT_TRUE(dut.is_constant()); EXPECT_EQ(dut.constant(), 0.25); EXPECT_EQ(dut.constant_or_nan(), 0.25); EXPECT_TRUE(dut.trivially_equals(dut)); EXPECT_FALSE(dut.trivially_equals(zero_)); } TEST_F(BoxedCellTest, CopyCtorConstant) { const BoxedCell original{0.25}; const BoxedCell dut{original}; EXPECT_EQ(original.constant(), 0.25); EXPECT_EQ(dut.constant(), 0.25); } TEST_F(BoxedCellTest, MoveCtorConstant) { BoxedCell original{0.25}; BoxedCell dut{std::move(original)}; EXPECT_EQ(original.constant(), 0.0); EXPECT_EQ(dut.constant(), 0.25); } TEST_F(BoxedCellTest, CopyAssignConstant) { const BoxedCell original{0.25}; BoxedCell dut{0.333}; dut = original; EXPECT_EQ(original.constant(), 0.25); EXPECT_EQ(dut.constant(), 0.25); } TEST_F(BoxedCellTest, MoveAssignConstant) { BoxedCell original{0.25}; BoxedCell dut{0.333}; dut = std::move(original); EXPECT_EQ(original.constant(), 0.0); EXPECT_EQ(dut.constant(), 0.25); } TEST_F(BoxedCellTest, Swap) { BoxedCell foo{1.0}; BoxedCell bar{2.0}; swap(foo, bar); EXPECT_EQ(foo.constant(), 2.0); EXPECT_EQ(bar.constant(), 1.0); } TEST_F(BoxedCellTest, Update) { BoxedCell dut; EXPECT_TRUE(dut.is_constant()); EXPECT_EQ(dut.constant(), 0.0); dut.update_constant(0.25); EXPECT_TRUE(dut.is_constant()); EXPECT_EQ(dut.constant(), 0.25); } TEST_F(BoxedCellTest, SetGetCell) { BoxedCell dut; dut.SetSharedCell(MakeVarCell()); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_TRUE(dut.is_kind<ExpressionKind::Var>()); EXPECT_FALSE(dut.is_kind<ExpressionKind::Add>()); EXPECT_FALSE(dut.is_constant()); EXPECT_TRUE(std::isnan(dut.constant_or_nan())); EXPECT_TRUE(dut.trivially_equals(dut)); EXPECT_FALSE(dut.trivially_equals(zero_)); EXPECT_EQ(dut.cell().get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.cell().use_count(), 1); } TEST_F(BoxedCellTest, TriviallyEquals) { BoxedCell boxed_var_cell; BoxedCell boxed_sqrt_cell; BoxedCell boxed_nan_cell; boxed_var_cell.SetSharedCell(MakeVarCell()); boxed_sqrt_cell.SetSharedCell(MakeSqrtCell()); boxed_nan_cell.SetSharedCell(MakeSqrtCell()); std::array<const BoxedCell*, 4> items{ // BR &zero_, &boxed_var_cell, &boxed_sqrt_cell, &boxed_nan_cell}; for (const BoxedCell* first : items) { for (const BoxedCell* second : items) { EXPECT_EQ(first->trivially_equals(*second), first == second); } } } TEST_F(BoxedCellTest, Release) { BoxedCell dut; dut.SetSharedCell(MakeVarCell()); dut = BoxedCell{0.25}; EXPECT_TRUE(dut.is_constant()); EXPECT_EQ(dut.constant(), 0.25); } TEST_F(BoxedCellTest, CopyCtorCell) { auto original = std::make_unique<BoxedCell>(); original->SetSharedCell(MakeVarCell()); const BoxedCell dut{*original}; EXPECT_EQ(original->get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_TRUE(dut.trivially_equals(*original)); EXPECT_EQ(dut.cell().use_count(), 2); original.reset(); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.cell().use_count(), 1); } TEST_F(BoxedCellTest, MoveCtorCell) { BoxedCell original; original.SetSharedCell(MakeVarCell()); const BoxedCell dut{std::move(original)}; EXPECT_EQ(original.get_kind(), ExpressionKind::Constant); EXPECT_EQ(original.constant(), 0.0); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.cell().use_count(), 1); } TEST_F(BoxedCellTest, CopyAssignCellOntoCell) { auto original = std::make_unique<BoxedCell>(); original->SetSharedCell(MakeVarCell()); BoxedCell dut; dut.SetSharedCell(MakeSqrtCell()); dut = *original; EXPECT_EQ(original->get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_TRUE(dut.trivially_equals(*original)); EXPECT_EQ(dut.cell().use_count(), 2); original.reset(); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.cell().use_count(), 1); } TEST_F(BoxedCellTest, CopyAssignCellOntoSelf) { BoxedCell dut; dut.SetSharedCell(MakeVarCell()); BoxedCell& self = dut; dut = self; EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_TRUE(dut.trivially_equals(dut)); EXPECT_EQ(dut.cell().use_count(), 1); } TEST_F(BoxedCellTest, CopyAssignCellOntoConstant) { auto original = std::make_unique<BoxedCell>(); original->SetSharedCell(MakeVarCell()); BoxedCell dut{0.25}; dut = *original; EXPECT_EQ(original->get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_TRUE(dut.trivially_equals(*original)); EXPECT_EQ(dut.cell().use_count(), 2); original.reset(); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.cell().use_count(), 1); } TEST_F(BoxedCellTest, CopyAssignConstantOntoCell) { auto original = std::make_unique<BoxedCell>(0.25); BoxedCell dut{0.25}; dut.SetSharedCell(MakeSqrtCell()); dut = *original; EXPECT_EQ(original->get_kind(), ExpressionKind::Constant); EXPECT_EQ(dut.get_kind(), ExpressionKind::Constant); EXPECT_EQ(dut.constant(), 0.25); EXPECT_TRUE(dut.trivially_equals(*original)); original.reset(); EXPECT_EQ(dut.get_kind(), ExpressionKind::Constant); } TEST_F(BoxedCellTest, MoveAssignCellOntoCell) { BoxedCell original; original.SetSharedCell(MakeVarCell()); BoxedCell dut; dut.SetSharedCell(MakeSqrtCell()); dut = std::move(original); EXPECT_EQ(original.get_kind(), ExpressionKind::Constant); EXPECT_EQ(original.constant(), 0.0); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.cell().use_count(), 1); } TEST_F(BoxedCellTest, MoveAssignCellOntoConstant) { BoxedCell original; original.SetSharedCell(MakeVarCell()); BoxedCell dut{0.25}; dut = std::move(original); EXPECT_EQ(original.get_kind(), ExpressionKind::Constant); EXPECT_EQ(original.constant(), 0.0); EXPECT_EQ(dut.get_kind(), ExpressionKind::Var); EXPECT_EQ(dut.cell().use_count(), 1); } TEST_F(BoxedCellTest, MoveAssignConstantOntoCell) { BoxedCell original{0.25}; BoxedCell dut; dut.SetSharedCell(MakeSqrtCell()); dut = std::move(original); EXPECT_EQ(original.get_kind(), ExpressionKind::Constant); EXPECT_EQ(original.constant(), 0.0); EXPECT_EQ(dut.get_kind(), ExpressionKind::Constant); EXPECT_EQ(dut.constant(), 0.25); } // Sanity check for NaN cell vs BoxedCell::value_ being NaN. // The two concepts are unrelated. TEST_F(BoxedCellTest, CellIsNaN) { BoxedCell dut; dut.SetSharedCell(MakeNaNCell()); EXPECT_EQ(dut.get_kind(), ExpressionKind::NaN); EXPECT_TRUE(dut.is_kind<ExpressionKind::NaN>()); EXPECT_FALSE(dut.is_kind<ExpressionKind::Add>()); EXPECT_FALSE(dut.is_constant()); EXPECT_TRUE(std::isnan(dut.constant_or_nan())); EXPECT_TRUE(dut.trivially_equals(dut)); EXPECT_FALSE(dut.trivially_equals(zero_)); EXPECT_EQ(dut.cell().get_kind(), ExpressionKind::NaN); EXPECT_EQ(dut.cell().use_count(), 1); dut = BoxedCell{0.25}; EXPECT_TRUE(dut.is_constant()); EXPECT_EQ(dut.constant(), 0.25); } } // namespace } // namespace internal } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/expression_expansion_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/common/symbolic/expression/all.h" /* clang-format on */ #include <cmath> #include <functional> #include <stdexcept> #include <utility> #include <vector> #include <gtest/gtest.h> #include "drake/common/test_utilities/limit_malloc.h" #include "drake/common/test_utilities/symbolic_test_util.h" using std::function; using std::pair; using std::runtime_error; using std::vector; namespace drake { using test::LimitMalloc; namespace symbolic { namespace { using test::ExprEqual; using test::ExprNotEqual; class SymbolicExpansionTest : 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_}; vector<Environment> envs_; void SetUp() override { // Set up environments (envs_). envs_.push_back({{var_x_, 1.7}, {var_y_, 2}, {var_z_, 2.3}}); // + + + 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}}); // - + - envs_.push_back({{var_x_, -2.2}, {var_y_, -4}, {var_z_, -2.3}}); // - - - } // Check if both e and e.Expand() are evaluated to the close-enough (<eps) // values under all symbolic environments in envs_. bool CheckExpandPreserveEvaluation(const Expression& e, const double eps) { return all_of(envs_.begin(), envs_.end(), [&](const Environment& env) { return std::fabs(e.Evaluate(env) - e.Expand().Evaluate(env)) < eps; }); } // Checks that e.is_expanded() is already true, and that the e == e.Expand() // invariant holds. bool CheckAlreadyExpanded(const Expression& e) { return e.is_expanded() && e.EqualTo(e.Expand()); } // Checks that e.is_expanded() is conservatively detected as being false, but // that the e == e.Expand() invariant still holds. This means that we could // imagine having `e.is_expanded()` be improved to report `true` in this case, // in the future if we found it helpful. bool CheckUnchangedExpand(const Expression& e) { return !e.is_expanded() && e.EqualTo(e.Expand()); } // Checks if e.Expand() == e.Expand().Expand(). bool CheckExpandIsFixpoint(const Expression& e) { return e.Expand().EqualTo(e.Expand().Expand()); } }; TEST_F(SymbolicExpansionTest, ExpressionAlreadyExpandedPolynomial) { // The following are all already expanded. EXPECT_TRUE(CheckAlreadyExpanded(0)); EXPECT_TRUE(CheckAlreadyExpanded(1)); EXPECT_TRUE(CheckAlreadyExpanded(-1)); EXPECT_TRUE(CheckAlreadyExpanded(42)); EXPECT_TRUE(CheckAlreadyExpanded(-5)); EXPECT_TRUE(CheckAlreadyExpanded(x_)); EXPECT_TRUE(CheckAlreadyExpanded(-x_)); EXPECT_TRUE(CheckAlreadyExpanded(3 * x_)); EXPECT_TRUE(CheckAlreadyExpanded(-2 * x_)); EXPECT_TRUE(CheckAlreadyExpanded(-(2 * x_))); EXPECT_TRUE(CheckAlreadyExpanded(x_ + y_)); EXPECT_TRUE(CheckAlreadyExpanded(-(x_ + y_))); EXPECT_TRUE(CheckAlreadyExpanded(3 * x_ * y_)); // 3xy EXPECT_TRUE(CheckAlreadyExpanded(3 * pow(x_, 2) * y_)); // 3x^2y EXPECT_TRUE(CheckAlreadyExpanded(3 / 10 * pow(x_, 2) * y_)); // 3/10*x^2y EXPECT_TRUE(CheckAlreadyExpanded(-7 + x_ + y_)); // -7 + x + y EXPECT_TRUE(CheckAlreadyExpanded(1 + 3 * x_ - 4 * y_)); // 1 + 3x -4y EXPECT_TRUE(CheckAlreadyExpanded(2 * pow(x_, y_))); // 2x^y } TEST_F(SymbolicExpansionTest, ExpressionAlreadyExpandedPow) { EXPECT_TRUE(CheckAlreadyExpanded(3 * pow(2, y_))); // 3*2^y EXPECT_TRUE(CheckAlreadyExpanded(pow(x_, y_))); // x^y EXPECT_TRUE(CheckAlreadyExpanded(pow(x_, -1))); // x^(-1) EXPECT_TRUE(CheckAlreadyExpanded(pow(x_, -1))); // x^(-1) // The following are all already expanded. They do not yet detect and report // `is_expanded() == true` upon construction, but in any case they must not // change form when `Expand()` is called. EXPECT_TRUE(CheckUnchangedExpand(pow(x_ + y_, -1))); // (x + y)^(-1) EXPECT_TRUE(CheckUnchangedExpand(pow(x_ + y_, 0.5))); // (x + y)^(0.5) EXPECT_TRUE(CheckUnchangedExpand(pow(x_ + y_, 2.5))); // (x + y)^(2.5) EXPECT_TRUE(CheckUnchangedExpand(pow(x_ + y_, x_ - y_))); // (x + y)^(x - y) } TEST_F(SymbolicExpansionTest, ExpressionExpansion) { // test_exprs includes pairs of expression `e` and its expected expansion // `expected`. For each pair (e, expected), we check the following: // 1. e.Expand() is structurally equal to expected. // 2. Evaluate e and e.Expand() under multiple environments to check the // correctness of expansions. // 3. A expansion is a fixpoint of Expand() function. That is, a expanded // expression shouldn't be expanded further. vector<pair<Expression, Expression>> test_exprs; // (2xy²)² = 4x²y⁴ test_exprs.emplace_back(pow(2 * x_ * y_ * y_, 2), 4 * pow(x_, 2) * pow(y_, 4)); // 5 * (3 + 2y) + 30 * (7 + x_) // = 15 + 10y + 210 + 30x // = 225 + 30x + 10y test_exprs.emplace_back(5 * (3 + 2 * y_) + 30 * (7 + x_), 225 + 30 * x_ + 10 * y_); // (x + 3y) * (2x + 5y) = 2x^2 + 11xy + 15y^2 test_exprs.emplace_back((x_ + 3 * y_) * (2 * x_ + 5 * y_), 2 * pow(x_, 2) + 11 * x_ * y_ + 15 * pow(y_, 2)); // (7 + x) * (5 + y) * (6 + z) // = (35 + 5x + 7y + xy) * (6 + z) // = (210 + 30x + 42y + 6xy) + (35z + 5xz + 7yz + xyz) test_exprs.emplace_back((7 + x_) * (5 + y_) * (6 + z_), 210 + 30 * x_ + 42 * y_ + 6 * x_ * y_ + 35 * z_ + 5 * x_ * z_ + 7 * y_ * z_ + x_ * y_ * z_); // (x + 3y) * (2x + 5y) * (x + 3y) // = (2x^2 + 11xy + 15y^2) * (x + 3y) // = 2x^3 + 11x^2y + 15xy^2 // + 6x^2y + 33xy^2 + 45y^3 // = 2x^3 + 17x^2y + 48xy^2 + 45y^3 test_exprs.emplace_back((x_ + 3 * y_) * (2 * x_ + 5 * y_) * (x_ + 3 * y_), 2 * pow(x_, 3) + 17 * pow(x_, 2) * y_ + 48 * x_ * pow(y_, 2) + 45 * pow(y_, 3)); // pow((x + y)^2 + 1, (x - y)^2) // = pow(x^2 + 2xy + y^2 + 1, x^2 -2xy + y^2) // Expand the base and exponent of pow. test_exprs.emplace_back(pow(pow(x_ + y_, 2) + 1, pow(x_ - y_, 2)), pow(pow(x_, 2) + 2 * x_ * y_ + pow(y_, 2) + 1, pow(x_, 2) - 2 * x_ * y_ + pow(y_, 2))); // (x + y + 1)^3 // = x^3 + 3x^2y + // 3x^2 + 3xy^2 + 6xy + 3x + // y^3 + 3y^2 + 3y + 1 test_exprs.emplace_back(pow(x_ + y_ + 1, 3), pow(x_, 3) + 3 * pow(x_, 2) * y_ + 3 * pow(x_, 2) + 3 * x_ * pow(y_, 2) + 6 * x_ * y_ + 3 * x_ + pow(y_, 3) + 3 * pow(y_, 2) + 3 * y_ + 1); // (x + y + 1)^4 // = 1 + 4x + 4y + 12xy + 12xy^2 + // 4xy^3 + 12x^2y + // 6x^2y^2 + 4x^3y + // 6x^2 + 4x^3 + x^4 + // 6y^2 + 4y^3 + y^4 test_exprs.emplace_back( pow(x_ + y_ + 1, 4), 1 + 4 * x_ + 4 * y_ + 12 * x_ * y_ + 12 * x_ * pow(y_, 2) + 4 * x_ * pow(y_, 3) + 12 * pow(x_, 2) * y_ + 6 * pow(x_, 2) * pow(y_, 2) + 4 * pow(x_, 3) * y_ + 6 * pow(x_, 2) + 4 * pow(x_, 3) + pow(x_, 4) + 6 * pow(y_, 2) + 4 * pow(y_, 3) + pow(y_, 4)); for (const pair<Expression, Expression>& p : test_exprs) { const Expression& e{p.first}; const Expression expanded{e.Expand()}; const Expression& expected{p.second}; EXPECT_PRED2(ExprEqual, expanded, expected); EXPECT_TRUE(expanded.is_expanded()); EXPECT_TRUE(CheckExpandPreserveEvaluation(e, 1e-8)); EXPECT_TRUE(CheckExpandIsFixpoint(e)); } } TEST_F(SymbolicExpansionTest, MathFunctions) { // For a math function f(x) and an expression e, we need to have the following // property: // // f(e).Expand() == f(e.Expand()) // // where '==' is structural equality (Expression::EqualTo). using F = function<Expression(const Expression&)>; vector<F> contexts; // clang-format off contexts.push_back([](const Expression& x) { return log(x); }); contexts.push_back([](const Expression& x) { return abs(x); }); contexts.push_back([](const Expression& x) { return exp(x); }); contexts.push_back([](const Expression& x) { return sqrt(x); }); contexts.push_back([](const Expression& x) { return sin(x); }); contexts.push_back([](const Expression& x) { return cos(x); }); contexts.push_back([](const Expression& x) { return tan(x); }); contexts.push_back([](const Expression& x) { return asin(x); }); contexts.push_back([](const Expression& x) { return acos(x); }); contexts.push_back([](const Expression& x) { return atan(x); }); contexts.push_back([](const Expression& x) { return sinh(x); }); contexts.push_back([](const Expression& x) { return cosh(x); }); contexts.push_back([](const Expression& x) { return tanh(x); }); contexts.push_back([&](const Expression& x) { return min(x, y_); }); contexts.push_back([&](const Expression& x) { return min(y_, x); }); contexts.push_back([&](const Expression& x) { return max(x, z_); }); contexts.push_back([&](const Expression& x) { return max(z_, x); }); contexts.push_back([](const Expression& x) { return ceil(x); }); contexts.push_back([](const Expression& x) { return floor(x); }); contexts.push_back([&](const Expression& x) { return atan2(x, y_); }); contexts.push_back([&](const Expression& x) { return atan2(y_, x); }); // clang-format on vector<Expression> expressions; expressions.push_back(5 * (3 + 2 * y_) + 30 * (7 + x_)); expressions.push_back((x_ + 3 * y_) * (2 * x_ + 5 * y_)); expressions.push_back((7 + x_) * (5 + y_) * (6 + z_)); expressions.push_back((x_ + 3 * y_) * (2 * x_ + 5 * y_) * (x_ + 3 * y_)); expressions.push_back(pow(pow(x_ + y_, 2) + 1, pow(x_ - y_, 2))); expressions.push_back(pow(x_ + y_ + 1, 3)); expressions.push_back(pow(x_ + y_ + 1, 4)); for (const F& f : contexts) { for (const Expression& e : expressions) { const Expression e1{f(e).Expand()}; const Expression e2{f(e.Expand())}; EXPECT_PRED2(ExprEqual, e1, e2); EXPECT_TRUE(CheckAlreadyExpanded(e1)); EXPECT_TRUE(CheckAlreadyExpanded(e2)); } } } TEST_F(SymbolicExpansionTest, NaN) { // NaN is considered as not expanded so that ExpressionNaN::Expand() is called // and throws an exception. EXPECT_FALSE(Expression::NaN().is_expanded()); // NaN should be detected during expansion and throw runtime_error. Expression dummy; EXPECT_THROW(dummy = Expression::NaN().Expand(), runtime_error); } TEST_F(SymbolicExpansionTest, IfThenElse) { const Expression e{if_then_else(x_ > y_, pow(x_ + y_, 2), pow(x_ - y_, 2))}; Expression dummy; EXPECT_THROW(dummy = e.Expand(), runtime_error); // An if-then-else expression is considered as not expanded so that // ExpressionIfThenElse::Expand() is called and throws an exception. EXPECT_FALSE(e.is_expanded()); } TEST_F(SymbolicExpansionTest, UninterpretedFunction) { const Expression uf1{uninterpreted_function("uf1", {})}; EXPECT_PRED2(ExprEqual, uf1, uf1.Expand()); EXPECT_TRUE(uf1.Expand().is_expanded()); const Expression e1{3 * (x_ + y_)}; const Expression e2{pow(x_ + y_, 2)}; const Expression uf2{uninterpreted_function("uf2", {e1, e2})}; EXPECT_PRED2(ExprNotEqual, uf2, uf2.Expand()); EXPECT_TRUE(uf2.Expand().is_expanded()); const Expression uf2_expand_expected{ uninterpreted_function("uf2", {e1.Expand(), e2.Expand()})}; EXPECT_PRED2(ExprEqual, uf2.Expand(), uf2_expand_expected); } TEST_F(SymbolicExpansionTest, DivideByConstant) { // (x) / 2 => 0.5 * x EXPECT_PRED2(ExprEqual, (x_ / 2).Expand(), 0.5 * x_); // 3 / 2 => 3 / 2 (no simplification) EXPECT_PRED2(ExprEqual, (Expression(3.0) / 2).Expand(), 3.0 / 2); // pow(x, y) / 2 => 0.5 * pow(x, y) EXPECT_PRED2(ExprEqual, (pow(x_, y_) / 2).Expand(), 0.5 * pow(x_, y_)); // (2x) / 2 => x EXPECT_PRED2(ExprEqual, ((2 * x_) / 2).Expand(), x_); // (10x / 5) / 2 => x EXPECT_PRED2(ExprEqual, (10 * x_ / 5 / 2).Expand(), x_); // (10x²y³z⁴) / -5 => -2x²y³z⁴ EXPECT_PRED2(ExprEqual, (10 * pow(x_, 2) * pow(y_, 3) * pow(z_, 4) / -5).Expand(), -2 * pow(x_, 2) * pow(y_, 3) * pow(z_, 4)); // (36xy / 4 / -3) => -3xy EXPECT_PRED2(ExprEqual, (36 * x_ * y_ / 4 / -3).Expand(), -3 * x_ * y_); std::cerr << (x_ / 2).is_polynomial() << std::endl; // (2x + 4xy + 6) / 2 => x + 2xy + 3 EXPECT_PRED2(ExprEqual, ((2 * x_ + 4 * x_ * y_ + 6) / 2).Expand(), x_ + 2 * x_ * y_ + 3); // (4x / 3) * (6y / 2) => 4xy EXPECT_PRED2(ExprEqual, ((4 * x_ / 3) * (6 * y_ / 2)).Expand(), 4 * x_ * y_); // (6xy / z / 3) => 2xy / z EXPECT_PRED2(ExprEqual, (6 * x_ * y_ / z_ / 3).Expand(), 2 * x_ * y_ / z_); // (36xy / x / -3) => -12xy / x // Note that we do not cancel x out since it can be zero. EXPECT_PRED2(ExprEqual, (36 * x_ * y_ / x_ / -3).Expand(), -12 * x_ * y_ / x_); } TEST_F(SymbolicExpansionTest, RepeatedExpandShouldBeNoop) { const Expression e{(x_ + y_) * (x_ + y_)}; // New ExpressionCells are created here. const Expression e_expanded{e.Expand()}; { LimitMalloc guard; // e_expanded is already expanded, so the following line should not create a // new cell and no memory allocation should occur. We use LimitMalloc to // check this claim. const Expression e_expanded_expanded = e_expanded.Expand(); EXPECT_PRED2(ExprEqual, e_expanded, e_expanded_expanded); } } TEST_F(SymbolicExpansionTest, ExpandMultiplicationsWithDivisions) { const Expression e1{((x_ + 1) / y_) * (x_ + 3)}; const Expression e2{(x_ + 3) * ((x_ + 1) / z_)}; const Expression e3{((x_ + 1) / (y_ + 6)) * ((x_ + 3) / (z_ + 7))}; const Expression e4{(x_ + y_ / ((z_ + x_) * (y_ + x_))) * (x_ - y_ / z_) * (x_ * y_ / z_)}; EXPECT_TRUE(CheckExpandIsFixpoint(e1)); EXPECT_TRUE(CheckExpandIsFixpoint(e2)); EXPECT_TRUE(CheckExpandIsFixpoint(e3)); EXPECT_TRUE(CheckExpandIsFixpoint(e4)); EXPECT_TRUE(CheckExpandPreserveEvaluation(e1, 1e-8)); EXPECT_TRUE(CheckExpandPreserveEvaluation(e2, 1e-8)); EXPECT_TRUE(CheckExpandPreserveEvaluation(e3, 1e-8)); EXPECT_TRUE(CheckExpandPreserveEvaluation(e4, 1e-8)); } } // namespace } // namespace symbolic } // namespace drake
0
/home/johnshepherd/drake/common/symbolic/expression
/home/johnshepherd/drake/common/symbolic/expression/test/expression_jacobian_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 { class SymbolicExpressionJacobianTest : public ::testing::Test { protected: const Variable x_{"x"}; const Variable y_{"y"}; const Variable z_{"z"}; }; TEST_F(SymbolicExpressionJacobianTest, Test1) { // Jacobian(2*x + 3*y + 4*z, [x, y, z]) // = [2, 3, 4] VectorX<Expression> f(1); f << 2 * x_ + 3 * y_ + 4 * z_; MatrixX<Expression> expected(1, 3); expected << 2, 3, 4; // std::vector of variables EXPECT_EQ(Jacobian(f, {x_, y_, z_}), expected); // Eigen::Vector of variables EXPECT_EQ(Jacobian(f, Vector3<Variable>{x_, y_, z_}), expected); } TEST_F(SymbolicExpressionJacobianTest, Test2) { // Jacobian([x * y * z, y^2, x + z], {x, y, z}) // = |(y * z) (x * z) (x * y)| // | 0 (2 * y) 0| // | 1 0 1| VectorX<Expression> f(3); f << x_ * y_ * z_, pow(y_, 2), x_ + z_; MatrixX<Expression> expected(3, 3); // clang-format off expected << y_ * z_, x_ * z_, x_ * y_, 0, 2 * y_, 0, 1, 0, 1; // clang-format on // std::vector of variables EXPECT_EQ(Jacobian(f, {x_, y_, z_}), expected); // Eigen::Vector of variables EXPECT_EQ(Jacobian(f, Vector3<Variable>{x_, y_, z_}), expected); } TEST_F(SymbolicExpressionJacobianTest, Test3) { // Jacobian([x^2*y, x*sin(y)], {x}) // = | 2*x*y | // | sin(y) | VectorX<Expression> f(2); f << pow(x_, 2) * y_, x_ * sin(y_); MatrixX<Expression> expected(2, 1); // clang-format off expected << 2 * x_ * y_, sin(y_); // clang-format on // std::vector of variables EXPECT_EQ(Jacobian(f, {x_}), expected); // Eigen::Vector of variables EXPECT_EQ(Jacobian(f, Vector1<Variable>{x_}), expected); } TEST_F(SymbolicExpressionJacobianTest, Test4) { // Jacobian([x * cos(y), x * sin(y), x^2], {x, y}) // = |cos(y) -x * sin(y)| // |sin(y) x * cos(y)| // | 2 * x 0| VectorX<Expression> f(3); f << x_ * cos(y_), x_ * sin(y_), pow(x_, 2); MatrixX<Expression> expected(3, 2); // clang-format off expected << cos(y_), -x_ * sin(y_), sin(y_), x_ * cos(y_), 2 * x_, 0; // clang-format on // std::vector of variables EXPECT_EQ(Jacobian(f, {x_, y_}), expected); // Eigen::Vector of variables EXPECT_EQ(Jacobian(f, Vector2<Variable>{x_, y_}), expected); } TEST_F(SymbolicExpressionJacobianTest, Test5) { // Jacobian([x * y + sin(x)], {x, z}) // = |cos(y) -x * sin(y)| // |sin(y) x * cos(y)| // | 2 * x 0| VectorX<Expression> f(1); f << x_ * y_ + sin(x_); MatrixX<Expression> expected(1, 2); // clang-format off expected << y_ + cos(x_), 0; // clang-format on // std::vector of variables EXPECT_EQ(Jacobian(f, {x_, z_}), expected); // Eigen::Vector of variables EXPECT_EQ(Jacobian(f, Vector2<Variable>{x_, z_}), expected); } } // namespace } // namespace symbolic } // namespace drake
0