repo_id
stringclasses 205
values | file_path
stringlengths 33
141
| content
stringlengths 1
307k
| __index_level_0__
int64 0
0
|
---|---|---|---|
/home/johnshepherd/drake | /home/johnshepherd/drake/common/bit_cast.h | #pragma once
#ifdef __cpp_lib_bit_cast
#include <bit>
namespace drake {
namespace internal {
using std::bit_cast;
} // namespace internal
} // namespace drake
#else // __cpp_lib_bit_cast
#include <cstring>
#include <type_traits>
namespace drake {
namespace internal {
/* Implements C++20 https://en.cppreference.com/w/cpp/numeric/bit_cast (but
without the overload resolution guards, which are not necessary in our case.)
(Once all of Drake's supported platforms offer std::bit_cast, we can remove
this function in lieu of the std one.) */
template <class To, class From>
To bit_cast(const From& from) noexcept {
static_assert(std::is_trivially_constructible_v<To>);
To result;
static_assert(sizeof(To) == sizeof(From));
static_assert(std::is_trivially_copyable_v<To>);
static_assert(std::is_trivially_copyable_v<From>);
std::memcpy(&result, &from, sizeof(result));
return result;
}
} // namespace internal
} // namespace drake
#endif // __cpp_lib_bit_cast
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/unused.h | #pragma once
namespace drake {
/// Documents the argument(s) as unused, placating GCC's -Wunused-parameter
/// warning. This can be called within function bodies to mark that certain
/// parameters are unused.
///
/// When possible, removing the unused parameter is better than placating the
/// warning. However, in some cases the parameter is part of a virtual API or
/// template concept that is used elsewhere, so we can't remove it. In those
/// cases, this function might be an appropriate work-around.
///
/// Here's rough advice on how to fix Wunused-parameter warnings:
///
/// (1) If the parameter can be removed entirely, prefer that as the first
/// choice. (This may not be possible if, e.g., a method must match some
/// virtual API or template concept.)
///
/// (2) Unless the parameter name has acute value, prefer to omit the name of
/// the parameter, leaving only the type, e.g.
/// @code
/// void Print(const State& state) override { /* No state to print. */ }
/// @endcode
/// changes to
/// @code
/// void Print(const State&) override { /* No state to print. */}
/// @endcode
/// This no longer triggers the warning and further makes it clear that a
/// parameter required by the API is definitively unused in the function.
///
/// This is an especially good solution in the context of method
/// definitions (vs declarations); the parameter name used in a definition
/// is entirely irrelevant to Doxygen and most readers.
///
/// (3) When leaving the parameter name intact has acute value, it is
/// acceptable to keep the name and mark it `unused`. For example, when
/// the name appears as part of a virtual method's base class declaration,
/// the name is used by Doxygen to document the method, e.g.,
/// @code
/// /** Sets the default State of a System. This default implementation is to
/// set all zeros. Subclasses may override to use non-zero defaults. The
/// custom defaults may be based on the given @p context, when relevant. */
/// virtual void SetDefault(const Context<T>& context, State<T>* state) const {
/// unused(context);
/// state->SetZero();
/// }
/// @endcode
///
template <typename... Args>
void unused(const Args&...) {}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/ssize.h | #pragma once
// Many C++20 std headers define ssize; pick one. This is needed even to
// get the __cpp_lib_ssize define set.
#include <vector>
#ifdef __cpp_lib_ssize
namespace drake {
using std::ssize;
} // namespace drake
#else // __cpp_lib_ssize
#include <cstddef> // For std::ptrdiff_t
#include <type_traits> // For std::common_type_t, std::make_signed_t
namespace drake {
/** Implements C++20 %std::ssize() for earlier compilers. See
https://en.cppreference.com/w/cpp/iterator/size for documentation. Will be
removed once all Drake-supported platforms offer %std::ssize(). */
// The implementations below are taken directly from the cppreference
// documentation. BTW std::size() is already supported on all Drake platforms.
template <class C>
constexpr auto ssize(const C& c)
-> std::common_type_t<std::ptrdiff_t,
std::make_signed_t<decltype(c.size())> > {
using R = std::common_type_t<std::ptrdiff_t,
std::make_signed_t<decltype(c.size())> >;
return static_cast<R>(c.size());
}
/** This signature returns the size of built-in (C style) arrays. */
template <class T, std::ptrdiff_t N>
constexpr std::ptrdiff_t ssize(const T (&array)[N]) noexcept {
return N;
}
} // namespace drake
#endif // __cpp_lib_ssize
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/is_less_than_comparable.h | #pragma once
#include <type_traits>
#include "drake/common/unused.h"
namespace drake {
#ifndef DRAKE_DOXYGEN_CXX
namespace is_less_than_comparable_internal {
// Default case; assumes that a class is *not* less-than comparable.
template <typename T, typename = void>
struct is_less_than_comparable_helper : std::false_type {};
// Special sauce for SFINAE. Only compiles if it can finds the method
// `operator<`. If this exists, the is_less_than_comparable implicitly
// prefers this overload over the default overload.
template <typename T>
struct is_less_than_comparable_helper<T, typename std::enable_if_t<true,
decltype(unused(std::declval<T&>() < std::declval<T&>()),
(void)0)>> : std::true_type {};
} // namespace is_less_than_comparable_internal
/** @endcond */
/**
@anchor is_less_than_comparable_doc
Provides method for determining at run time if a class is comparable using
the less-than operator (<).
__Usage__
This gets used like `type_traits` functions (e.g., `is_copy_constructible`,
`is_same`, etc.) To determine if a class is less-than comparable simply invoke:
@code
bool value = drake::is_less_than_comparable<Foo>::value;
@endcode
If `Foo` is less-than comparable, it will evaluate to true. It can also be used
in compile-time tests (e.g., SFINAE and `static_assert`s):
@code
static_assert(is_less_than_comparable<Foo>::value, "This method requires its "
"classes to be less-than comparable.");
@endcode
__Definition of "less-than comparability"__
To be less-than comparable, the class `Foo` must have a public method of the
form:
@code
bool Foo::operator<(const Foo&) const;
@endcode
or a definition external to the class of the form:
@code
bool operator<(const Foo&, const Foo&);
@endcode
@tparam T The class to test for less-than comparability.
*/
template <typename T>
using is_less_than_comparable =
is_less_than_comparable_internal::is_less_than_comparable_helper<T, void>;
} // namespace drake
#endif
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/is_approx_equal_abstol.h | #pragma once
#include <vector>
#include <Eigen/Dense>
namespace drake {
/// Returns true if and only if the two matrices are equal to within a certain
/// absolute elementwise @p tolerance. Special values (infinities, NaN, etc.)
/// do not compare as equal elements.
template <typename DerivedA, typename DerivedB>
bool is_approx_equal_abstol(const Eigen::MatrixBase<DerivedA>& m1,
const Eigen::MatrixBase<DerivedB>& m2,
double tolerance) {
return ((m1.rows() == m2.rows()) && (m1.cols() == m2.cols()) &&
((m1 - m2).template lpNorm<Eigen::Infinity>() <= tolerance));
}
/// Returns true if and only if a simple greedy search reveals a permutation
/// of the columns of m2 to make the matrix equal to m1 to within a certain
/// absolute elementwise @p tolerance. E.g., there exists a P such that
/// <pre>
/// forall i,j, |m1 - m2*P|_{i,j} <= tolerance
/// where P is a permutation matrix:
/// P(i,j)={0,1}, sum_i P(i,j)=1, sum_j P(i,j)=1.
/// </pre>
/// Note: Returns false for matrices of different sizes.
/// Note: The current implementation is O(n^2) in the number of columns.
/// Note: In marginal cases (with similar but not identical columns) this
/// algorithm can fail to find a permutation P even if it exists because it
/// accepts the first column match (m1(i),m2(j)) and removes m2(j) from the
/// pool. It is possible that other columns of m2 would also match m1(i) but
/// that m2(j) is the only match possible for a later column of m1.
template <typename DerivedA, typename DerivedB>
bool IsApproxEqualAbsTolWithPermutedColumns(
const Eigen::MatrixBase<DerivedA>& m1,
const Eigen::MatrixBase<DerivedB>& m2, double tolerance) {
if ((m1.cols() != m2.cols()) || (m1.rows() != m2.rows())) return false;
std::vector<bool> available(m2.cols());
for (int i = 0; i < m2.cols(); i++) available[i] = true;
for (int i = 0; i < m1.cols(); i++) {
bool found_match = false;
for (int j = 0; j < m2.cols(); j++) {
if (available[j] &&
is_approx_equal_abstol(m1.col(i), m2.col(j), tolerance)) {
found_match = true;
available[j] = false;
break;
}
}
if (!found_match) return false;
}
return true;
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/autodiffxd.h | #pragma once
// This file is a modification of Eigen-3.3.3's AutoDiffScalar.h file which is
// available at
// https://gitlab.com/libeigen/eigen/-/blob/3.3.3/unsupported/Eigen/src/AutoDiff/AutoDiffScalar.h
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2017 Drake Authors
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef DRAKE_COMMON_AUTODIFF_HEADER
// TODO(soonho-tri): Change to #error.
#warning Do not directly include this file. Include "drake/common/autodiff.h".
#endif
#include <cmath>
#include <limits>
#include <ostream>
#include <type_traits>
#include <Eigen/Dense>
#include "drake/common/fmt_ostream.h"
namespace Eigen {
#if !defined(DRAKE_DOXYGEN_CXX)
// Explicit template specializations of Eigen::AutoDiffScalar for VectorXd.
//
// AutoDiffScalar tries to call internal::make_coherent to promote empty
// derivatives. However, it fails to do the promotion when an operand is an
// expression tree (i.e. CwiseBinaryOp). Our solution is to provide special
// overloading for VectorXd and change the return types of its operators. With
// this change, the operators evaluate terms immediately and return an
// AutoDiffScalar<VectorXd> instead of expression trees (such as CwiseBinaryOp).
// Eigen's implementation of internal::make_coherent makes use of const_cast in
// order to promote zero sized derivatives. This however interferes badly with
// our caching system and produces unexpected behaviors. See #10971 for details.
// Therefore our implementation stops using internal::make_coherent and treats
// scalars with zero sized derivatives as constants, as it should.
//
// We also provide overloading of math functions for AutoDiffScalar<VectorXd>
// which return AutoDiffScalar<VectorXd> instead of an expression tree.
//
// See https://github.com/RobotLocomotion/drake/issues/6944 for more
// information. See also drake/common/autodiff_overloads.h.
//
// TODO(soonho-tri): Next time when we upgrade Eigen, please check if we still
// need these specializations.
//
// @note move-aware arithmetic
// Prior implementations of arithmetic overloads required construction of new
// objects at each operation, which induced costly heap allocations. In modern
// C++, it is possible to instead exploit move semantics to avoid allocation in
// many cases. In particular, the compiler can implicitly use moves to satisfy
// pass-by-value parameters in cases where moves are possible (move construction
// and assignment are available), and the storage in question is not needed
// afterward. This allows definitions of operators that pass and return by
// value, and only allocate when needed, as determined by the compiler. For C++
// considerations, see Scott Meyers' _Effective Modern C++_ Item 41. See #13985
// for more discussion of Drake considerations.
//
// @note default initialization
// Value initialization is not part of the Eigen::AutoDiffScalar contract nor
// part of the contract for our AutoDiffXd specialization of that template
// class. Thus no code should be written assuming that default-constructed
// AutoDiffXd objects will be value initialized. However, leaving the value
// uninitialized triggered hard-to-eliminate maybe-uninitialized warnings (not
// necessarily spurious) from some versions of gcc (not seen with clang).
// After determining that there is a negligible effect on performance, we
// decided (see PRs #15699 and #15792) to initialize the value member to avoid
// those warnings. Initializing to NaN (as opposed to zero) ensures that no code
// will function with uninitialized AutoDiffXd objects, just as it should not
// with any other Eigen::AutoDiffScalar.
template <>
class AutoDiffScalar<VectorXd>
: public internal::auto_diff_special_op<VectorXd, false> {
public:
typedef internal::auto_diff_special_op<VectorXd, false> Base;
typedef typename internal::remove_all<VectorXd>::type DerType;
typedef typename internal::traits<DerType>::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real Real;
using Base::operator+;
using Base::operator*;
// Default constructor leaves the value effectively uninitialized and the
// derivatives vector zero length.
AutoDiffScalar() {}
AutoDiffScalar(const Scalar& value, int nbDer, int derNumber)
: m_value(value), m_derivatives(DerType::Zero(nbDer)) {
m_derivatives.coeffRef(derNumber) = Scalar(1);
}
// NOLINTNEXTLINE(runtime/explicit): Code from Eigen.
AutoDiffScalar(const Real& value) : m_value(value) {
if (m_derivatives.size() > 0) m_derivatives.setZero();
}
AutoDiffScalar(const Scalar& value, const DerType& der)
: m_value(value), m_derivatives(der) {}
template <typename OtherDerType>
AutoDiffScalar(
const AutoDiffScalar<OtherDerType>& other
#ifndef EIGEN_PARSED_BY_DOXYGEN
,
typename std::enable_if<
internal::is_same<
Scalar, typename internal::traits<typename internal::remove_all<
OtherDerType>::type>::Scalar>::value,
void*>::type = 0
#endif
)
: m_value(other.value()), m_derivatives(other.derivatives()) {
}
friend std::ostream& operator<<(std::ostream& s, const AutoDiffScalar& a) {
return s << a.value();
}
AutoDiffScalar(const AutoDiffScalar& other)
: m_value(other.value()), m_derivatives(other.derivatives()) {}
// Move construction and assignment are trivial, but need to be explicitly
// requested, since we have user-declared copy and assignment operators.
AutoDiffScalar(AutoDiffScalar&&) = default;
AutoDiffScalar& operator=(AutoDiffScalar&&) = default;
template <typename OtherDerType>
inline AutoDiffScalar& operator=(const AutoDiffScalar<OtherDerType>& other) {
m_value = other.value();
m_derivatives = other.derivatives();
return *this;
}
inline AutoDiffScalar& operator=(const AutoDiffScalar& other) {
m_value = other.value();
m_derivatives = other.derivatives();
return *this;
}
inline AutoDiffScalar& operator=(const Scalar& other) {
m_value = other;
if (m_derivatives.size() > 0) m_derivatives.setZero();
return *this;
}
inline const Scalar& value() const { return m_value; }
inline Scalar& value() { return m_value; }
inline const DerType& derivatives() const { return m_derivatives; }
inline DerType& derivatives() { return m_derivatives; }
inline bool operator<(const Scalar& other) const { return m_value < other; }
inline bool operator<=(const Scalar& other) const { return m_value <= other; }
inline bool operator>(const Scalar& other) const { return m_value > other; }
inline bool operator>=(const Scalar& other) const { return m_value >= other; }
inline bool operator==(const Scalar& other) const { return m_value == other; }
inline bool operator!=(const Scalar& other) const { return m_value != other; }
friend inline bool operator<(const Scalar& a, const AutoDiffScalar& b) {
return a < b.value();
}
friend inline bool operator<=(const Scalar& a, const AutoDiffScalar& b) {
return a <= b.value();
}
friend inline bool operator>(const Scalar& a, const AutoDiffScalar& b) {
return a > b.value();
}
friend inline bool operator>=(const Scalar& a, const AutoDiffScalar& b) {
return a >= b.value();
}
friend inline bool operator==(const Scalar& a, const AutoDiffScalar& b) {
return a == b.value();
}
friend inline bool operator!=(const Scalar& a, const AutoDiffScalar& b) {
return a != b.value();
}
template <typename OtherDerType>
inline bool operator<(const AutoDiffScalar<OtherDerType>& b) const {
return m_value < b.value();
}
template <typename OtherDerType>
inline bool operator<=(const AutoDiffScalar<OtherDerType>& b) const {
return m_value <= b.value();
}
template <typename OtherDerType>
inline bool operator>(const AutoDiffScalar<OtherDerType>& b) const {
return m_value > b.value();
}
template <typename OtherDerType>
inline bool operator>=(const AutoDiffScalar<OtherDerType>& b) const {
return m_value >= b.value();
}
template <typename OtherDerType>
inline bool operator==(const AutoDiffScalar<OtherDerType>& b) const {
return m_value == b.value();
}
template <typename OtherDerType>
inline bool operator!=(const AutoDiffScalar<OtherDerType>& b) const {
return m_value != b.value();
}
// The arithmetic operators below exploit move-awareness to avoid heap
// allocations. See note `move-aware arithmetic` above. Particular details
// will be called out below, the first time they appear.
// Using a friend operator instead of a method allows the ADS parameter to be
// used as storage when move optimizations are possible.
friend inline AutoDiffScalar operator+(AutoDiffScalar a, const Scalar& b) {
a += b;
return a;
}
friend inline AutoDiffScalar operator+(const Scalar& a, AutoDiffScalar b) {
b += a;
return b;
}
// Compound assignment operators contain the primitive implementations, since
// the choice of writable storage is clear. Binary operations invoke the
// compound assignments.
inline AutoDiffScalar& operator+=(const Scalar& other) {
value() += other;
return *this;
}
// It is possible that further overloads could exploit more move-awareness
// here. However, overload ambiguities are difficult to resolve. Currently
// only the left-hand operand is available for optimizations. See #13985,
// #14039 for discussion.
template <typename OtherDerType>
friend inline AutoDiffScalar<DerType> operator+(
AutoDiffScalar<DerType> a, const AutoDiffScalar<OtherDerType>& b) {
a += b;
return a;
}
template <typename OtherDerType>
inline AutoDiffScalar& operator+=(const AutoDiffScalar<OtherDerType>& other) {
const bool has_this_der = m_derivatives.size() > 0;
const bool has_both_der = has_this_der && (other.derivatives().size() > 0);
m_value += other.value();
if (has_both_der) {
m_derivatives += other.derivatives();
} else if (has_this_der) {
// noop
} else {
m_derivatives = other.derivatives();
}
return *this;
}
friend inline AutoDiffScalar operator-(AutoDiffScalar a, const Scalar& b) {
a -= b;
return a;
}
// Scalar-on-the-left non-commutative operations must also contain primitive
// implementations.
friend inline AutoDiffScalar operator-(const Scalar& a, AutoDiffScalar b) {
b.value() = a - b.value();
b.derivatives() *= -1;
return b;
}
inline AutoDiffScalar& operator-=(const Scalar& other) {
m_value -= other;
return *this;
}
template <typename OtherDerType>
friend inline AutoDiffScalar<DerType> operator-(
AutoDiffScalar<DerType> a, const AutoDiffScalar<OtherDerType>& other) {
a -= other;
return a;
}
template <typename OtherDerType>
inline AutoDiffScalar& operator-=(const AutoDiffScalar<OtherDerType>& other) {
const bool has_this_der = m_derivatives.size() > 0;
const bool has_both_der = has_this_der && (other.derivatives().size() > 0);
m_value -= other.value();
if (has_both_der) {
m_derivatives -= other.derivatives();
} else if (has_this_der) {
// noop
} else {
m_derivatives = -other.derivatives();
}
return *this;
}
// Phrasing unary negation as a value-passing friend permits some move
// optimizations.
friend inline AutoDiffScalar operator-(AutoDiffScalar a) {
a.value() *= -1;
a.derivatives() *= -1;
return a;
}
friend inline AutoDiffScalar operator*(AutoDiffScalar a, const Scalar& b) {
a *= b;
return a;
}
friend inline AutoDiffScalar operator*(const Scalar& a, AutoDiffScalar b) {
b *= a;
return b;
}
friend inline AutoDiffScalar operator/(AutoDiffScalar a, const Scalar& b) {
a /= b;
return a;
}
friend inline AutoDiffScalar operator/(const Scalar& a, AutoDiffScalar b) {
b.derivatives() *= Scalar(-a) / (b.value() * b.value());
b.value() = a / b.value();
return b;
}
template <typename OtherDerType>
friend inline AutoDiffScalar<DerType> operator/(
AutoDiffScalar<DerType> a, const AutoDiffScalar<OtherDerType>& b) {
a /= b;
return a;
}
template <typename OtherDerType>
friend inline AutoDiffScalar<DerType> operator*(
AutoDiffScalar<DerType> a, const AutoDiffScalar<OtherDerType>& b) {
a *= b;
return a;
}
inline AutoDiffScalar& operator*=(const Scalar& other) {
m_value *= other;
m_derivatives *= other;
return *this;
}
template <typename OtherDerType>
inline AutoDiffScalar& operator*=(const AutoDiffScalar<OtherDerType>& other) {
const bool has_this_der = m_derivatives.size() > 0;
const bool has_both_der = has_this_der && (other.derivatives().size() > 0);
// Some of the math below may look tempting to rewrite using `*=`, but
// performance measurement and analysis show that this formulation is
// faster because it results in better expression tree optimization and
// inlining.
if (has_both_der) {
m_derivatives = m_derivatives * other.value() +
other.derivatives() * m_value;
} else if (has_this_der) {
m_derivatives = m_derivatives * other.value();
} else {
m_derivatives = other.derivatives() * m_value;
}
m_value *= other.value();
return *this;
}
inline AutoDiffScalar& operator/=(const Scalar& other) {
m_value /= other;
m_derivatives *= Scalar(1) / other;
return *this;
}
template <typename OtherDerType>
inline AutoDiffScalar& operator/=(const AutoDiffScalar<OtherDerType>& other) {
auto& this_der = m_derivatives;
const auto& other_der = other.derivatives();
const bool has_this_der = m_derivatives.size() > 0;
const bool has_both_der = has_this_der && (other.derivatives().size() > 0);
const Scalar scale = Scalar(1) / (other.value() * other.value());
if (has_both_der) {
this_der *= other.value();
this_der -= other_der * m_value;
this_der *= scale;
} else if (has_this_der) {
this_der *= Scalar(1) / other.value();
} else {
this_der = other_der * -m_value * scale;
}
m_value /= other.value();
return *this;
}
protected:
// See class documentation above for why we are initializing the value here
// even though that is not part of the Eigen::AutoDiffScalar contract.
// Scalar is always double in this specialization.
Scalar m_value{std::numeric_limits<double>::quiet_NaN()};
DerType m_derivatives;
};
#define DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(FUNC, CODE) \
inline AutoDiffScalar<VectorXd> FUNC( \
AutoDiffScalar<VectorXd> x) { \
EIGEN_UNUSED typedef double Scalar; \
CODE; \
return x; \
}
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
abs, using std::abs;
x.derivatives() *= (x.value() < 0 ? -1 : 1);
x.value() = abs(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
abs2, using numext::abs2;
x.derivatives() *= (Scalar(2) * x.value());
x.value() = abs2(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
sqrt, using std::sqrt;
Scalar sqrtx = sqrt(x.value());
x.value() = sqrtx;
x.derivatives() *= (Scalar(0.5) / sqrtx);)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
cos, using std::cos; using std::sin;
x.derivatives() *= -sin(x.value());
x.value() = cos(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
sin, using std::sin; using std::cos;
x.derivatives() *= cos(x.value());
x.value() = sin(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
exp, using std::exp;
x.value() = exp(x.value());
x.derivatives() *= x.value();)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
log, using std::log;
x.derivatives() *= Scalar(1) / x.value();
x.value() = log(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
tan, using std::tan; using std::cos;
auto sq = [](Scalar n) { return n * n; };
x.derivatives() *= Scalar(1) / sq(cos(x.value()));
x.value() = tan(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
asin, using std::sqrt; using std::asin;
auto sq = [](Scalar n) { return n * n; };
x.derivatives() *= Scalar(1) / sqrt(1 - sq(x.value()));
x.value() = asin(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
acos, using std::sqrt; using std::acos;
auto sq = [](Scalar n) { return n * n; };
x.derivatives() *= Scalar(-1) / sqrt(1 - sq(x.value()));
x.value() = acos(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
atan, using std::atan;
auto sq = [](Scalar n) { return n * n; };
x.derivatives() *= Scalar(1) / (1 + sq(x.value()));
x.value() = atan(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
tanh, using std::cosh; using std::tanh;
auto sq = [](Scalar n) { return n * n; };
x.derivatives() *= Scalar(1) / sq(cosh(x.value()));
x.value() = tanh(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
sinh, using std::sinh; using std::cosh;
x.derivatives() *= cosh(x.value());
x.value() = sinh(x.value());)
DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY(
cosh, using std::sinh; using std::cosh;
x.derivatives() *= sinh(x.value());
x.value() = cosh(x.value());)
#undef DRAKE_EIGEN_AUTODIFFXD_DECLARE_GLOBAL_UNARY
// We have this specialization here because the Eigen-3.3.3's atan2
// implementation for AutoDiffScalar does not make a return with properly sized
// derivatives.
inline AutoDiffScalar<VectorXd> atan2(AutoDiffScalar<VectorXd> a,
const AutoDiffScalar<VectorXd>& b) {
const bool has_a_der = a.derivatives().size() > 0;
const bool has_both_der = has_a_der && (b.derivatives().size() > 0);
const double squared_hypot = a.value() * a.value() + b.value() * b.value();
if (has_both_der) {
a.derivatives() *= b.value();
a.derivatives() -= a.value() * b.derivatives();
} else if (has_a_der) {
a.derivatives() *= b.value();
} else {
a.derivatives() = -a.value() * b.derivatives();
}
a.derivatives() /= squared_hypot;
a.value() = std::atan2(a.value(), b.value());
return a;
}
// Right-hand pass-by-value optimizations for atan2() are blocked by code in
// Eigen; see #14039.
inline AutoDiffScalar<VectorXd> pow(AutoDiffScalar<VectorXd> a, double b) {
// TODO(rpoyner-tri): implementation seems fishy --see #14052.
using std::pow;
a.derivatives() *= b * pow(a.value(), b - 1);
a.value() = pow(a.value(), b);
return a;
}
// We have these implementations here because Eigen's implementations do not
// have consistent behavior when a == b. We enforce the following rules for that
// case:
// 1) If both a and b are ADS with non-empty derivatives, return a.
// 2) If both a and b are doubles, return a.
// 3) If one of a, b is a double, and the other is an ADS, return the ADS.
// 4) Treat ADS with empty derivatives as though they were doubles.
// Points (1) and (4) are handled here. Points (2) and (3) are already handled
// by Eigen's overloads.
// See https://gitlab.com/libeigen/eigen/-/issues/1870.
inline const AutoDiffScalar<VectorXd> min(const AutoDiffScalar<VectorXd>& a,
const AutoDiffScalar<VectorXd>& b) {
// If both a and b have derivatives, then their derivative sizes must match.
DRAKE_ASSERT(
a.derivatives().size() == 0 || b.derivatives().size() == 0 ||
a.derivatives().size() == b.derivatives().size());
// The smaller of a or b wins; ties go to a iff it has any derivatives.
return ((a < b) || ((a == b) && (a.derivatives().size() != 0))) ? a : b;
}
// NOLINTNEXTLINE(build/include_what_you_use)
inline const AutoDiffScalar<VectorXd> max(const AutoDiffScalar<VectorXd>& a,
const AutoDiffScalar<VectorXd>& b) {
// If both a and b have derivatives, then their derivative sizes must match.
DRAKE_ASSERT(
a.derivatives().size() == 0 || b.derivatives().size() == 0 ||
a.derivatives().size() == b.derivatives().size());
// The larger of a or b wins; ties go to a iff it has any derivatives.
return ((a > b) || ((a == b) && (a.derivatives().size() != 0))) ? a : b;
}
#endif
} // namespace Eigen
namespace fmt {
template <>
struct formatter<drake::AutoDiffXd> : drake::ostream_formatter {};
} // namespace fmt
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/network_policy.h | #pragma once
#include <string_view>
namespace drake {
/** @addtogroup environment_variables
@{
@defgroup allow_network DRAKE_ALLOW_NETWORK
Users can set the environment variable `DRAKE_ALLOW_NETWORK` to a
colon-separated list to limit which components are permitted network access.
If `DRAKE_ALLOW_NETWORK` is unset or set to the empty string, then all
networking is allowed.
The component values supported by Drake are:
- <b>lcm</b> (see drake::lcm::DrakeLcm)
- <b>meshcat</b> (see drake::geometry::Meshcat)
- <b>package_map</b> (see drake::multibody::PackageMap)
- <b>render_gltf_client</b> (see drake::geometry::MakeRenderEngineVtk())
... as well as the special value <b>none</b>.
The environment variable only governs the *network* access of the component.
If the component also supports other mechanisms (e.g., files or memory buffers)
those are unaffected.
---
For example, to allow only lcm and meshcat, run this command in your terminal:
```sh
export DRAKE_ALLOW_NETWORK=lcm:meshcat
```
To disable all networking, run this command in your terminal:
```sh
export DRAKE_ALLOW_NETWORK=none
```
@} */
namespace internal {
/* Returns true iff the given component is allowed to access the network based
on the current value of the DRAKE_ALLOW_NETWORK environment variable.
@param component is the name to query, which must be alphanumeric lowercase
(underscores allowed) and must not be "none" nor the empty string. */
bool IsNetworkingAllowed(std::string_view component);
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/nice_type_name_override.cc | #include "drake/common/nice_type_name_override.h"
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
namespace drake {
namespace internal {
namespace {
NiceTypeNamePtrOverride& ptr_override() {
static never_destroyed<NiceTypeNamePtrOverride> value;
return value.access();
}
} // namespace
void SetNiceTypeNamePtrOverride(NiceTypeNamePtrOverride new_ptr_override) {
DRAKE_DEMAND(ptr_override() == nullptr);
DRAKE_DEMAND(new_ptr_override != nullptr);
ptr_override() = new_ptr_override;
}
const NiceTypeNamePtrOverride& GetNiceTypeNamePtrOverride() {
return ptr_override();
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/extract_double.h | #pragma once
#include "drake/common/eigen_types.h"
namespace drake {
/// Returns @p scalar as a double. Never throws.
inline double ExtractDoubleOrThrow(double scalar) {
return scalar;
}
/// 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, double>,
MatrixLikewise<double, Derived>>
ExtractDoubleOrThrow(const Eigen::MatrixBase<Derived>& matrix) {
return matrix
.unaryExpr([](const typename Derived::Scalar& value) {
return ExtractDoubleOrThrow(value);
})
.eval();
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/add_text_logging_gflags.cc | // This is a Drake-internal utility for use only as a direct dependency
// of executable (drake_cc_binary) targets.
//
// To add --spdlog_level and --spdlog_pattern to the gflags command line of any
// `drake_cc_binary`, add "//common:add_text_logging_gflags" to the `deps`
// attribute in its BUILD.
#include <string>
#include <gflags/gflags.h>
#include "drake/common/text_logging.h"
#include "drake/common/unused.h"
// Declare the gflags options.
DEFINE_string(spdlog_level, drake::logging::kSetLogLevelUnchanged,
drake::logging::kSetLogLevelHelpMessage);
DEFINE_string(spdlog_pattern, "%+", drake::logging::kSetLogPatternHelpMessage);
// Validate flags and update Drake's configuration to match their values.
namespace {
bool ValidateSpdlogLevel(const char* name, const std::string& value) {
drake::unused(name);
drake::logging::set_log_level(value);
return true;
}
bool ValidateSpdlogPattern(const char* name, const std::string& value) {
drake::unused(name);
drake::logging::set_log_pattern(value);
return true;
}
} // namespace
DEFINE_validator(spdlog_level, &ValidateSpdlogLevel);
DEFINE_validator(spdlog_pattern, &ValidateSpdlogPattern);
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/timer.h | #pragma once
// TODO(#16486): Remove chrono include by encapsulating into timer.cc
#include <chrono>
#include "drake/common/drake_copyable.h"
/// @file
/// Provides drake::Timer interface and drake::SteadyTimer for timing events.
namespace drake {
/// Abstract base class for timing utility.
class Timer {
public:
/// Properly implemented Timers must start timing upon construction.
Timer() = default;
virtual ~Timer() = default;
/// Begins timing. Call Start every time you want to reset the timer to zero.
virtual void Start() = 0;
/// Obtains a timer measurement in seconds.
/// Call this repeatedly to get multiple measurements.
/// @return the amount of time since the timer started.
virtual double Tick() = 0;
protected:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Timer) // protected from slicing
};
/// Implementation of timing utility that uses monotonic
/// std::chrono::steady_clock.
class SteadyTimer final : public Timer {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(SteadyTimer)
SteadyTimer();
void Start() final;
double Tick() final;
private:
using clock = std::chrono::steady_clock;
clock::time_point start_time_;
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/identifier.h | #pragma once
#include <cstdint>
#include <ostream>
#include <string>
#include <utility>
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/common/fmt_ostream.h"
#include "drake/common/hash.h"
namespace drake {
namespace internal {
int64_t get_new_identifier();
} // namespace internal
/**
A simple identifier class.
@note This is *purposely* a separate class from @ref TypeSafeIndex. For more
explanatation, see @ref TypeSafeIndexVsIndentifier "this section".
This class serves as an upgrade to the standard practice of passing `int`s
around as unique identifiers (or, as in this case, `int64_t`s). In the common
practice, a method that takes identifiers to different types of objects would
have an interface like:
@code
void foo(int64_t bar_id, int64_t thing_id);
@endcode
It is possible for a programmer to accidentally switch the two ids in an
invocation. This mistake would still be _syntactically_ correct; it will
successfully compile but lead to inscrutable run-time errors. This identifier
class provides the same speed and efficiency of passing `int64_t`s, but
enforces unique types and limits the valid operations, providing compile-time
checking. The function would now look like:
@code
void foo(BarId bar_id, ThingId thing_id)
@endcode
and the compiler will catch instances where the order is reversed.
The identifier is a _stripped down_ 64-bit int. Each uniquely declared
identifier type has the following properties:
- The identifier's default constructor produces _invalid_ identifiers.
- Valid identifiers must be constructed via the copy constructor or through
Identifier::get_new_id().
- The identifier is immutable.
- The identifier can only be tested for equality/inequality with other
identifiers of the _same_ type.
- Identifiers of different types are _not_ interconvertible.
- The identifier can be queried for its underlying `int64_t` value.
- The identifier can be written to an output stream; its underlying `int64_t`
value gets written.
- Identifiers are not guaranteed to possess _meaningful_ ordering. I.e.,
identifiers for two objects created sequentially may not have sequential
identifier values.
- Identifiers can only be generated from the static method get_new_id().
While there _is_ the concept of an invalid identifier, this only exists to
facilitate use with STL containers that require default constructors. Using an
invalid identifier is generally considered to be an error. In Debug build,
attempts to compare, get the value of, or write an invalid identifier to a
stream will throw an exception.
Functions that query for identifiers should not return invalid identifiers. We
prefer the practice of returning std::optional<Identifier> instead.
It is the designed intent of this class, that ids derived from this class can
be passed and returned by value. (Drake's typical calling convention requires
passing input arguments by const reference, or by value when moved from. That
convention does not apply to this class.)
The following alias will create a unique identifier type for class `Foo`:
@code{.cpp}
using FooId = Identifier<class FooTag>;
@endcode
__Examples of valid and invalid operations__
The %Identifier guarantees that id instances of different types can't be
compared or combined. Efforts to do so will cause a compile-time failure.
For example:
@code
using AId = Identifier<class ATag>;
using BId = Identifier<class BTag>;
AId a1; // Compiler error; there is no
// default constructor.
AId a2 = AId::get_new_id(); // Ok.
AId a3(a2); // Ok.
AId a4 = AId::get_new_id(); // Ok.
BId b = BId::get_new_id(); // Ok.
if ( a2 == 1 ) { ... } // Compiler error.
if ( a2 == a4 ) { ... } // Ok, evaluates to false.
if ( a2 == a3 ) { ... } // Ok, evaluates to true.
if ( a2 == b ) { ... } // Compiler error.
a4 = a2; // Ok.
a3 = 7; // Compiler error.
@endcode
@anchor TypeSafeIndexVsIndentifier
__TypeSafeIndex vs Identifier__
In principle, the *identifier* is related to the @ref TypeSafeIndex. In
some sense, both are "type-safe" `int`s. They differ in their semantics. We can
consider `ints`, indices, and identifiers as a list of `int` types with
_decreasing_ functionality.
- The int, obviously, has the full range of C++ ints.
- The @ref TypeSafeIndex can be implicitly cast *to* an int, but there are a
limited number of operations _on_ the index that produce other instances
of the index (e.g., increment, in-place addition, etc.) They can be
compared with `int` and other indices of the same type. This behavior
arises from the intention of having them serve as an _index_ in an
ordered set (e.g., `std::vector`).
- The %Identifier is the most restricted. They exist solely to serve as a
unique identifier. They are immutable when created. Very few operations
exist on them (comparison for _equality_ with other identifiers of the same
type, hashing, writing to output stream). These *cannot* be used as
indices.
Ultimately, indices _can_ serve as identifiers (within the scope of the object
they index into). Although, their mutability could make this a dangerous
practice for a public API. Identifiers are more general in that they don't
reflect an object's position in memory (hence the inability to transform to or
compare with an `int`). This decouples details of implementation from the idea
of the object. Combined with its immutability, it would serve well as a element
of a public API.
@sa TypeSafeIndex
@tparam Tag The name of the tag that uniquely segregates one
instantiation from another.
*/
template <class Tag>
class Identifier {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Identifier)
/** Default constructor; the result is an _invalid_ identifier. This only
exists to satisfy demands of working with various container classes. */
Identifier() : value_(0) {}
/** Extracts the underlying representation from the identifier. This is
considered invalid for invalid ids and is strictly enforced in Debug builds.
*/
int64_t get_value() const {
if (kDrakeAssertIsArmed) {
DRAKE_THROW_UNLESS(this->is_valid());
}
return value_;
}
/** Reports if the id is valid. */
bool is_valid() const { return value_ > 0; }
/** Compares one identifier with another of the same type for equality. This
is considered invalid for invalid ids and is strictly enforced in Debug
builds. */
bool operator==(Identifier other) const {
return this->get_value() == other.get_value();
}
/** Compares one identifier with another of the same type for inequality. This
is considered invalid for invalid ids and is strictly enforced in Debug
builds. */
bool operator!=(Identifier other) const {
return this->get_value() != other.get_value();
}
/** Compare two identifiers in order to define a total ordering among
identifiers. This makes identifiers compatible with data structures which
require total ordering (e.g., std::set). */
bool operator<(Identifier other) const {
return this->get_value() < other.get_value();
}
/** Generates a new identifier for this id type. This new identifier will be
different from all previous identifiers created. This method does _not_
make any guarantees about the values of ids from successive invocations.
This method is guaranteed to be thread safe. */
static Identifier get_new_id() {
return Identifier(internal::get_new_identifier());
}
/** Implements the @ref hash_append concept. And invalid id will successfully
hash (in order to satisfy STL requirements), and it is up to the user to
confirm it is valid before using it as a key (or other hashing application).
*/
template <typename HashAlgorithm>
friend void hash_append(HashAlgorithm& hasher, const Identifier& i) noexcept {
using drake::hash_append;
hash_append(hasher, i.value_);
}
// TODO(jwnimmer-tri) Implementing both hash_append and AbslHashValue yields
// undesirable redundancy. Is there a way to avoid repeating ourselves?
/** Implements Abseil's hashing concept.
See https://abseil.io/docs/cpp/guides/hash. */
template <typename H>
friend H AbslHashValue(H state, const Identifier& id) {
return H::combine(std::move(state), id.value_);
}
/** (Internal use only) Compares this possibly-invalid Identifier with one
that is known to be valid and returns `false` if they don't match. It is an
error if `valid_id` is not actually valid, and that is strictly enforced in
Debug builds. However, it is not an error if `this` id is invalid; that
results in a `false` return. This method can be faster than testing
separately for validity and equality. */
bool is_same_as_valid_id(Identifier valid_id) const {
return value_ == valid_id.get_value();
}
protected:
// Instantiates an identifier from the underlying representation type.
explicit Identifier(int64_t val) : value_(val) {}
private:
// The underlying value.
int64_t value_{};
};
/** Streaming output operator. This is considered invalid for invalid ids and
is strictly enforced in Debug builds.
@relates Identifier
*/
template <typename Tag>
std::ostream& operator<<(std::ostream& out, const Identifier<Tag>& id) {
out << id.get_value();
return out;
}
/** Enables use of identifiers with to_string. It requires ADL to work. So,
it should be invoked as: `to_string(id);` and should be preceded by
`using std::to_string`.*/
template <typename Tag>
std::string to_string(const drake::Identifier<Tag>& id) {
return std::to_string(id.get_value());
}
} // namespace drake
namespace std {
/** Enables use of the identifier to serve as a key in STL containers.
@relates Identifier
*/
template <typename Tag>
struct hash<drake::Identifier<Tag>> : public drake::DefaultHash {};
} // namespace std
// TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<.
namespace fmt {
template <typename Tag>
struct formatter<drake::Identifier<Tag>> : drake::ostream_formatter {};
} // namespace fmt
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/scoped_singleton.h | #pragma once
#include <memory>
#include <mutex>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
namespace drake {
/**
* Provides thread-safe, global-safe access to a shared resource. When
* all references are gone, the resource will be freed due to using a weak_ptr.
* @tparam T Class of the resource. Must be default-constructible.
* @tparam Unique Optional class, meant to make a unique specialization, such
* that you can have multiple singletons of T if necessary.
*
* @note An example application is obtaining license for multiple disjoint
* solver objects, where acquiring a license requires network communication,
* and the solver is under an interface where you cannot explicitly pass the
* license resource to the solver without violating encapsulation.
*/
template <typename T, typename Unique = void>
std::shared_ptr<T> GetScopedSingleton() {
// Confine implementation to a class.
class Singleton {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Singleton)
Singleton() {}
/*
* Acquire a reference to resource if no other instance exists.
* Otherwise, return a shared reference to the resource.
*/
std::shared_ptr<T> Acquire() {
// We must never create more than one instance of a T at a time, since it
// is supposed to be a singleton. Thus, we need at least the make_shared
// to appear in a critical section. Rather than worrying about a double-
// checked locking pattern, we'll just hold the lock for the entire
// method for simplicity.
std::lock_guard<std::mutex> lock(mutex_);
std::shared_ptr<T> result;
// Attempt to promote the weak_ptr to a shared_ptr. If the singleton
// already existed, this will extend its lifetime to our return value.
result = weak_ref_.lock();
if (!result) {
// The singleton does not exist. Since we hold the exclusive lock on
// weak_ref_, we know that its safe for us to create the singleton now.
result = std::make_shared<T>();
// Store the weak reference to the result, so that other callers will
// be able to use it, as long as our caller keeps it alive.
weak_ref_ = result;
}
DRAKE_DEMAND(result.get() != nullptr);
return result;
}
private:
// The mutex guards all access and changes to weak_ref_, but does not guard
// the use of the T instance that weak_ref_ points to.
std::mutex mutex_;
std::weak_ptr<T> weak_ref_;
};
// Allocate singleton as a static function local to control initialization.
static never_destroyed<Singleton> singleton;
return singleton.access().Acquire();
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/nice_type_name_override.h | #pragma once
/**
@file
(Advanced) Provides the ability to override NiceTypeName::Get(T*) so that
Python objects can have human-readable names.
*/
#include <functional>
#include <string>
#include <typeinfo>
namespace drake {
namespace internal {
// Structure for passing a type-erased pointer with RTTI.
struct type_erased_ptr {
const void* raw{};
const std::type_info& info;
};
// Callback for overriding an object's nice type name.
using NiceTypeNamePtrOverride =
std::function<std::string(const type_erased_ptr&)>;
// Sets override for nice type names. This can only ever be set once, and
// must be given a non-empty function<> object.
void SetNiceTypeNamePtrOverride(NiceTypeNamePtrOverride new_ptr_override);
// Gets the override. If unset, it will be an empty function<> object.
const NiceTypeNamePtrOverride& GetNiceTypeNamePtrOverride();
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/polynomial.h | #pragma once
#include <complex>
#include <map>
#include <random>
#include <set>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
#include <Eigen/Core>
#include <unsupported/Eigen/Polynomials>
#include "drake/common/autodiff.h"
#include "drake/common/default_scalars.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
#include "drake/common/fmt_ostream.h"
#include "drake/common/symbolic/expression.h"
namespace drake {
/** A scalar multi-variate polynomial, modeled after the msspoly in spotless.
*
* Polynomial represents a list of additive Monomials, each one of which is a
* product of a constant coefficient (of T, which by default is double) and any
* number of distinct Terms (variables raised to positive integer powers).
*
* Variables are identified by integer indices rather than symbolic names, but
* an automatic facility is provided to convert variable names up to four
* characters into unique integers, provided those variables are named using
* only lowercase letters and the "@#_." characters followed by a number. For
* example, valid names include "dx4" and "m_x".
*
* Monomials which have the same variables and powers may be constructed but
* will be automatically combined: (3 * a * b * a) + (1.5 * b * a**2) will be
* reduced to (4.5 * b * a**2) internally after construction.
*
* Polynomials can be added, subtracted, and multiplied. They may only be
* divided by scalars (of T) because Polynomials are not closed under division.
*
* @tparam_default_scalar
*/
template <typename T = double>
class Polynomial {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Polynomial);
typedef unsigned int VarType;
/// This should be 'unsigned int' but MSVC considers a call to std::pow(...,
/// unsigned int) ambiguous because it won't cast unsigned int to int.
typedef int PowerType;
typedef typename Eigen::NumTraits<T>::Real RealScalar;
typedef std::complex<RealScalar> RootType;
typedef Eigen::Matrix<RootType, Eigen::Dynamic, 1> RootsType;
template <typename Rhs, typename Lhs>
struct Product {
typedef decltype(static_cast<Rhs>(0) * static_cast<Lhs>(0)) type;
};
/// An individual variable raised to an integer power; e.g. x**2.
class Term {
public:
VarType var;
PowerType power;
bool operator==(const Term& other) const {
return (var == other.var) && (power == other.power);
}
/// A comparison to allow std::lexicographical_compare on this class; does
/// not reflect any sort of mathematical total order.
bool operator<(const Term& other) const {
return ((var < other.var) ||
((var == other.var) && (power < other.power)));
}
};
/// An additive atom of a Polynomial: The product of any number of
/// Terms and a coefficient.
class Monomial {
public:
T coefficient;
std::vector<Term> terms; // a list of N variable ids
bool operator==(const Monomial& other) const {
return (coefficient == other.coefficient) && (terms == other.terms);
}
/// A comparison to allow std::lexicographical_compare on this class; does
/// not reflect any sort of mathematical total order.
bool operator<(const Monomial& other) const {
return ((coefficient < other.coefficient) ||
((coefficient == other.coefficient) && (terms < other.terms)));
}
int GetDegree() const;
int GetDegreeOf(VarType var) const;
bool HasSameExponents(const Monomial& other) const;
bool HasVariable(const VarType& var) const;
/// Factors this by other; returns 0 iff other does not divide this.
Monomial Factor(const Monomial& divisor) const;
};
/// Construct the vacuous polynomial, "0".
Polynomial(void) : is_univariate_(true) {}
/// Construct a Polynomial of a single constant. e.g. "5".
// This is required for some Eigen operations when used in a
// polynomial matrix.
// NOLINTNEXTLINE(runtime/explicit) This conversion is desirable.
Polynomial(const T& scalar);
/// Construct a Polynomial consisting of a single Monomial, e.g. "5xy**3".
Polynomial(const T coeff, const std::vector<Term>& terms);
/// Construct a Polynomial from a sequence of Monomials.
Polynomial(typename std::vector<Monomial>::const_iterator start,
typename std::vector<Monomial>::const_iterator finish);
/// Constructs a polynomial consisting of a single Monomial of the variable
/// named `varname1`.
///
/// @note: This constructor is only provided for T = double. For the other
/// cases, a user should use the constructor with two arguments below (taking
/// std::string and unsigned int). If we provided this constructor for T =
/// AutoDiffXd and T = symbolic::Expression, there would be compiler errors
/// for `Polynomial<T>(0)` as the following candidates are ambiguous:
/// - Polynomial(const T& scalar)
/// - Polynomial(const std::string& varname, const unsigned int num = 1)
template <typename U = T>
explicit Polynomial(
const std::enable_if_t<std::is_same_v<U, double>, std::string>& varname)
: Polynomial<T>(varname, 1) {
// TODO(soonho-tri): Consider deprecating this constructor to make the API
// consistent for different scalar types.
}
/// Construct a polynomial consisting of a single Monomial of the variable
/// named varname + num.
Polynomial(const std::string& varname, unsigned int num);
/// Construct a single Monomial of the given coefficient and variable.
Polynomial(const T& coeff, const VarType& v);
/// A constructor for univariate polynomials: takes a vector of coefficients
/// for the x**0, x**1, x**2, x**3... Monomials. All terms are always added,
/// even if a coefficient is zero.
template <typename Derived>
explicit Polynomial(const Eigen::MatrixBase<Derived>& coefficients) {
DRAKE_THROW_UNLESS((coefficients.cols() == 1) ||
(coefficients.rows() == 1) ||
(coefficients.size() == 0));
*this = Polynomial(WithCoefficients{coefficients.template cast<T>()});
}
/// Returns the number of unique Monomials (and thus the number of
/// coefficients) in this Polynomial.
int GetNumberOfCoefficients() const;
/** Returns the highest degree of any Monomial in this Polynomial.
*
* The degree of a multivariate Monomial is the product of the degrees of
* each of its terms. */
int GetDegree() const;
/// Returns true iff this is a sum of terms of degree 1, plus a constant.
bool IsAffine() const;
/// If the polynomial is "simple" -- e.g. just a single term with
/// coefficient 1 -- then returns that variable; otherwise returns 0.
VarType GetSimpleVariable() const;
const std::vector<Monomial>& GetMonomials() const;
VectorX<T> GetCoefficients() const;
/// Returns a set of all of the variables present in this Polynomial.
std::set<VarType> GetVariables() const;
/** Evaluate a univariate Polynomial at a specific point.
*
* Evaluates a univariate Polynomial at the given x.
* @throws std::exception if this Polynomial is not univariate.
*
* @p x may be of any type supporting the ** and + operations (which can be
* different from both CoefficientsType and RealScalar).
*
* This method may also be used for efficient evaluation of the derivatives of
* the univariate polynomial, evaluated at @p x. @p derivative_order = 0 (the
* default) returns the polynomial value without differentiation. @p
* derivative_order = 1 returns the first derivative, etc.
*
* @pre derivative_order must be non-negative.
*/
template <typename U>
typename Product<T, U>::type EvaluateUnivariate(
const U& x, int derivative_order = 0) const {
// Note: have to remove_const because Product<AutoDiff, AutoDiff>::type and
// even Product<double, AutoDiff>::type returns const AutoDiff.
typedef typename std::remove_const_t<typename Product<T, U>::type>
ProductType;
if (!is_univariate_)
throw std::runtime_error(
"this method can only be used for univariate polynomials");
DRAKE_DEMAND(derivative_order >= 0);
ProductType value = 0;
using std::pow;
for (typename std::vector<Monomial>::const_iterator iter =
monomials_.begin();
iter != monomials_.end(); iter++) {
PowerType degree = iter->terms.empty() ? 0 : iter->terms[0].power;
if (degree < derivative_order) continue;
T coefficient = iter->coefficient;
for (int i = 0; i < derivative_order; i++) {
coefficient *= degree--;
}
if (degree == 0) {
value += coefficient;
} else if (degree == 1) {
value += coefficient * x;
} else { // degree > 1.
value += coefficient * pow(static_cast<ProductType>(x), degree);
}
}
return value;
}
/** Evaluate a multivariate Polynomial at a specific point.
*
* Evaluates a Polynomial with the given values for each variable.
* @throws std::exception if the Polynomial contains variables for which
* values were not provided.
*
* The provided values may be of any type which is std::is_arithmetic
* (supporting the std::pow, *, and + operations) and need not be
* CoefficientsType or RealScalar)
*/
template <typename U>
typename Product<T, U>::type EvaluateMultivariate(
const std::map<VarType, U>& var_values) const {
using std::pow;
typedef typename std::remove_const_t<typename Product<T, U>::type>
ProductType;
ProductType value = 0;
for (const Monomial& monomial : monomials_) {
ProductType monomial_value = monomial.coefficient;
for (const Term& term : monomial.terms) {
monomial_value *=
pow(static_cast<ProductType>(var_values.at(term.var)), term.power);
}
value += monomial_value;
}
return value;
}
/** Substitute values for some but not necessarily all variables of a
* Polynomial.
*
* Analogous to EvaluateMultivariate, but:
* (1) Restricted to T, and
* (2) Need not map every variable in var_values.
*
* Returns a Polynomial in which each variable in var_values has been
* replaced with its value and constants appropriately combined.
*/
Polynomial EvaluatePartial(const std::map<VarType, T>& var_values) const;
/// Replaces all instances of variable orig with replacement.
void Subs(const VarType& orig, const VarType& replacement);
/// Replaces all instances of variable orig with replacement.
Polynomial Substitute(const VarType& orig,
const Polynomial& replacement) const;
/** Takes the derivative of this (univariate) Polynomial.
*
* Returns a new Polynomial that is the derivative of this one in its sole
* variable.
* @throws std::exception if this Polynomial is not univariate.
*
* If derivative_order is given, takes the nth derivative of this
* Polynomial.
*/
Polynomial Derivative(int derivative_order = 1) const;
/** Takes the integral of this (univariate, non-constant) Polynomial.
*
* Returns a new Polynomial that is the indefinite integral of this one in
* its sole variable.
* @throws std::exception if this Polynomial is not univariate, or if it has
* no variables.
*
* If integration_constant is given, adds that constant as the constant
* term (zeroth-order coefficient) of the resulting Polynomial.
*/
Polynomial Integral(const T& integration_constant = 0.0) const;
/** Returns true if this is a univariate polynomial */
bool is_univariate() const;
bool operator==(const Polynomial& other) const;
Polynomial& operator+=(const Polynomial& other);
Polynomial& operator-=(const Polynomial& other);
Polynomial& operator*=(const Polynomial& other);
Polynomial& operator+=(const T& scalar);
Polynomial& operator-=(const T& scalar);
Polynomial& operator*=(const T& scalar);
Polynomial& operator/=(const T& scalar);
const Polynomial operator+(const Polynomial& other) const;
const Polynomial operator-(const Polynomial& other) const;
const Polynomial operator-() const;
const Polynomial operator*(const Polynomial& other) const;
friend const Polynomial operator+(const Polynomial& p, const T& scalar) {
Polynomial ret = p;
ret += scalar;
return ret;
}
friend const Polynomial operator+(const T& scalar, const Polynomial& p) {
Polynomial ret = p;
ret += scalar;
return ret;
}
friend const Polynomial operator-(const Polynomial& p, const T& scalar) {
Polynomial ret = p;
ret -= scalar;
return ret;
}
friend const Polynomial operator-(const T& scalar, const Polynomial& p) {
Polynomial ret = -p;
ret += scalar;
return ret;
}
friend const Polynomial operator*(const Polynomial& p, const T& scalar) {
Polynomial ret = p;
ret *= scalar;
return ret;
}
friend const Polynomial operator*(const T& scalar, const Polynomial& p) {
Polynomial ret = p;
ret *= scalar;
return ret;
}
const Polynomial operator/(const T& scalar) const;
/// A comparison to allow std::lexicographical_compare on this class; does
/// not reflect any sort of mathematical total order.
bool operator<(const Polynomial& other) const {
// Just delegate to the default vector std::lexicographical_compare.
return monomials_ < other.monomials_;
}
/** Returns the roots of this (univariate) Polynomial.
*
* Returns the roots of a univariate Polynomial as an Eigen column vector of
* complex numbers whose components are of the RealScalar type.
* @throws std::exception of this Polynomial is not univariate.
*/
RootsType Roots() const;
/** Checks if a Polynomial is approximately equal to this one.
*
* Checks that every coefficient of `other` is within `tol` of the
* corresponding coefficient of this Polynomial.
*
* Note: When `tol_type` is kRelative, if any monomials appear in `this` or
* `other` but not both, then the method returns false (since the comparison
* is relative to a missing zero coefficient). Use kAbsolute if you want to
* ignore non-matching monomials with coefficients less than `tol`.
*/
boolean<T> CoefficientsAlmostEqual(
const Polynomial<T>& other, const RealScalar& tol = 0.0,
const ToleranceType& tol_type = ToleranceType::kAbsolute) const;
/** Constructs a Polynomial representing the symbolic expression `e`.
* Note that the ID of a variable is preserved in this translation.
*
* @throws std::exception if `e` is not polynomial-convertible.
* @pre e.is_polynomial() is true.
*/
static Polynomial<T> FromExpression(const drake::symbolic::Expression& e);
// TODO(jwnimmer-tri) Rewrite this as a fmt::formatter specialization.
friend std::ostream& operator<<(std::ostream& os, const Monomial& m) {
// if (m.coefficient == 0) return os;
bool print_star = false;
if (m.coefficient == -1) {
os << "-";
} else if (m.coefficient != 1 || m.terms.empty()) {
os << '(' << m.coefficient << ")";
print_star = true;
}
for (typename std::vector<Term>::const_iterator iter = m.terms.begin();
iter != m.terms.end(); iter++) {
if (print_star)
os << '*';
else
print_star = true;
os << IdToVariableName(iter->var);
if (iter->power != 1) {
os << "^" << iter->power;
}
}
return os;
}
// TODO(jwnimmer-tri) Rewrite this as a fmt::formatter specialization.
friend std::ostream& operator<<(std::ostream& os, const Polynomial& poly) {
if (poly.monomials_.empty()) {
os << "0";
return os;
}
for (typename std::vector<Monomial>::const_iterator iter =
poly.monomials_.begin();
iter != poly.monomials_.end(); iter++) {
os << *iter;
if (iter + 1 != poly.monomials_.end() && (iter + 1)->coefficient != -1)
os << '+';
}
return os;
}
//@{
/** Variable name/ID conversion facility. */
static bool IsValidVariableName(const std::string name);
static VarType VariableNameToId(const std::string name, unsigned int m = 1);
static std::string IdToVariableName(const VarType id);
//@}
template <typename U>
friend Polynomial<U> pow(const Polynomial<U>& p,
typename Polynomial<U>::PowerType n);
private:
// A wrapper struct to help guide constructor overload resolution.
struct WithCoefficients {
Eigen::Ref<const VectorX<T>> value;
};
explicit Polynomial(const WithCoefficients& coefficients);
/// The Monomial atoms of the Polynomial.
std::vector<Monomial> monomials_;
/// True iff only 0 or 1 distinct variables appear in the Polynomial.
bool is_univariate_;
/// Sorts through Monomial list and merges any that have the same powers.
void MakeMonomialsUnique(void);
};
/** Provides power function for Polynomial. */
template <typename T>
Polynomial<T> pow(const Polynomial<T>& base,
typename Polynomial<T>::PowerType exponent) {
DRAKE_DEMAND(exponent >= 0);
if (exponent == 0) {
return Polynomial<T>{1.0};
}
const Polynomial<T> pow_half{pow(base, exponent / 2)};
if (exponent % 2 == 1) {
return base * pow_half * pow_half; // Odd exponent case.
} else {
return pow_half * pow_half; // Even exponent case.
}
}
// TODO(jwnimmer-tri) Rewrite this as a fmt::formatter specialization,
// most likely just fmt_eigen without anything extra.
template <typename T, int Rows, int Cols>
std::ostream& operator<<(
std::ostream& os,
const Eigen::Matrix<Polynomial<T>, Rows, Cols>& poly_mat) {
for (int i = 0; i < poly_mat.rows(); i++) {
os << "[ ";
for (int j = 0; j < poly_mat.cols(); j++) {
os << poly_mat(i, j);
if (j < (poly_mat.cols() - 1)) os << " , ";
}
os << " ]" << std::endl;
}
return os;
}
typedef Polynomial<double> Polynomiald;
/// A column vector of polynomials; used in several optimization classes.
typedef Eigen::Matrix<Polynomiald, Eigen::Dynamic, 1> VectorXPoly;
} // namespace drake
// TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<.
namespace fmt {
template <typename T>
struct formatter<drake::Polynomial<T>> : drake::ostream_formatter {};
template <>
struct formatter<drake::Polynomial<double>::Monomial>
: drake::ostream_formatter {};
} // namespace fmt
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::Polynomial)
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/overloaded.h | #pragma once
/** @file
The "overloaded" variant-visit pattern.
The C++ std::visit (typeswitch dispatch) is very useful for std::variant but
doesn't support it natively. There is a commonly used two-line boilerplate
that bridges this gap; see
https://en.cppreference.com/w/cpp/utility/variant/visit
This file should be included by classes that wish to
use the variant visit pattern, i.e.
@code {.cpp}
using MyVariant = std::variant<int, std::string>;
MyVariant v = 5;
std::string result = std::visit<const char*>(overloaded{
[](const int arg) { return "found an int"; },
[](const std::string& arg) { return "found a string"; }
}, v);
EXPECT_EQ(result, "found an int");
@endcode
@warning This file must never be included by a header, only by a cc file.
This is enforced by a lint rule in `tools/lint/drakelint.py`.
*/
// We put this in the anonymous namespace to ensure that it will not generate
// linkable symbols for every specialization in every library that uses it.
namespace { // NOLINT(build/namespaces)
// Boilerplate for `std::visit`; see
// https://en.cppreference.com/w/cpp/utility/variant/visit
template <class... Ts>
struct overloaded : Ts... {
using Ts::operator()...;
};
// Even though Drake requires C++20, Clang versions prior to 17 do not implement
// P1816 yet, so we need to write out a deduction guide. We can remove this once
// Drake requires Clang 17 or newer (as well as the matching Apple Clang).
template <class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
} // namespace
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/pointer_cast.cc | #include "drake/common/pointer_cast.h"
// For now, this is an empty .cc file that only serves to confirm that
// pointer_cast.h is a stand-alone header.
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/value.cc | #include "drake/common/value.h"
#include <atomic>
#include <fmt/format.h>
#include "drake/common/text_logging.h"
namespace drake {
namespace internal {
int ReportZeroHash(const std::type_info& detail) {
// Log a debug message noting the possible performance impairment. Elevate
// it to a warning the first time it happens -- but only elevate it at most
// once per process, to avoid spamming.
static std::atomic<bool> g_has_warned{false};
const bool has_warned = g_has_warned.exchange(true);
const std::string bad_class = NiceTypeName::Get(detail);
const std::string message = fmt::format(
"The {} class is incompatible with the typename hasher that provides the"
" type-erasure checking for AbstractValue casts, most likely because the"
" problematic class mixes template parameters with nested classes or"
" non-type template parameters."
//
" As a result, operations on Value<{}> will suffer from slightly impaired"
" performance."
//
" If the problem relates to nested classes, you may be able to resolve it"
" by un-nesting the class in question."
//
" If the problem relates to a single non-type template parameter, you may"
" be able to resolve it by adding 'using NonTypeTemplateParameter = ...'."
" See drake/common/test/value_test.cc for an example.",
bad_class, bad_class);
if (!has_warned) {
log()->warn(
message +
" This is the first instance of an impaired T within this process."
" Additional instances will not be warned about, but you may set"
" the drake::log() level to 'debug' to see all instances.");
} else {
log()->debug(message);
}
return 0;
}
} // namespace internal
AbstractValue::~AbstractValue() = default;
std::string AbstractValue::GetNiceTypeName() const {
return NiceTypeName::Canonicalize(NiceTypeName::Demangle(type_info().name()));
}
void AbstractValue::ThrowCastError(const std::string& requested_type) const {
const auto dynamic_type = GetNiceTypeName();
const auto static_type = NiceTypeName::Get(static_type_info());
if (dynamic_type != static_type) {
throw std::logic_error(fmt::format(
"AbstractValue: a request to cast to '{}' failed because the value "
"was created using the static type '{}' (with a dynamic type of '{}').",
requested_type, static_type, dynamic_type));
}
throw std::logic_error(fmt::format(
"AbstractValue: a request to cast to '{}' failed because the value was "
"created using the static type '{}'.",
requested_type, static_type));
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/temp_directory.cc | #include "drake/common/temp_directory.h"
#include <unistd.h>
#include <cstdlib>
#include <filesystem>
#include "drake/common/drake_throw.h"
namespace drake {
namespace fs = std::filesystem;
std::string temp_directory() {
fs::path path;
const char* tmpdir = nullptr;
(tmpdir = std::getenv("TEST_TMPDIR")) || (tmpdir = std::getenv("TMPDIR")) ||
(tmpdir = "/tmp");
fs::path path_template(tmpdir);
path_template.append("robotlocomotion_drake_XXXXXX");
std::string path_template_str = path_template.string();
const char* dtemp = ::mkdtemp(&path_template_str[0]);
DRAKE_THROW_UNLESS(dtemp != nullptr);
path = dtemp;
DRAKE_THROW_UNLESS(fs::is_directory(path));
std::string path_string = path.string();
DRAKE_DEMAND(path_string.back() != '/');
return path_string;
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_path.cc | #include "drake/common/drake_path.h"
#include <filesystem>
#include "drake/common/find_resource.h"
// N.B. This code is unit tested in test/find_resource_test.cc.
namespace drake {
std::optional<std::string> MaybeGetDrakePath() {
// Find something that represents where Drake resources live. This will be
// "/path/to/drake/.drake-find_resource-sentinel" where "/path/to/" names the
// root of Drake's git source tree (or perhaps an installed version of same).
const auto& find_result = FindResource("drake/.drake-find_resource-sentinel");
if (find_result.get_error_message()) {
return std::nullopt;
}
std::filesystem::path sentinel_path(find_result.get_absolute_path_or_throw());
// Take the dirname of sentinel_path, so that we have a folder where looking
// up "drake/foo/bar.urdf" makes sense.
return sentinel_path.parent_path().string();
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_assertion_error.h | #pragma once
#include <stdexcept>
#include <string>
namespace drake {
namespace internal {
// This is what DRAKE_ASSERT and DRAKE_DEMAND throw when our assertions are
// configured to throw.
class assertion_error : public std::runtime_error {
public:
explicit assertion_error(const std::string& what_arg)
: std::runtime_error(what_arg) {}
};
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/string_hash.h | #pragma once
#include <string>
#include <string_view>
namespace drake {
namespace internal {
/* StringHash allows us unordered maps and sets with `std::string` keys to
accept either `std::string` or `std::string_view` or `const char*` key during
lookup operations (find, count, etc.) via "transparent" lookups. */
struct StringHash final : public std::hash<std::string_view> {
using is_transparent = void;
// Note that the call operator `operator()(std::string_view)` is inherited
// from our base class. We don't need to add overloads for `std::string` or
// `const char*` because those implicitly convert to `string_view`.
};
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/temp_directory.h | #pragma once
#include <string>
namespace drake {
/// Returns a directory location suitable for temporary files.
/// The directory will be called ${parent}/robotlocomotion_drake_XXXXXX where
/// each X is replaced by a character from the portable filename character set.
/// The path ${parent} is defined as one of the following (in decreasing
/// priority):
///
/// - ${TEST_TMPDIR}
/// - ${TMPDIR}
/// - /tmp
///
/// If successful, this will always create a new directory. While the caller is
/// not obliged to delete the directory, it has full power to do so based on
/// specific context and need.
///
/// @return The path representing a newly created directory There will be no
/// trailing `/`.
/// @throws if the directory ${parent}/robotlocomotion_drake_XXXXXX cannot be
/// created, or is not a directory.
std::string temp_directory();
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/hash.h | #pragma once
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <optional>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_throw.h"
/// @defgroup hash_append hash_append generic hashing
/// @{
/// @ingroup cxx
/// @brief Drake uses the hash_append pattern as described by N3980.
///
/// For a full treatment of the hash_append pattern, refer to:
/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3980.html
///
/// <h3>Providing hash_append support within a class</h3>
///
/// Drake types may implement a `hash_append` function.
/// The function appends every hash-relevant member field into the hasher:
/// @code
/// class MyValue {
/// public:
/// ...
/// /// Implements the @ref hash_append concept.
/// template <class HashAlgorithm>
/// friend void hash_append(
/// HashAlgorithm& hasher, const MyValue& item) noexcept {
/// using drake::hash_append;
/// hash_append(hasher, item.my_data_);
/// }
/// ...
/// private:
/// std::string my_data_;
/// };
/// @endcode
///
/// Checklist for reviewing a `hash_append` implementation:
///
/// - The function cites `@ref hash_append` in its Doxygen comment.
/// - The function is marked `noexcept`.
///
/// <h3>Using hashable types</h3>
///
/// Types that implement this pattern may be used in unordered collections:
/// @code
/// std::unordered_set<MyValue, drake::DefaultHash> foo;
/// @endcode
///
/// Some Drake types may also choose to specialize `std::hash<MyValue>` to use
/// `DefaultHash`, so that the second template argument to `std::unordered_set`
/// can be omitted. For example, Drake's `symbolic::Expression` header says:
/// @code
/// namespace std {
/// struct hash<drake::symbolic::Expression> : public drake::DefaultHash {};
/// } // namespace std
/// @endcode
/// so that users are able to simply write:
/// @code
/// std::unordered_set<drake::symbolic::Expression> foo;
/// @endcode
///
/// @}
namespace drake {
/// Provides @ref hash_append for integral constants.
template <class HashAlgorithm, class T>
std::enable_if_t<std::is_integral_v<T>>
hash_append(
HashAlgorithm& hasher, const T& item) noexcept {
hasher(std::addressof(item), sizeof(item));
}
/// Provides @ref hash_append for bare pointers.
template <class HashAlgorithm, class T>
void hash_append(HashAlgorithm& hasher, const T* item) noexcept {
hash_append(hasher, reinterpret_cast<std::uintptr_t>(item));
};
/// Provides @ref hash_append for enumerations.
template <class HashAlgorithm, class T>
std::enable_if_t<std::is_enum_v<T>>
hash_append(
HashAlgorithm& hasher, const T& item) noexcept {
hasher(std::addressof(item), sizeof(item));
}
/// Provides @ref hash_append for floating point values.
template <class HashAlgorithm, class T>
std::enable_if_t<std::is_floating_point_v<T>>
hash_append(
HashAlgorithm& hasher, const T& item) noexcept {
// Hashing a NaN makes no sense, since they cannot compare as equal.
DRAKE_ASSERT(!std::isnan(item));
// +0.0 and -0.0 are equal, so must hash identically.
if (item == 0.0) {
const T zero{0.0};
hasher(std::addressof(zero), sizeof(zero));
} else {
hasher(std::addressof(item), sizeof(item));
}
}
/// Provides @ref hash_append for std::string.
/// (Technically, any string based on `CharT = char`.)
template <class HashAlgorithm, class Traits, class Allocator>
void hash_append(
HashAlgorithm& hasher,
const std::basic_string<char, Traits, Allocator>& item) noexcept {
using drake::hash_append;
hasher(item.data(), item.size());
// All collection types must send their size, after their contents.
// See the #hash_append_vector anchor in N3980.
hash_append(hasher, item.size());
}
// Prior to this point, we've defined hashers for primitive types and similar
// kinds of "singular" types, where the template arguments form a bounded set.
//
// Following this point, we'll define hashers for types where the template
// argument can be anything (e.g., collections). That means for proper namespace
// lookups we need to declare them all first, and then define them all second.
/// Provides @ref hash_append for std::pair.
template <class HashAlgorithm, class T1, class T2>
void hash_append(HashAlgorithm& hasher, const std::pair<T1, T2>& item) noexcept;
/// Provides @ref hash_append for std::optional.
///
/// Note that `std::hash<std::optional<T>>` provides the peculiar invariant
/// that the hash of an `optional` bearing a value `v` shall evaluate to the
/// same hash as that of the value `v` itself. Hash operations implemented
/// with this `hash_append` do *not* provide that invariant.
template <class HashAlgorithm, class T>
void hash_append(HashAlgorithm& hasher, const std::optional<T>& item) noexcept;
/// Provides @ref hash_append for std::map.
///
/// Note that there is no `hash_append` overload for `std::unordered_map`. See
/// [N3980](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3980.html#unordered)
/// for details.
template <class HashAlgorithm, class T1, class T2, class Compare,
class Allocator>
void hash_append(HashAlgorithm& hasher,
const std::map<T1, T2, Compare, Allocator>& item) noexcept;
/// Provides @ref hash_append for std::set.
///
/// Note that there is no `hash_append` overload for `std::unordered_set. See
/// [N3980](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3980.html#unordered)
/// for details.
template <class HashAlgorithm, class Key, class Compare, class Allocator>
void hash_append(HashAlgorithm& hasher,
const std::set<Key, Compare, Allocator>& item) noexcept;
// Now that all of the templated hashers are declared, we can define them.
template <class HashAlgorithm, class T1, class T2>
void hash_append(HashAlgorithm& hasher,
const std::pair<T1, T2>& item) noexcept {
using drake::hash_append;
hash_append(hasher, item.first);
hash_append(hasher, item.second);
}
template <class HashAlgorithm, class T>
void hash_append(HashAlgorithm& hasher, const std::optional<T>& item) noexcept {
if (item) {
hash_append(hasher, *item);
}
hash_append(hasher, item.has_value());
};
/// Provides @ref hash_append for a range, as given by two iterators.
template <class HashAlgorithm, class Iter>
void hash_append_range(
// NOLINTNEXTLINE(runtime/references) Per hash_append convention.
HashAlgorithm& hasher, Iter begin, Iter end) noexcept {
using drake::hash_append;
size_t count{0};
for (Iter iter = begin; iter != end; ++iter, ++count) {
hash_append(hasher, *iter);
}
// All collection types must send their size, after their contents.
// See the #hash_append_vector anchor in N3980.
hash_append(hasher, count);
}
template <class HashAlgorithm, class T1, class T2, class Compare,
class Allocator>
void hash_append(HashAlgorithm& hasher,
const std::map<T1, T2, Compare, Allocator>& item) noexcept {
return hash_append_range(hasher, item.begin(), item.end());
};
template <class HashAlgorithm, class Key, class Compare, class Allocator>
void hash_append(HashAlgorithm& hasher,
const std::set<Key, Compare, Allocator>& item) noexcept {
return hash_append_range(hasher, item.begin(), item.end());
};
/// A hashing functor, somewhat like `std::hash`. Given an item of type @p T,
/// applies @ref hash_append to it, directing the bytes to append into the
/// given @p HashAlgorithm, and then finally returning the algorithm's result.
template <class HashAlgorithm>
struct uhash {
using result_type = typename HashAlgorithm::result_type;
template <class T>
result_type operator()(const T& item) const noexcept {
HashAlgorithm hasher;
using drake::hash_append;
hash_append(hasher, item);
return static_cast<result_type>(hasher);
}
};
namespace internal {
/// The FNV1a hash algorithm, used for @ref hash_append.
/// https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
class FNV1aHasher {
public:
using result_type = size_t;
/// Feeds a block of memory into this hash.
void operator()(const void* data, size_t length) noexcept {
const uint8_t* const begin = static_cast<const uint8_t*>(data);
const uint8_t* const end = begin + length;
for (const uint8_t* iter = begin; iter < end; ++iter) {
hash_ = (hash_ ^ *iter) * kFnvPrime;
}
}
/// Feeds a single byte into this hash.
constexpr void add_byte(uint8_t byte) noexcept {
hash_ = (hash_ ^ byte) * kFnvPrime;
}
/// Returns the hash.
explicit constexpr operator size_t() noexcept { return hash_; }
private:
static_assert(sizeof(result_type) == (64 / 8), "We require a 64-bit size_t");
result_type hash_{0xcbf29ce484222325u};
static constexpr size_t kFnvPrime = 1099511628211u;
};
} // namespace internal
/// The default HashAlgorithm concept implementation across Drake. This is
/// guaranteed to have a result_type of size_t to be compatible with std::hash.
using DefaultHasher = internal::FNV1aHasher;
/// The default hashing functor, akin to std::hash.
using DefaultHash = drake::uhash<DefaultHasher>;
/// An adapter that forwards the HashAlgorithm::operator(data, length) function
/// concept into a runtime-provided std::function of the same signature. This
/// is useful for passing a concrete HashAlgorithm implementation through into
/// non-templated code, such as with an Impl or Cell pattern.
struct DelegatingHasher {
/// A std::function whose signature matches HashAlgorithm::operator().
using Func = std::function<void(const void*, size_t)>;
/// Create a delegating hasher that calls the given @p func.
explicit DelegatingHasher(Func func) : func_(std::move(func)) {
// In order for operator() to be noexcept, it must have a non-empty func_.
DRAKE_THROW_UNLESS(static_cast<bool>(func_));
}
/// Append [data, data + length) bytes into the wrapped algorithm.
void operator()(const void* data, size_t length) noexcept {
func_(data, length);
}
private:
const Func func_;
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_resource.cc | #include "drake/common/find_resource.h"
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include "drake/common/drake_marker.h"
#include "drake/common/drake_throw.h"
#include "drake/common/find_loaded_library.h"
#include "drake/common/find_runfiles.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
using std::getenv;
using std::string;
namespace drake {
namespace fs = std::filesystem;
using Result = FindResourceResult;
std::optional<string> Result::get_absolute_path() const {
return absolute_path_;
}
string Result::get_absolute_path_or_throw() const {
// If we have a path, return it.
const auto& optional_path = get_absolute_path();
if (optional_path) {
return *optional_path;
}
// Otherwise, throw the error message.
const auto& optional_error = get_error_message();
DRAKE_ASSERT(optional_error != std::nullopt);
throw std::runtime_error(*optional_error);
}
std::optional<string> Result::get_error_message() const {
// If an error has been set, return it.
if (error_message_ != std::nullopt) {
DRAKE_ASSERT(absolute_path_ == std::nullopt);
return error_message_;
}
// If successful, return no-error.
if (absolute_path_ != std::nullopt) {
return std::nullopt;
}
// Both optionals are null; we are empty; return a default error message.
DRAKE_ASSERT(resource_path_.empty());
return string("No resource was requested (empty result)");
}
string Result::get_resource_path() const {
return resource_path_;
}
Result Result::make_success(string resource_path, string absolute_path) {
DRAKE_THROW_UNLESS(!resource_path.empty());
DRAKE_THROW_UNLESS(!absolute_path.empty());
Result result;
result.resource_path_ = std::move(resource_path);
result.absolute_path_ = std::move(absolute_path);
result.CheckInvariants();
return result;
}
Result Result::make_error(string resource_path, string error_message) {
DRAKE_THROW_UNLESS(!resource_path.empty());
DRAKE_THROW_UNLESS(!error_message.empty());
Result result;
result.resource_path_ = std::move(resource_path);
result.error_message_ = std::move(error_message);
result.CheckInvariants();
return result;
}
Result Result::make_empty() {
Result result;
result.CheckInvariants();
return result;
}
void Result::CheckInvariants() {
if (resource_path_.empty()) {
// For our "empty" state, both success and error must be empty.
DRAKE_DEMAND(absolute_path_ == std::nullopt);
DRAKE_DEMAND(error_message_ == std::nullopt);
} else {
// For our "non-empty" state, we must have exactly one of success or error.
DRAKE_DEMAND((absolute_path_ == std::nullopt) !=
(error_message_ == std::nullopt));
}
// When non-nullopt, the path and error cannot be the empty string.
DRAKE_DEMAND((absolute_path_ == std::nullopt) || !absolute_path_->empty());
DRAKE_DEMAND((error_message_ == std::nullopt) || !error_message_->empty());
}
namespace {
// A valid resource root will always contain this file.
const char* const kSentinelRelpath = "drake/.drake-find_resource-sentinel";
// Returns true iff the path is relative (not absolute nor empty).
bool IsRelativePath(const string& path) {
return !path.empty() && (path[0] != '/');
}
// Taking `root` to be Drake's resource root, confirm that the sentinel file
// exists and return the found resource_path (or an error if either the
// sentinel or resource_path was missing).
Result CheckAndMakeResult(const string& root_description, const string& root,
const string& resource_path) {
DRAKE_DEMAND(!root_description.empty());
DRAKE_DEMAND(!root.empty());
DRAKE_DEMAND(!resource_path.empty());
DRAKE_DEMAND(fs::is_directory({root}));
DRAKE_DEMAND(IsRelativePath(resource_path));
// Check for the sentinel.
if (!fs::is_regular_file({root + "/" + kSentinelRelpath})) {
return Result::make_error(
resource_path,
fmt::format(
"Could not find Drake resource_path '{}' because {} specified a "
"resource root of '{}' but that root did not contain the expected "
"sentinel file '{}'.",
resource_path, root_description, root, kSentinelRelpath));
}
// Check for the resource_path.
const string abspath = root + '/' + resource_path;
if (!fs::is_regular_file({abspath})) {
return Result::make_error(
resource_path,
fmt::format(
"Could not find Drake resource_path '{}' because {} specified a "
"resource root of '{}' but that root did not contain the expected "
"file '{}'.",
resource_path, root_description, root, abspath));
}
return Result::make_success(resource_path, abspath);
}
// If the DRAKE_RESOURCE_ROOT environment variable is usable as a resource
// root, returns its value, else returns nullopt.
std::optional<string> MaybeGetEnvironmentResourceRoot() {
const char* const env_name = kDrakeResourceRootEnvironmentVariableName;
const char* const env_value = getenv(env_name);
if (!env_value) {
log()->debug("FindResource ignoring {} because it is not set.", env_name);
return std::nullopt;
}
const std::string root{env_value};
if (!fs::is_directory({root})) {
static const logging::Warn log_once(
"FindResource ignoring {}='{}' because it does not exist.", env_name,
env_value);
return std::nullopt;
}
if (!fs::is_directory({root + "/drake"})) {
static const logging::Warn log_once(
"FindResource ignoring {}='{}' because it does not contain a 'drake' "
"subdirectory.",
env_name, env_value);
return std::nullopt;
}
if (!fs::is_regular_file({root + "/" + kSentinelRelpath})) {
static const logging::Warn log_once(
"FindResource ignoring {}='{}' because it does not contain the "
"expected sentinel file '{}'.",
env_name, env_value, kSentinelRelpath);
return std::nullopt;
}
return root;
}
// If we are linked against libdrake_marker.so, and the install-tree-relative
// path resolves correctly, returns the install tree resource root, else
// returns nullopt.
std::optional<string> MaybeGetInstallResourceRoot() {
// Ensure that we have the library loaded.
DRAKE_DEMAND(drake::internal::drake_marker_lib_check() == 1234);
std::optional<string> maybe_libdrake_dir =
LoadedLibraryPath("libdrake_marker.so");
if (maybe_libdrake_dir) {
log()->debug("FindResource libdrake_dir='{}'", *maybe_libdrake_dir);
const fs::path libdrake_dir{*maybe_libdrake_dir};
const fs::path root = libdrake_dir / "../share";
if (fs::is_directory(root)) {
return root.string();
}
const fs::path canonical_root =
fs::canonical(libdrake_dir / "libdrake_marker.so")
.parent_path()
.parent_path() /
"share";
if (fs::is_directory(canonical_root)) {
return canonical_root.string();
}
log()->debug(
"FindResource ignoring CMake install candidate '{}' ('{}') because it "
"does not exist",
root.string(), canonical_root.string());
} else {
log()->debug("FindResource has no CMake install candidate");
}
return std::nullopt;
}
Result MakeResultFrom(const string& resource_path, RlocationOrError other) {
return other.error.empty()
? Result::make_success(resource_path, std::move(other.abspath))
: Result::make_error(resource_path, std::move(other.error));
}
} // namespace
const char* const kDrakeResourceRootEnvironmentVariableName =
"DRAKE_RESOURCE_ROOT";
Result FindResource(const string& resource_path) {
// Check if resource_path is well-formed: a relative path that starts with
// "drake" as its first directory name. A valid example would look like:
// "drake/common/test/find_resource_test_data.txt". Requiring strings passed
// to drake::FindResource to start with "drake" is redundant, but preserves
// compatibility with the original semantics of this function; if we want to
// offer a function that takes paths without "drake", we can use a new name.
if (!IsRelativePath(resource_path)) {
return Result::make_error(
resource_path,
fmt::format("Drake resource_path '{}' is not a relative path.",
resource_path));
}
const string prefix("drake/");
if (!resource_path.starts_with(prefix)) {
return Result::make_error(
resource_path,
fmt::format("Drake resource_path '{}' does not start with {}.",
resource_path, prefix));
}
// We will check each potential resource root one by one. The first root
// that is present will be chosen, even if does not contain the particular
// resource_path. We expect that all sources offer all files.
// (1) Check the environment variable.
if (auto guess = MaybeGetEnvironmentResourceRoot()) {
return CheckAndMakeResult(
fmt::format("{} environment variable",
kDrakeResourceRootEnvironmentVariableName),
*guess, resource_path);
}
// (2) Check the Runfiles. If and only if we have Drake's runfiles (not just
// any old runfiles) should we consider runfiles as a source for FindResource.
// Downstream projects that use Bazel but don't build Drake from source will
// have runfiles but not Drake's runfiles; in that case we should skip this
// option and continue to option (3) instead.
if (HasRunfiles()) {
if (FindRunfile(kSentinelRelpath).error.empty()) {
return MakeResultFrom(resource_path, FindRunfile(resource_path));
} else {
log()->debug(
"FindResource ignoring Bazel runfiles with no sentinel file {}.",
kSentinelRelpath);
}
}
// (3) Check the `libdrake_marker.so` location in the install tree.
if (auto guess = MaybeGetInstallResourceRoot()) {
return CheckAndMakeResult("Drake CMake install marker", *guess,
resource_path);
}
// No resource roots were found.
return Result::make_error(
resource_path,
fmt::format(
"Could not find Drake resource_path '{}' because no resource roots "
"of any kind could be found: {} is unset, a {} could not be created "
"or did not contain {}, and there is no Drake CMake install marker.",
resource_path, kDrakeResourceRootEnvironmentVariableName,
"bazel::tools::cpp::runfiles::Runfiles", kSentinelRelpath));
}
string FindResourceOrThrow(const string& resource_path) {
return FindResource(resource_path).get_absolute_path_or_throw();
}
std::optional<string> ReadFile(const std::filesystem::path& path) {
std::optional<string> result;
std::ifstream input(path, std::ios::binary);
if (input.is_open()) {
std::stringstream content;
content << input.rdbuf();
result.emplace(std::move(content).str());
}
return result;
}
std::string ReadFileOrThrow(const std::filesystem::path& path) {
std::optional<string> result = ReadFile(path);
if (!result) {
throw std::runtime_error(
fmt::format("Error reading from '{}'", path.string()));
}
return std::move(*result);
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/nice_type_name.h | #pragma once
#include <memory>
#include <string>
#include <typeinfo>
#include <utility>
#include <vector>
#include "drake/common/never_destroyed.h"
namespace drake {
/** @brief Obtains canonicalized, platform-independent, human-readable names for
arbitrarily-complicated C++ types.
Usage: @code
// For types:
using std::pair; using std::string;
using MyVectorType = pair<int,string>;
std::cout << "Type MyVectorType was: "
<< drake::NiceTypeName::Get<MyVectorType>() << std::endl;
// Output: std::pair<int,std::string>
// For expressions:
std::unique_ptr<AbstractThing> thing; // Assume actual type is ConcreteThing.
std::cout << "Actual type of 'thing' was: "
<< drake::NiceTypeName::Get(*thing) << std::endl;
// Output: ConcreteThing
@endcode
We demangle and attempt to canonicalize the compiler-generated type names as
reported by `typeid(T).name()` so that the same string is returned by all
supported compilers and platforms. The output of NiceTypeName::Get<T>() is
useful in error and log messages and testing. It also provides a
persistent, platform-independent identifier for types; `std::type_info` cannot
provide that.
@warning Don't expect usable names for types that are defined in an anonymous
namespace or for function-local types. Names will still be produced but they
won't be unique, pretty, or compiler-independent.
This class exists only to group type name-related static methods; don't try
to construct an object of this type. */
class NiceTypeName {
public:
/** Returns a nicely demangled and canonicalized type name that is the same
on all platforms, using Canonicalize(). This is calculated on the fly so is
expensive whenever called, though very reasonable for use in error messages.
For repeated or performance-sensitive uses, see GetFromStorage(). */
template <typename T>
static std::string Get() {
return NiceTypeName::Get(typeid(T));
}
/** Like Get<T>() but only computed once per process for a given type `T`.
The returned reference will not be deleted even at program termination, so
feel free to use it in error messages even in destructors that may be
invoked during program tear-down. */
template <typename T>
static const std::string& GetFromStorage() {
static const never_destroyed<std::string> result(NiceTypeName::Get<T>());
return result.access();
}
/** Returns the type name of the most-derived type of an object of type T,
typically but not necessarily polymorphic. This must be calculated on the fly
so is expensive whenever called, though very reasonable for use in error
messages. For non-polymorphic types this produces the same result as would
`Get<decltype(thing)>()` but for polymorphic types the results will
differ. */
template <typename T>
static std::string Get(const T& thing) {
return GetWithPossibleOverride(&thing, typeid(thing));
}
/** Returns the nicely demangled and canonicalized type name of `info`. This
must be calculated on the fly so is expensive whenever called, though very
reasonable for use in error messages. */
static std::string Get(const std::type_info& info) {
return Canonicalize(Demangle(info.name()));
}
/** Using the algorithm appropriate to the current compiler, demangles a type
name as returned by `typeid(T).name()`, with the result hopefully suitable for
meaningful display to a human. The result is compiler-dependent.
@see Canonicalize() */
static std::string Demangle(const char* typeid_name);
/** Given a compiler-dependent demangled type name string as returned by
Demangle(), attempts to form a canonicalized representation that will be
the same for any compiler. Unnecessary spaces and superfluous keywords like
"class" and "struct" are removed. The NiceTypeName::Get<T>() method
uses this function to produce a human-friendly type name that is the same on
any platform. */
static std::string Canonicalize(const std::string& demangled_name);
/** Given a canonical type name that may include leading namespaces, attempts
to remove those namespaces. For example,
`drake::systems::MyThing<internal::type>` becomes `MyThing<internal::type>`.
If the last segment ends in `::`, the original string is returned unprocessed.
Note that this is just string processing -- a segment that looks like a
namespace textually will be treated as one, even if it is really a class. So
`drake::MyClass::Impl` will be reduced to `Impl` while
`drake::MyClass<T>::Impl` is reduced to `MyClass<T>::Impl`. */
static std::string RemoveNamespaces(const std::string& canonical_name);
private:
// No instances of this class should be created.
NiceTypeName() = delete;
static std::string GetWithPossibleOverride(const void* ptr,
const std::type_info& info);
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/cond.h | #pragma once
#include <functional>
#include <type_traits>
#include "drake/common/double_overloads.h"
namespace drake {
/** @name cond
Constructs conditional expression (similar to Lisp's cond).
@verbatim
cond(cond_1, expr_1,
cond_2, expr_2,
..., ...,
cond_n, expr_n,
expr_{n+1})
@endverbatim
The value returned by the above cond expression is @c expr_1 if @c cond_1 is
true; else if @c cond_2 is true then @c expr_2; ... ; else if @c cond_n is
true then @c expr_n. If none of the conditions are true, it returns @c
expr_{n+1}.
@note This functions assumes that @p ScalarType provides @c operator< and the
type of @c f_cond is the type of the return type of <tt>operator<(ScalarType,
ScalarType)</tt>. For example, @c symbolic::Expression can be used as a @p
ScalarType because it provides <tt>symbolic::Formula
operator<(symbolic::Expression, symbolic::Expression)</tt>.
@{
*/
template <typename ScalarType>
ScalarType cond(const ScalarType& e) {
return e;
}
template <typename ScalarType, typename... Rest>
ScalarType cond(const decltype(ScalarType() < ScalarType())& f_cond,
const ScalarType& e_then, Rest... rest) {
return if_then_else(f_cond, e_then, cond(rest...));
}
///@}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_deprecated.h | #pragma once
#include <string>
#include <string_view>
/** @file
Provides a portable macro for use in generating compile-time warnings for
use of code that is permitted but discouraged. */
#ifdef DRAKE_DOXYGEN_CXX
/** Use `DRAKE_DEPRECATED("removal_date", "message")` to discourage use of
certain APIs. It can be used on classes, typedefs, variables, non-static data
members, functions, arguments, enumerations, and template specializations. When
code refers to the deprecated item, a compile time warning will be issued
displaying the given message, preceded by "DRAKE DEPRECATED: ". The Doxygen API
reference will show that the API is deprecated, along with the message.
This is typically used for constructs that have been replaced by something
better and it is good practice to suggest the appropriate replacement in the
deprecation message. Deprecation warnings are conventionally used to convey to
users that a feature they are depending on will be removed in a future release.
Every deprecation notice must include a date (as YYYY-MM-DD string) where the
deprecated item is planned for removal. Future commits may change the date
(e.g., delaying the removal) but should generally always reflect the best
current expectation for removal.
Absent any other particular need, we prefer to use a deprecation period of
three months by default, often rounded up to the next first of the month. So
for code announced as deprecated on 2018-01-22 the removal_date would nominally
be set to 2018-05-01.
Try to keep the date string immediately after the DRAKE_DEPRECATED macro name,
even if the message itself must be wrapped to a new line:
@code
DRAKE_DEPRECATED("2038-01-19",
"foo is being replaced with a safer, const-method named bar().")
int foo();
@endcode
Sample uses: @code
// Attribute comes *before* declaration of a deprecated function or variable;
// no semicolon is allowed.
DRAKE_DEPRECATED("2038-01-19", "f() is slow; use g() instead.")
int f(int arg);
// Attribute comes *after* struct, class, enum keyword.
class DRAKE_DEPRECATED("2038-01-19", "Use MyNewClass instead.")
MyClass {
};
// Type alias goes before the '='.
using OldType
DRAKE_DEPRECATED("2038-01-19", "Use NewType instead.")
= NewType;
@endcode
*/
#define DRAKE_DEPRECATED(removal_date, message)
#else // DRAKE_DOXYGEN_CXX
#define DRAKE_DEPRECATED(removal_date, message) \
[[deprecated("\nDRAKE DEPRECATED: " message \
"\nThe deprecated code will be removed from Drake" \
" on or after " removal_date ".")]]
#endif // DRAKE_DOXYGEN_CXX
namespace drake {
namespace internal {
/* When constructed, logs a deprecation message; the destructor is guaranteed
to be trivial. This is useful for declaring an instance of this class as a
function-static global, so that a warning is logged the first time the program
encounters some code, but does not repeat the warning on subsequent encounters
within the same process.
For example:
<pre>
void OldCalc(double data) {
static const drake::internal::WarnDeprecated warn_once(
"2038-01-19", "The method OldCalc() has been renamed to NewCalc().");
return NewCalc(data);
}
</pre> */
class[[maybe_unused]] WarnDeprecated {
public:
/* The removal_date must be in the form YYYY-MM-DD. */
WarnDeprecated(std::string_view removal_date, std::string_view message);
};
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_path.h | #pragma once
#include <optional>
#include <string>
namespace drake {
/// (Advanced) Returns the fully-qualified path to the first folder containing
/// Drake resources as located by FindResource, or nullopt if none is found.
/// For example `${result}/examples/pendulum/Pendulum.urdf` would be the path
/// to the Pendulum example's URDF resource.
///
/// Most users should prefer FindResource() or FindResourceOrThrow() to locate
/// Drake resources for a specific resource filename. This method only exists
/// for legacy compatibility reasons, and might eventually be removed.
std::optional<std::string> MaybeGetDrakePath();
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/autodiff.h | #pragma once
/// @file
/// This header provides a single inclusion point for autodiff-related header
/// files in the `drake/common` directory. Users should include this file.
/// Including other individual headers such as `drake/common/autodiffxd.h`
/// will generate a compile-time warning.
// In each header included below, it asserts that this macro
// `DRAKE_COMMON_AUTODIFF_HEADER` is defined. If the macro is not defined, it
// generates diagnostic warning messages.
#define DRAKE_COMMON_AUTODIFF_HEADER
#include <Eigen/Core>
#include <unsupported/Eigen/AutoDiff>
// Do not alpha-sort the following block of hard-coded #includes, which is
// protected by `clang-format on/off`.
//
// Rationale: We want to maximize the use of this header, `autodiff.h`, even
// inside of the autodiff-related files to avoid any mistakes which might not be
// detected. By centralizing the list here, we make sure that everyone will see
// the correct order which respects the inter-dependencies of the autodiff
// headers. This shields us from triggering undefined behaviors due to
// order-of-specialization-includes-changed mistakes.
//
// clang-format off
#include "drake/common/eigen_autodiff_types.h"
#include "drake/common/autodiffxd.h"
#include "drake/common/autodiff_overloads.h"
// clang-format on
#undef DRAKE_COMMON_AUTODIFF_HEADER
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/random.cc | #include "drake/common/random.h"
#include "drake/common/autodiff.h"
namespace drake {
std::unique_ptr<RandomGenerator::Engine> RandomGenerator::CreateEngine(
result_type seed) {
return std::make_unique<RandomGenerator::Engine>(seed);
}
template <typename T>
T CalcProbabilityDensity(RandomDistribution distribution,
const Eigen::Ref<const VectorX<T>>& x) {
switch (distribution) {
case RandomDistribution::kUniform: {
for (int i = 0; i < x.rows(); ++i) {
if (x(i) < 0.0 || x(i) > 1.0) {
return T(0.);
}
}
return T(1.);
}
case RandomDistribution::kGaussian: {
return ((-0.5 * x.array() * x.array()).exp() / std::sqrt(2 * M_PI))
.prod();
}
case RandomDistribution::kExponential: {
for (int i = 0; i < x.rows(); ++i) {
if (x(i) < 0.0) {
return T(0.);
}
}
return (-x.array()).exp().prod();
}
}
DRAKE_UNREACHABLE();
}
// TODO(jwnimmer-tri) Use DRAKE_DEFINE_FUNCTION_TEMPLATE_INSTANTIATIONS_...
// here, once we can break the dependency cycle.
template double CalcProbabilityDensity<double>(
RandomDistribution, const Eigen::Ref<const VectorX<double>>&);
template AutoDiffXd CalcProbabilityDensity<AutoDiffXd>(
RandomDistribution, const Eigen::Ref<const VectorX<AutoDiffXd>>&);
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_assert.h | #pragma once
#include <type_traits>
/// @file
/// Provides Drake's assertion implementation. This is intended to be used
/// both within Drake and by other software. Drake's asserts can be armed
/// and disarmed independently from the system-wide asserts.
#ifdef DRAKE_DOXYGEN_CXX
/// @p DRAKE_ASSERT(condition) is similar to the built-in @p assert(condition)
/// from the C++ system header @p <cassert>. Unless Drake's assertions are
/// disarmed by the pre-processor definitions listed below, @p DRAKE_ASSERT
/// will evaluate @p condition and iff the value is false will trigger an
/// assertion failure with a message showing at least the condition text,
/// function name, file, and line.
///
/// By default, assertion failures will :abort() the program. However, when
/// using the pydrake python bindings, assertion failures will instead throw a
/// C++ exception that causes a python SystemExit exception.
///
/// Assertions are enabled or disabled using the following pre-processor macros:
///
/// - If @p DRAKE_ENABLE_ASSERTS is defined, then @p DRAKE_ASSERT is armed.
/// - If @p DRAKE_DISABLE_ASSERTS is defined, then @p DRAKE_ASSERT is disarmed.
/// - If both macros are defined, then it is a compile-time error.
/// - If neither are defined, then NDEBUG governs assertions as usual.
///
/// This header will define exactly one of either @p DRAKE_ASSERT_IS_ARMED or
/// @p DRAKE_ASSERT_IS_DISARMED to indicate whether @p DRAKE_ASSERT is armed.
///
/// This header will define both `constexpr bool drake::kDrakeAssertIsArmed`
/// and `constexpr bool drake::kDrakeAssertIsDisarmed` globals.
///
/// One difference versus the standard @p assert(condition) is that the
/// @p condition within @p DRAKE_ASSERT is always syntax-checked, even if
/// Drake's assertions are disarmed.
///
/// Treat @p DRAKE_ASSERT like a statement -- it must always be used
/// in block scope, and must always be followed by a semicolon.
#define DRAKE_ASSERT(condition)
/// Like @p DRAKE_ASSERT, except that the expression must be void-valued; this
/// allows for guarding expensive assertion-checking subroutines using the same
/// macros as stand-alone assertions.
#define DRAKE_ASSERT_VOID(expression)
/// Evaluates @p condition and iff the value is false will trigger an assertion
/// failure with a message showing at least the condition text, function name,
/// file, and line.
#define DRAKE_DEMAND(condition)
/// Silences a "no return value" compiler warning by calling a function that
/// always raises an exception or aborts (i.e., a function marked noreturn).
/// Only use this macro at a point where (1) a point in the code is truly
/// unreachable, (2) the fact that it's unreachable is knowable from only
/// reading the function itself (and not, e.g., some larger design invariant),
/// and (3) there is a compiler warning if this macro were removed. The most
/// common valid use is with a switch-case-return block where all cases are
/// accounted for but the enclosing function is supposed to return a value. Do
/// *not* use this macro as a "logic error" assertion; it should *only* be used
/// to silence false positive warnings. When in doubt, throw an exception
/// manually instead of using this macro.
#define DRAKE_UNREACHABLE()
#else // DRAKE_DOXYGEN_CXX
// Users should NOT set these; only this header should set them.
#ifdef DRAKE_ASSERT_IS_ARMED
# error Unexpected DRAKE_ASSERT_IS_ARMED defined.
#endif
#ifdef DRAKE_ASSERT_IS_DISARMED
# error Unexpected DRAKE_ASSERT_IS_DISARMED defined.
#endif
// Decide whether Drake assertions are enabled.
#if defined(DRAKE_ENABLE_ASSERTS) && defined(DRAKE_DISABLE_ASSERTS)
# error Conflicting assertion toggles.
#elif defined(DRAKE_ENABLE_ASSERTS)
# define DRAKE_ASSERT_IS_ARMED
#elif defined(DRAKE_DISABLE_ASSERTS) || defined(NDEBUG)
# define DRAKE_ASSERT_IS_DISARMED
#else
# define DRAKE_ASSERT_IS_ARMED
#endif
namespace drake {
namespace internal {
// Abort the program with an error message.
[[noreturn]] void Abort(const char* condition, const char* func,
const char* file, int line);
// Report an assertion failure; will either Abort(...) or throw.
[[noreturn]] void AssertionFailed(const char* condition, const char* func,
const char* file, int line);
} // namespace internal
namespace assert {
// Allows for specialization of how to bool-convert Conditions used in
// assertions, in case they are not intrinsically convertible. See
// common/symbolic/expression/formula.h for an example use. This is a public
// interface to extend; it is intended to be specialized by unusual Scalar
// types that require special handling.
template <typename Condition>
struct ConditionTraits {
static constexpr bool is_valid = std::is_convertible_v<Condition, bool>;
static bool Evaluate(const Condition& value) {
return value;
}
};
} // namespace assert
} // namespace drake
#define DRAKE_UNREACHABLE() \
::drake::internal::Abort( \
"Unreachable code was reached?!", __func__, __FILE__, __LINE__)
#define DRAKE_DEMAND(condition) \
do { \
typedef ::drake::assert::ConditionTraits< \
typename std::remove_cv_t<decltype(condition)>> Trait; \
static_assert(Trait::is_valid, "Condition should be bool-convertible."); \
static_assert( \
!std::is_pointer_v<decltype(condition)>, \
"When using DRAKE_DEMAND on a raw pointer, always write out " \
"DRAKE_DEMAND(foo != nullptr), do not write DRAKE_DEMAND(foo) " \
"and rely on implicit pointer-to-bool conversion."); \
if (!Trait::Evaluate(condition)) { \
::drake::internal::AssertionFailed( \
#condition, __func__, __FILE__, __LINE__); \
} \
} while (0)
#ifdef DRAKE_ASSERT_IS_ARMED
// Assertions are enabled.
namespace drake {
constexpr bool kDrakeAssertIsArmed = true;
constexpr bool kDrakeAssertIsDisarmed = false;
} // namespace drake
# define DRAKE_ASSERT(condition) DRAKE_DEMAND(condition)
# define DRAKE_ASSERT_VOID(expression) do { \
static_assert( \
std::is_convertible_v<decltype(expression), void>, \
"Expression should be void."); \
expression; \
} while (0)
#else
// Assertions are disabled, so just typecheck the expression.
namespace drake {
constexpr bool kDrakeAssertIsArmed = false;
constexpr bool kDrakeAssertIsDisarmed = true;
} // namespace drake
# define DRAKE_ASSERT(condition) do { \
typedef ::drake::assert::ConditionTraits< \
typename std::remove_cv_t<decltype(condition)>> Trait; \
static_assert(Trait::is_valid, "Condition should be bool-convertible."); \
static_assert( \
!std::is_pointer_v<decltype(condition)>, \
"When using DRAKE_ASSERT on a raw pointer, always write out " \
"DRAKE_ASSERT(foo != nullptr), do not write DRAKE_ASSERT(foo) " \
"and rely on implicit pointer-to-bool conversion."); \
} while (0)
# define DRAKE_ASSERT_VOID(expression) static_assert( \
std::is_convertible_v<decltype(expression), void>, \
"Expression should be void.")
#endif
#endif // DRAKE_DOXYGEN_CXX
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/drake_marker.cc | #include "drake/common/drake_marker.h"
namespace drake {
namespace internal {
int drake_marker_lib_check() {
return 1234;
}
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/sorted_pair.cc | #include "drake/common/sorted_pair.h"
namespace drake {
// Some template instantiations.
template struct SortedPair<double>;
template struct SortedPair<int>;
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/default_scalars.h | #pragma once
#include "drake/common/autodiff.h"
#include "drake/common/symbolic/expression.h"
// N.B. `CommonScalarPack` and `NonSymbolicScalarPack` in `systems_pybind.h`
// should be kept in sync with this file.
/// @defgroup default_scalars Default Scalars
/// @ingroup technical_notes
/// @{
/// Similar to the Eigen library, many classes in Drake use a template argument
/// to specify the numeric scalar type to use for computation. We typically
/// name that template argument <b>`<T>`</b>. For an example, see the class
/// drake::math::RigidTransform.
///
/// Most scalar-templated classes in Drake only support a small, fixed set of
/// scalar types:
/// - `double` (always)
/// - drake::AutoDiffXd (almost always)
/// - drake::symbolic::Expression (sometimes)
///
/// When Drake documentation refers to "default scalars", it means all three
/// of the types above.
///
/// Alternatively, reference to "default nonsymbolic scalars" means all except
/// `drake::symbolic::Expression`.
///
/// For code within Drake, we offer Doxygen custom commands to document the
/// `<T>` template parameter in the conventional cases:
///
/// - @c \@tparam_default_scalar for the default scalars.
/// - @c \@tparam_nonsymbolic_scalar for the default nonsymbolic scalars.
/// - @c \@tparam_double_only for only the `double` scalar and nothing else.
///
/// All three commands assume that the template parameter is named `T`. When
/// possible, prefer to use these commands instead of writing out a @c \@tparam
/// line manually.
/// @name Class template instantiation macros
/// These macros either declare or define class template instantiations for
/// Drake's supported scalar types (see @ref default_scalars), either "default
/// scalars" or "default nonsymbolic scalars". Use the `DECLARE` macros only
/// in .h files; use the `DEFINE` macros only in .cc files.
///
/// @param SomeType the template typename to instantiate, *including* the
/// leading `class` or `struct` keyword, but *excluding* the template argument
/// for the scalar type.
///
/// Example `my_system.h`:
/// @code
/// #include "drake/common/default_scalars.h"
///
/// namespace sample {
/// template <typename T>
/// class MySystem final : public drake::systems::LeafSystem<T> {
/// ...
/// };
/// } // namespace sample
///
/// DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
/// class ::sample::MySystem)
/// @endcode
///
/// Example `my_system.cc`:
/// @code
/// #include "my_system.h"
///
/// DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
/// class ::sample::MySystem)
/// @endcode
///
/// See also @ref system_scalar_conversion.
/// @{
/// Defines template instantiations for Drake's default scalars.
/// This should only be used in .cc files, never in .h files.
#define DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( \
SomeType) \
template SomeType<double>; \
template SomeType<::drake::AutoDiffXd>; \
template SomeType<::drake::symbolic::Expression>;
/// Defines template instantiations for Drake's default nonsymbolic scalars.
/// This should only be used in .cc files, never in .h files.
#define \
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS( \
SomeType) \
template SomeType<double>; \
template SomeType<::drake::AutoDiffXd>;
/// Declares that template instantiations exist for Drake's default scalars.
/// This should only be used in .h files, never in .cc files.
#define DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( \
SomeType) \
extern template SomeType<double>; \
extern template SomeType<::drake::AutoDiffXd>; \
extern template SomeType<::drake::symbolic::Expression>;
/// Declares that template instantiations exist for Drake's default nonsymbolic
/// scalars. This should only be used in .h files, never in .cc files.
#define \
DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS( \
SomeType) \
extern template SomeType<double>; \
extern template SomeType<::drake::AutoDiffXd>;
/// @}
/// @name Function template instantiation macros
/// These macros define template function instantiations for Drake's supported
/// scalar types (see @ref default_scalars), either "default scalars" or
/// "default nonsymbolic scalars". Use the `DEFINE` macros only in .cc files.
///
/// @param FunctionPointersTuple a parenthesized, comma-separated list of
/// functions to instantiate (provided as function pointers), *including*
/// the template argument(s) for the scalar type. The template arguments `T`
/// and `U` will be provided by the macro; the function will be instantiated
/// for all combinations of `T` and `U` over the default scalars.
///
/// Example `example.h`:
/// @code
/// #include "drake/common/default_scalars.h"
///
/// namespace sample {
///
/// template <typename T>
/// double Func1(const T&);
///
/// template <typename T, typename U>
/// double Func2(const T&, const U&);
///
/// template <typename T>
/// class SomeClass {
/// ...
/// template <typename U>
/// SomeClass cast() const;
/// ...
/// };
///
/// } // namespace sample
/// @endcode
///
/// Example `example.cc`:
/// @code
/// #include "example.h"
///
/// namespace sample {
///
/// template <typename T>
/// double Func1(const T&) {
/// ...
/// }
///
/// template <typename T, typename U>
/// double Func2(const T&, const U&) {
/// ...
/// }
///
/// template <typename T>
/// template <typename U>
/// SomeClass<T>::SomeClass::cast() const {
/// ...
/// };
///
/// // N.B. Place the macro invocation inside the functions' namespace.
/// DRAKE_DEFINE_FUNCTION_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS((
/// &Func1<T>,
/// &Func2<T, U>,
/// &SomeClass<T>::template cast<U>
/// ))
///
/// } // namespace sample
/// @endcode
///
/// @note In the case of an overloaded function, the `&FunctionName<T>` syntax
/// is ambiguous. To resolve the ambiguity, you will need a
/// <a href=https://en.cppreference.com/w/cpp/language/static_cast#Notes>static_cast</a>.
// N.B. Below we use "Make_Function_Pointers" (etc.) as function names and
// static variable names, which violates our function name style guide by mixing
// inner capitalization with underscores. However, we've done this on purpose,
// to avoid conflicts with user-provided code in the same translation unit. We
// can't use a namespace because we need to allow for easy friendship in case a
// member function does not have public access.
/// Defines template instantiations for Drake's default scalars.
/// This should only be used in .cc files, never in .h files.
#define DRAKE_DEFINE_FUNCTION_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( \
FunctionPointersTuple) \
template<typename T, typename U> \
constexpr auto Make_Function_Pointers() { \
return std::make_tuple FunctionPointersTuple ; \
} \
template<typename T, typename... Us> \
constexpr auto Make_Function_Pointers_Pack2() { \
return std::tuple_cat(Make_Function_Pointers<T, Us>()...); \
} \
template<typename... Ts> \
constexpr auto Make_Function_Pointers_Pack1() { \
return std::tuple_cat(Make_Function_Pointers_Pack2<Ts, Ts...>()...); \
} \
static constexpr auto Function_Femplates __attribute__((used)) = \
Make_Function_Pointers_Pack1< \
double, \
::drake::AutoDiffXd, \
::drake::symbolic::Expression>();
/// Defines template instantiations for Drake's default nonsymbolic scalars.
/// This should only be used in .cc files, never in .h files.
#define \
DRAKE_DEFINE_FUNCTION_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS( \
FunctionPointersTuple) \
template<typename T, typename U> \
constexpr auto Make_Function_Pointers_Nonsym() { \
return std::make_tuple FunctionPointersTuple ; \
} \
template<typename T, typename... Us> \
constexpr auto Make_Function_Pointers_Nonsym_Pack2() { \
return std::tuple_cat(Make_Function_Pointers_Nonsym<T, Us>()...); \
} \
template<typename... Ts> \
constexpr auto Make_Function_Pointers_Nonsym_Pack1() { \
return std::tuple_cat(Make_Function_Pointers_Nonsym_Pack2<Ts, Ts...>()...); \
} \
static constexpr auto Function_Templates_Nonsym __attribute__((used)) = \
Make_Function_Pointers_Nonsym_Pack1< \
double, \
::drake::AutoDiffXd>();
/// @}
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/reset_after_move.h | #pragma once
#include <type_traits>
#include <utility>
namespace drake {
/// Type wrapper that performs value-initialization on the wrapped type, and
/// guarantees that when moving from this type that the donor object is reset
/// to its value-initialized value.
///
/// Background:
///
/// For performance reasons, we often like to provide overloaded move functions
/// on our types, instead of relying on the copy functions. When doing so, it
/// is more robust to rely on the compiler's `= default` implementation using
/// member-wise move, instead of writing out the operations manually. In
/// general, move functions should reset the donor object of the move to its
/// default-constructed (empty) resource state. Inductively, the member
/// fields' existing move implementations do this already, except in the case
/// of non-class (primitive) members, where the donor object's primitives will
/// not be zeroed. By wrapping primitive members fields with this type, they
/// are guaranteed to be zeroed on construction and after being moved from.
///
/// Example:
///
/// <pre>
/// class Foo {
/// public:
/// DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Foo)
/// Foo() = default;
///
/// private:
/// std::vector<int> items_;
/// reset_after_move<int> sum_;
/// };
/// </pre>
///
/// When moving from `Foo`, the donor object will reset to its default state:
/// `items_` will be empty and `sum_` will be zero. If `Foo` had not used the
/// `reset_after_move` wrapper, the `sum_` would remain intact (be copied)
/// while moving, even though `items_` was cleared.
///
/// @tparam T must support CopyConstructible, CopyAssignable, MoveConstructible,
/// and MoveAssignable and must not throw exceptions during construction or
/// assignment.
/// @see reset_on_copy
template <typename T>
class reset_after_move {
public:
/// Constructs a reset_after_move<T> with a value-initialized wrapped value.
/// See http://en.cppreference.com/w/cpp/language/value_initialization.
reset_after_move() noexcept(std::is_nothrow_default_constructible_v<T>) {}
/// Constructs a reset_after_move<T> with the given wrapped value. This is
/// an implicit conversion, so that reset_after_move<T> behaves more like
/// the unwrapped type.
// NOLINTNEXTLINE(runtime/explicit)
reset_after_move(const T& value) noexcept(
std::is_nothrow_copy_constructible_v<T>)
: value_(value) {}
/// @name Implements CopyConstructible, CopyAssignable, MoveConstructible,
/// MoveAssignable.
//@{
reset_after_move(const reset_after_move&) = default;
reset_after_move& operator=(const reset_after_move&) = default;
reset_after_move(reset_after_move&& other) noexcept(
std::is_nothrow_default_constructible_v<T>&&
std::is_nothrow_move_assignable_v<T>) {
value_ = std::move(other.value_);
other.value_ = T{};
}
reset_after_move& operator=(reset_after_move&& other) noexcept(
std::is_nothrow_default_constructible_v<T>&&
std::is_nothrow_move_assignable_v<T>) {
if (this != &other) {
value_ = std::move(other.value_);
other.value_ = T{};
}
return *this;
}
//@}
/// @name Implicit conversion operators to make reset_after_move<T> act
/// as the wrapped type.
//@{
operator T&() { return value_; }
operator const T&() const { return value_; }
//@}
/// @name Dereference operators if T is a pointer type.
/// If type T is a pointer, these exist and return the pointed-to object.
/// For non-pointer types these methods are not instantiated.
//@{
template <typename T1 = T>
std::enable_if_t<std::is_pointer_v<T1>, T> operator->() const {
return value_;
}
template <typename T1 = T>
std::enable_if_t<std::is_pointer_v<T1>,
std::add_lvalue_reference_t<std::remove_pointer_t<T>>>
operator*() const {
return *value_;
}
//@}
private:
T value_{};
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/string_unordered_map.h | #pragma once
#include <functional>
#include <string>
#include <unordered_map>
#include "drake/common/string_hash.h"
namespace drake {
/** Like `std::unordered_map<std::string, T>`, but with better defaults than the
plain `std::unordered_map<std::string, T>` spelling. We need the custom hash and
comparison functions so that `std::string_view` and `const char*` can be used as
lookup keys without copying them to a `std::string`. */
template <typename T>
using string_unordered_map =
std::unordered_map<std::string, T, internal::StringHash,
std::equal_to<void>>;
/** Like `std::unordered_multimap<std::string, T>`, but with better defaults
than the plain `std::unordered_multimap<std::string, T>` spelling. We need the
custom hash and comparison functions so that `std::string_view` and `const
char*` can be used as lookup keys without copying them to a `std::string`. */
template <typename T>
using string_unordered_multimap =
std::unordered_multimap<std::string, T, internal::StringHash,
std::equal_to<void>>;
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/never_destroyed.h | #pragma once
#include <new>
#include <type_traits>
#include <utility>
#include "drake/common/drake_copyable.h"
namespace drake {
/// Wraps an underlying type T such that its storage is a direct member field
/// of this object (i.e., without any indirection into the heap), but *unlike*
/// most member fields T's destructor is never invoked.
///
/// This is especially useful for function-local static variables that are not
/// trivially destructable. We shouldn't call their destructor at program exit
/// because of the "indeterminate order of ... destruction" as mentioned in
/// cppguide's
/// <a href="https://drake.mit.edu/styleguide/cppguide.html#Static_and_Global_Variables">Static
/// and Global Variables</a> section, but other solutions to this problem place
/// the objects on the heap through an indirection.
///
/// Compared with other approaches, this mechanism more clearly describes the
/// intent to readers, avoids "possible leak" warnings from memory-checking
/// tools, and is probably slightly faster.
///
/// Example uses:
///
/// The singleton pattern:
/// @code
/// class Singleton {
/// public:
/// DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Singleton)
/// static Singleton& getInstance() {
/// static never_destroyed<Singleton> instance;
/// return instance.access();
/// }
/// private:
/// friend never_destroyed<Singleton>;
/// Singleton() = default;
/// };
/// @endcode
///
/// A lookup table, created on demand the first time its needed, and then
/// reused thereafter:
/// @code
/// enum class Foo { kBar, kBaz };
/// Foo ParseFoo(const std::string& foo_string) {
/// using Dict = std::unordered_map<std::string, Foo>;
/// static const drake::never_destroyed<Dict> string_to_enum{
/// std::initializer_list<Dict::value_type>{
/// {"bar", Foo::kBar},
/// {"baz", Foo::kBaz},
/// }
/// };
/// return string_to_enum.access().at(foo_string);
/// }
/// @endcode
///
/// In cases where computing the static data is more complicated than an
/// initializer_list, you can use a temporary lambda to populate the value:
/// @code
/// const std::vector<double>& GetConstantMagicNumbers() {
/// static const drake::never_destroyed<std::vector<double>> result{[]() {
/// std::vector<double> prototype;
/// std::mt19937 random_generator;
/// for (int i = 0; i < 10; ++i) {
/// double new_value = random_generator();
/// prototype.push_back(new_value);
/// }
/// return prototype;
/// }()};
/// return result.access();
/// }
/// @endcode
///
/// Note in particular the `()` after the lambda. That causes it to be invoked.
//
// The above examples are repeated in the unit test; keep them in sync.
template <typename T>
class never_destroyed {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(never_destroyed)
/// Passes the constructor arguments along to T using perfect forwarding.
template <typename... Args>
explicit never_destroyed(Args&&... args) {
// Uses "placement new" to construct a `T` in `storage_`.
new (&storage_) T(std::forward<Args>(args)...);
}
/// Does nothing. Guaranteed!
~never_destroyed() = default;
/// Returns the underlying T reference.
T& access() { return *reinterpret_cast<T*>(&storage_); }
const T& access() const { return *reinterpret_cast<const T*>(&storage_); }
private:
typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_;
};
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/pointer_cast.h | #pragma once
#include <memory>
#include <stdexcept>
#include <fmt/format.h>
#include "drake/common/nice_type_name.h"
namespace drake {
/// Casts the object owned by the std::unique_ptr `other` from type `U` to `T`;
/// no runtime type checking is performed.
///
/// This method is analogous to the built-in std::static_pointer_cast that
/// operates on a std::shared_ptr.
///
/// Note that this function only supports default deleters.
template <class T, class U>
std::unique_ptr<T> static_pointer_cast(std::unique_ptr<U>&& other) noexcept {
return std::unique_ptr<T>(static_cast<T*>(other.release()));
}
/// Casts the object owned by the std::unique_ptr `other` from type `U` to `T`;
/// if the cast fails, returns nullptr. Casting is performed using
/// `dynamic_cast` on the managed value (i.e., the result of `other.get()`).
/// On success, `other`'s managed value is transferred to the result and
/// `other` is empty; on failure, `other` will retain its original managed
/// value and the result is empty. As with `dynamic_cast`, casting nullptr to
/// anything always succeeds, so a nullptr result could indicate either that
/// the argument was nullptr or that the cast failed.
///
/// This method is analogous to the built-in std::dynamic_pointer_cast that
/// operates on a std::shared_ptr.
///
/// Note that this function only supports default deleters.
template <class T, class U>
std::unique_ptr<T> dynamic_pointer_cast(std::unique_ptr<U>&& other) noexcept {
T* result = dynamic_cast<T*>(other.get());
if (!result) {
return nullptr;
}
other.release();
return std::unique_ptr<T>(result);
}
/// Casts the object owned by the std::unique_ptr `other` from type `U` to `T`;
/// if `other` is nullptr or the cast fails, throws a std::exception.
/// Casting is performed using `dynamic_cast` on the managed value (i.e., the
/// result of `other.get()`). On success, `other`'s managed value is
/// transferred to the result and `other` is empty; on failure, `other` will
/// retain its original managed value.
///
/// @throws std::exception if the cast fails.
///
/// Note that this function only supports default deleters.
template <class T, class U>
std::unique_ptr<T> dynamic_pointer_cast_or_throw(std::unique_ptr<U>&& other) {
if (!other) {
throw std::logic_error(fmt::format(
"Cannot cast a unique_ptr<{}> containing nullptr to unique_ptr<{}>.",
NiceTypeName::Get<U>(), NiceTypeName::Get<T>()));
}
T* result = dynamic_cast<T*>(other.get());
if (!result) {
throw std::logic_error(fmt::format(
"Cannot cast a unique_ptr<{}> containing an object of type {} to "
"unique_ptr<{}>.",
NiceTypeName::Get<U>(), NiceTypeName::Get(*other),
NiceTypeName::Get<T>()));
}
other.release();
return std::unique_ptr<T>(result);
}
/// Casts the pointer `other` from type `U` to `T` using `dynamic_cast`.
/// The result is never nullptr.
///
/// This differs from the C++ built-in dynamic_cast by providing a nicer
/// exception message, and always throwing on any failure.
///
/// @throws std::exception if `other` is nullptr or the cast fails.
template <class T, class U>
T* dynamic_pointer_cast_or_throw(U* other) {
if (!other) {
throw std::logic_error(fmt::format("Cannot cast a nullptr {}* to {}*.",
NiceTypeName::Get<U>(),
NiceTypeName::Get<T>()));
}
T* result = dynamic_cast<T*>(other);
if (!result) {
throw std::logic_error(fmt::format(
"Cannot cast a {}* pointing to an object of type {} to {}*.",
NiceTypeName::Get<U>(), NiceTypeName::Get(*other),
NiceTypeName::Get<T>()));
}
return result;
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/diagnostic_policy.h | #pragma once
#include <functional>
#include <optional>
#include <string>
#include "drake/common/drake_copyable.h"
namespace drake {
namespace internal {
/* Captures details about a warning or error condition.
Additional member fields might be added in future revisions. */
struct DiagnosticDetail {
std::optional<std::string> filename;
std::optional<int> line;
std::string message;
/* @return a formatted diagnostic message like one of:
file.txt:35: severity: some message
file.txt: severity: some message
severity: some message
depending on which fields are populated.
@pre severity must not be empty.
*/
std::string Format(const std::string& severity) const;
/* @return the result of Format("warning"). */
std::string FormatWarning() const;
/* @return the result of Format("error"). */
std::string FormatError() const;
};
/* A structured mechanism for functions that accept untrustworthy data to
report problems back to their caller.
By default, warnings will merely be logged into drake::log(), and errors will
throw exceptions. The user can customize this behavior via the Set methods.
Note in particular that the user's replacement error callback is not required
to throw. Code that calls policy.Error must be prepared to receive control
back from that method; typically, this means "return;" should follow its use.
*/
class DiagnosticPolicy {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(DiagnosticPolicy)
DiagnosticPolicy() = default;
/* Triggers a warning. */
void Warning(std::string message) const;
/* Triggers an error. */
void Error(std::string message) const;
/* (Advanced) Triggers a warning. */
void Warning(const DiagnosticDetail& detail) const;
/* (Advanced) Triggers an error. */
void Error(const DiagnosticDetail& detail) const;
/* (Advanced) Processes a warning using default behavior. */
static void WarningDefaultAction(const DiagnosticDetail& detail);
/* (Advanced) Processes an error using default behavior. */
[[noreturn]] static void ErrorDefaultAction(const DiagnosticDetail& detail);
/* Replaces the behavior for warnings with the supplied functor.
Setting to nullptr restores the default behavior (i.e., to log). */
void SetActionForWarnings(std::function<void(const DiagnosticDetail&)>);
/* Replaces the behavior for errors with the supplied functor.
Setting to nullptr restores the default behavior (i.e., to throw). */
void SetActionForErrors(std::function<void(const DiagnosticDetail&)>);
private:
std::function<void(const DiagnosticDetail&)> on_warning_;
std::function<void(const DiagnosticDetail&)> on_error_;
};
} // namespace internal
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/fmt.h | #pragma once
#include <string>
#include <string_view>
#include <fmt/format.h>
// This file contains the essentials of fmt support in Drake, mainly
// compatibility code to inter-operate with different versions of fmt.
namespace drake {
#if FMT_VERSION >= 80000 || defined(DRAKE_DOXYGEN_CXX)
/** When using fmt >= 8, this is an alias for
<a href="https://fmt.dev/latest/api.html#compile-time-format-string-checks">fmt::runtime</a>.
When using fmt < 8, this is a no-op. */
inline auto fmt_runtime(std::string_view s) {
return fmt::runtime(s);
}
/** When using fmt >= 8, this is defined to be `const` to indicate that the
`fmt::formatter<T>::format(...)` function should be object-const.
When using fmt < 8, the function signature was incorrect (lacking the const),
so this macro will be empty. */
#define DRAKE_FMT8_CONST const
#else // FMT_VERSION
inline auto fmt_runtime(std::string_view s) {
return s;
}
#define DRAKE_FMT8_CONST
#endif // FMT_VERSION
/** Returns `fmt::to_string(x)` but always with at least one digit after the
decimal point. Different versions of fmt disagree on whether to omit the
trailing ".0" when formatting integer-valued floating-point numbers. */
template <typename T>
std::string fmt_floating_point(T x) {
std::string result = fmt::format("{:#}", x);
if (result.back() == '.') {
result.push_back('0');
}
return result;
}
namespace internal::formatter_as {
/* The DRAKE_FORMATTER_AS macro specializes this for it's format_as types.
This struct is a functor that performs a conversion. See below for details.
@tparam T is the TYPE to be formatted. */
template <typename T>
struct Converter;
/* Provides convenient type shortcuts for the TYPE in DRAKE_FORMATTER_AS. */
template <typename T>
struct Traits {
/* The type being formatted. */
using InputType = T;
/* The format_as functor that provides the alternative object to format. */
using Functor = Converter<T>;
/* The type of the alternative object. */
using OutputType = decltype(Functor::call(std::declval<InputType>()));
/* The fmt::formatter<> for the alternative object. */
using OutputTypeFormatter = fmt::formatter<OutputType>;
};
/* Implements fmt::formatter<TYPE> for DRAKE_FORMATER_AS types. The macro
specializes this for it's format_as types. See below for details.
@tparam T is the TYPE to be formatted. */
template <typename T>
struct Formatter;
} // namespace internal::formatter_as
} // namespace drake
/** Adds a `fmt::formatter<NAMESPACE::TYPE>` template specialization that
formats the `TYPE` by delegating the formatting using a transformed expression,
as if a conversion function like this were interposed during formatting:
@code{cpp}
template <TEMPLATE_ARGS>
auto format_as(const NAMESPACE::TYPE& ARG) {
return EXPR;
}
@endcode
For example, this declaration ...
@code{cpp}
DRAKE_FORMATTER_AS(, my_namespace, MyType, x, x.to_string())
@endcode
... changes this code ...
@code{cpp}
MyType foo;
fmt::print(foo);
@endcode
... to be equivalent to ...
@code{cpp}
MyType foo;
fmt::print(foo.to_string());
@endcode
... allowing user to format `my_namespace::MyType` objects without manually
adding the `to_string` call every time.
This provides a convenient mechanism to add formatters for classes that already
have a `to_string` function, or classes that are just thin wrappers over simple
types (ints, enums, etc.).
Always use this macro in the global namespace, and do not use a semicolon (`;`)
afterward.
@param TEMPLATE_ARGS The optional first argument `TEMPLATE_ARGS` can be used in
case the `TYPE` is templated, e.g., it might commonly be set to `typename T`. It
should be left empty when the TYPE is not templated. In case `TYPE` has multiple
template arguments, note that macros will fight with commas so you should use
`typename... Ts` instead of writing them all out.
@param NAMESPACE The namespace that encloses the `TYPE` being formatted. Cannot
be empty. For nested namespaces, use intemediate colons, e.g., `%drake::common`.
Do not place _leading_ colons on the `NAMESPACE`.
@param TYPE The class name (or struct name, or enum name, etc.) being formatted.
Do not place _leading_ double-colons on the `TYPE`. If the type is templated,
use the template arguments here, e.g., `MyOptional<T>` if `TEMPLATE_ARGS` was
chosen as `typename T`.
@param ARG A placeholder variable name to use for the value (i.e., object)
being formatted within the `EXPR` expression.
@param EXPR An expression to `return` from the format_as function; it can
refer to the given `ARG` name which will be of type `const TYPE& ARG`.
@note In future versions of fmt (perhaps fmt >= 10) there might be an ADL
`format_as` customization point with this feature built-in. If so, then we can
update this macro to use that spelling, and eventually deprecate the macro once
Drake drops support for earlier version of fmt. */
#define DRAKE_FORMATTER_AS(TEMPLATE_ARGS, NAMESPACE, TYPE, ARG, EXPR) \
/* Specializes the Converter<> class template for our TYPE. */ \
namespace drake::internal::formatter_as { \
template <TEMPLATE_ARGS> \
struct Converter<NAMESPACE::TYPE> { \
using InputType = NAMESPACE::TYPE; \
static auto call(const InputType& ARG) { return EXPR; } \
}; \
\
/* Provides the fmt::formatter<TYPE> implementation. */ \
template <TEMPLATE_ARGS> \
struct Formatter<NAMESPACE::TYPE> \
: fmt::formatter<typename Traits<NAMESPACE::TYPE>::OutputType> { \
using MyTraits = Traits<NAMESPACE::TYPE>; \
/* Shadow our base class member function template of the same name. */ \
template <typename FormatContext> \
auto format(const typename MyTraits::InputType& x, \
FormatContext& ctx) DRAKE_FMT8_CONST { \
/* Call the base class member function after laundering the object */ \
/* through the user's provided format_as function. Older versions of */ \
/* fmt have const-correctness bugs, which we can fix with some good */ \
/* old fashioned const_cast-ing here. */ \
using Base = typename MyTraits::OutputTypeFormatter; \
const Base* const self = this; \
return const_cast<Base*>(self)->format(MyTraits::Functor::call(x), ctx); \
} \
}; \
} /* namespace drake::internal::formatter_as */ \
\
/* Specializes the fmt::formatter<> class template for TYPE. */ \
namespace fmt { \
template <TEMPLATE_ARGS> \
struct formatter<NAMESPACE::TYPE> \
: drake::internal::formatter_as::Formatter<NAMESPACE::TYPE> {}; \
} /* namespace fmt */
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/hash.cc | #include "drake/common/hash.h"
// For now, this is an empty .cc file that only serves to confirm
// hash.h is a stand-alone header.
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/parallelism.cc | #include "drake/common/parallelism.h"
#include <charconv>
#include <cstdlib>
#include <thread>
#include "drake/common/text_logging.h"
namespace drake {
namespace internal {
namespace {
constexpr char kEnvDrakeNumThreads[] = "DRAKE_NUM_THREADS";
constexpr char kEnvOmpNumThreads[] = "OMP_NUM_THREADS";
/* If `input` is a positive integer, returns it; otherwise, returns null.
Integers must be in base 10 (no hex, no octal). */
std::optional<int> ParsePositiveInt(std::string_view input) {
int parsed{};
const char* const first = input.data();
const char* const last = first + input.size();
const auto [ptr, error] = std::from_chars(first, last, parsed);
if (ptr == last && error == std::errc() && parsed >= 1) {
return parsed;
}
return std::nullopt;
}
} // namespace
// Parse the maximum number of threads as specified by the given environment
// variable values. In normal use, this function is only ever called once per
// process, with `drake_num_threads` set to `getenv("DRAKE_NUM_THREADS")` and
// `omp_num_threads` set to `getenv("OMP_NUM_THREADS")`. However, during unit
// testing, values NOT from the environment will be used instead.
int ConfigureMaxNumThreads(const char* const drake_num_threads,
const char* const omp_num_threads) {
const int hardware_concurrency = std::thread::hardware_concurrency();
if (drake_num_threads != nullptr) {
const std::optional<int> parsed = ParsePositiveInt(drake_num_threads);
if (!parsed) {
drake::log()->error(
"Failed to parse environment variable {}={}, falling back to "
"initializing max threads from hardware concurrency {}",
kEnvDrakeNumThreads, drake_num_threads, hardware_concurrency);
return hardware_concurrency;
} else if (*parsed > hardware_concurrency) {
drake::log()->warn(
"Environment variable {}={} is out of range [1, {}], falling back "
"to initializing max threads from hardware concurrency {}",
kEnvDrakeNumThreads, drake_num_threads, hardware_concurrency,
hardware_concurrency);
return hardware_concurrency;
} else {
drake::log()->debug(
"Initializing max threads to {} from environment variable {}",
*parsed, kEnvDrakeNumThreads);
return *parsed;
}
} else if (omp_num_threads != nullptr) {
const std::optional<int> parsed = ParsePositiveInt(omp_num_threads);
if (!parsed || parsed > hardware_concurrency) {
drake::log()->debug(
"Cannot use environment variable {}={}, falling back to "
"initializing max threads from hardware concurrency {}",
kEnvOmpNumThreads, omp_num_threads, hardware_concurrency);
return hardware_concurrency;
} else {
drake::log()->debug(
"Initializing max threads to {} from environment variable {}",
*parsed, kEnvOmpNumThreads);
return *parsed;
}
} else {
drake::log()->debug(
"Environment variables {} and {} not found, initializing max threads "
"from hardware concurrency {}",
kEnvDrakeNumThreads, kEnvOmpNumThreads, hardware_concurrency);
return hardware_concurrency;
}
}
} // namespace internal
Parallelism Parallelism::Max() {
static const int latched_max = internal::ConfigureMaxNumThreads(
std::getenv(internal::kEnvDrakeNumThreads),
std::getenv(internal::kEnvOmpNumThreads));
return Parallelism(latched_max);
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/find_runfiles.cc | #include "drake/common/find_runfiles.h"
#include <cstdlib>
#include <memory>
#include <stdexcept>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include <filesystem>
#include "tools/cpp/runfiles/runfiles.h"
#include <fmt/format.h>
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
using bazel::tools::cpp::runfiles::Runfiles;
namespace drake {
namespace {
namespace fs = std::filesystem;
// Replace `nullptr` with `"nullptr",` or else just return `arg` unchanged.
const char* nullable_to_string(const char* arg) {
return arg ? arg : "nullptr";
}
// Either a bazel_tools Runfiles object xor an error string.
struct RunfilesSingleton {
std::unique_ptr<Runfiles> runfiles;
std::string runfiles_dir;
std::string error;
};
// Create a bazel_tools Runfiles object xor an error string. This is memoized
// by GetSingletonRunfiles (i.e., this is only called once per process).
RunfilesSingleton Create() {
const char* mechanism{};
RunfilesSingleton result;
std::string bazel_error;
// Chose a mechanism based on environment variables.
if (std::getenv("TEST_SRCDIR")) {
// When running under bazel test, use the test heuristics.
mechanism = "TEST_SRCDIR";
result.runfiles.reset(Runfiles::CreateForTest(&bazel_error));
} else if ((std::getenv("RUNFILES_MANIFEST_FILE") != nullptr) ||
(std::getenv("RUNFILES_DIR") != nullptr)) {
// When running with some RUNFILES_* env already set, just use that.
mechanism = "RUNFILES_{MANIFEST_FILE,DIR}";
result.runfiles.reset(Runfiles::Create({}, &bazel_error));
} else {
// When running from the user's command line, use argv0.
mechanism = "argv0";
#ifdef __APPLE__
std::string argv0;
argv0.resize(4096);
uint32_t buf_size = argv0.size();
int error = _NSGetExecutablePath(&argv0.front(), &buf_size);
if (error) {
throw std::runtime_error("Error from _NSGetExecutablePath");
}
argv0 = argv0.c_str(); // Remove trailing nil bytes.
drake::log()->debug("_NSGetExecutablePath = {}", argv0);
#else
const std::string& argv0 = fs::read_symlink({"/proc/self/exe"}).string();
drake::log()->debug("readlink(/proc/self/exe) = {}", argv0);
#endif
result.runfiles.reset(Runfiles::Create(argv0, &bazel_error));
}
drake::log()->debug("FindRunfile mechanism = {}", mechanism);
drake::log()->debug("cwd = \"{}\"", fs::current_path().string());
// If there were runfiles, identify the RUNFILES_DIR.
if (result.runfiles) {
for (const auto& key_value : result.runfiles->EnvVars()) {
if (key_value.first == "RUNFILES_DIR") {
// N.B. We must normalize the path; otherwise the path may include
// `parent/./path` if the binary was run using `./bazel-bin/target` vs
// `bazel-bin/target`.
// TODO(eric.cousineau): Show this in Drake itself. This behavior was
// encountered in Anzu issue 5653, in a Python binary.
fs::path path = key_value.second;
path = fs::absolute(path);
path = path.lexically_normal();
result.runfiles_dir = path.string();
break;
}
}
// If we didn't find it, something was very wrong.
if (result.runfiles_dir.empty()) {
bazel_error = "RUNFILES_DIR was not provided by the Runfiles object";
result.runfiles.reset();
} else if (!fs::is_directory({result.runfiles_dir})) {
bazel_error =
fmt::format("RUNFILES_DIR '{}' does not exist", result.runfiles_dir);
result.runfiles.reset();
}
}
// Report any error.
if (!result.runfiles) {
result.runfiles_dir.clear();
result.error = fmt::format(
"{} (created using {} with TEST_SRCDIR={} and "
"RUNFILES_MANIFEST_FILE={} and RUNFILES_DIR={})",
bazel_error, mechanism, nullable_to_string(std::getenv("TEST_SRCDIR")),
nullable_to_string(std::getenv("RUNFILES_MANIFEST_FILE")),
nullable_to_string(std::getenv("RUNFILES_DIR")));
drake::log()->debug("FindRunfile error: {}", result.error);
}
// Sanity check our return value.
if (result.runfiles.get() == nullptr) {
DRAKE_DEMAND(result.runfiles_dir.empty());
DRAKE_DEMAND(result.error.length() > 0);
} else {
DRAKE_DEMAND(result.runfiles_dir.length() > 0);
DRAKE_DEMAND(result.error.empty());
}
return result;
}
// Returns the RunfilesSingleton for the current process, latch-initializing it
// first if necessary.
const RunfilesSingleton& GetRunfilesSingleton() {
static const never_destroyed<RunfilesSingleton> result{Create()};
return result.access();
}
} // namespace
bool HasRunfiles() {
return GetRunfilesSingleton().runfiles.get() != nullptr;
}
RlocationOrError FindRunfile(const std::string& resource_path) {
const auto& singleton = GetRunfilesSingleton();
// Check for HasRunfiles.
RlocationOrError result;
if (!singleton.runfiles) {
DRAKE_DEMAND(!singleton.error.empty());
result.error = singleton.error;
return result;
}
// Check the user input.
if (resource_path.empty()) {
result.error = "Resource path must not be empty";
return result;
}
if (resource_path[0] == '/') {
result.error = fmt::format(
"Resource path '{}' must not be an absolute path", resource_path);
return result;
}
// Locate the file on the manifest and in the directory.
const std::string by_man = singleton.runfiles->Rlocation(resource_path);
const std::string by_dir = singleton.runfiles_dir + "/" + resource_path;
const bool by_man_ok = fs::is_regular_file({by_man});
const bool by_dir_ok = fs::is_regular_file({by_dir});
drake::log()->debug(
"FindRunfile found by-manifest '{}' ({}) and by-directory '{}' ({})",
by_man, by_man_ok ? "good" : "bad", by_dir, by_dir_ok ? "good" : "bad");
if (by_man_ok && by_dir_ok) {
// We must always return the directory-based result (not the manifest
// result) because the result itself may be a file that contains embedded
// relative pathnames. The manifest result might actually be in the source
// tree, not the runfiles directory, and in that case relative paths may
// not work (e.g., when the relative path refers to a genfile).
result.abspath = by_dir;
return result;
}
// Report an error.
const char* detail{};
if (!by_man_ok && !by_dir_ok) {
detail =
"but the file does not exist at that location "
"nor is it on the manifest";
} else if (!by_man_ok && by_dir_ok) {
detail =
"and the file exists at that location "
"but it is not on the manifest";
} else {
DRAKE_DEMAND(by_man_ok && !by_dir_ok);
detail =
"and it is on the manifest"
"but the file does not exist at that location";
}
result.error = fmt::format(
"Sought '{}' in runfiles directory '{}' {}; "
"perhaps a 'data = []' dependency is missing.",
resource_path, singleton.runfiles_dir, detail);
return result;
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/double_overloads.cc | #include "drake/common/double_overloads.h"
// For now, this is an empty .cc file that only serves to confirm that
// double_overloads.h is a stand-alone header.
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/autodiff_overloads.h | /// @file
/// Overloads for STL mathematical operations on AutoDiffScalar.
///
/// Used via argument-dependent lookup (ADL). These functions appear
/// in the Eigen namespace so that ADL can automatically choose between
/// the STL version and the overloaded version to match the type of the
/// arguments. The proper use would be e.g.
///
/// \code{.cc}
/// void mymethod() {
/// using std::isinf;
/// isinf(myval);
/// }
/// \endcode{}
///
/// @note The if_then_else and cond functions for AutoDiffScalar are in
/// namespace drake because cond is defined in namespace drake in
/// "drake/common/cond.h" file.
#pragma once
#ifndef DRAKE_COMMON_AUTODIFF_HEADER
// TODO(soonho-tri): Change to #error.
#warning Do not directly include this file. Include "drake/common/autodiff.h".
#endif
#include <cmath>
#include <limits>
#include "drake/common/cond.h"
#include "drake/common/drake_assert.h"
#include "drake/common/dummy_value.h"
namespace Eigen {
/// Overloads nexttoward to mimic std::nexttoward from <cmath>.
template <typename DerType>
double nexttoward(const Eigen::AutoDiffScalar<DerType>& from, long double to) {
using std::nexttoward;
return nexttoward(from.value(), to);
}
/// Overloads round to mimic std::round from <cmath>.
template <typename DerType>
double round(const Eigen::AutoDiffScalar<DerType>& x) {
using std::round;
return round(x.value());
}
/// Overloads isinf to mimic std::isinf from <cmath>.
template <typename DerType>
bool isinf(const Eigen::AutoDiffScalar<DerType>& x) {
using std::isinf;
return isinf(x.value());
}
/// Overloads isfinite to mimic std::isfinite from <cmath>.
template <typename DerType>
bool isfinite(const Eigen::AutoDiffScalar<DerType>& x) {
using std::isfinite;
return isfinite(x.value());
}
/// Overloads isnan to mimic std::isnan from <cmath>.
template <typename DerType>
bool isnan(const Eigen::AutoDiffScalar<DerType>& x) {
using std::isnan;
return isnan(x.value());
}
/// Overloads floor to mimic std::floor from <cmath>.
template <typename DerType>
double floor(const Eigen::AutoDiffScalar<DerType>& x) {
using std::floor;
return floor(x.value());
}
/// Overloads ceil to mimic std::ceil from <cmath>.
template <typename DerType>
double ceil(const Eigen::AutoDiffScalar<DerType>& x) {
using std::ceil;
return ceil(x.value());
}
/// Overloads copysign from <cmath>.
template <typename DerType, typename T>
Eigen::AutoDiffScalar<DerType> copysign(const Eigen::AutoDiffScalar<DerType>& x,
const T& y) {
using std::isnan;
if (isnan(x)) return (y >= 0) ? NAN : -NAN;
if ((x < 0 && y >= 0) || (x >= 0 && y < 0))
return -x;
else
return x;
}
/// Overloads copysign from <cmath>.
template <typename DerType>
double copysign(double x, const Eigen::AutoDiffScalar<DerType>& y) {
using std::isnan;
if (isnan(x)) return (y >= 0) ? NAN : -NAN;
if ((x < 0 && y >= 0) || (x >= 0 && y < 0))
return -x;
else
return x;
}
/// Overloads pow for an AutoDiffScalar base and exponent, implementing the
/// chain rule.
template <typename DerTypeA, typename DerTypeB>
Eigen::AutoDiffScalar<
typename internal::remove_all<DerTypeA>::type::PlainObject>
pow(const Eigen::AutoDiffScalar<DerTypeA>& base,
const Eigen::AutoDiffScalar<DerTypeB>& exponent) {
// The two AutoDiffScalars being exponentiated must have the same matrix
// type. This includes, but is not limited to, the same scalar type and
// the same dimension.
static_assert(std::is_same_v<
typename internal::remove_all<DerTypeA>::type::PlainObject,
typename internal::remove_all<DerTypeB>::type::PlainObject>,
"The derivative types must match.");
internal::make_coherent(base.derivatives(), exponent.derivatives());
const auto& x = base.value();
const auto& xgrad = base.derivatives();
const auto& y = exponent.value();
const auto& ygrad = exponent.derivatives();
using std::log;
using std::pow;
const auto x_to_the_y = pow(x, y);
if (ygrad.isZero(std::numeric_limits<double>::epsilon()) ||
ygrad.size() == 0) {
// The derivative only depends on ∂(x^y)/∂x -- this prevents undefined
// behavior in the corner case where ∂(x^y)/∂y is infinite when x = 0,
// despite ∂y/∂v being 0.
return Eigen::MakeAutoDiffScalar(x_to_the_y, y * pow(x, y - 1) * xgrad);
}
return Eigen::MakeAutoDiffScalar(
// The value is x ^ y.
x_to_the_y,
// The multivariable chain rule states:
// df/dv_i = (∂f/∂x * dx/dv_i) + (∂f/∂y * dy/dv_i)
// ∂f/∂x is y*x^(y-1)
y * pow(x, y - 1) * xgrad +
// ∂f/∂y is (x^y)*ln(x)
x_to_the_y * log(x) * ygrad);
}
} // namespace Eigen
namespace drake {
/// Returns the autodiff scalar's value() as a double. Never throws.
/// Overloads ExtractDoubleOrThrow from common/extract_double.h.
/// @see math::ExtractValue(), math::DiscardGradient()
template <typename DerType>
double ExtractDoubleOrThrow(const Eigen::AutoDiffScalar<DerType>& scalar) {
return static_cast<double>(scalar.value());
}
/// 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.
/// @see math::ExtractValue(), math::DiscardGradient()
template <typename DerType, int RowsAtCompileTime, int ColsAtCompileTime,
int Options, int MaxRowsAtCompileTime, int MaxColsAtCompileTime>
auto ExtractDoubleOrThrow(
const Eigen::MatrixBase<Eigen::Matrix<
Eigen::AutoDiffScalar<DerType>, RowsAtCompileTime, ColsAtCompileTime,
Options, MaxRowsAtCompileTime, MaxColsAtCompileTime>>& matrix) {
return matrix
.unaryExpr([](const typename Eigen::AutoDiffScalar<DerType>& value) {
return ExtractDoubleOrThrow(value);
})
.eval();
}
/// Specializes common/dummy_value.h.
template <typename DerType>
struct dummy_value<Eigen::AutoDiffScalar<DerType>> {
static constexpr Eigen::AutoDiffScalar<DerType> get() {
constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
DerType derivatives;
derivatives.fill(kNaN);
return Eigen::AutoDiffScalar<DerType>(kNaN, derivatives);
}
};
/// Provides if-then-else expression for Eigen::AutoDiffScalar type. To support
/// Eigen's generic expressions, we use casting to the plain object after
/// applying Eigen::internal::remove_all. It is based on the Eigen's
/// implementation of min/max function for AutoDiffScalar type
/// (https://bitbucket.org/eigen/eigen/src/10a1de58614569c9250df88bdfc6402024687bc6/unsupported/Eigen/src/AutoDiff/AutoDiffScalar.h?at=default&fileviewer=file-view-default#AutoDiffScalar.h-546).
template <typename DerType1, typename DerType2>
Eigen::AutoDiffScalar<
typename Eigen::internal::remove_all<DerType1>::type::PlainObject>
if_then_else(bool f_cond, const Eigen::AutoDiffScalar<DerType1>& x,
const Eigen::AutoDiffScalar<DerType2>& y) {
typedef Eigen::AutoDiffScalar<
typename Eigen::internal::remove_all<DerType1>::type::PlainObject>
ADS1;
typedef Eigen::AutoDiffScalar<
typename Eigen::internal::remove_all<DerType2>::type::PlainObject>
ADS2;
static_assert(std::is_same_v<ADS1, ADS2>, "The derivative types must match.");
return f_cond ? ADS1(x) : ADS2(y);
}
/// Provides special case of cond expression for Eigen::AutoDiffScalar type.
template <typename DerType, typename... Rest>
Eigen::AutoDiffScalar<
typename Eigen::internal::remove_all<DerType>::type::PlainObject>
cond(bool f_cond, const Eigen::AutoDiffScalar<DerType>& e_then, Rest... rest) {
return if_then_else(f_cond, e_then, cond(rest...));
}
} // namespace drake
| 0 |
/home/johnshepherd/drake | /home/johnshepherd/drake/common/is_cloneable.h | #pragma once
#include <memory>
#include <type_traits>
namespace drake {
/** @cond */
namespace is_cloneable_internal {
// Default case; assumes that a class is *not* cloneable.
template <typename T, class>
struct is_cloneable_helper : std::false_type {};
// Special sauce for SFINAE. Only compiles if it can finds the method
// `unique_ptr<T> T::Clone() const`. If this exists, the is_cloneable implicitly
// prefers this overload over the default overload.
template <typename T>
struct is_cloneable_helper<
T, typename std::enable_if_t<
std::is_same_v<decltype(std::declval<const T>().Clone().release()),
typename std::remove_const_t<T>*>>> : std::true_type {
};
} // namespace is_cloneable_internal
/** @endcond */
/**
@anchor is_cloneable_doc
Provides method for determining at run time if a class is "cloneable".
__Usage__
This gets used like `type_traits` functions (e.g., `is_copy_constructible`,
`is_same`, etc.) To determine if a class is cloneable simply invoke:
@code
bool value = drake::is_cloneable<Foo>::value;
@endcode
If `Foo` is cloneable, it will evaluate to true. It can also be used in
compile-time tests (e.g., SFINAE and `static_assert`s):
@code
static_assert(is_cloneable<Foo>::value, "This method requires its classes to "
"be cloneable.");
@endcode
__Definition of "cloneability"__
To be cloneable, the class `Foo` must have a _public_ method of the form:
@code
unique_ptr<Foo> Foo::Clone() const;
@endcode
Note that "friend" access for the %is_cloneable-using class is not sufficient.
The `Foo::Clone()` method must actually be public.
<!-- Developer note: if you change or extend the definition of an acceptable
clone method here, be sure to consider whether
copyable_unique_ptr::can_clone() should be changed as well. -->
The pointer contained in the returned `unique_ptr` must point to a
heap-allocated deep copy of the _concrete_ object. This test can confirm the
proper signature, but cannot confirm the heap-allocated deep copy. A Clone()
method that doesn't return such a copy of the _concrete_ object should be
considered a malformed function.
@warning It is important to note, that a `Clone()` method that returns a
`unique_ptr` to a _super_ class is _not_ sufficient to be cloneable. In other
words the presence of:
@code
unique_ptr<Base> Derived::Clone() const;
@endcode
will not make the `Derived` class cloneable.
@tparam T The class to test for cloneability.
*/
template <typename T>
using is_cloneable = is_cloneable_internal::is_cloneable_helper<T, void>;
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/ad/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 = "ad",
visibility = ["//visibility:private"],
deps = [
":auto_diff",
],
)
drake_cc_library(
name = "auto_diff",
srcs = [
"internal/partials.cc",
"internal/standard_operations.cc",
],
hdrs = [
"auto_diff.h",
"internal/eigen_specializations.h",
"internal/partials.h",
"internal/standard_operations.h",
],
deps = [
"//common:essential",
],
)
drake_cc_googletest(
name = "auto_diff_basic_test",
deps = [
":auto_diff",
],
)
drake_cc_googletest(
name = "matrix_test",
deps = [
":auto_diff",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "partials_test",
deps = [
":auto_diff",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_throws_message",
],
)
drake_cc_library(
name = "standard_operations_test_h",
testonly = True,
hdrs = ["test/standard_operations_test.h"],
visibility = [
# TODO(jwnimmer-tri) Once drake/common/autodiffxd.h is finally deleted,
# we can also delete its unit test and thus withdraw this visibility.
"//common:__pkg__",
],
deps = [
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "standard_operations_test",
# The test is split into multiple source files to improve compilation time.
srcs = [
"test/standard_operations_abs2_test.cc",
"test/standard_operations_abs_test.cc",
"test/standard_operations_acos_test.cc",
"test/standard_operations_add_test.cc",
"test/standard_operations_asin_test.cc",
"test/standard_operations_atan2_test.cc",
"test/standard_operations_atan_test.cc",
"test/standard_operations_cmp_test.cc",
"test/standard_operations_cos_test.cc",
"test/standard_operations_cosh_test.cc",
"test/standard_operations_dec_test.cc",
"test/standard_operations_div_test.cc",
"test/standard_operations_exp_test.cc",
"test/standard_operations_inc_test.cc",
"test/standard_operations_integer_test.cc",
"test/standard_operations_log_test.cc",
"test/standard_operations_max_test.cc",
"test/standard_operations_min_test.cc",
"test/standard_operations_mul_test.cc",
"test/standard_operations_pow_special_test.cc",
"test/standard_operations_pow_test.cc",
"test/standard_operations_sin_test.cc",
"test/standard_operations_sinh_test.cc",
"test/standard_operations_sqrt_test.cc",
"test/standard_operations_stream_test.cc",
"test/standard_operations_sub_test.cc",
"test/standard_operations_tan_test.cc",
"test/standard_operations_tanh_test.cc",
],
copts = [
# The test fixture at requires some configuration for the specific
# autodiff class to be tested.
"-DDRAKE_AUTODIFFXD_DUT=drake::ad::AutoDiff",
],
shard_count = 16,
deps = [
":auto_diff",
":standard_operations_test_h",
],
)
add_lint_tests()
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/ad/README.md |
Drake's AutoDiff implementation
-------------------------------
This directory is a work-in-progress for Drake's forthcoming replacement of
`Eigen::AutoDiffScalar<Eigen::VectorXd>`.
The `namespace ad { ... }` is chosen for it's compact size in debugging traces,
but is not otherwise exposed to users.
Users should continue to `#include <drake/common/autodiff.h>` and refer to
`drake::AutoDiffXd` in their code.
Once we are confident with our replacement implementation, we will switch that
alias to refer to this new code instead of Eigen's AutoDiffScalar.
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/ad/auto_diff.h | #pragma once
#include "drake/common/ad/internal/partials.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/fmt.h"
namespace drake {
namespace ad {
/** A scalar type that performs automatic differentiation, similar to
`Eigen::AutoDiffScalar<Eigen::VectorXd>`. Unlike `Eigen::AutoDiffScalar`,
Drake's AutoDiff is not templated; it only supports dynamically-sized
derivatives using floating-point doubles.
At the moment, the features of this class are similar to Eigen::AutoDiffScalar,
but in the future Drake will further customize this class to optimize its
runtime performance and better integrate it with our optimization tools. */
class AutoDiff {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(AutoDiff);
/** Compatibility alias to mimic Eigen::AutoDiffScalar. */
using DerType = Eigen::VectorXd;
/** Compatibility alias to mimic Eigen::AutoDiffScalar. */
using Scalar = double;
/** Constructs zero. */
AutoDiff() = default;
/** Constructs a value with empty derivatives. */
// NOLINTNEXTLINE(runtime/explicit): This conversion is desirable.
AutoDiff(double value) : value_{value} {}
/** Constructs a value with a single partial derivative of 1.0 at the given
`offset` in a vector of `size` otherwise-zero derivatives. */
AutoDiff(double value, Eigen::Index size, Eigen::Index offset)
: value_{value}, partials_{size, offset} {}
/** Constructs a value with the given derivatives. */
AutoDiff(double value, const Eigen::Ref<const Eigen::VectorXd>& derivatives)
: value_{value}, partials_{derivatives} {}
/** Assigns a value and clears the derivatives. */
AutoDiff& operator=(double value) {
value_ = value;
partials_.SetZero();
return *this;
}
~AutoDiff() = default;
/** Returns the value part of this %AutoDiff (readonly). */
double value() const { return value_; }
/** (Advanced) Returns the value part of this %AutoDiff (mutable).
Operations on this value will NOT alter the derivatives. */
double& value() { return value_; }
/** Returns a view of the derivatives part of this %AutoDiff (readonly).
Do not presume any specific C++ type for the the return value. It will act
like an Eigen column-vector expression (e.g., Eigen::Block<const VectorXd>),
but we reserve the right to change the return type for efficiency down the
road. */
const Eigen::VectorXd& derivatives() const {
return partials_.make_const_xpr();
}
/** (Advanced) Returns a mutable view of the derivatives part of this
%AutoDiff.
Instead of mutating the derivatives after construction, it's generally
preferable to set them directly in the constructor if possible.
Do not presume any specific C++ type for the the return value. It will act
like a mutable Eigen column-vector expression (e.g., Eigen::Block<VectorXd>)
that also allows for assignment and resizing, but we reserve the right to
change the return type for efficiency down the road. */
Eigen::VectorXd& derivatives() { return partials_.get_raw_storage_mutable(); }
/// @name Internal use only
//@{
/** (Internal use only)
Users should call derivatives() instead. */
const internal::Partials& partials() const { return partials_; }
/** (Internal use only)
Users should call derivatives() instead. */
internal::Partials& partials() { return partials_; }
//@}
private:
double value_{0.0};
internal::Partials partials_;
};
} // namespace ad
} // namespace drake
// These further refine our AutoDiff type and must appear in exactly this order.
// clang-format off
#include "drake/common/ad/internal/standard_operations.h"
#include "drake/common/ad/internal/eigen_specializations.h"
// clang-format on
/* Formats the `value()` part of x to the stream.
To format the derivatives use `drake::fmt_eigen(x.derivatives())`. */
DRAKE_FORMATTER_AS(, drake::ad, AutoDiff, x, x.value())
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/internal/standard_operations.cc | // Our header file doesn't stand on its own; it should only ever be included
// indirectly via auto_diff.h
/* clang-format off to disable clang-format-includes */
// NOLINTNEXTLINE(build/include)
#include "drake/common/ad/auto_diff.h"
/* clang-format on */
#include <ostream>
#include <fmt/format.h>
namespace drake {
namespace ad {
AutoDiff sin(AutoDiff x) {
const double new_value = std::sin(x.value());
// ∂/∂x sin(x) = cos(x)
// The domain of sin & cos are identical; no need for special cases here.
x.partials().Mul(std::cos(x.value()));
x.value() = new_value;
return x;
}
AutoDiff cos(AutoDiff x) {
const double new_value = std::cos(x.value());
// ∂/∂x cos(x) = -sin(x)
// The domain of cos & sin are identical; no need for special cases here.
x.partials().Mul(-std::sin(x.value()));
x.value() = new_value;
return x;
}
AutoDiff tan(AutoDiff x) {
const double new_value = std::tan(x.value());
// ∂/∂x tan(x) = sec²(x) = cos⁻²(x)
// The mathematical tan() function has poles at (½ + n)π; however no common
// floating-point representation is able to represent π/2 exactly, so there is
// no argument value for which a pole error occurs, and so the domain of
// std::tan & std::cos are identical (only non-finite values are disallowed).
const double cos_x = std::cos(x.value());
x.partials().Div(cos_x * cos_x);
x.value() = new_value;
return x;
}
AutoDiff asin(AutoDiff x) {
const double new_value = std::asin(x.value());
// ∂/∂x asin(x) = 1 / sqrt(1 - x²)
// The domain of asin is [-1, 1], which is the same as sqrt(1-x²); no need
// for special cases here.
const double x2 = x.value() * x.value();
x.partials().Div(std::sqrt(1 - x2));
x.value() = new_value;
return x;
}
AutoDiff acos(AutoDiff x) {
const double new_value = std::acos(x.value());
// ∂/∂x acos(x) = -1 / sqrt(1 - x²)
// The domain of acos is [-1, 1], which is the same as sqrt(1-x²); no need
// for special cases here.
const double x2 = x.value() * x.value();
x.partials().Div(-std::sqrt(1 - x2));
x.value() = new_value;
return x;
}
AutoDiff atan(AutoDiff x) {
const double new_value = std::atan(x.value());
// ∂/∂x atan(x) = 1 / (1 + x²)
// The domain of atan includes everything except NaN, which will propagate
// automatically via 1 + x²; no need for special cases here.
const double x2 = x.value() * x.value();
x.partials().Div(1 + x2);
x.value() = new_value;
return x;
}
AutoDiff atan2(AutoDiff a, const AutoDiff& b) {
const double new_value = std::atan2(a.value(), b.value());
// ∂/∂x atan2(a, b) = (ba' - ab')/(a² + b²)
// The domain of atan2 includes everything except NaN, which will propagate
// automatically via `norm`.
// TODO(jwnimmer-tri) Handle the IEEE special cases for ±∞ and ±0 as input(s).
// Figure out the proper gradients in that case.
const double norm = a.value() * a.value() + b.value() * b.value();
a.partials().Mul(b.value());
a.partials().AddScaled(-a.value(), b.partials());
a.partials().Div(norm);
a.value() = new_value;
return a;
}
AutoDiff atan2(AutoDiff a, double b) {
const double new_value = std::atan2(a.value(), b);
// ∂/∂x atan2(a, b) = (ba' - ab')/(a² + b²) = ba'/(a² + b²)
// The domain of atan2 includes everything except NaN, which will propagate
// automatically via `norm`.
// TODO(jwnimmer-tri) Handle the IEEE special cases for ±∞ and ±0 as input(s).
// Figure out the proper gradients in that case.
const double norm = a.value() * a.value() + b * b;
a.partials().Mul(b / norm);
a.value() = new_value;
return a;
}
AutoDiff atan2(double a, AutoDiff b) {
const double new_value = std::atan2(a, b.value());
// ∂/∂x atan2(a, b) = (ba' - ab')/(a² + b²) = -ab'/(a² + b²)
// The domain of atan2 includes everything except NaN, which will propagate
// automatically via `norm`.
// TODO(jwnimmer-tri) Handle the IEEE special cases for ±∞ and ±0 as input(s).
// Figure out the proper gradients in that case.
const double norm = a * a + b.value() * b.value();
b.partials().Mul(-a / norm);
b.value() = new_value;
return b;
}
AutoDiff sinh(AutoDiff x) {
const double new_value = std::sinh(x.value());
// ∂/∂x sinh(x) = cosh(x)
// The domain of sinh & cosh are identical; no need for special cases here.
x.partials().Mul(std::cosh(x.value()));
x.value() = new_value;
return x;
}
AutoDiff cosh(AutoDiff x) {
const double new_value = std::cosh(x.value());
// ∂/∂x cosh(x) = sinh(x)
// The domain of cosh & sinh are identical; no need for special cases here.
x.partials().Mul(std::sinh(x.value()));
x.value() = new_value;
return x;
}
AutoDiff tanh(AutoDiff x) {
const double new_value = std::tanh(x.value());
// ∂/∂x tanh(x) = 1 - tanh²(x)
x.partials().Mul(1 - (new_value * new_value));
x.value() = new_value;
return x;
}
AutoDiff exp(AutoDiff x) {
// ∂/∂x eˣ = eˣ
const double new_value = std::exp(x.value());
x.partials().Mul(new_value);
x.value() = new_value;
return x;
}
AutoDiff log(AutoDiff x) {
const double new_value = std::log(x.value());
// ∂/∂x ln(x) = x⁻¹
x.partials().Div(x.value());
x.value() = new_value;
return x;
}
namespace {
constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
// Iterates over the partials of `input`. For any non-zero elements, sets the
// corresponding partial in `output` to NaN.
// @pre output->MatchSizeOf(input) has already been performed.
void UndefineOutputGradWhereInputGradNonzero(const AutoDiff& input,
AutoDiff* output) {
DRAKE_DEMAND(output != nullptr);
// If either input or output are empty, there's nothing to do.
if (output->partials().size() == 0) {
// MatchSizeOf guarantees this.
DRAKE_ASSERT(input.partials().size() == 0);
return;
}
if (input.partials().size() == 0) {
return;
}
// In case input and output are the same object, we need to call the
// non-const member function first.
auto& output_grad = output->partials().get_raw_storage_mutable();
const auto& input_grad = input.partials().make_const_xpr();
// Update the `output` per our API contract.
const int size = output_grad.size();
DRAKE_ASSERT(size == input_grad.size());
for (int i = 0; i < size; ++i) {
if (!(input_grad[i] == 0.0)) {
output_grad[i] = kNaN;
}
}
}
} // namespace
AutoDiff pow(AutoDiff base_ad, const AutoDiff& exp_ad) {
// It's convenient to immediately set up the result, so we'll need to take a
// picture of `base_ad.value()` first. Might as well do `exp` for convenience.
const double base = base_ad.value();
const double exp = exp_ad.value();
// Result starts out holding the proper return value, but its partials are
// just grad(base) to start. We'll adjust them at the end; for now, just
// set them to the correct size.
AutoDiff result = std::move(base_ad);
result.value() = std::pow(base, exp);
result.partials().MatchSizeOf(exp_ad.partials());
// If any of {base, exp, result} are NaN, then grad(result) is always NaN.
if (std::isnan(result.value()) || std::isnan(base) || std::isnan(exp)) {
result.partials().Mul(kNaN);
return result;
}
// When dealing with infinities (or a zero base where a sign-change to the
// exponent introduces infinities), trying to compute well-defined gradients
// with appropriate symmetries is impractical. In that case, when grad(base)
// and grad(exp) are both zero we'll leave grad(result) as zero, but otherwise
// any non-zero input gradient becomes ill-defined in the result.
if (base == 0 || !std::isfinite(base) || !std::isfinite(exp)) {
UndefineOutputGradWhereInputGradNonzero(result, &result);
UndefineOutputGradWhereInputGradNonzero(exp_ad, &result);
return result;
}
// For the gradient, we have:
// ∂/∂v bˣ
// = ∂/∂v eˡⁿ⁽ᵇ⁾ˣ # Power via logarithms
// = eˡⁿ⁽ᵇ⁾ˣ ∂/∂v ln(b)x # Derivative of exponentiation
// = bˣ ∂/∂v ln(b)x # Undo power via logarithms
// = bˣ (x ∂/∂v ln(b) + ln(b) ∂x/∂v) # Multiplication chain rule
// = bˣ (xb⁻¹ ∂b/∂v + ln(b) ∂x/∂v) # Derivative of logarithm
// = xbˣ⁻¹ ∂b/∂v + bˣln(b) ∂x/∂v # Distribute
// Account for the contribution of grad(base) on grad(result).
// Don't try to compute (xbˣ⁻¹) with x == 0, in case it comes out as a NaN
// (e.g., 0 * ∞). Instead, just assume that the x == 0 wins, such that the
// grad(base) has no contribution to the result.
const double base_grad_scale = (exp == 0) ? 0 : exp * std::pow(base, exp - 1);
DRAKE_DEMAND(std::isfinite(base_grad_scale));
result.partials().Mul(base_grad_scale);
// Account for the contribution of grad(exp) on grad(result).
if (base < 0) {
UndefineOutputGradWhereInputGradNonzero(exp_ad, &result);
} else {
DRAKE_DEMAND(base > 0);
const double exp_grad_scale = result.value() * std::log(base);
DRAKE_DEMAND(std::isfinite(exp_grad_scale));
result.partials().AddScaled(exp_grad_scale, exp_ad.partials());
}
return result;
}
AutoDiff pow(double base, const AutoDiff& exp) {
return pow(AutoDiff{base}, exp);
}
AutoDiff pow(AutoDiff base, double exp) {
return pow(std::move(base), AutoDiff{exp});
}
AutoDiff sqrt(AutoDiff x) {
// ∂/∂x x¹ᐟ² = ½x⁻¹ᐟ² = 1/(2x¹ᐟ²)
const double new_value = std::sqrt(x.value());
x.partials().Div(2 * new_value);
x.value() = new_value;
return x;
}
AutoDiff ceil(AutoDiff x) {
x.value() = std::ceil(x.value());
x.partials().SetZero();
return x;
}
AutoDiff floor(AutoDiff x) {
x.value() = std::floor(x.value());
x.partials().SetZero();
return x;
}
AutoDiff round(AutoDiff x) {
x.value() = std::round(x.value());
x.partials().SetZero();
return x;
}
AutoDiff nexttoward(AutoDiff from, long double to) {
from.value() = std::nexttoward(from.value(), to);
from.partials().SetZero();
return from;
}
std::ostream& operator<<(std::ostream& s, const AutoDiff& x) {
return s << fmt::format("{}", x.value());
}
} // namespace ad
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/internal/eigen_specializations.h | #pragma once
#include <limits>
#include <Eigen/Core>
/* This file contains Eigen-related specializations for Drake's AutoDiff
scalar type (plus the intimately related std::numeric_limits specialization).
NOTE: This file should never be included directly, rather only from
auto_diff.h in a very specific order. */
#ifndef DRAKE_DOXYGEN_CXX
namespace std {
template <>
class numeric_limits<drake::ad::AutoDiff> : public numeric_limits<double> {};
} // namespace std
namespace Eigen {
// === See Eigen/src/Core/NumTraits.h ===
// See https://eigen.tuxfamily.org/dox/structEigen_1_1NumTraits.html.
// We'll Inherit the constants from `double`, but be sure to fatten a few types
// up to full AutoDiff where necessary.
template <>
struct NumTraits<drake::ad::AutoDiff> : public NumTraits<double> {
// This refers to the "real part" of a complex number (e.g., std::complex).
// Because we're not a complex number, it's just the same type as ourselves.
using Real = drake::ad::AutoDiff;
// This promotes integer types during operations like quotients, square roots,
// etc. We're already floating-point, so it's just the same type as ourselves.
using NonInteger = drake::ad::AutoDiff;
// Eigen says "If you don't know what this means, just use [your type] here."
using Nested = drake::ad::AutoDiff;
// Our constructor is required during matrix storage initialization.
enum { RequireInitialization = 1 };
};
// Computing "ADS [op] double" yields an ADS.
template <typename BinOp>
struct ScalarBinaryOpTraits<drake::ad::AutoDiff, double, BinOp> {
using ReturnType = drake::ad::AutoDiff;
};
// Computing "double [op] ADS" yields an ADS.
template <typename BinOp>
struct ScalarBinaryOpTraits<double, drake::ad::AutoDiff, BinOp> {
using ReturnType = drake::ad::AutoDiff;
};
} // namespace Eigen
#endif // DRAKE_DOXYGEN_CXX
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/internal/partials.h | #pragma once
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
namespace drake {
namespace ad {
namespace internal {
/* A vector of partial derivatives, for use with Drake's AutoDiff.
Partials are dynamically sized, and can have size() == 0.
When adding two Partials, they must have a compatible size(). A Partials with
size() == 0 may be freely combined with any other size, and is treated as-if
it were filled with all zeros. When adding two Partials where each one has a
non-zero size, the two sizes must be identical.
Note that a Partials object with non-zero size might still be filled with zeros
for its values. Once a non-zero size() has been established, it is "sticky" and
never returns back to being zero-sized (unless the Partials is moved-from).
In particular, note that the result of a binary operation takes on the size from
either operand, e.g., foo.Add(bar) with foo.size() == 0 and bar.size() == 4 will
will result in foo.size() == 4 after the addition, and that's true even if bar's
vector was all zeros. */
class Partials {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Partials);
/* Constructs an empty vector. */
Partials() = default;
/* Constructs a single partial derivative of `coeff` at the given `offset` in
a vector of `size` otherwise-zero derivatives.
@throws std::exception if offset >= size */
Partials(Eigen::Index size, Eigen::Index offset, double coeff = 1.0);
/* Constructs a vector with a copy of the given value. */
explicit Partials(const Eigen::Ref<const Eigen::VectorXd>& value);
~Partials() = default;
/* Returns the size of this vector. */
int size() const { return derivatives_.size(); }
/* Updates `this` to be the same size as `other`.
If `this` and `other` are already the same size then does nothing.
Otherwise, if `other` has size 0 then does nothing.
Otherwise, if `this` has size 0 then sets this to a zero vector of size
`other.size`.
Otherwise, throws an exception for mismatched sizes. */
void MatchSizeOf(const Partials& other);
/* Set this to zero. */
void SetZero() { derivatives_.setZero(); }
/* Scales this vector by the given amount. */
void Mul(double factor) { derivatives_ *= factor; }
/* Scales this vector by the reciprocal of the given amount. */
void Div(double factor) { derivatives_ /= factor; }
/* Adds `other` into `this`. */
void Add(const Partials& other);
/* Adds `scale * other` into `this`. */
void AddScaled(double scale, const Partials& other);
/* Returns the underlying storage vector (readonly).
TODO(jwnimmer-tri) Use a more Xpr-like return type. By "Xpr", we mean what
Eigen calls an XprType, e.g., something like Eigen::CwiseBinaryOp. */
const Eigen::VectorXd& make_const_xpr() const { return derivatives_; }
/* Returns the underlying storage vector (mutable). */
Eigen::VectorXd& get_raw_storage_mutable() { return derivatives_; }
private:
void ThrowIfDifferentSize(const Partials& other);
// TODO(jwnimmer-tri) Replace this implementation with a more efficient
// representation.
Eigen::VectorXd derivatives_;
};
} // namespace internal
} // namespace ad
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/internal/standard_operations.h | #pragma once
#include <cmath>
#include <iosfwd>
/* This file contains free function operators for Drake's AutoDiff type.
The functions provide not only arithmetic (+,-,*,/) and boolean comparison
(<,<=,>,>=,==,!=) but also argument-dependent lookup ("ADL") compatibility with
the standard library's mathematical functions (abs, etc.)
(See https://en.cppreference.com/w/cpp/language/adl for details about ADL.)
A few functions for Eigen::numext are also added to argument-dependent lookup.
Functions that cannot preserve gradients will return a primitive type (`bool`
or `double`) instead of an AutoDiff.
NOTE: This file should never be included directly, rather only from
auto_diff.h in a very specific order. */
namespace drake {
namespace ad {
/// @name Increment and decrement
///
/// https://en.cppreference.com/w/cpp/language/operators#Increment_and_decrement
//@{
/** Standard prefix increment operator (i.e., `++x`). */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator++(AutoDiff& x) {
++x.value();
return x;
}
/** Standard postfix increment operator (i.e., `x++`). */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff operator++(AutoDiff& x, int) {
AutoDiff result = x;
++x.value();
return result;
}
/** Standard prefix decrement operator (i.e., `--x`). */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator--(AutoDiff& x) {
--x.value();
return x;
}
/** Standard postfix decrement operator (i.e., `x--`). */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff operator--(AutoDiff& x, int) {
AutoDiff result = x;
--x.value();
return result;
}
//@}
/// @name Arithmetic operators
///
/// https://en.cppreference.com/w/cpp/language/operators#Binary_arithmetic_operators
//@{
/** Standard compound addition and assignment operator. */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator+=(AutoDiff& a, const AutoDiff& b) {
// ∂/∂x a + b = a' + b'
a.partials().Add(b.partials());
a.value() += b.value();
return a;
}
/** Standard compound addition and assignment operator. */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator+=(AutoDiff& a, double b) {
// ∂/∂x a + b = a' + b' == a'
a.value() += b;
return a;
}
/** Standard compound subtraction and assignment operator. */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator-=(AutoDiff& a, const AutoDiff& b) {
// ∂/∂x a - b = a' - b'
a.partials().AddScaled(-1, b.partials());
a.value() -= b.value();
return a;
}
/** Standard compound subtraction and assignment operator. */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator-=(AutoDiff& a, double b) {
// ∂/∂x a - b = a' - b' == a'
a.value() -= b;
return a;
}
/** Standard compound multiplication and assignment operator. */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator*=(AutoDiff& a, const AutoDiff& b) {
// ∂/∂x a * b = ba' + ab'
// Special case to avoid changing b.partials() via a.partials() aliasing.
if (&a == &b) {
// ∂/∂x a * a = 2aa'
a.partials().Mul(2.0 * a.value());
} else {
a.partials().Mul(b.value());
a.partials().AddScaled(a.value(), b.partials());
}
a.value() *= b.value();
return a;
}
/** Standard compound multiplication and assignment operator. */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator*=(AutoDiff& a, double b) {
// ∂/∂x a * b = ba' + ab' = ba'
a.partials().Mul(b);
a.value() *= b;
return a;
}
/** Standard compound division and assignment operator. */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator/=(AutoDiff& a, const AutoDiff& b) {
// ∂/∂x a / b = (ba' - ab') / b²
// Special case to avoid changing b.partials() via a.partials() aliasing.
if (&a == &b) {
// ∂/∂x a / a = 0
a.partials().SetZero();
} else {
a.partials().Mul(b.value());
a.partials().AddScaled(-a.value(), b.partials());
a.partials().Div(b.value() * b.value());
}
a.value() /= b.value();
return a;
}
/** Standard compound division and assignment operator. */
// NOLINTNEXTLINE(runtime/references) to match the required signature.
inline AutoDiff& operator/=(AutoDiff& a, double b) {
// ∂/∂x a / b = (ba' - ab') / b² = a'/b
a.partials().Div(b);
a.value() /= b;
return a;
}
/** Standard addition operator. */
inline AutoDiff operator+(AutoDiff a, const AutoDiff& b) {
a += b;
return a;
}
/** Standard addition operator. */
inline AutoDiff operator+(AutoDiff a, double b) {
a += b;
return a;
}
/** Standard addition operator. */
inline AutoDiff operator+(double a, AutoDiff b) {
b += a;
return b;
}
/** Standard unary plus operator. */
inline AutoDiff operator+(AutoDiff x) {
return x;
}
/** Standard subtraction operator. */
inline AutoDiff operator-(AutoDiff a, const AutoDiff& b) {
a -= b;
return a;
}
/** Standard subtraction operator. */
inline AutoDiff operator-(AutoDiff a, double b) {
a -= b;
return a;
}
/** Standard subtraction operator. */
inline AutoDiff operator-(double a, AutoDiff b) {
b *= -1;
b += a;
return b;
}
/** Standard unary minus operator. */
inline AutoDiff operator-(AutoDiff x) {
x *= -1;
return x;
}
/** Standard multiplication operator. */
inline AutoDiff operator*(AutoDiff a, const AutoDiff& b) {
a *= b;
return a;
}
/** Standard multiplication operator. */
inline AutoDiff operator*(AutoDiff a, double b) {
a *= b;
return a;
}
/** Standard multiplication operator. */
inline AutoDiff operator*(double a, AutoDiff b) {
b *= a;
return b;
}
/** Standard division operator. */
inline AutoDiff operator/(AutoDiff a, const AutoDiff& b) {
a /= b;
return a;
}
/** Standard division operator. */
inline AutoDiff operator/(AutoDiff a, double b) {
a /= b;
return a;
}
/** Standard division operator. */
inline AutoDiff operator/(double a, const AutoDiff& b) {
AutoDiff result{a};
result /= b;
return result;
}
//@}
/// @name Comparison operators
///
/// https://en.cppreference.com/w/cpp/language/operators#Comparison_operators
//@{
/** Standard comparison operator. Discards the derivatives. */
inline bool operator<(const AutoDiff& a, const AutoDiff& b) {
return a.value() < b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator<=(const AutoDiff& a, const AutoDiff& b) {
return a.value() <= b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator>(const AutoDiff& a, const AutoDiff& b) {
return a.value() > b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator>=(const AutoDiff& a, const AutoDiff& b) {
return a.value() >= b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator==(const AutoDiff& a, const AutoDiff& b) {
return a.value() == b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator!=(const AutoDiff& a, const AutoDiff& b) {
return a.value() != b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator<(const AutoDiff& a, double b) {
return a.value() < b;
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator<=(const AutoDiff& a, double b) {
return a.value() <= b;
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator>(const AutoDiff& a, double b) {
return a.value() > b;
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator>=(const AutoDiff& a, double b) {
return a.value() >= b;
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator==(const AutoDiff& a, double b) {
return a.value() == b;
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator!=(const AutoDiff& a, double b) {
return a.value() != b;
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator<(double a, const AutoDiff& b) {
return a < b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator<=(double a, const AutoDiff& b) {
return a <= b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator>(double a, const AutoDiff& b) {
return a > b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator>=(double a, const AutoDiff& b) {
return a >= b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator==(double a, const AutoDiff& b) {
return a == b.value();
}
/** Standard comparison operator. Discards the derivatives. */
inline bool operator!=(double a, const AutoDiff& b) {
return a != b.value();
}
//@}
/// @name Minimum/maximum operations
///
/// https://en.cppreference.com/w/cpp/algorithm#Minimum.2Fmaximum_operations
//@{
/** ADL overload to mimic std::max from <algorithm>.
Note that like std::max, this function returns a reference to whichever
argument was chosen; it does not make a copy. When `a` and `b` are equal,
retains the derivatives of `a` (by returning `a`) unless `a` has empty
derivatives, in which case `b` is returned. */
inline const AutoDiff& max(const AutoDiff& a, const AutoDiff& b) {
if (a.value() == b.value()) {
return a.derivatives().size() > 0 ? a : b;
}
return a.value() < b.value() ? b : a;
}
/** ADL overload to mimic std::max from <algorithm>.
When `a` and `b` are equal, retains the derivatives of `a`. */
inline AutoDiff max(AutoDiff a, double b) {
if (a.value() < b) {
a = b;
}
return a;
}
/** ADL overload to mimic std::max from <algorithm>.
When `a` and `b` are equal, retains the derivatives of `b`. */
inline AutoDiff max(double a, AutoDiff b) {
if (a < b.value()) {
return b;
}
b = a;
return b;
}
/** ADL overload to mimic std::min from <algorithm>.
Note that like std::min, this function returns a reference to whichever
argument was chosen; it does not make a copy. When `a` and `b` are equal,
retains the derivatives of `a` (by returning `a`) unless `a` has empty
derivatives, in which case `b` is returned. */
inline const AutoDiff& min(const AutoDiff& a, const AutoDiff& b) {
if (a.value() == b.value()) {
return a.derivatives().size() > 0 ? a : b;
}
return b.value() < a.value() ? b : a;
}
/** ADL overload to mimic std::min from <algorithm>.
When `a` and `b` are equal, retains the derivatives of `a`. */
inline AutoDiff min(AutoDiff a, double b) {
if (b < a.value()) {
a = b;
}
return a;
}
/** ADL overload to mimic std::min from <algorithm>.
When `a` and `b` are equal, retains the derivatives of `b`. */
// NOLINTNEXTLINE(build/include_what_you_use) false positive.
inline AutoDiff min(double a, AutoDiff b) {
if (a < b.value()) {
b = a;
}
return b;
}
//@}
/// @name Math functions: Basic operations
///
/// https://en.cppreference.com/w/cpp/numeric/math#Basic_operations
//@{
/** ADL overload to mimic std::abs from <cmath>. */
inline AutoDiff abs(AutoDiff x) {
// Conditionally negate negative numbers.
if (x.value() < 0) {
x *= -1;
}
return x;
}
/** ADL overload to mimic Eigen::numext::abs2. */
inline AutoDiff abs2(AutoDiff x) {
// ∂/∂x x² = 2x
x.partials().Mul(2 * x.value());
x.value() *= x.value();
return x;
}
//@}
/// @name Math functions: Exponential and Power functions
///
/// https://en.cppreference.com/w/cpp/numeric/math#Exponential_functions
///
/// https://en.cppreference.com/w/cpp/numeric/math#Power_functions
//@{
/** ADL overload to mimic std::exp from <cmath>. */
AutoDiff exp(AutoDiff x);
/** ADL overload to mimic std::log from <cmath>. */
AutoDiff log(AutoDiff x);
/** ADL overload to mimic std::pow from <cmath>.
The resulting partial derivative ∂/∂vᵢ is undefined (i.e., NaN) for all of the
following cases:
- base is NaN
- exp is NaN
- pow(base, exp) is NaN
- ∂base/∂vᵢ is non-zero and either:
- base is zero or not finite, or
- exp is not finite
- ∂exp/∂vᵢ is non-zero and either:
- base is not positive-finite, or
- exp is not finite
In all other cases, if the base and exp partial derivatives were well-defined
then the resulting partial derivatives will also be well-defined. */
AutoDiff pow(AutoDiff base, const AutoDiff& exp);
/** ADL overload to mimic std::pow from <cmath>.
Refer to pow(AutoDiff,const AutoDiff&) for an explanation of special cases. */
AutoDiff pow(double base, const AutoDiff& exp);
/** ADL overload to mimic std::pow from <cmath>.
Refer to pow(AutoDiff,const AutoDiff&) for an explanation of special cases. */
AutoDiff pow(AutoDiff base, double exp);
/** ADL overload to mimic std::sqrt from <cmath>. */
AutoDiff sqrt(AutoDiff x);
//@}
/// @name Math functions: Trigonometric functions
///
/// https://en.cppreference.com/w/cpp/numeric/math#Trigonometric_functions
//@{
/** ADL overload to mimic std::sin from <cmath>. */
AutoDiff sin(AutoDiff x);
/** ADL overload to mimic std::cos from <cmath>. */
AutoDiff cos(AutoDiff x);
/** ADL overload to mimic std::tan from <cmath>. */
AutoDiff tan(AutoDiff x);
/** ADL overload to mimic std::asin from <cmath>. */
AutoDiff asin(AutoDiff x);
/** ADL overload to mimic std::acos from <cmath>. */
AutoDiff acos(AutoDiff x);
/** ADL overload to mimic std::atan from <cmath>. */
AutoDiff atan(AutoDiff x);
/** ADL overload to mimic std::atan2 from <cmath>. */
AutoDiff atan2(AutoDiff a, const AutoDiff& b);
/** ADL overload to mimic std::atan2 from <cmath>. */
AutoDiff atan2(AutoDiff a, double b);
/** ADL overload to mimic std::atan2 from <cmath>. */
AutoDiff atan2(double a, AutoDiff b);
//@}
/// @name Math functions: Hyperbolic functions
///
/// https://en.cppreference.com/w/cpp/numeric/math#Hyperbolic_functions
//@{
/** ADL overload to mimic std::sinh from <cmath>. */
AutoDiff sinh(AutoDiff x);
/** ADL overload to mimic std::cosh from <cmath>. */
AutoDiff cosh(AutoDiff x);
/** ADL overload to mimic std::tanh from <cmath>. */
AutoDiff tanh(AutoDiff x);
//@}
/// @name Math functions: Nearest integer floating point operations
///
/// https://en.cppreference.com/w/cpp/numeric/math#Nearest_integer_floating_point_operations
///
/// https://en.cppreference.com/w/cpp/numeric/math#Floating_point_manipulation_functions
//@{
/** ADL overload to mimic std::ceil from <cmath>.
The result's derivatives are always zero. */
AutoDiff ceil(AutoDiff x);
/** ADL overload to mimic std::floor from <cmath>.
The result's derivatives are always zero. */
AutoDiff floor(AutoDiff x);
/** ADL overload to mimic std::round from <cmath>.
The result's derivatives are always zero. */
AutoDiff round(AutoDiff x);
/** ADL overload to mimic std::nexttoward from <cmath>.
The result's derivatives are always zero. */
AutoDiff nexttoward(AutoDiff from, long double to);
/** ADL overload to mimic std::isfinite from <cmath>.
Because the return type is `bool`, the derivatives are not preserved. */
inline bool isfinite(const AutoDiff& x) {
return std::isfinite(x.value());
}
/** ADL overload to mimic std::isinf from <cmath>.
Because the return type is `bool`, the derivatives are not preserved. */
inline bool isinf(const AutoDiff& x) {
return std::isinf(x.value());
}
/** ADL overload to mimic std::isnan from <cmath>.
Because the return type is `bool`, the derivatives are not preserved. */
inline bool isnan(const AutoDiff& x) {
return std::isnan(x.value());
}
//@}
/// @name Miscellaneous functions
//@{
// TODO(jwnimmer-tri) Deprecate me.
/** Outputs the `value()` part of x to the stream.
To output the derivatives use `<< x.derivatives().transpose()`. */
std::ostream& operator<<(std::ostream& s, const AutoDiff& x);
//@}
} // namespace ad
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/internal/partials.cc | #include "drake/common/ad/internal/partials.h"
#include <stdexcept>
#include <fmt/format.h>
namespace drake {
namespace ad {
namespace internal {
namespace {
// Narrow an Eigen::Index to a plain int index, throwing when out-of-range.
int IndexToInt(Eigen::Index index) {
if (index < 0) {
throw std::out_of_range(fmt::format(
"AutoDiff derivatives size or offset {} is negative", index));
}
if (index > INT32_MAX) {
throw std::out_of_range(fmt::format(
"AutoDiff derivatives size or offset {} is too large", index));
}
return static_cast<int>(index);
}
} // namespace
Partials::Partials(Eigen::Index size, Eigen::Index offset, double coeff)
: derivatives_{Eigen::VectorXd::Zero(IndexToInt(size))} {
if (IndexToInt(offset) >= size) {
throw std::out_of_range(fmt::format(
"AutoDiff offset {} must be strictly less than size {}", offset, size));
}
derivatives_[offset] = coeff;
}
Partials::Partials(const Eigen::Ref<const Eigen::VectorXd>& value)
: derivatives_{value} {}
void Partials::MatchSizeOf(const Partials& other) {
if (other.size() == 0) {
return;
}
if (size() == 0) {
derivatives_ = Eigen::VectorXd::Zero(other.size());
return;
}
ThrowIfDifferentSize(other);
}
void Partials::Add(const Partials& other) {
AddScaled(1.0, other);
}
void Partials::AddScaled(double scale, const Partials& other) {
if (other.size() == 0) {
return;
}
if (size() == 0) {
derivatives_ = scale * other.derivatives_;
return;
}
ThrowIfDifferentSize(other);
derivatives_ += scale * other.derivatives_;
}
void Partials::ThrowIfDifferentSize(const Partials& other) {
if (size() != other.size()) {
throw std::logic_error(fmt::format(
"The size of AutoDiff partial derivative vectors must be uniform"
" throughout the computation, but two different sizes ({} and {})"
" were encountered at runtime.",
size(), other.size()));
}
}
} // namespace internal
} // namespace ad
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_abs2_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Abs2) {
CHECK_UNARY_FUNCTION(abs2, x, y, 0.1);
CHECK_UNARY_FUNCTION(abs2, x, y, -0.1);
CHECK_UNARY_FUNCTION(abs2, y, x, 0.1);
CHECK_UNARY_FUNCTION(abs2, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_atan_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
// Eigen doesn't provide an atan() overload, so we need to do it.
// This assumes the standard_operations_test.h is implemented using AutoDiff3.
AutoDiff3 atan(const AutoDiff3& x) {
// ∂/∂x atan(x) = 1 / (1 + x²)
return AutoDiff3{std::atan(x.value()),
x.derivatives() / (1 + x.value() * x.value())};
}
TEST_F(StandardOperationsTest, Atan) {
CHECK_UNARY_FUNCTION(atan, x, y, 0.1);
CHECK_UNARY_FUNCTION(atan, x, y, -0.1);
CHECK_UNARY_FUNCTION(atan, y, x, 0.1);
CHECK_UNARY_FUNCTION(atan, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_sub_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Subtraction) {
CHECK_BINARY_OP(-, x, y, 1.0);
CHECK_BINARY_OP(-, x, y, -1.0);
CHECK_BINARY_OP(-, y, x, 1.0);
CHECK_BINARY_OP(-, y, x, -1.0);
}
namespace {
// We need to wrap the operator under test, to give it a name.
AutoDiffDut unary_negate(const AutoDiffDut& x) {
return -x;
}
AutoDiff3 unary_negate(const AutoDiff3& x) {
return -x;
}
} // namespace
TEST_F(StandardOperationsTest, UnaryNegation) {
CHECK_UNARY_FUNCTION(unary_negate, x, y, 1.0);
CHECK_UNARY_FUNCTION(unary_negate, x, y, -1.0);
CHECK_UNARY_FUNCTION(unary_negate, y, x, 1.0);
CHECK_UNARY_FUNCTION(unary_negate, y, x, -1.0);
}
TEST_F(StandardOperationsTest, UnaryNegationZero) {
const Eigen::Vector3d derivatives = Eigen::Vector3d::LinSpaced(1.0, 3.0);
const AutoDiffDut positive_zero{+0.0, derivatives};
EXPECT_FALSE(std::signbit(positive_zero.value()));
const AutoDiffDut negative_zero = -positive_zero;
EXPECT_EQ(negative_zero.value(), 0);
EXPECT_TRUE(std::signbit(negative_zero.value()));
EXPECT_EQ(negative_zero.derivatives(), -derivatives);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_div_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Division) {
CHECK_BINARY_OP(/, x, y, 1.0);
CHECK_BINARY_OP(/, x, y, -1.0);
CHECK_BINARY_OP(/, y, x, 1.0);
CHECK_BINARY_OP(/, y, x, -1.0);
}
// The CHECK_BINARY_OP typically copies the first argument, so does not test
// aliasing between the two arguments. We'll do that here specifically.
TEST_F(StandardOperationsTest, DivisionInPlace) {
AutoDiffDut x{0.5, 3, 0};
const AutoDiffDut& y = x;
x /= y;
EXPECT_EQ(x.value(), 1.0);
EXPECT_EQ(x.derivatives(), Eigen::Vector3d::Zero());
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_sinh_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Sinh) {
CHECK_UNARY_FUNCTION(sinh, x, y, 0.1);
CHECK_UNARY_FUNCTION(sinh, x, y, -0.1);
CHECK_UNARY_FUNCTION(sinh, y, x, 0.1);
CHECK_UNARY_FUNCTION(sinh, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_test.h | #pragma once
#include <algorithm>
#include <cmath>
#include <limits>
#include <Eigen/Core>
#include <gtest/gtest.h>
#include <unsupported/Eigen/AutoDiff>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace test {
// While we are transitioning between the old and new auto diff implementations
// (`Eigen::AutoDiffScalar<Eigen::VectorXd>` and `drake::ad::AutoDiff`) this
// DRAKE_AUTODIFFXD_DUT preprocessor macro allows us to reuse the
// StandardOperationsTest fixture and its associated macros for both
// implementations' test suites.
//
// The value used for DRAKE_AUTODIFFXD_DUT is defined by the build system as
// either `drake::AutoDiffXd` or `drake::ad::AutoDiff` for the old and new
// implementations, respectively (via `copts` in `common/BUILD.bazel` and
// `common/ad/BUILD.bazel`).
//
// Once we finally drop the old implementation, we should undo the use of
// the preprocessor for this alias.
using AutoDiffDut = DRAKE_AUTODIFFXD_DUT;
// This is Eigen's "reference implementation" of autodiff. We'll compare our
// AutoDiff results to Eigen's AutoDiffScalar results for unit testing.
using AutoDiff3 = Eigen::AutoDiffScalar<Eigen::Matrix<double, 3, 1>>;
class StandardOperationsTest : public ::testing::Test {
protected:
// Evaluates a given function f with values of AutoDiffXd and values with
// AutoDiffd<3>. It checks if the values and the derivatives of those
// evaluation results are matched.
template <typename F>
::testing::AssertionResult Check(const F& f) {
// AutoDiffXd constants -- x and y.
const AutoDiffDut x_xd{0.4};
AutoDiffDut y_xd{0.3};
// AutoDiffd<3> constants -- x and y.
const AutoDiff3 x_3d{x_xd.value()};
AutoDiff3 y_3d{y_xd.value()};
// We only set the derivatives of y and leave x's uninitialized.
y_xd.derivatives() = Eigen::VectorXd::Ones(3);
y_3d.derivatives() = Eigen::Vector3d::Ones();
// Compute the expression results.
const AutoDiffDut e_xd{f(x_xd, y_xd)};
const AutoDiff3 e_3d{f(x_3d, y_3d)};
// Pack the results into a 4-vector (for easier comparison and reporting).
Eigen::Vector4d value_and_der_x;
Eigen::Vector4d value_and_der_3;
value_and_der_x.setZero();
value_and_der_3.setZero();
value_and_der_x(0) = e_xd.value();
value_and_der_3(0) = e_3d.value();
// When the values are finite, compare the derivatives. When the value are
// not finite, then derivatives are allowed to be nonsense.
if (std::isfinite(e_xd.value()) && std::isfinite(e_3d.value())) {
value_and_der_3.tail(3) = e_3d.derivatives();
// When an AutoDiffXd derivatives vector is empty, the implication is
// that all derivatives are zero.
if (e_xd.derivatives().size() > 0) {
value_and_der_x.tail(3) = e_xd.derivatives();
}
} else {
value_and_der_3.tail(3) = Eigen::Vector3d::Constant(NAN);
value_and_der_x.tail(3) = Eigen::Vector3d::Constant(NAN);
}
return CompareMatrices(value_and_der_x, value_and_der_3,
10 * std::numeric_limits<double>::epsilon(),
MatrixCompareType::relative)
<< "\n(where xd.size() = " << e_xd.derivatives().size() << ")";
}
};
// We need to specify the return type of the polymorphic lambda function that is
// passed to StandardOperationsTest::Check() method.
#define CHECK_EXPR(expr) \
EXPECT_TRUE( \
Check([](const auto& x, const auto& y) -> \
typename Eigen::internal::remove_reference<decltype(x)>::type { \
return expr; \
})) \
<< #expr // Print statement to locate it if it fails
// clang-format off
#define CHECK_BINARY_OP(bop, x, y, c) \
CHECK_EXPR((x bop x)bop(y bop y)); \
CHECK_EXPR((x bop y)bop(x bop y)); \
CHECK_EXPR((x bop y)bop c); \
CHECK_EXPR((x bop y)bop c); \
CHECK_EXPR((x bop c)bop y); \
CHECK_EXPR((c bop x)bop y); \
CHECK_EXPR(x bop(y bop c)); \
CHECK_EXPR(x bop(c bop y)); \
CHECK_EXPR(c bop(x bop y));
// clang-format on
// The multiplicative factor 0.9 < 1.0 let us call function such as asin, acos,
// etc. whose arguments must be in [-1, 1].
// clang-format off
#define CHECK_UNARY_FUNCTION(f, x, y, c) \
CHECK_EXPR(f(x + x) + (y + y)); \
CHECK_EXPR(f(x + y) + (x + y)); \
CHECK_EXPR(f(x - x + 5.0) + (y - y)); \
CHECK_EXPR(f(x - y + 5.0) + (x - y)); \
CHECK_EXPR(f(x * x) + (y * y)); \
CHECK_EXPR(f(x * y) + (x * y)); \
CHECK_EXPR(f(0.9 * x / x) + (y / y)); \
CHECK_EXPR(f(x / y) + (x / y)); \
CHECK_EXPR(f(x + c) + y); \
CHECK_EXPR(f(x - c + 5.0) + y); \
CHECK_EXPR(f(x * c + 5.0) + y); \
CHECK_EXPR(f(x + 5.0) + y / c); \
CHECK_EXPR(f(c + x + 5.0) + y); \
CHECK_EXPR(f(c - x + 5.0) + y); \
CHECK_EXPR(f(c * x + 5.0) + y); \
CHECK_EXPR(f(c / x + 5.0) + y); \
CHECK_EXPR(f(-x + 5.0) + y);
// clang-format on
// clang-format off
#define CHECK_BINARY_FUNCTION_ADS_ADS(f, x, y, c) \
CHECK_EXPR(f(x + x, y + y) + x); \
CHECK_EXPR(f(x + x, y + y) + y); \
CHECK_EXPR(f(x + y, y + y) + x); \
CHECK_EXPR(f(x + y, y + y) + y); \
CHECK_EXPR(f(x - x, y - y) - x); \
CHECK_EXPR(f(x - x, y - y) - y); \
CHECK_EXPR(f(x - y, y - y) - x); \
CHECK_EXPR(f(x - y, y - y) - y); \
CHECK_EXPR(f(x* x, y* y) * x); \
CHECK_EXPR(f(x* x, y* y) * y); \
CHECK_EXPR(f(x* y, y* y) * x); \
CHECK_EXPR(f(x* y, y* y) * y); \
CHECK_EXPR(f(x / x, y / y) / x); \
CHECK_EXPR(f(x / x, y / y) / y); \
CHECK_EXPR(f(x / y, y / y) / x); \
CHECK_EXPR(f(x / y, y / y) / y); \
CHECK_EXPR(f(x + c, y + c) + x); \
CHECK_EXPR(f(c + x, c + x) + y); \
CHECK_EXPR(f(x* c, y* c) + x); \
CHECK_EXPR(f(c* x, c* x) + y); \
CHECK_EXPR(f(-x, -y) + y)
// clang-format on
// clang-format off
#define CHECK_BINARY_FUNCTION_ADS_SCALAR(f, x, y, c) \
CHECK_EXPR(f(x, c) + y); \
CHECK_EXPR(f(x + x, c) + y); \
CHECK_EXPR(f(x + y, c) + y); \
CHECK_EXPR(f(x - x + 5.0, c) - y); \
CHECK_EXPR(f(x * x, c) * y); \
CHECK_EXPR(f(x / x, c) / y); \
CHECK_EXPR(f(x + c, c) + y); \
CHECK_EXPR(f(c + x, c) + y); \
CHECK_EXPR(f(x * c, c) + y); \
CHECK_EXPR(f(c * x, c) + y); \
CHECK_EXPR(f(-x, c) + y);
// clang-format on
// clang-format off
#define CHECK_BINARY_FUNCTION_SCALAR_ADS(f, x, y, c) \
CHECK_EXPR(f(c, x) + y); \
CHECK_EXPR(f(c, x + x) + y); \
CHECK_EXPR(f(c, x + y) + y); \
CHECK_EXPR(f(c, x - x + 5.0) - y); \
CHECK_EXPR(f(c, x * x) * y); \
CHECK_EXPR(f(c, x / x) / y); \
CHECK_EXPR(f(c, x + c) + y); \
CHECK_EXPR(f(c, c + x) + y); \
CHECK_EXPR(f(c, x * c) + y); \
CHECK_EXPR(f(c, c * x) + y); \
CHECK_EXPR(f(c, -x) + y);
// clang-format on
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_asin_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Asin) {
CHECK_UNARY_FUNCTION(asin, x, y, 0.1);
CHECK_UNARY_FUNCTION(asin, x, y, -0.1);
CHECK_UNARY_FUNCTION(asin, y, x, 0.1);
CHECK_UNARY_FUNCTION(asin, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_mul_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Multiplication) {
CHECK_BINARY_OP(*, x, y, 1.0);
CHECK_BINARY_OP(*, x, y, -1.0);
CHECK_BINARY_OP(*, y, x, 1.0);
CHECK_BINARY_OP(*, y, x, -1.0);
}
// The CHECK_BINARY_OP typically copies the first argument, so does not test
// aliasing between the two arguments. We'll do that here specifically.
TEST_F(StandardOperationsTest, MultiplicationInPlace) {
AutoDiffDut x{0.75, 3, 0};
const AutoDiffDut& y = x;
x *= y;
EXPECT_EQ(x.value(), 0.5625);
// We have ∂/∂x x² = 2x x'.
EXPECT_EQ(x.derivatives(), 2 * 0.75 * Eigen::Vector3d::Unit(0));
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_sqrt_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Sqrt) {
CHECK_UNARY_FUNCTION(sqrt, x, y, 0.1);
CHECK_UNARY_FUNCTION(sqrt, x, y, -0.1);
CHECK_UNARY_FUNCTION(sqrt, y, x, 0.1);
CHECK_UNARY_FUNCTION(sqrt, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_atan2_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
// Eigen doesn't provide mixed-scalar atan2() overloads, so we need to do it.
// This assumes the standard_operations_test.h is implemented using AutoDiff3.
AutoDiff3 atan2(const AutoDiff3& y, double x) {
return atan2(y, AutoDiff3{x});
}
AutoDiff3 atan2(double y, const AutoDiff3& x) {
return atan2(AutoDiff3{y}, x);
}
TEST_F(StandardOperationsTest, Atan2AdsAds) {
CHECK_BINARY_FUNCTION_ADS_ADS(atan2, x, y, 0.1);
CHECK_BINARY_FUNCTION_ADS_ADS(atan2, x, y, -0.1);
CHECK_BINARY_FUNCTION_ADS_ADS(atan2, y, x, 0.4);
CHECK_BINARY_FUNCTION_ADS_ADS(atan2, y, x, -0.4);
}
TEST_F(StandardOperationsTest, Atan2AdsDouble) {
CHECK_BINARY_FUNCTION_ADS_SCALAR(atan2, x, y, 0.1);
CHECK_BINARY_FUNCTION_ADS_SCALAR(atan2, x, y, -0.1);
CHECK_BINARY_FUNCTION_ADS_SCALAR(atan2, y, x, 0.4);
CHECK_BINARY_FUNCTION_ADS_SCALAR(atan2, y, x, -0.4);
}
TEST_F(StandardOperationsTest, Atan2DoubleAds) {
CHECK_BINARY_FUNCTION_SCALAR_ADS(atan2, x, y, 0.1);
CHECK_BINARY_FUNCTION_SCALAR_ADS(atan2, x, y, -0.1);
CHECK_BINARY_FUNCTION_SCALAR_ADS(atan2, y, x, 0.4);
CHECK_BINARY_FUNCTION_SCALAR_ADS(atan2, y, x, -0.4);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_exp_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Exp) {
CHECK_UNARY_FUNCTION(exp, x, y, 0.1);
CHECK_UNARY_FUNCTION(exp, x, y, -0.1);
CHECK_UNARY_FUNCTION(exp, y, x, 0.1);
CHECK_UNARY_FUNCTION(exp, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/partials_test.cc | #include <limits>
#include <gtest/gtest.h>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
namespace drake {
namespace ad {
namespace internal {
namespace {
using Eigen::Vector2d;
using Eigen::Vector4d;
using Eigen::VectorXd;
// An empty fixture for later expansion.
class PartialsTest : public ::testing::Test {};
TEST_F(PartialsTest, DefaultCtor) {
const Partials dut;
EXPECT_EQ(dut.size(), 0);
EXPECT_EQ(dut.make_const_xpr().size(), 0);
}
TEST_F(PartialsTest, UnitCtor2Arg) {
const Partials dut{4, 2};
EXPECT_EQ(dut.size(), 4);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Unit(2)));
}
TEST_F(PartialsTest, UnitCtor3Arg) {
const Partials dut{4, 2, -1.0};
EXPECT_EQ(dut.size(), 4);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), -Vector4d::Unit(2)));
}
TEST_F(PartialsTest, UnitCtorZeroCoeff) {
const Partials dut{4, 2, 0.0};
EXPECT_EQ(dut.size(), 4);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Zero()));
}
TEST_F(PartialsTest, UnitCtorInsanelyLarge) {
const Eigen::Index terabyte = Eigen::Index{1} << 40;
DRAKE_EXPECT_THROWS_MESSAGE(Partials(terabyte, 0), ".*too large.*");
}
TEST_F(PartialsTest, UnitCtorMisuse) {
DRAKE_EXPECT_THROWS_MESSAGE(Partials(4, -1), ".*is negative.*");
DRAKE_EXPECT_THROWS_MESSAGE(Partials(-1, 0), ".*is negative.*");
DRAKE_EXPECT_THROWS_MESSAGE(Partials(2, 2), ".*strictly less.*");
}
TEST_F(PartialsTest, FullCtor) {
const Partials dut{Vector4d::LinSpaced(10.0, 13.0)};
EXPECT_EQ(dut.size(), 4);
EXPECT_TRUE(
CompareMatrices(dut.make_const_xpr(), Vector4d::LinSpaced(10.0, 13.0)));
}
TEST_F(PartialsTest, FullCtorEmpty) {
const Partials dut{VectorXd{}};
EXPECT_EQ(dut.size(), 0);
EXPECT_EQ(dut.make_const_xpr().size(), 0);
}
TEST_F(PartialsTest, FullCtorZeros) {
const Partials dut{Vector4d::Zero()};
EXPECT_EQ(dut.size(), 4);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Zero()));
}
TEST_F(PartialsTest, SetZeroFromDefaultCtor) {
Partials dut;
dut.SetZero();
EXPECT_EQ(dut.size(), 0);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), VectorXd{}));
}
TEST_F(PartialsTest, SetZeroFromUnitCtor) {
Partials dut{4, 2};
dut.SetZero();
EXPECT_EQ(dut.size(), 4);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Zero()));
}
TEST_F(PartialsTest, SetZeroFromFullCtor) {
Partials dut{Vector4d::LinSpaced(10.0, 13.0)};
dut.SetZero();
EXPECT_EQ(dut.size(), 4);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Zero()));
}
TEST_F(PartialsTest, MatchSizeOf) {
Partials dut{4, 2};
// No-op to match size == 0.
dut.MatchSizeOf(Partials{});
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Unit(2)));
// No-op to match size == 4.
dut.MatchSizeOf(Partials{4, 0});
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Unit(2)));
// Inherits size == 4 from dut.
Partials foo;
foo.MatchSizeOf(dut);
EXPECT_TRUE(CompareMatrices(foo.make_const_xpr(), Vector4d::Zero()));
// Mismatched sizes.
const Partials wrong{5, 0};
DRAKE_EXPECT_THROWS_MESSAGE(foo.MatchSizeOf(wrong), ".*different sizes.*");
}
TEST_F(PartialsTest, Mul) {
Partials dut{4, 2};
dut.Mul(-2.0);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), -2 * Vector4d::Unit(2)));
dut.Mul(0.0);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Zero()));
dut = Partials{Vector2d{1.0, 2.0}};
dut.Mul(-2.0);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector2d{-2.0, -4.0}));
dut.Mul(0.0);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector2d::Zero()));
}
TEST_F(PartialsTest, Div) {
Partials dut{4, 2};
dut.Div(-0.5);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), -2 * Vector4d::Unit(2)));
dut.SetZero();
dut.Div(-0.5);
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), -Vector4d::Zero()));
}
TEST_F(PartialsTest, DivZero) {
Partials dut{4, 2};
dut.Div(0.0);
const double kInf = std::numeric_limits<double>::infinity();
const double kNaN = std::numeric_limits<double>::quiet_NaN();
EXPECT_TRUE(
CompareMatrices(dut.make_const_xpr(), Vector4d(kNaN, kNaN, kInf, kNaN)));
}
TEST_F(PartialsTest, Add) {
Partials dut{4, 0};
dut.Add(Partials(4, 1));
dut.Add(Partials(4, 2));
dut.Add(Partials(4, 3));
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Ones()));
}
TEST_F(PartialsTest, AddScaled) {
Partials dut{4, 0};
dut.AddScaled(2.0, Partials(4, 1));
dut.AddScaled(3.0, Partials(4, 2));
dut.AddScaled(4.0, Partials(4, 3));
EXPECT_TRUE(
CompareMatrices(dut.make_const_xpr(), Vector4d::LinSpaced(1.0, 4.0)));
}
TEST_F(PartialsTest, AddRhsEmpty) {
Partials dut{4, 2};
dut.Add(Partials{});
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Unit(2)));
}
TEST_F(PartialsTest, AddScaledRhsEmpty) {
Partials dut{4, 2};
dut.AddScaled(1.0, Partials{});
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Unit(2)));
}
TEST_F(PartialsTest, AddLhsEmpty) {
Partials dut;
dut.Add(Partials(4, 2));
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), Vector4d::Unit(2)));
}
TEST_F(PartialsTest, AddScaledLhsEmpty) {
Partials dut;
dut.AddScaled(-1.0, Partials(4, 2));
EXPECT_TRUE(CompareMatrices(dut.make_const_xpr(), -Vector4d::Unit(2)));
}
TEST_F(PartialsTest, AddBothEmpty) {
Partials dut;
dut.Add(dut);
EXPECT_EQ(dut.size(), 0);
}
TEST_F(PartialsTest, AddScaledBothEmpty) {
Partials dut;
dut.AddScaled(1.0, dut);
EXPECT_EQ(dut.size(), 0);
}
TEST_F(PartialsTest, AddDifferentSizes) {
Partials dut{4, 2};
DRAKE_EXPECT_THROWS_MESSAGE(dut.Add(Partials(2, 0)), ".*different sizes.*");
}
TEST_F(PartialsTest, AddScaledDifferentSizes) {
Partials dut{4, 2};
DRAKE_EXPECT_THROWS_MESSAGE(dut.AddScaled(-1.0, Partials(2, 0)),
".*different sizes.*");
}
TEST_F(PartialsTest, DefaultCtorMutableGetter) {
Partials dut;
EXPECT_EQ(dut.get_raw_storage_mutable().size(), 0);
dut.get_raw_storage_mutable().resize(4);
EXPECT_EQ(dut.get_raw_storage_mutable().size(), 4);
}
} // namespace
} // namespace internal
} // namespace ad
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_stream_test.cc | #include <sstream>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Stream) {
const AutoDiffDut x{0.25, 3, 0};
std::stringstream stream;
stream << x;
EXPECT_EQ(stream.str(), "0.25");
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_cosh_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Cosh) {
CHECK_UNARY_FUNCTION(cosh, x, y, 0.1);
CHECK_UNARY_FUNCTION(cosh, x, y, -0.1);
CHECK_UNARY_FUNCTION(cosh, y, x, 0.1);
CHECK_UNARY_FUNCTION(cosh, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_max_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, MaxBothAds) {
CHECK_BINARY_FUNCTION_ADS_ADS(max, x, y, 0.3);
CHECK_BINARY_FUNCTION_ADS_ADS(max, x, y, -0.3);
CHECK_BINARY_FUNCTION_ADS_ADS(max, y, x, 0.4);
CHECK_BINARY_FUNCTION_ADS_ADS(max, y, x, -0.4);
}
TEST_F(StandardOperationsTest, MaxLhsAds) {
CHECK_BINARY_FUNCTION_ADS_SCALAR(max, x, y, 0.3);
CHECK_BINARY_FUNCTION_ADS_SCALAR(max, x, y, -0.3);
CHECK_BINARY_FUNCTION_ADS_SCALAR(max, y, x, 0.4);
CHECK_BINARY_FUNCTION_ADS_SCALAR(max, y, x, -0.4);
}
TEST_F(StandardOperationsTest, MaxRhsAds) {
CHECK_BINARY_FUNCTION_SCALAR_ADS(max, x, y, 0.3);
CHECK_BINARY_FUNCTION_SCALAR_ADS(max, x, y, -0.3);
CHECK_BINARY_FUNCTION_SCALAR_ADS(max, y, x, 0.4);
CHECK_BINARY_FUNCTION_SCALAR_ADS(max, y, x, -0.4);
}
TEST_F(StandardOperationsTest, TieBreakingCheckMaxBothNonEmpty) {
// Given `max(v1, v2)`, our overload returns the first argument `v1` when
// `v1 == v2` holds if both `v1` and `v2` have non-empty derivatives. In
// Drake, we rely on this implementation-detail. This test checks if the
// property holds so that we can detect a possible change in future.
const AutoDiffDut v1{1.0, Vector1<double>(3.)};
const AutoDiffDut v2{1.0, Vector1<double>(2.)};
EXPECT_EQ(max(v1, v2).derivatives()[0], 3.0); // Returns v1, not v2.
}
TEST_F(StandardOperationsTest, TieBreakingCheckMaxOneNonEmpty) {
// Given `max(v1, v2)`, our overload returns whichever argument has non-empty
// derivatives in the case where only one has non-empty derivatives. In
// Drake, we rely on this implementation-detail. This test checks if the
// property holds so that we can detect a possible change in future.
const AutoDiffDut v1{1.0};
const AutoDiffDut v2{1.0, Vector1<double>(2.)};
EXPECT_TRUE(CompareMatrices(min(v1, v2).derivatives(),
Vector1<double>(2.))); // Returns v2, not v1.
EXPECT_TRUE(CompareMatrices(min(v2, v1).derivatives(),
Vector1<double>(2.))); // Returns v2, not v1.
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/matrix_test.cc | #include <gtest/gtest.h>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace ad {
namespace {
using Eigen::Vector3d;
GTEST_TEST(MatrixTest, MatrixProduct) {
const AutoDiff x{0.4, Vector3d::LinSpaced(0.0, 2.0)};
const AutoDiff y{0.3, Vector3d::LinSpaced(-1.0, 1.0)};
// clang-format off
MatrixX<AutoDiff> A(2, 3);
A << 0, x, y,
y, x, 0;
MatrixX<AutoDiff> B(3, 1);
B << x,
y,
0;
// clang-format on
// Check the ScalarBinaryOpTraits by multiplying mixed-type scalars.
EXPECT_TRUE((std::is_same_v<decltype(A * 2.0)::Scalar, AutoDiff>));
EXPECT_TRUE((std::is_same_v<decltype(2.0 * B)::Scalar, AutoDiff>));
MatrixX<AutoDiff> A2 = A * 2.0;
MatrixX<AutoDiff> B2 = 2.0 * B;
// Spot check some matrix multiplication. Between the partials_test and the
// standard_operations test this probably will never catch any novel bugs, but
// it's easy enough to check that it seems worthwhile.
MatrixX<AutoDiff> C = A2 * B2;
// We expect:
// [[ 4xy ]
// [ 8xy ]]
// We don't need a tight tolerance, these spot checks are all-or-nothing.
constexpr double tol = 1e-10;
ASSERT_EQ(C.rows(), 2);
ASSERT_EQ(C.cols(), 1);
EXPECT_NEAR(C(0, 0).value(), 4 * 0.4 * 0.3, tol);
EXPECT_NEAR(C(1, 0).value(), 8 * 0.4 * 0.3, tol);
const Vector3d xy_grad(-0.4, 0.3, 1.0); // (xy)' = yx' + xy'
EXPECT_TRUE(CompareMatrices(C(0, 0).derivatives(), 4 * xy_grad, tol));
EXPECT_TRUE(CompareMatrices(C(1, 0).derivatives(), 8 * xy_grad, tol));
}
} // namespace
} // namespace ad
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_tanh_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Tanh) {
CHECK_UNARY_FUNCTION(tanh, x, y, 0.1);
CHECK_UNARY_FUNCTION(tanh, x, y, -0.1);
CHECK_UNARY_FUNCTION(tanh, y, x, 0.1);
CHECK_UNARY_FUNCTION(tanh, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_acos_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Acos) {
CHECK_UNARY_FUNCTION(acos, x, y, 0.1);
CHECK_UNARY_FUNCTION(acos, x, y, -0.1);
CHECK_UNARY_FUNCTION(acos, y, x, 0.1);
CHECK_UNARY_FUNCTION(acos, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_integer_test.cc | #include <sstream>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Ceil) {
const AutoDiffDut x{0.5, 3, 0};
const AutoDiffDut y = ceil(x);
EXPECT_EQ(y.value(), std::ceil(x.value()));
EXPECT_EQ(y.derivatives(), Eigen::Vector3d::Zero());
}
TEST_F(StandardOperationsTest, Floor) {
const AutoDiffDut x{0.5, 3, 0};
const AutoDiffDut y = floor(x);
EXPECT_EQ(y.value(), std::floor(x.value()));
EXPECT_EQ(y.derivatives(), Eigen::Vector3d::Zero());
}
TEST_F(StandardOperationsTest, Round) {
const AutoDiffDut x{0.5, 3, 0};
const AutoDiffDut y = round(x);
EXPECT_EQ(y.value(), std::round(x.value()));
EXPECT_EQ(y.derivatives(), Eigen::Vector3d::Zero());
}
TEST_F(StandardOperationsTest, NextToward) {
const AutoDiffDut x{0.5, 3, 0};
const AutoDiffDut y = nexttoward(x, 1.0);
EXPECT_EQ(y.value(), std::nexttoward(x.value(), 1.0));
EXPECT_EQ(y.derivatives(), Eigen::Vector3d::Zero());
}
TEST_F(StandardOperationsTest, Classify) {
const AutoDiffDut a{0.5, 3, 0};
const AutoDiffDut b{std::numeric_limits<double>::infinity(), 3, 0};
const AutoDiffDut c{std::numeric_limits<double>::quiet_NaN(), 3, 0};
for (const auto& x : {a, b, c}) {
EXPECT_EQ(isfinite(x), std::isfinite(x.value())) << x;
EXPECT_EQ(isinf(x), std::isinf(x.value())) << x;
EXPECT_EQ(isnan(x), std::isnan(x.value())) << x;
}
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_pow_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
// Note that standard_operations_pow_special_test has separate tests for all of
// the special cases (infinities, zeros, NaNs, etc.). This test only covers the
// everyday cases with real numbers where the chain rule happens as expected.
// For the pow(ADS,double), Eigen provides a reference implementation that we
// can compare against.
TEST_F(StandardOperationsTest, PowAdsDouble) {
CHECK_BINARY_FUNCTION_ADS_SCALAR(pow, x, y, 0.3);
CHECK_BINARY_FUNCTION_ADS_SCALAR(pow, x, y, -0.3);
CHECK_BINARY_FUNCTION_ADS_SCALAR(pow, y, x, 0.4);
CHECK_BINARY_FUNCTION_ADS_SCALAR(pow, y, x, -0.4);
}
// Eigen does not provide an implementation of pow(ADS,ADS) nor pow(double,ADS)
// for us to compare against, so we'll need to get creative.
//
// For starters, when the exponent has an empty gradient the results should be
// equivalent to pow(ADS,double).
AutoDiffDut pow_no_exp_grad(const AutoDiffDut& base, const AutoDiffDut& exp) {
return pow(base, exp);
}
AutoDiffDut pow_no_exp_grad(double base, const AutoDiffDut& exp) {
return pow(base, exp);
}
AutoDiff3 pow_no_exp_grad(const AutoDiff3& base, const AutoDiff3& exp) {
DRAKE_DEMAND(exp.derivatives().isZero(0.0));
return pow(base, exp.value());
}
AutoDiff3 pow_no_exp_grad(double base, const AutoDiff3& exp) {
DRAKE_DEMAND(exp.derivatives().isZero(0.0));
return std::pow(base, exp.value());
}
TEST_F(StandardOperationsTest, PowNoExpGradAdsAds) {
// N.B. In our text fixture, `x` has an empty partial derivatives vector.
// We'll use only expressions over x (and not y) as an exponent.
CHECK_EXPR(pow_no_exp_grad(y, x));
CHECK_EXPR(pow_no_exp_grad(y, x + 1.0));
CHECK_EXPR(pow_no_exp_grad(y, x - 1.0));
CHECK_EXPR(pow_no_exp_grad(x + y, x));
CHECK_EXPR(pow_no_exp_grad(x + y, x + 1.0));
CHECK_EXPR(pow_no_exp_grad(x + y, x - 1.0));
CHECK_EXPR(pow_no_exp_grad(5.0 * (x + y), 3.0 * x));
}
TEST_F(StandardOperationsTest, PowNoExpGradDoubleAds) {
// N.B. In our text fixture, `x` has an empty partial derivatives vector.
// We'll use only expressions over x (and not y) as an exponent.
CHECK_EXPR(pow_no_exp_grad(0.3, x));
CHECK_EXPR(pow_no_exp_grad(0.3, x + 1.0));
CHECK_EXPR(pow_no_exp_grad(0.3, x - 1.0));
CHECK_EXPR(pow_no_exp_grad(0.3, 3.0 * x));
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_log_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Log) {
CHECK_UNARY_FUNCTION(log, x, y, 0.1);
CHECK_UNARY_FUNCTION(log, x, y, -0.1);
CHECK_UNARY_FUNCTION(log, y, x, 0.1);
CHECK_UNARY_FUNCTION(log, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_abs_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Abs) {
CHECK_UNARY_FUNCTION(abs, x, y, 1.1);
CHECK_UNARY_FUNCTION(abs, x, y, -1.1);
CHECK_UNARY_FUNCTION(abs, y, x, 1.1);
CHECK_UNARY_FUNCTION(abs, y, x, -1.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_dec_test.cc | #include <sstream>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Postdecrement) {
AutoDiffDut x{0.25, 3, 0};
EXPECT_EQ((x--).value(), 0.25);
EXPECT_EQ(x.value(), -0.75);
EXPECT_EQ(x.derivatives()[0], 1.0);
}
TEST_F(StandardOperationsTest, Predecrement) {
AutoDiffDut x{0.25, 3, 0};
EXPECT_EQ((--x).value(), -0.75);
EXPECT_EQ(x.value(), -0.75);
EXPECT_EQ(x.derivatives()[0], 1.0);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_min_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, MinBothAds) {
CHECK_BINARY_FUNCTION_ADS_ADS(min, x, y, 0.3);
CHECK_BINARY_FUNCTION_ADS_ADS(min, x, y, -0.3);
CHECK_BINARY_FUNCTION_ADS_ADS(min, y, x, 0.4);
CHECK_BINARY_FUNCTION_ADS_ADS(min, y, x, -0.4);
}
TEST_F(StandardOperationsTest, MinLhsAds) {
CHECK_BINARY_FUNCTION_ADS_SCALAR(min, x, y, 0.3);
CHECK_BINARY_FUNCTION_ADS_SCALAR(min, x, y, -0.3);
CHECK_BINARY_FUNCTION_ADS_SCALAR(min, y, x, 0.4);
CHECK_BINARY_FUNCTION_ADS_SCALAR(min, y, x, -0.4);
}
TEST_F(StandardOperationsTest, MinRhsAds) {
CHECK_BINARY_FUNCTION_SCALAR_ADS(min, x, y, 0.3);
CHECK_BINARY_FUNCTION_SCALAR_ADS(min, x, y, -0.3);
CHECK_BINARY_FUNCTION_SCALAR_ADS(min, y, x, 0.4);
CHECK_BINARY_FUNCTION_SCALAR_ADS(min, y, x, -0.4);
}
TEST_F(StandardOperationsTest, TieBreakingCheckMinBothNonEmpty) {
// Given `min(v1, v2)`, our overload returns the first argument `v1` when
// `v1 == v2` holds if both `v1` and `v2` have non-empty derivatives. In
// Drake, we rely on this implementation-detail. This test checks if the
// property holds so that we can detect a possible change in future.
const AutoDiffDut v1{1.0, Vector1<double>(3.)};
const AutoDiffDut v2{1.0, Vector1<double>(2.)};
EXPECT_EQ(min(v1, v2).derivatives()[0], 3.0); // Returns v1, not v2.
}
TEST_F(StandardOperationsTest, TieBreakingCheckMinOneNonEmpty) {
// Given `min(v1, v2)`, our overload returns whichever argument has non-empty
// derivatives in the case where only one has non-empty derivatives. In
// Drake, we rely on this implementation-detail. This test checks if the
// property holds so that we can detect a possible change in future.
const AutoDiffDut v1{1.0};
const AutoDiffDut v2{1.0, Vector1<double>(2.)};
EXPECT_TRUE(CompareMatrices(min(v1, v2).derivatives(),
Vector1<double>(2.))); // Returns v2, not v1.
EXPECT_TRUE(CompareMatrices(min(v2, v1).derivatives(),
Vector1<double>(2.))); // Returns v2, not v1.
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_add_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Addition) {
CHECK_BINARY_OP(+, x, y, 1.0);
CHECK_BINARY_OP(+, x, y, -1.0);
CHECK_BINARY_OP(+, y, x, 1.0);
CHECK_BINARY_OP(+, y, x, -1.0);
}
namespace {
// We need to wrap the operator under test, to give it a name.
// Eigen doesn't provide unary operator+, so we'll no-op instead.
AutoDiffDut unary_add(const AutoDiffDut& x) {
return +x;
}
AutoDiff3 unary_add(const AutoDiff3& x) {
return x;
}
} // namespace
TEST_F(StandardOperationsTest, UnaryAddition) {
CHECK_UNARY_FUNCTION(unary_add, x, y, 1.0);
CHECK_UNARY_FUNCTION(unary_add, x, y, -1.0);
CHECK_UNARY_FUNCTION(unary_add, y, x, 1.0);
CHECK_UNARY_FUNCTION(unary_add, y, x, -1.0);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_cos_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Cos) {
CHECK_UNARY_FUNCTION(cos, x, y, 0.1);
CHECK_UNARY_FUNCTION(cos, x, y, -0.1);
CHECK_UNARY_FUNCTION(cos, y, x, 0.1);
CHECK_UNARY_FUNCTION(cos, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_sin_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Sin) {
CHECK_UNARY_FUNCTION(sin, x, y, 0.1);
CHECK_UNARY_FUNCTION(sin, x, y, -0.1);
CHECK_UNARY_FUNCTION(sin, y, x, 0.1);
CHECK_UNARY_FUNCTION(sin, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_inc_test.cc | #include <sstream>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Postincrement) {
AutoDiffDut x{0.25, 3, 0};
EXPECT_EQ((x++).value(), 0.25);
EXPECT_EQ(x.value(), 1.25);
EXPECT_EQ(x.derivatives()[0], 1.0);
}
TEST_F(StandardOperationsTest, Preincrement) {
AutoDiffDut x{0.25, 3, 0};
EXPECT_EQ((++x).value(), 1.25);
EXPECT_EQ(x.value(), 1.25);
EXPECT_EQ(x.derivatives()[0], 1.0);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_tan_test.cc | #include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
TEST_F(StandardOperationsTest, Tan) {
CHECK_UNARY_FUNCTION(tan, x, y, 0.1);
CHECK_UNARY_FUNCTION(tan, x, y, -0.1);
CHECK_UNARY_FUNCTION(tan, y, x, 0.1);
CHECK_UNARY_FUNCTION(tan, y, x, -0.1);
}
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_cmp_test.cc | #include <sstream>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
#define DRAKE_CHECK_CMP(cmp) \
EXPECT_EQ(0 cmp 1, AutoDiffDut{0} cmp AutoDiffDut{1}); \
EXPECT_EQ(1 cmp 0, AutoDiffDut{1} cmp AutoDiffDut{0}); \
EXPECT_EQ(1 cmp 1, AutoDiffDut{1} cmp AutoDiffDut{1}); \
EXPECT_EQ(0 cmp 1, AutoDiffDut{0} cmp 1); /* NOLINT */ \
EXPECT_EQ(1 cmp 0, AutoDiffDut{1} cmp 0); /* NOLINT */ \
EXPECT_EQ(1 cmp 1, AutoDiffDut{1} cmp 1); /* NOLINT */ \
EXPECT_EQ(0 cmp 1, 0 cmp AutoDiffDut{1}); \
EXPECT_EQ(1 cmp 0, 1 cmp AutoDiffDut{0}); \
EXPECT_EQ(1 cmp 1, 1 cmp AutoDiffDut{1})
TEST_F(StandardOperationsTest, CmpLt) {
DRAKE_CHECK_CMP(<); // NOLINT
}
TEST_F(StandardOperationsTest, CmpLe) {
DRAKE_CHECK_CMP(<=);
}
TEST_F(StandardOperationsTest, CmpGt) {
DRAKE_CHECK_CMP(>); // NOLINT
}
TEST_F(StandardOperationsTest, CmpGe) {
DRAKE_CHECK_CMP(>=);
}
TEST_F(StandardOperationsTest, CmpEq) {
DRAKE_CHECK_CMP(==);
}
TEST_F(StandardOperationsTest, CmpNe) {
DRAKE_CHECK_CMP(!=);
}
#undef DRAKE_CHECK_CMP
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/standard_operations_pow_special_test.cc | #include <algorithm>
#include <initializer_list>
#include <gmock/gmock.h>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/ad/test/standard_operations_test.h"
namespace drake {
namespace test {
namespace {
constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
constexpr double kInf = std::numeric_limits<double>::infinity();
constexpr double kTol = 1e-14;
// The Eigen reference implementation does not handle any of the IEEE floating-
// point special cases, so we'll use a custom test fixture and directly test our
// AutoDiffDut, rather than try to compare it to a reference implementation.
struct PowCase {
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(PowCase);
PowCase(double base_in, double exp_in) : base(base_in), exp(exp_in) {
expected_value = std::pow(base, exp);
// Whether any of {base, exp, result} is a NaN.
is_nan = std::isnan(base) || std::isnan(exp) || std::isnan(expected_value);
// In some cases, any non-zero element in the grad(base) leads to an
// ill-defined (i.e., NaN) corresponding element in the grad(result).
ill_defined_base_grad =
(base == 0.0) || (!std::isfinite(base)) || (!std::isfinite(exp));
// In some cases, the grad(base) is unconditionally zeroed out because
// the result is a constant, and stays the same constant for infinitesimally
// small changes to the base.
ignore_base_grad = !ill_defined_base_grad && (exp == 0);
// In some cases, any non-zero element in the grad(exp) leads to an
// ill-defined (i.e., NaN) corresponding element in the grad(result).
ill_defined_exp_grad =
(base <= 0.0) || (!std::isfinite(base)) || (!std::isfinite(exp));
}
double base{};
double exp{};
double expected_value{};
bool is_nan{};
bool ill_defined_base_grad{};
bool ignore_base_grad{};
bool ill_defined_exp_grad{};
};
void PrintTo(const PowCase& pow_case, std::ostream* os) {
*os << fmt::format("pow({}, {})", pow_case.base, pow_case.exp);
}
std::vector<PowCase> SweepAllCases() {
std::vector<PowCase> result;
// A representative sampling of both special and non-special values.
std::initializer_list<double> sweep = {
-kInf, -2.5, -2.0, -1.5, -1.0, -0.5, -0.0, +0.0,
0.5, 1.0, 1.5, 2.0, 2.5, kInf, kNaN,
};
// Let's do all-pairs testing!
for (double base : sweep) {
for (double exp : sweep) {
result.emplace_back(base, exp);
}
}
return result;
}
class PowSpecial : public ::testing::TestWithParam<PowCase> {};
std::string ToAlphaNumeric(double value) {
if (std::isnan(value)) {
return "nan";
}
if (std::isinf(value)) {
return std::signbit(value) ? "neg_inf" : "pos_inf";
}
if (value == 0) {
return std::signbit(value) ? "neg_zero" : "pos_zero";
}
std::string result = fmt::format("{}", value);
std::replace(result.begin(), result.end(), '-', 'n');
std::replace(result.begin(), result.end(), '.', 'd');
return result;
}
// The test case name must be alphanumeric only (a-z0-9_).
std::string CalcTestName(const testing::TestParamInfo<PowCase>& info) {
return fmt::format("{}__{}", ToAlphaNumeric(info.param.base),
ToAlphaNumeric(info.param.exp));
}
// Here we sweep the pow(AD,AD) overload only. We don't test either of the two
// other overloads (AD,double / double,AD) because we know they are implemented
// as one-line wrappers the AD,AD function.
TEST_P(PowSpecial, AdsAds) {
const PowCase& pow_case = GetParam();
const AutoDiffDut base(pow_case.base, 3, 1);
const AutoDiffDut exp(pow_case.exp, 3, 2);
const AutoDiffDut result = pow(base, exp);
EXPECT_THAT(result.value(),
testing::NanSensitiveDoubleEq(pow_case.expected_value));
ASSERT_EQ(result.derivatives().size(), 3);
const Eigen::Vector3d grad = result.derivatives();
// If the result was NaN, then the gradient should be NaN.
if (pow_case.is_nan) {
EXPECT_THAT(grad[0], testing::IsNan());
EXPECT_THAT(grad[1], testing::IsNan());
EXPECT_THAT(grad[2], testing::IsNan());
return;
}
// Neither base nor exp has an input gradient in the 0th index.
// That should remain true for the result as well.
EXPECT_EQ(grad[0], 0.0);
// The 1st grad index is the partial wrt base.
if (pow_case.ignore_base_grad) {
EXPECT_EQ(grad[1], 0.0);
} else if (pow_case.ill_defined_base_grad) {
EXPECT_THAT(grad[1], testing::IsNan());
} else {
const double expected =
pow_case.exp * std::pow(pow_case.base, pow_case.exp - 1);
EXPECT_NEAR(grad[1], expected, kTol);
}
// The 2nd grad index is the partial wrt exp.
if (pow_case.ill_defined_exp_grad) {
EXPECT_THAT(grad[2], testing::IsNan());
} else {
const double expected = pow_case.expected_value * std::log(pow_case.base);
EXPECT_NEAR(grad[2], expected, kTol);
}
}
INSTANTIATE_TEST_SUITE_P(StandardOperationsTest, PowSpecial,
testing::ValuesIn(SweepAllCases()), &CalcTestName);
} // namespace
} // namespace test
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/ad | /home/johnshepherd/drake/common/ad/test/auto_diff_basic_test.cc | #include <limits>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/ad/auto_diff.h"
#include "drake/common/eigen_types.h"
// This file contains only the very most basic unit tests for AutoDiffXd, e.g.,
// construction and assignment. Tests for the derivative math are elsewhere.
namespace drake {
namespace ad {
namespace {
using Eigen::VectorXd;
GTEST_TEST(AutodiffBasicTest, DefaultCtor) {
const AutoDiff dut;
EXPECT_EQ(dut.value(), 0.0);
EXPECT_EQ(dut.derivatives().size(), 0);
}
GTEST_TEST(AutodiffBasicTest, ConvertingCtor) {
const AutoDiff dut{1.0};
EXPECT_EQ(dut.value(), 1.0);
EXPECT_EQ(dut.derivatives().size(), 0);
}
GTEST_TEST(AutodiffBasicTest, UnitCtor) {
const AutoDiff dut{1.0, 4, 2};
EXPECT_EQ(dut.value(), 1.0);
EXPECT_EQ(dut.derivatives().size(), 4);
EXPECT_EQ(dut.derivatives()[2], 1.0);
}
GTEST_TEST(AutodiffBasicTest, VectorCtor) {
const Eigen::VectorXd derivs = Eigen::VectorXd::LinSpaced(3, 1.0, 3.0);
const AutoDiff dut{1.0, derivs};
EXPECT_EQ(dut.value(), 1.0);
EXPECT_EQ(dut.derivatives().size(), 3);
EXPECT_EQ(dut.derivatives(), derivs);
}
GTEST_TEST(AutodiffBasicTest, AssignConstant) {
AutoDiff dut{1.0, 4, 2};
EXPECT_EQ(dut.value(), 1.0);
EXPECT_EQ(dut.derivatives().size(), 4);
dut = -1.0;
EXPECT_EQ(dut.value(), -1.0);
EXPECT_EQ(dut.derivatives().size(), 4);
EXPECT_TRUE(dut.derivatives().isZero(0.0));
}
constexpr double kInf = std::numeric_limits<double>::infinity();
GTEST_TEST(AutodiffBasicTest, StdTraits) {
// Our AutoDiff implementation of std::numeric_limits is a one-liner, so it's
// sufficient to just spot-check one value. Constants don't have gradients, so
// check that the return type is double.
EXPECT_THAT(std::numeric_limits<AutoDiff>::infinity(),
testing::TypedEq<double>(kInf));
}
GTEST_TEST(AutodiffBasicTest, EigenTraits) {
using NumTraits = Eigen::NumTraits<AutoDiff>;
EXPECT_TRUE(NumTraits::RequireInitialization);
EXPECT_TRUE((std::is_same_v<NumTraits::Real, AutoDiff>));
EXPECT_TRUE((std::is_same_v<NumTraits::NonInteger, AutoDiff>));
EXPECT_TRUE((std::is_same_v<NumTraits::Nested, AutoDiff>));
EXPECT_TRUE((std::is_same_v<NumTraits::Literal, double>));
// Constants don't have gradients, so check that the return type is double.
EXPECT_THAT(NumTraits::infinity(), testing::TypedEq<double>(kInf));
}
} // namespace
} // namespace ad
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/proto/rpc_pipe_temp_directory.cc | #include "drake/common/proto/rpc_pipe_temp_directory.h"
#include <cstdlib>
#include <filesystem>
#include "drake/common/drake_throw.h"
namespace drake {
namespace common {
std::string GetRpcPipeTempDirectory() {
const char* path_str = nullptr;
(path_str = std::getenv("TEST_TMPDIR")) || (path_str = "/tmp");
const std::filesystem::path path(path_str);
DRAKE_THROW_UNLESS(std::filesystem::is_directory(path));
return path.string();
}
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/proto/BUILD.bazel | load("//tools/install:install.bzl", "install")
load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_googletest",
"drake_cc_library",
"drake_cc_package_library",
)
load(
"//tools/skylark:drake_py.bzl",
"drake_py_binary",
"drake_py_library",
"drake_py_unittest",
)
package(default_visibility = ["//visibility:public"])
drake_cc_package_library(
name = "proto",
visibility = ["//visibility:public"],
deps = [
":call_python",
":rpc_pipe_temp_directory",
],
)
drake_cc_library(
name = "call_python",
srcs = ["call_python.cc"],
hdrs = ["call_python.h"],
deps = [
":rpc_pipe_temp_directory",
"//common:essential",
"//lcmtypes:call_python",
],
)
drake_py_library(
name = "call_python_client",
srcs = ["call_python_client.py"],
imports = ["."],
deps = [
"//lcmtypes:lcmtypes_drake_py",
],
)
drake_py_binary(
name = "call_python_client_cli",
srcs = ["call_python_client.py"],
main = "call_python_client.py",
deps = [
":call_python_client",
],
)
drake_cc_library(
name = "rpc_pipe_temp_directory",
srcs = ["rpc_pipe_temp_directory.cc"],
hdrs = ["rpc_pipe_temp_directory.h"],
visibility = ["//visibility:private"],
interface_deps = [],
deps = [
"//common:essential",
],
)
# === test/ ===
drake_cc_googletest(
name = "call_python_server_test",
tags = ["manual"],
deps = [
":call_python",
],
)
# TODO(eric.cousineau): Add a test which will use an interactive matplotlib
# backend on CI only.
drake_py_unittest(
name = "call_python_test",
size = "small",
data = [
":call_python_client_cli",
":call_python_server_test",
],
# TODO(eric.cousineau): Find the source of sporadic CI failures.
flaky = 1,
# We wish to access neighboring files.
isolate = 0,
# Fails when run under Valgrind tools.
tags = ["no_valgrind_tools"],
)
drake_cc_googletest(
name = "rpc_pipe_temp_directory_test",
deps = [
":rpc_pipe_temp_directory",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/proto/call_python_client.py | """
Permits calling arbitrary functions and passing some forms of data from C++
to Python (only one direction) as a server-client pair.
The server in this case is the C++ program, and the client is this binary.
For an example of C++ usage, see `call_python_server_test.cc`.
Here's an example of running with the C++ test program:
cd drake
bazel build //common/proto:call_python_client_cli //common/proto:call_python_server_test # noqa
# Create default pipe file.
rm -f /tmp/python_rpc && mkfifo /tmp/python_rpc
# In Terminal 1, run client.
./bazel-bin/common/proto/call_python_client_cli
# In Terminal 2, run server (or your C++ program).
./bazel-bin/common/proto/call_python_server_test
To use in Jupyter (if you have it installed) without a FIFO file (such that
it's non-blocking):
cd drake
bazel build //common/proto:call_python_client_cli //common/proto:call_python_server_test # noqa
rm -f /tmp/python_rpc # Do not make it FIFO
# In Terminal 1, run server, create output.
./bazel-bin/common/proto/call_python_server_test
# In Terminal 2, run client in notebook.
./bazel-bin/common/proto/call_python_client_cli \
-c jupyter notebook ${PWD}/common/proto/call_python_client_notebook.ipynb # noqa
# Execute: Cell > Run All
Note:
Occasionally, the plotting will not come through on the notebook. I (Eric)
am unsure why.
"""
import argparse
import os
from queue import Queue
import signal
import stat
import sys
from threading import Thread
import time
import traceback
import numpy as np
from drake import lcmt_call_python, lcmt_call_python_data
def _ensure_sigint_handler():
# @ref https://stackoverflow.com/a/47801921/2654527
if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
signal.signal(signal.SIGINT, signal.default_int_handler)
def _get_required_helpers(scope_locals):
# Provides helpers to keep C++ interface as simple as possible.
# @returns Dictionary containing the helpers needed.
def getitem(obj, index):
"""Global function for `obj[index]`. """
return obj[index]
def setitem(obj, index, value):
"""Global function for `obj[index] = value`. """
obj[index] = value
return obj[index]
def call(obj, *args, **kwargs):
return obj(*args, **kwargs)
def pass_through(value):
"""Pass-through for direct variable access. """
return value
def make_tuple(*args):
"""Create a tuple from an argument list. """
return tuple(args)
def make_list(*args):
"""Create a list from an argument list. """
return list(args)
def make_kwargs(*args):
"""Create a keyword argument object from an argument list. """
assert len(args) % 2 == 0
keys = args[0::2]
values = args[1::2]
kwargs = dict(zip(keys, values))
return _KwArgs(**kwargs)
def _make_slice(expr):
"""Parse a slice object from a string. """
def to_piece(s):
return s and int(s) or None
pieces = list(map(to_piece, expr.split(':')))
if len(pieces) == 1:
return slice(pieces[0], pieces[0] + 1)
else:
return slice(*pieces)
def make_slice_arg(*args):
"""Create a scalar or tuple for accessing objects via slices. """
out = [None] * len(args)
for i, arg in enumerate(args):
if isinstance(arg, str):
out[i] = _make_slice(arg)
else:
out[i] = arg
# Special case: If single index, collapse.
if len(out) == 1:
return out[0]
else:
return tuple(out)
def setvar(var, value):
"""Sets a variable in the client's locals. """
scope_locals[var] = value
def setvars(*args):
"""Sets multiple variables in the client's locals. """
scope_locals.update(make_kwargs(*args))
execution_check = _ExecutionCheck()
out = locals().copy()
# Scrub extra stuff.
del out["scope_locals"]
return out
class _KwArgs(dict):
# Indicates values meant solely for `**kwargs`.
pass
class _ExecutionCheck:
# Allows checking that we received and executed a complete set of
# instructions.
def __init__(self):
self.count = 0
def start(self):
self.count += 1
def finish(self):
assert self.count > 0
self.count -= 1
def _merge_dicts(*args):
# Merges a list of dict's.
out = {}
for arg in args:
out.update(arg)
return out
def _fix_pyplot(plt):
# This patches matplotlib/matplotlib#9412 by injecting `time` into the
# module (#7597).
cur = plt.__dict__
if 'time' not in cur:
cur['time'] = time
def default_globals():
"""Creates default globals for code that the client side can execute.
This is geared for convenient (not necessarily efficient) plotting
with `matplotlib`.
"""
# @note This imports modules at a function-scope rather than at a
# module-scope, which does not satisfy PEP8. This is intentional, as it
# allows for a cleaner scope separation between the client core code (e.g.
# `CallPythonClient`) and the client user code (e.g. `plot(x, y)`).
# TODO(eric.cousineau): Consider relegating this to a different module,
# possibly when this falls under `pydrake`.
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
# On Ubuntu the Debian package python3-tk is a recommended (but not
# required) dependency of python3-matplotlib; help users understand that
# by providing a nicer message upon a failure to import.
try:
import matplotlib.pyplot as plt
except ImportError as e:
if e.name == 'tkinter':
plt = None
else:
raise
if plt is None:
raise NotImplementedError(
"On Ubuntu when using the default pyplot configuration (i.e., the"
" TkAgg backend) you must 'sudo apt install python3-tk' to obtain"
" Tk support. Alternatively, you may set MPLBACKEND to something"
" else (e.g., Qt5Agg).")
import pylab # See `%pylab?` in IPython.
# TODO(eric.cousineau): Where better to put this?
matplotlib.interactive(True)
_fix_pyplot(plt)
def disp(value):
"""Alias for print."""
print(value)
def wait():
"""Waits to allow user interaction with plots."""
plt.show(block=True)
def pause(interval):
"""Pause for `interval` seconds, letting the GUI flush its event queue.
@note This is a *necessary* function to be defined if these globals are
not used!
"""
plt.pause(interval)
def box(bmin, bmax, rstride=1, cstride=1, **kwargs):
"""Plots a box bmin[i] <= x[i] <= bmax[i] for i < 3."""
ax = plt.subplot(projection='3d')
u = np.linspace(1, 9, 5) * np.pi / 4
U, V = np.meshgrid(u, u)
cx, cy, cz = (bmax + bmin) / 2
dx, dy, dz = bmax - bmin
X = cx + dx * np.cos(U) * np.sin(V)
Y = cy + dy * np.sin(U) * np.sin(V)
Z = cz + dz * np.cos(V) / np.sqrt(2)
ax.plot_surface(X, Y, Z, rstride=rstride, cstride=cstride, **kwargs)
def plot3(x, y, z, **kwargs):
"""Plots a 3d line plot."""
ax = plt.subplot(projection='3d')
ax.plot(x, y, z, **kwargs)
def sphere(n, rstride=1, cstride=1, **kwargs):
"""Plots a sphere."""
ax = plt.subplot(projection='3d')
u = np.linspace(0, np.pi, n)
v = np.linspace(0, 2 * np.pi, n)
X = np.outer(np.sin(u), np.sin(v))
Y = np.outer(np.sin(u), np.cos(v))
Z = np.outer(np.cos(u), np.ones_like(v))
ax.plot_surface(X, Y, Z, rstride=rstride, cstride=cstride, **kwargs)
def surf(x, y, Z, rstride=1, cstride=1, **kwargs):
"""Plots a 3d surface."""
ax = plt.subplot(projection='3d')
X, Y = np.meshgrid(x, y)
ax.plot_surface(X, Y, Z, rstride=rstride, cstride=cstride, **kwargs)
def show():
"""Shows `matplotlib` images without blocking.
Generally not needed if `matplotlib.is_interactive()` is true.
"""
plt.show(block=False)
def magic(N):
"""Provides simple odd-only case for magic squares.
@ref https://scipython.com/book/chapter-6-numpy/examples/creating-a-magic-square # noqa
"""
assert N % 2 == 1
magic_square = np.zeros((N, N), dtype=int)
n = 1
i, j = 0, N//2
while n <= N**2:
magic_square[i, j] = n
n += 1
newi, newj = (i - 1) % N, (j + 1) % N
if magic_square[newi, newj]:
i += 1
else:
i, j = newi, newj
return magic_square
# Use <module>.__dict__ to simulate `from <module> import *`, since that is
# normally invalid in a function with nested functions.
return _merge_dicts(
globals(),
plt.__dict__,
pylab.__dict__,
locals())
class CallPythonClient:
"""Provides a client to receive Python commands.
Enables printing or plotting from a C++ application for debugging
purposes.
"""
def __init__(self, filename=None, stop_on_error=True,
scope_globals=None, scope_locals=None,
threaded=False, wait=False):
if filename is None:
# TODO(jamiesnape): Implement and use a
# drake.common.GetRpcPipeTempDirectory function.
temp_directory = os.environ.get("TEST_TMPDIR", "/tmp")
self.filename = os.path.join(temp_directory, "python_rpc")
else:
self.filename = filename
# Scope. Give it access to everything here.
# However, keep it's written values scoped.
if scope_locals is None:
self.scope_locals = {}
else:
self.scope_locals = scope_locals
# Define globals as (a) required helpers for C++ interface, and
# (b) convenience plotting functionality.
# N.B. The provided locals OR globals can shadow the helpers. BE
# CAREFUL!
required_helpers = _get_required_helpers(self.scope_locals)
if scope_globals is None:
scope_globals = default_globals()
self.scope_globals = _merge_dicts(required_helpers, scope_globals)
self._stop_on_error = stop_on_error
self._threaded = threaded
self._loop = False
self._wait = False
if wait:
if _is_fifo(self.filename):
self._loop = True
print("Looping for FIFO file (wait=True).")
else:
self._wait = True
print("Waiting after processing non-FIFO file (wait=True).")
# Variables indexed by GUID.
self._client_vars = {}
self._had_error = False
self._done = False
self._file = None
def _to_array(self, arg, dtype):
# Converts a lcmt_call_python argument to the appropriate NumPy array
# (or scalar).
np_raw = np.frombuffer(arg.data, dtype=dtype)
if arg.shape_type == lcmt_call_python_data.SCALAR:
assert arg.cols == 1 and arg.rows == 1
return np_raw[0]
elif arg.shape_type == lcmt_call_python_data.VECTOR:
assert arg.cols == 1
return np_raw.reshape(arg.rows)
elif arg.shape_type is None or \
arg.shape_type == lcmt_call_python_data.MATRIX:
# TODO(eric.cousineau): Figure out how to ensure `np.frombuffer`
# creates a column-major array?
return np_raw.reshape(arg.cols, arg.rows).T
def _execute_message(self, msg):
# Executes a message, handling / recording that an error occurred.
if self._stop_on_error:
# Do not wrap in a `try` / `catch` to simplify debugging.
self._execute_message_impl(msg)
else:
try:
self._execute_message_impl(msg)
except Exception as e:
traceback.print_exc(file=sys.stderr)
sys.stderr.write(" Continuing (no --stop_on_error)\n")
self._had_error = True
def _execute_message_impl(self, msg):
# Executes relevant portions of a message.
# Create input arguments.
inputs = []
kwargs = None
for i, arg in enumerate(msg.rhs):
value = None
if (arg.data_type
== lcmt_call_python_data.REMOTE_VARIABLE_REFERENCE):
id = np.frombuffer(arg.data, dtype=np.uint64).reshape(1)[0]
if id not in self._client_vars:
raise RuntimeError("Unknown local variable. "
"Dropping message.")
value = self._client_vars[id]
elif arg.data_type == lcmt_call_python_data.DOUBLE:
value = self._to_array(arg, np.double)
elif arg.data_type == lcmt_call_python_data.CHAR:
assert arg.rows == 1
value = arg.data.decode('utf8')
elif arg.data_type == lcmt_call_python_data.LOGICAL:
value = self._to_array(arg, bool)
elif arg.data_type == lcmt_call_python_data.INT:
value = self._to_array(arg, np.int32)
else:
assert False
if isinstance(value, _KwArgs):
assert kwargs is None
kwargs = value
else:
inputs.append(value)
# Call the function
# N.B. No security measures to sanitize function name.
function_name = msg.function_name
assert isinstance(function_name, str), type(function_name)
self.scope_locals.update(_tmp_args=inputs, _tmp_kwargs=kwargs or {})
# N.B. No try-catch block here. Can change this if needed.
if function_name == "exec":
assert len(inputs) == 1
assert kwargs is None or len(kwargs) == 0
# Merge globals and locals so that any functions or lambdas can
# have closures that refer to locals. For more information, see
# https://stackoverflow.com/a/28951271/7829525
globals_and_locals = _merge_dicts(
self.scope_globals, self.scope_locals)
exec(inputs[0], globals_and_locals, self.scope_locals)
out = None
else:
out = eval(function_name + "(*_tmp_args, **_tmp_kwargs)",
self.scope_globals, self.scope_locals)
self.scope_locals.update(_tmp_out=out)
# Update outputs.
self._client_vars[msg.lhs] = out
def run(self):
"""Runs the client code.
@return True if no error encountered.
"""
if self._threaded:
self._handle_messages_threaded()
else:
self.handle_messages(record=False)
# Check any execution in progress.
execution_check = self.scope_globals['execution_check']
if not self._had_error and execution_check.count != 0:
self._had_error = True
sys.stderr.write(
"ERROR: Invalid termination. "
"'execution_check.finish' called insufficient number of "
"times: {}\n".format(execution_check.count))
if self._wait and not self._had_error:
wait_func = self.scope_globals["wait"]
wait_func()
return not self._had_error
def _handle_messages_threaded(self):
# Handles messages in a threaded fashion.
queue = Queue()
def producer_loop():
# Read messages from file, and queue them for execution.
for msg in self._read_next_message():
queue.put(msg)
# Check if an error occurred.
if self._done:
break
# Wait until the queue empties out to signal completion from the
# producer's side.
if not self._done:
queue.join()
self._done = True
producer = Thread(name="Producer", target=producer_loop)
# @note Previously, when trying to do `queue.clear()` in the consumer,
# and `queue.join()` in the producer, there would be intermittent
# deadlocks. By demoting the producer to a daemon, I (eric.c) have not
# yet encountered a deadlock.
producer.daemon = True
producer.start()
# Consume.
# TODO(eric.cousineau): Trying to quit via Ctrl+C is awkward (but kinda
# works). Is there a way to have `plt.pause` handle Ctrl+C differently?
try:
pause = self.scope_globals['pause']
while not self._done:
# Process messages.
while not queue.empty():
msg = queue.get()
queue.task_done()
self._execute_message(msg)
# Spin busy for a bit, let matplotlib (or whatever) flush its
# event queue.
pause(0.01)
except KeyboardInterrupt:
# User pressed Ctrl+C.
self._done = True
print("Quitting")
except Exception as e:
# We encountered an error, and must stop.
self._done = True
self._had_error = True
traceback.print_exc(file=sys.stderr)
sys.stderr.write(" Stopping (--stop_on_error)\n")
# No need to worry about waiting for the producer, as it is a daemon
# thread.
def handle_messages(self, max_count=None, record=True, execute=True):
"""Handle all messages sent (e.g., through IPython).
@param max_count Maximum number of messages to handle.
@param record Record all messages and return them.
@param execute Execute the given message upon receiving it.
@return (count, msgs) where `count` is how many messages were processed
(e.g. 0 if no more messages left).
and `msgs` are either the messages themselves for playback.
and (b) the messages themselves for playback (if record==True),
otherwise an empty list.
"""
assert record or execute, "Not doing anything useful?"
count = 0
msgs = []
for msg in self._read_next_message():
if execute:
self._execute_message(msg)
count += 1
if record:
msgs.append(msg)
if max_count is not None and count >= max_count:
break
return (count, msgs)
def execute_messages(self, msgs):
"""Executes a set of recorded messages."""
for msg in msgs:
self._execute_message(msg)
def _read_next_message(self):
"""Returns incoming messages using a generator."""
while not self._done:
fifo = self._get_file()
# Close the file if we reach the end, NOT when exiting the scope
# (which is why `with` is not used here).
# This way the user can read a few messages at a time, with the
# same file handle.
# @note We must close / reopen the file when looping because the
# C++ program will effectively send a EOF signal when it closes
# the pipe.
while not self._done:
message = self._read_fifo_message(fifo)
if message is not None:
yield message
self._close_file()
if not self._loop:
break
def _read_fifo_message(self, fifo):
"""Reads at most one message from the given fifo."""
# Read the datagram size. (The C++ code encodes the datagram_size
# integer as an ASCII string.)
datagram_size = None
buffer = bytearray()
while not self._done:
byte = fifo.read(1)
if not byte: # EOF
return None
if byte == b'\0': # EOM
datagram_size = int(buffer.decode())
break
else:
buffer.extend(byte)
# Read the payload.
buffer[:] = ()
while not self._done:
byte = fifo.read(1)
if not byte: # EOF
return None
buffer.extend(byte)
if len(buffer) == datagram_size:
byte = fifo.read(1)
assert byte == b'\0' # EOM
return lcmt_call_python.decode(bytes(buffer))
def _get_file(self):
# Gets file handle, opening if needed.
if self._file is None:
self._file = open(self.filename, 'rb')
return self._file
def _close_file(self):
# Closes file if open.
if self._file is not None:
self._file.close()
self._file = None
def _is_fifo(filepath):
# Determine if a file is a FIFO named pipe or not.
# @ref https://stackoverflow.com/a/8558940/7829525
return stat.S_ISFIFO(os.stat(filepath).st_mode)
def main(argv):
_ensure_sigint_handler()
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
"--no_wait", action='store_true',
help="Close client after messages are processed. "
"For FIFO, this means the client will close after the C++ "
"binary is executed once.")
parser.add_argument(
"--no_threading", action='store_true',
help="Disable threaded dispatch.")
parser.add_argument(
"--stop_on_error", action='store_true',
help="Stop client if there is an error when executing a call.")
parser.add_argument("-f", "--file", type=str, default=None)
parser.add_argument(
"-c", "--command", type=str, nargs='+', default=None,
help="Execute command (e.g. `jupyter notebook`) instead of running "
"client.")
args = parser.parse_args(argv)
if args.command is not None:
# Execute command s.t. it has access to the relevant PYTHNOPATH.
os.execvp(args.command[0], args.command)
# Control should not return to this program unless there was an error.
return False
else:
client = CallPythonClient(
args.file, stop_on_error=args.stop_on_error,
threaded=not args.no_threading, wait=not args.no_wait)
good = client.run()
return good
if __name__ == "__main__":
good = main(sys.argv[1:])
if not good:
exit(1)
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/proto/call_python.h | #pragma once
#include <string>
#include "drake/common/eigen_types.h"
#include "drake/lcmt_call_python.hpp"
/// @file
/// Utilities for calling Python from C++ over an RPC.
///
/// For command-line examples, see the documentation in `call_python_client.py`.
/// For C++ examples, see `call_python_test.cc`.
namespace drake {
namespace common {
/// Initializes `CallPython` for a given file. If this function is not called,
/// then the filename defaults to `/tmp/python_rpc`.
/// @throws std::exception If either this function or `CallPython` have
/// already been called.
void CallPythonInit(const std::string& filename);
/// A proxy to a variable stored in Python side.
class PythonRemoteVariable;
/// Calls a Python client with a given function and arguments, returning
/// a handle to the result. For example uses, see `call_python_test.cc`.
template <typename... Types>
PythonRemoteVariable CallPython(const std::string& function_name,
Types... args);
/// Creates a tuple in Python.
template <typename... Types>
PythonRemoteVariable ToPythonTuple(Types... args);
/// Creates a keyword-argument list to be unpacked.
/// @param args Argument list in the form of (key1, value1, key2, value2, ...).
template <typename... Types>
PythonRemoteVariable ToPythonKwargs(Types... args);
// ===========================================================================
// All code below this point is implementation details.
// ===========================================================================
#ifndef DRAKE_DOXYGEN_CXX
namespace internal {
class PythonItemPolicy;
class PythonAttrPolicy;
template <typename Policy>
class PythonAccessor;
using PythonItemAccessor = PythonAccessor<PythonItemPolicy>;
using PythonAttrAccessor = PythonAccessor<PythonAttrPolicy>;
// Mimic pybind11's `object_api` and `accessor<>` setup, such that we can
// chain operations together more conveniently.
template <typename Derived>
class PythonApi {
public:
/// Calls object with given arguments, returning the remote result.
template <typename... Types>
PythonRemoteVariable operator()(Types... args) const;
/// Accesses an attribute.
PythonAttrAccessor attr(const std::string& name) const;
/// Accesses an item.
template <typename Type>
PythonItemAccessor operator[](Type key) const;
/// Accesses a NumPy-friendly slice.
template <typename... Types>
PythonItemAccessor slice(Types... args) const;
private:
// Provides type-cast view for CRTP implementation.
const Derived& derived() const {
return static_cast<const Derived&>(*this);
}
};
} // namespace internal
class PythonRemoteVariable : public internal::PythonApi<PythonRemoteVariable> {
public:
PythonRemoteVariable();
// TODO(eric.cousineau): To support deletion, disable copy constructor, only
// allow moving (if we want to avoid needing a global reference counter).
int64_t unique_id() const { return unique_id_; }
private:
const int64_t unique_id_{};
};
namespace internal {
/// Creates a new remote variable with the corresponding value set.
template <typename T>
PythonRemoteVariable NewPythonVariable(T value) {
return CallPython("pass_through", value);
}
// Gets/sets an object's attribute.
class PythonAttrPolicy {
public:
using KeyType = std::string;
static PythonRemoteVariable get(PythonRemoteVariable obj,
const KeyType& key) {
return CallPython("getattr", obj, key);
}
static PythonRemoteVariable set(PythonRemoteVariable obj,
const KeyType& key,
PythonRemoteVariable value) {
return CallPython("setattr", obj, key, value);
}
};
// Gets/sets an object's item.
class PythonItemPolicy {
public:
using KeyType = PythonRemoteVariable;
static PythonRemoteVariable get(PythonRemoteVariable obj,
const KeyType& key) {
return CallPython("getitem", obj, key);
}
static PythonRemoteVariable set(PythonRemoteVariable obj,
const KeyType& key,
PythonRemoteVariable value) {
return CallPython("setitem", obj, key, value);
}
};
// API-consistent mechanism to access a portion of an object (item or attr).
template <typename Policy>
class PythonAccessor : public PythonApi<PythonAccessor<Policy>> {
public:
using KeyType = typename Policy::KeyType;
// Given a variable (and key), makes a PythonAccessor.
PythonAccessor(PythonRemoteVariable obj, const KeyType& key)
: obj_(obj), key_(key) {}
// Copying a PythonAccessor aliases the original remote variable (reference
// semantics), it does not create a new remote variable.
PythonAccessor(const PythonAccessor&) = default;
// Implicitly converts to a PythonRemoteVariable.
operator PythonRemoteVariable() const { return value(); }
// Assigning from another PythonAccessor delegates to set_value from that
// `value`'s underlying PythonRemoteVariable.
PythonRemoteVariable operator=(const PythonAccessor& value) {
return set_value(value);
}
// Assigning from another PythonRemoteVariable delegates to set_value from it.
PythonRemoteVariable operator=(const PythonRemoteVariable& value) {
return set_value(value);
}
// Assigning from some literal value creates a new PythonRemoveVariable to
// bind the value.
template <typename T>
PythonRemoteVariable operator=(const T& value) {
return set_value(NewPythonVariable(value));
}
private:
PythonRemoteVariable value() const { return Policy::get(obj_, key_); }
PythonRemoteVariable set_value(const PythonRemoteVariable& value) const {
return Policy::set(obj_, key_, value);
}
PythonRemoteVariable obj_;
KeyType key_;
};
// Now that we have our types defined, we can implement the functionality for
// the API.
template <typename Derived>
PythonAttrAccessor PythonApi<Derived>::attr(const std::string& name) const {
return {derived(), name};
}
template <typename Derived>
template <typename... Types>
PythonRemoteVariable PythonApi<Derived>::operator()(Types... args) const {
return CallPython("call", derived(), args...);
}
template <typename Derived>
template <typename Type>
PythonItemAccessor PythonApi<Derived>::operator[](Type key) const {
return {derived(), NewPythonVariable(key)};
}
template <typename Derived>
template <typename... Types>
PythonItemAccessor PythonApi<Derived>::slice(Types... args) const {
return {derived(), CallPython("make_slice_arg", args...)};
}
void ToPythonRemoteData(const PythonRemoteVariable&,
lcmt_call_python_data*);
template <typename Derived>
void ToPythonRemoteData(const Eigen::MatrixBase<Derived>&,
lcmt_call_python_data*);
void ToPythonRemoteData(double scalar,
lcmt_call_python_data*);
void ToPythonRemoteData(int scalar,
lcmt_call_python_data*);
void ToPythonRemoteData(const std::string&, lcmt_call_python_data*);
void ToPythonRemoteDataMatrix(const Eigen::Ref<const MatrixX<bool>>&,
lcmt_call_python_data*, bool is_vector);
void ToPythonRemoteDataMatrix(const Eigen::Ref<const Eigen::MatrixXd>&,
lcmt_call_python_data*, bool is_vector);
void ToPythonRemoteDataMatrix(const Eigen::Ref<const Eigen::MatrixXi>&,
lcmt_call_python_data*, bool is_vector);
template <typename Derived>
void ToPythonRemoteData(const Eigen::MatrixBase<Derived>& mat,
lcmt_call_python_data* message) {
const bool is_vector = (Derived::ColsAtCompileTime == 1);
return ToPythonRemoteDataMatrix(mat, message, is_vector);
}
inline void AssembleRemoteMessage(lcmt_call_python*) {
// Intentionally left blank. Base case for template recursion.
}
template <typename T, typename... Types>
void AssembleRemoteMessage(lcmt_call_python* message, T first,
Types... args) {
message->rhs.emplace_back();
ToPythonRemoteData(first, &(message->rhs.back()));
AssembleRemoteMessage(message, args...);
}
void PublishCallPython(const lcmt_call_python& message);
} // namespace internal
// These items are forward-declared atop the file.
template <typename... Types>
PythonRemoteVariable CallPython(const std::string& function_name,
Types... args) {
PythonRemoteVariable output;
lcmt_call_python message{};
message.lhs = output.unique_id();
internal::AssembleRemoteMessage(&message, args...);
message.num_rhs = message.rhs.size();
message.function_name = function_name;
internal::PublishCallPython(message);
return output;
}
template <typename... Types>
PythonRemoteVariable ToPythonTuple(Types... args) {
return CallPython("make_tuple", args...);
}
template <typename... Types>
PythonRemoteVariable ToPythonKwargs(Types... args) {
return CallPython("make_kwargs", args...);
}
#endif // DRAKE_DOXYGEN_CXX
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/proto/call_python_client_notebook.ipynb | # N.B. Explicitly initialize backend. Otherwise, plots may not show up the
# first time.
%matplotlib inline# Example Python client.
from drake.common.proto.call_python_client import CallPythonClient# Using `locals()` permits the C++ client to use functions defined here
# and overwrite variables.
client = CallPythonClient(scope_locals=locals())
client.run()# Print some values.
print(b1) | 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/proto/rpc_pipe_temp_directory.h | #pragma once
#include <string>
namespace drake {
namespace common {
/// Returns a directory location suitable for temporary files for the call_*
/// clients and libraries.
/// @return The value of the environment variable TEST_TMPDIR if defined or
/// otherwise /tmp. Any trailing / will be stripped from the output.
/// @throws std::exception If the path referred to by TEST_TMPDIR or /tmp
/// does not exist or is not a directory.
std::string GetRpcPipeTempDirectory();
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/proto/call_python.cc | #include "drake/common/proto/call_python.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <cstring>
#include <fstream>
#include <limits>
#include <memory>
#include <optional>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/proto/rpc_pipe_temp_directory.h"
namespace drake {
namespace common {
static int py_globally_unique_id = 0;
PythonRemoteVariable::PythonRemoteVariable()
: unique_id_(py_globally_unique_id++)
{}
namespace internal {
// Copies `size` bytes at `data` into `message->data`.
void CopyBytes(const void* bytes, const int size,
lcmt_call_python_data* message) {
message->num_bytes = size;
message->data.resize(size);
std::memcpy(message->data.data(), bytes, size);
}
void ToPythonRemoteData(const PythonRemoteVariable& variable,
lcmt_call_python_data* message) {
message->data_type = lcmt_call_python_data::REMOTE_VARIABLE_REFERENCE;
message->shape_type = lcmt_call_python_data::SCALAR;
message->rows = 1;
message->cols = 1;
int64_t uid = variable.unique_id();
CopyBytes(&uid, sizeof(uid), message);
}
void ToPythonRemoteData(double scalar, lcmt_call_python_data* message) {
message->data_type = lcmt_call_python_data::DOUBLE;
message->shape_type = lcmt_call_python_data::SCALAR;
message->rows = 1;
message->cols = 1;
CopyBytes(&scalar, sizeof(scalar), message);
}
void ToPythonRemoteData(int scalar, lcmt_call_python_data* message) {
message->data_type = lcmt_call_python_data::INT;
message->shape_type = lcmt_call_python_data::SCALAR;
message->rows = 1;
message->cols = 1;
CopyBytes(&scalar, sizeof(scalar), message);
}
void ToPythonRemoteData(const std::string& str,
lcmt_call_python_data* message) {
message->data_type = lcmt_call_python_data::CHAR;
message->shape_type = lcmt_call_python_data::VECTOR;
message->rows = 1;
message->cols = str.length();
CopyBytes(str.data(), str.size(), message);
}
void ToPythonRemoteDataMatrix(const Eigen::Ref<const MatrixX<bool>>& mat,
lcmt_call_python_data* message, bool is_vector) {
message->data_type = lcmt_call_python_data::LOGICAL;
message->shape_type =
is_vector ? lcmt_call_python_data::VECTOR : lcmt_call_python_data::MATRIX;
message->rows = mat.rows();
message->cols = mat.cols();
int num_bytes = sizeof(bool) * mat.rows() * mat.cols();
CopyBytes(mat.data(), num_bytes, message);
}
void ToPythonRemoteDataMatrix(const Eigen::Ref<const Eigen::MatrixXd>& mat,
lcmt_call_python_data* message, bool is_vector) {
message->data_type = lcmt_call_python_data::DOUBLE;
message->shape_type =
is_vector ? lcmt_call_python_data::VECTOR : lcmt_call_python_data::MATRIX;
message->rows = mat.rows();
message->cols = mat.cols();
int num_bytes = sizeof(double) * mat.rows() * mat.cols();
CopyBytes(mat.data(), num_bytes, message);
}
void ToPythonRemoteDataMatrix(
const Eigen::Ref<const Eigen::MatrixXi>& mat,
lcmt_call_python_data* message, bool is_vector) {
message->data_type = lcmt_call_python_data::INT;
message->shape_type =
is_vector ? lcmt_call_python_data::VECTOR : lcmt_call_python_data::MATRIX;
message->rows = mat.rows();
message->cols = mat.cols();
int num_bytes = sizeof(int) * mat.rows() * mat.cols();
CopyBytes(mat.data(), num_bytes, message);
}
} // namespace internal
namespace {
// Latch-initialize the ofstream output that writes to the python client.
// The return value is a long-lived pointer to a singleton.
std::ofstream* InitOutput(const std::optional<std::string>& filename) {
static never_destroyed<std::unique_ptr<std::ofstream>> raw_output;
if (!raw_output.access()) {
// If we do not yet have a file, create it.
const std::string filename_default
= GetRpcPipeTempDirectory() + "/python_rpc";
const std::string filename_actual = filename ? *filename : filename_default;
raw_output.access() = std::make_unique<std::ofstream>(filename_actual);
} else {
// If we already have a file, ensure that this does not come from
// `CallPythonInit`.
if (filename) {
throw std::runtime_error(
"`CallPython` or `CallPythonInit` has already been called");
}
}
return raw_output.access().get();
}
void PublishCall(std::ofstream* stream_arg, const lcmt_call_python& message) {
DRAKE_DEMAND(stream_arg != nullptr);
std::ofstream& stream = *stream_arg;
const int num_bytes = message.getEncodedSize();
DRAKE_DEMAND(num_bytes >= 0);
const size_t size_bytes = static_cast<size_t>(num_bytes);
std::vector<uint8_t> encoded(size_bytes);
message.encode(encoded.data(), 0, num_bytes);
stream << size_bytes;
stream << '\0';
const void* const data = encoded.data();
stream.write(static_cast<const char*>(data), encoded.size());
stream << '\0';
stream.flush();
}
} // namespace
void CallPythonInit(const std::string& filename) {
InitOutput(filename);
}
void internal::PublishCallPython(const lcmt_call_python& message) {
static const never_destroyed<std::ofstream*> output{InitOutput(std::nullopt)};
PublishCall(output.access(), message);
}
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/proto | /home/johnshepherd/drake/common/proto/test/call_python_server_test.cc | #include <chrono>
#include <cmath>
#include <string>
#include <thread>
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include "drake/common/proto/call_python.h"
// N.B. The following flags are used for testing only, and are not necessary if
// you are writing your own client.
DEFINE_string(file, "/tmp/python_rpc",
"File written to by this binary, read by client.");
// This file signals to `call_python_full_test.sh` that a full execution has
// been completed. This is useful for the `threading-loop` case, where we want
// send a Ctrl+C interrupt only when finished.
DEFINE_string(done_file, "/tmp/python_rpc_done",
"Signifies last Python command has been executed.");
// Ensure that we test error behavior.
DEFINE_bool(with_error, false, "Inject an error towards the end.");
DEFINE_bool(sleep_at_end, false,
"Sleep at end to check behavior of C++ if the Python client "
"fails.");
// TODO(eric.cousineau): Instrument client to verify output (and make this a
// unittest).
namespace drake {
namespace common {
// N.B. This is NOT necessary for normal use; it is only done for testing.
// If you use any `CallPython` calls prior to `CallPythonInit`, then the
// default pipe will be used.
GTEST_TEST(TestCallPython, Start) {
CallPythonInit(FLAGS_file);
// Tell client to expect a finishing signal.
CallPython("execution_check.start");
}
GTEST_TEST(TestCallPython, DispStr) {
CallPython("print", "Hello");
CallPython("disp", "World");
}
GTEST_TEST(TestCallPython, CheckKwargs) {
// Ensure that we can create dict with Kwargs (MATLAB-style of arguments).
auto out = CallPython("dict", ToPythonKwargs("a", 2, "b", "hello"));
CallPython("print", out);
}
GTEST_TEST(TestCallPython, SetVar) {
CallPython("setvar", "example_var", "Howdy");
// Execute code printing the value.
CallPython("eval", "print(example_var)");
// Print a letter.
CallPython("print", CallPython("eval", "example_var")[2]);
// Print all variables available.
CallPython("print", CallPython("locals").attr("keys")());
}
GTEST_TEST(TestCallPython, DispEigenMatrix) {
Eigen::Matrix2d m;
m << 1, 2, 3, 4;
CallPython("print", m);
Eigen::Matrix<bool, 2, 2> b;
b << true, false, true, false;
CallPython("print", b);
}
GTEST_TEST(TestCallPython, RemoteVarTest) {
auto magic = CallPython("magic", 3);
// N.B. `var.slice(x, y, ...)` and `var[x][y]...` should be interchangeable if
// you are dealing with NumPy matrices; however, `slice(...)` will allow
// strings to be specified for slices (e.g. ":", ":-2", "::-1").
CallPython("print", magic);
CallPython("print", "element(0,0) is ");
CallPython("print", magic[0][0]);
CallPython("print", "element(2,1) is ");
// Show using both `operator[]` and `.slice`.
CallPython("print", magic[2][1]);
CallPython("print", magic.slice(2, 1));
CallPython("print", "elements ([0, 2]) are");
CallPython("print", magic.slice(Eigen::Vector2i(0, 2)));
CallPython("print", "row 2 is ");
CallPython("print", magic.slice(2, ":"));
CallPython("print", "rows [0, 1] are");
CallPython("print", magic[Eigen::VectorXi::LinSpaced(2, 0, 1)]);
CallPython("print", "row 1 (accessed via logicals) is");
CallPython("print", magic.slice(Vector3<bool>(false, true, false), ":"));
// Place error code toward the end, so that the test fails if this is not
// processed.
if (FLAGS_with_error) {
CallPython("bad_function_name");
}
CallPython("print", "Third column should now be [1, 2, 3]: ");
magic.slice(":", 2) = Eigen::Vector3d(1, 2, 3);
CallPython("print", magic);
// Send variables in different ways.
CallPython("print", "Variable setting:");
CallPython("setvar", "a1", "abc");
CallPython("setvars", "a2", "def", "a3", "ghi");
CallPython("exec", "a4 = 'jkl'");
CallPython("locals")["a5"] = "mno";
CallPython("locals").attr("update")(ToPythonKwargs("a6", "pqr"));
CallPython("eval", "print(a1 + a2 + a3 + a4 + a5 + a6)");
// Test deleting variables.
CallPython("exec", "assert 'a6' in locals()");
CallPython("exec", "del a6");
CallPython("exec", "assert 'a6' not in locals()");
CallPython("print", "Deleted variable");
// Test primitive assignment.
CallPython("setvar", "b1", 10);
CallPython("exec", "b1 += 20");
CallPython("exec", "assert b1 == 30");
// Test defining function with closure.
CallPython("exec", "def my_func(x): return x + b1");
CallPython("exec", "my_func(10) == 40");
// - with mutation (closure of mutable object by reference).
CallPython("exec", "items = []");
CallPython("exec", "def add_item(x): items.append(x)");
CallPython("exec", "add_item(1); add_item(2)");
CallPython("exec", "assert items == [1, 2]");
}
GTEST_TEST(TestCallPython, Plot2d) {
const int N = 100;
Eigen::VectorXd time(N), val(N);
for (int i = 0; i < N; i++) {
time[i] = 0.01 * i;
val[i] = sin(2 * M_PI * time[i]);
}
CallPython("print", "Plotting a sine wave.");
CallPython("figure", 1);
CallPython("clf");
CallPython("plot", time, val);
// Send variables.
CallPython("setvars", "time", time, "val", val);
CallPython("eval", "print(len(time) + len(val))");
}
GTEST_TEST(TestCallPython, Plot3d) {
const int N = 25, M = 35;
Eigen::VectorXd x(N), y(M);
Eigen::MatrixXd Z(M, N);
for (int i = 0; i < N; i++) {
x(i) = -3.0 + 6.0 * i / (N - 1);
}
for (int i = 0; i < M; i++) {
y(i) = -3.0 + 6.0 * i / (M - 1);
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
Z(j, i) = 3 * pow(1 - x(i), 2) * exp(-pow(x(i), 2) - pow(y(j) + 1, 2)) -
10 * (x(i) / 5 - pow(x(i), 3) - pow(y(j), 5)) *
exp(-pow(x(i), 2) - pow(y(j), 2)) -
1.0 / 3.0 * exp(-pow(x(i) + 1, 2) - pow(y(j), 2));
}
}
CallPython("print", "Plotting a simple 3D surface");
CallPython("figure", 2);
CallPython("clf");
CallPython("surf", x, y, Z);
// Send variables.
CallPython("setvars", "x", x, "y", y, "Z", Z);
CallPython("eval", "print(len(x) + len(y) + len(Z))");
}
// N.B. This is NOT necessary for normal use; it is only done for testing.
GTEST_TEST(TestCallPython, Finish) {
if (FLAGS_sleep_at_end) {
// If the Python client closes before this program closes the FIFO pipe,
// then this executable should receive a SIGPIPE signal (and fail).
// Sleeping here simulates this condition for manual testing.
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// Signal finishing to client.
CallPython("execution_check.finish");
// Signal finishing to `call_python_full_test.sh`.
// Use persistence to increment the number of times this has been executed.
CallPython("setvar", "done_file", FLAGS_done_file);
CallPython("exec", R"""(
if 'done_count' in locals():
done_count += 1
else:
done_count = 1
with open(done_file, 'w') as f:
f.write(str(done_count))
)""");
}
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/proto | /home/johnshepherd/drake/common/proto/test/rpc_pipe_temp_directory_test.cc | #include "drake/common/proto/rpc_pipe_temp_directory.h"
#include <cstdlib>
#include <string>
#include <gtest/gtest.h>
namespace drake {
namespace common {
namespace {
GTEST_TEST(RpcPipeTempDirectoryTest, TestTmpdirSet) {
const char* test_tmpdir = std::getenv("TEST_TMPDIR");
ASSERT_STRNE(nullptr, test_tmpdir);
const std::string temp_directory_with_test_tmpdir_set
= GetRpcPipeTempDirectory();
EXPECT_NE('/', temp_directory_with_test_tmpdir_set.back());
EXPECT_EQ(std::string(test_tmpdir), temp_directory_with_test_tmpdir_set);
}
GTEST_TEST(RpcPipeTempDirectoryTest, TestTmpdirUnset) {
const char* test_tmpdir = std::getenv("TEST_TMPDIR");
ASSERT_STRNE(nullptr, test_tmpdir);
const int unset_result = ::unsetenv("TEST_TMPDIR");
ASSERT_EQ(0, unset_result);
const std::string temp_directory_with_test_tmpdir_unset
= GetRpcPipeTempDirectory();
EXPECT_EQ("/tmp", temp_directory_with_test_tmpdir_unset);
const int setenv_result = ::setenv("TEST_TMPDIR", test_tmpdir, 1);
ASSERT_EQ(0, setenv_result);
}
} // namespace
} // namespace common
} // namespace drake
| 0 |
/home/johnshepherd/drake/common/proto | /home/johnshepherd/drake/common/proto/test/call_python_test.py | """Tests the `call_python_client` CLI and `call_python_server_test`
together."""
from contextlib import contextmanager
import os
import signal
import subprocess
import time
import unittest
@contextmanager
def scoped_file(filepath, is_fifo=False):
# Ensures a file does not exist, creates it, and then destroys it upon
# exiting the context.
assert not os.path.exists(filepath)
try:
if is_fifo:
os.mkfifo(filepath)
else:
with open(filepath, 'w'):
pass
yield
finally:
os.unlink(filepath)
assert "TEST_TMPDIR" in os.environ, "Must run under `bazel test`"
# TODO(eric.cousineau): See if it's possible to make test usefully pass for
# "Template" backend.
os.environ["MPLBACKEND"] = "ps"
SIGPIPE_STATUS = 141
cur_dir = os.path.dirname(os.path.abspath(__file__))
# N.B. Need parent directories because this is under `test/*.py`, but the
# Bazel-generated script is one level above.
server_bin = os.path.join(cur_dir, "../call_python_server_test")
client_bin = os.path.join(cur_dir, "../call_python_client_cli")
file = os.path.join(os.environ["TEST_TMPDIR"], "python_rpc")
done_file = file + "_done"
def wait_for_done_count(num_expected, attempt_max=1000):
done_count = -1
attempt = 0
values_read = set()
while done_count < num_expected:
with open(done_file) as f:
try:
done_count = int(f.read().strip())
except ValueError:
pass
if done_count >= 0:
values_read.add(done_count)
time.sleep(0.005)
attempt += 1
if attempt == attempt_max:
raise RuntimeError(
"Did not get updated 'done count'. Read values: {}"
.format(values_read))
class TestCallPython(unittest.TestCase):
def run_server_and_client(self, with_error):
"""Runs and tests server and client in parallel."""
server_flags = ["--file=" + file, "--done_file=" + done_file]
client_flags = ["--file=" + file]
if with_error:
server_flags += ["--with_error"]
client_flags += ["--stop_on_error"]
with scoped_file(file, is_fifo=True), scoped_file(done_file):
with open(done_file, 'w') as f:
f.write("0\n")
# Start client.
client = subprocess.Popen([client_bin] + client_flags)
# Start server.
server = subprocess.Popen([server_bin] + server_flags)
# Join with processes, check return codes.
server_valid_statuses = [0]
if with_error:
# If the C++ binary has not finished by the time the Python
# client exits due to failure, then the C++ binary will fail
# with SIGPIPE.
server_valid_statuses.append(SIGPIPE_STATUS)
self.assertIn(server.wait(), server_valid_statuses)
if not with_error:
# Execute once more.
server = subprocess.Popen([server_bin] + server_flags)
self.assertIn(server.wait(), server_valid_statuses)
# Wait until the client has indicated that the server process
# has run twice. We want to run twice to ensure that looping on
# the client end runs correctly.
wait_for_done_count(2)
client.send_signal(signal.SIGINT)
client_status = client.wait()
self.assertEqual(client_status, int(with_error))
def test_help(self):
text = subprocess.check_output(
[client_bin, "--help"], stderr=subprocess.STDOUT).decode("utf8")
# Print output, since `assertIn` does not provide user-friendly
# multiline error messages.
print(text)
self.assertTrue("Here's an example" in text)
def test_basic(self):
for with_error in [False, True]:
print("[ with_error: {} ]".format(with_error))
self.run_server_and_client(with_error)
# TODO(eric.cousineau): Cover other use cases if it's useful, or prune
# them from the code.
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/schema/rotation.cc | #include "drake/common/schema/rotation.h"
#include "drake/common/drake_throw.h"
#include "drake/common/overloaded.h"
#include "drake/math/random_rotation.h"
#include "drake/math/rotation_matrix.h"
namespace drake {
namespace schema {
using symbolic::Expression;
Rotation::Rotation(const math::RotationMatrix<double>& arg)
: Rotation(math::RollPitchYaw<double>(arg)) {}
Rotation::Rotation(const math::RollPitchYaw<double>& arg) {
const Eigen::Vector3d rpy_rad = arg.vector();
set_rpy_deg(rpy_rad * 180 / M_PI);
}
bool Rotation::IsDeterministic() const {
return std::visit<bool>(overloaded{
[](const Identity&) {
return true;
},
[](const Rpy& rpy) {
return schema::IsDeterministic(rpy.deg);
},
[](const AngleAxis& aa) {
return schema::IsDeterministic(aa.angle_deg) &&
schema::IsDeterministic(aa.axis);
},
[](const Uniform&) {
return false;
},
}, value);
}
math::RotationMatrixd Rotation::GetDeterministicValue() const {
DRAKE_THROW_UNLESS(this->IsDeterministic());
const Matrix3<Expression> symbolic = this->ToSymbolic().matrix();
const Eigen::Matrix3d result = symbolic.unaryExpr([](const auto& e) {
return ExtractDoubleOrThrow(e);
});
return math::RotationMatrixd(result);
}
namespace {
// Converts a degree distribution to radians. Our symbolic representations do
// not yet handle gaussian angles correctly, so we forbid them for now.
Expression deg2rad(const DistributionVariant& deg_var) {
DRAKE_THROW_UNLESS(!std::holds_alternative<Gaussian>(deg_var));
const Expression deg_sym = schema::ToSymbolic(deg_var);
return deg_sym * (M_PI / 180.0);
}
template <int Size>
Vector<Expression, Size> deg2rad(
const DistributionVectorVariant<Size>& deg_var) {
DRAKE_THROW_UNLESS(!std::holds_alternative<GaussianVector<Size>>(deg_var));
const Vector<Expression, Size> deg_sym =
schema::ToDistributionVector(deg_var)->ToSymbolic();
return deg_sym * (M_PI / 180.0);
}
} // namespace
math::RotationMatrix<Expression> Rotation::ToSymbolic() const {
using Result = math::RotationMatrix<Expression>;
return std::visit<Result>(overloaded{
[](const Identity&) {
return Result{};
},
[](const Rpy& rpy) {
const Vector3<Expression> rpy_rad = deg2rad(rpy.deg);
return Result{math::RollPitchYaw<Expression>(rpy_rad)};
},
[](const AngleAxis& aa) {
const Expression angle_rad = deg2rad(aa.angle_deg);
const Vector3<Expression> axis =
schema::ToDistributionVector(aa.axis)->ToSymbolic().normalized();
const Eigen::AngleAxis<Expression> theta_lambda(angle_rad, axis);
return Result{theta_lambda};
},
[](const Uniform&) {
RandomGenerator generator;
return math::UniformlyRandomRotationMatrix<Expression>(&generator);
},
}, value);
}
} // namespace schema
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/schema/rotation.h | #pragma once
#include <variant>
#include "drake/common/name_value.h"
#include "drake/common/schema/stochastic.h"
#include "drake/math/roll_pitch_yaw.h"
#include "drake/math/rotation_matrix.h"
namespace drake {
namespace schema {
/// A specification for an SO(3) rotation, to be used for serialization
/// purposes, e.g., to define stochastic scenarios. This structure specifies
/// either one specific rotation or else a distribution of possible rotations.
/// It does not provide mathematical operators to compose or mutate rotations.
/// Instead, users should call either GetDeterministicValue() or ToSymbolic()
/// to obtain a RotationMatrix value that can be operated on.
///
/// For an overview of configuring stochastic transforms, see
/// @ref schema_transform and @ref schema_stochastic.
///
/// See @ref implementing_serialize "Implementing Serialize" for implementation
/// details, especially the unusually public member fields.
class Rotation {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Rotation)
/// Constructs the Identity rotation.
Rotation() = default;
/// Constructs an Rpy rotation with the given value.
explicit Rotation(const math::RotationMatrix<double>&);
/// Constructs an Rpy rotation with the given value.
explicit Rotation(const math::RollPitchYaw<double>&);
/// No-op rotation.
struct Identity {
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Identity)
Identity() = default;
template <typename Archive>
void Serialize(Archive*) {}
};
/// A roll-pitch-yaw rotation, using the angle conventions of Drake's
/// RollPitchYaw.
struct Rpy {
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Rpy)
Rpy() = default;
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(deg));
}
DistributionVectorVariant<3> deg{Eigen::Vector3d::Zero()};
};
/// Rotation constructed from a fixed axis and an angle.
struct AngleAxis {
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(AngleAxis)
AngleAxis() = default;
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(angle_deg));
a->Visit(DRAKE_NVP(axis));
}
DistributionVariant angle_deg;
DistributionVectorVariant<3> axis{Eigen::Vector3d::UnitZ()};
};
/// Rotation sampled from a uniform distribution over SO(3).
struct Uniform {
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Uniform)
Uniform() = default;
template <typename Archive>
void Serialize(Archive*) {}
};
/// Returns true iff this is fully deterministic.
bool IsDeterministic() const;
/// If this is deterministic, retrieves its value.
/// @throws std::exception if this is not fully deterministic.
math::RotationMatrixd GetDeterministicValue() const;
/// Returns the symbolic form of this rotation. If this is deterministic,
/// the result will contain no variables. If this is random, the result will
/// contain one or more random variables, based on the distributions in use.
math::RotationMatrix<symbolic::Expression> ToSymbolic() const;
/// Sets this value to the given deterministic RPY, in degrees.
void set_rpy_deg(const Eigen::Vector3d& rpy_deg) {
value.emplace<Rotation::Rpy>().deg = rpy_deg;
}
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(value));
}
using Variant = std::variant<Identity, Rpy, AngleAxis, Uniform>;
Variant value;
};
} // namespace schema
} // namespace drake
| 0 |
/home/johnshepherd/drake/common | /home/johnshepherd/drake/common/schema/transform.h | #pragma once
#include <optional>
#include <string>
#include "drake/common/name_value.h"
#include "drake/common/schema/rotation.h"
#include "drake/common/schema/stochastic.h"
#include "drake/math/rigid_transform.h"
namespace drake {
namespace schema {
/** @defgroup schema_transform Configuring transforms
@ingroup stochastic_systems
@{
This page describes how to use classes such as schema::Rotation and
schema::Transform to denote stochastic quantities, as a bridge between loading
a scenario specification and populating the corresponding math::RigidTransform
quantities.
The broader concepts are discussed at @ref schema_stochastic. Here, we cover
details related to rotations and transforms in particular.
We'll explain uses of schema::Rotation and schema::Transform using their
matching YAML syntax as parsed by yaml::LoadYamlFile.
# Rotations
This shows the syntax for a schema::Rotation.
When no details are given, the default rotation is the identity matrix:
```
rotation: {}
```
For clarity, you may also specify `Identity` variant tag explicitly.
This version and the above version have exactly the same effect:
```
rotation: !Identity {}
```
To specify roll, pitch, yaw angles using math::RollPitchYaw conventions, use
`Rpy` as the variant tag:
```
rotation: !Rpy
deg: [10.0, 20.0, 30.0]
```
To specify a rotation angle and axis in the sense of Eigen::AngleAxis, use
`AngleAxis` as the variant tag:
```
rotation: !AngleAxis
angle_deg: 10.0
axis: [0.0, 1.0, 0.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.
```
rotation: !Rpy { deg: [10.0, 20.0, 30.0] }
```
```
rotation: !AngleAxis { angle_deg: 10.0, axis: [0.0, 1.0, 0.0] }
```
## Stochastic Rotations
To specify a stochastic rotation sampled from a uniform distribution over
SO(3):
```
rotation: !Uniform {}
```
The other available representations also accept stochastic distributions for
their values:
```
rotation: !Rpy
deg: !UniformVector
min: [ 0.0, 10.0, 20.0]
max: [30.0, 40.0, 50.0]
```
Or:
```
rotation: !AngleAxis
angle_deg: !Uniform
min: 8.0
max: 10.0
axis: !UniformVector
min: [0.0, 0.9, 0.0]
max: [0.1, 1.0, 0.0]
```
For an explanation of `!Uniform`, `!UniformVector`, and other available options
(%Gaussian, etc.) for scalar and vector quantities, see @ref schema_stochastic.
# Transforms
This shows the syntax for a schema::Transform. A transform is merely a
translation and rotation, optionally with a some given string as a base_frame.
```
transform:
translation: [1.0, 2.0, 3.0]
rotation: !Rpy { deg: [10.0, 20.0, 30.0] }
```
Or:
```
transform:
base_frame: foo
translation: [0.0, 0.0, 1.0]
rotation: !Identity {}
```
## Stochastic Transforms
Either or both of the rotational or translation component can be stochastic:
```
transform:
translation: !UniformVector
min: [-1.0, -1.0, -1.0]
max: [ 1.0, 1.0, 1.0]
rotation: !Uniform {}
```
For an explanation of `!Uniform`, `!UniformVector`, and other available options
(%Gaussian, etc.) for scalar and vector quantities, see @ref schema_stochastic.
@} */
/// A specification for a 3d rotation and translation, optionally with respect
/// to a base frame.
///
/// For an overview of configuring stochastic transforms, see
/// @ref schema_transform and @ref schema_stochastic.
///
/// See @ref implementing_serialize "Implementing Serialize" for implementation
/// details, especially the unusually public member fields.
class Transform {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(Transform)
/// Constructs the Identity transform.
Transform() = default;
/// Constructs the given transform.
explicit Transform(const math::RigidTransformd&);
/// Sets the rotation field to the given deterministic RPY, in degrees.
void set_rotation_rpy_deg(const Eigen::Vector3d& rpy_deg) {
rotation.set_rpy_deg(rpy_deg);
}
/// Returns true iff this is fully deterministic.
bool IsDeterministic() const;
/// If this is deterministic, retrieves its value.
/// @throws std::exception if this is not fully deterministic.
math::RigidTransformd GetDeterministicValue() const;
/// Returns the symbolic form of this rotation. If this is deterministic,
/// the result will contain no variables. If this is random, the result will
/// contain one or more random variables, based on the distributions in use.
math::RigidTransform<symbolic::Expression> ToSymbolic() const;
/// Returns the mean of this rotation. If this is deterministic, the result
/// is the same as GetDeterministicValue. If this is random, note that the
/// mean here is simply defined as setting all of the random variables
/// individually to their mean. Various other measures of the resulting
/// RigidTransform (e.g., the distribution of one of the Euler angles) may
/// not necessarily match that measure on the returned value.
math::RigidTransformd Mean() const;
/// Samples this Transform. If this is deterministic, the result is the same
/// as GetDeterministicValue.
math::RigidTransformd Sample(RandomGenerator* generator) const;
/// Samples this Transform; the returned value is deterministic and has the
/// same base frame.
Transform SampleAsTransform(RandomGenerator* generator) const;
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(base_frame));
a->Visit(DRAKE_NVP(translation));
a->Visit(MakeNameValue("rotation", &rotation.value));
}
/// An optional base frame name for this transform. When left unspecified,
/// the default depends on the semantics of the enclosing struct.
std::optional<std::string> base_frame;
/// A translation vector, in meters.
DistributionVectorVariant<3> translation{Eigen::Vector3d::Zero()};
/// A variant that allows for several ways to specify a rotation.
Rotation rotation;
};
} // namespace schema
} // namespace drake
| 0 |