repo_id
stringclasses 205
values | file_path
stringlengths 33
141
| content
stringlengths 1
307k
| __index_level_0__
int64 0
0
|
---|---|---|---|
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/forwarddiff.py | import numpy as np
from .autodiffutils import AutoDiffXd
def derivative(function, x):
"""Compute the derivative of the function evaluated at the scalar input x
using Eigen's automatic differentiation.
The function should be scalar-input and scalar-output.
"""
x_ad = AutoDiffXd(value=x, size=1, offset=0)
y_ad = function(x_ad)
return y_ad.derivatives()[0]
def gradient(function, x):
"""Compute the gradient of the function evaluated at the vector input x
using Eigen's automatic differentiation.
``function`` should be vector-input and be either a scalar output or a
vector of size 1, where the element must be of type AutoDiffXd.
"""
x = np.asarray(x)
assert x.ndim == 1, "x must be a vector"
x_ad = np.empty(x.shape, dtype=AutoDiffXd)
for i in range(x.size):
x_ad.flat[i] = AutoDiffXd(value=x.flat[i], size=x.size, offset=i)
y_ad = np.asarray(function(x_ad))
# TODO(eric.cousineau): Consider restricting this in the future to only be
# a scalar.
assert y_ad.size == 1 and y_ad.ndim <= 1, (
"The output of `function` must be of a scalar or a vector of size 1")
y_ad = y_ad.reshape(()) # To scalar.
return y_ad.item().derivatives()
def jacobian(function, x):
"""Compute the jacobian of the function evaluated at the vector input x
using Eigen's automatic differentiation. The dimension of the jacobian will
be one more than the output of ``function``.
``function`` should be vector-input, and can be any dimension output, and
must return an array with AutoDiffXd elements.
"""
x = np.asarray(x)
assert x.ndim == 1, "x must be a vector"
x_ad = np.empty(x.shape, dtype=object)
for i in range(x.size):
x_ad.flat[i] = AutoDiffXd(value=x.flat[i], size=x.size, offset=i)
y_ad = np.asarray(function(x_ad))
# An AutoDiffXd variable with empty derivatives should be treated as
# having all zero derivatives. Checking the length of the derivatives
# vector, and replacing it with all zeros ensures np.vstack doesn't
# throw an error when the shapes don't line up.
return np.vstack(
[y.derivatives() if len(y.derivatives()) > 0 else np.zeros(x.size)
for y in y_ad.flat]).reshape(y_ad.shape + (-1,))
# Method overloads:
# These are obviously not a complete set of mathematical functions for
# autodiff numbers. Rather, they exist just as a demonstration of *how*
# to overload individual mathematical functions to work with both
# AutoDiff and numeric inputs.
def sin(x):
if isinstance(x, AutoDiffXd):
return x.sin()
else:
return np.sin(x)
def cos(x):
if isinstance(x, AutoDiffXd):
return x.cos()
else:
return np.cos(x)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/all.py | """Provides a roll-up of all user-visible modules and symbols in `pydrake`.
Things to note:
* The `.all` modules in `pydrake` are intended as convenient end-user shortcut
for interactive or tutorial use. Please only use it for prototyping, but do
not use it in production code.
* Code within pydrake itself should not use the all shortcut, but rather
import only exactly what is needed.
* The downsides of importing an `.all` module are (a) pulling in additional
dependencies, (b) the potential to lose a symbol if there is a conflict
(e.g. something like `pydrake.multibody.shapes.Element` vs
`pydrake.multibody.collision.Element` (which does not exist yet)), and
(c) deprecated symbols could get removed without warning from `all` modules.
* Deprecated modules will *not* be incorporated in `all` modules, because
otherwise, `all` would emit noisy deprecation warnings, or if they are
suppressed, subseqeuent imports of those deprecated modules will not trigger
warnings.
To see example usages, please see `doc/python_bindings.rst`.
Note:
Import order matters! If there is a name conflict, the last one imported
wins. See "Preferred Ordering" section below.
**Preferred Ordering**: In service of maintaining convenient spellings, we have
a "preferred ordering" section in this top-level module. Please note that this
ordering is subject to change without notice. If you desire stability, please
**do not use** ``pydrake.all``. If you have a preferred ordering, please submit
a PR that will be subject to discussion and review. If you wish to debug
collisions, please run ``bazel run //bindings/pydrake:print_symbol_collision``
from the Drake source tree.
"""
# Normal symbols.
from . import getDrakePath
from .autodiffutils import *
from .forwarddiff import *
from .lcm import *
from .manipulation import *
from .math import *
from .perception import *
from .planning import *
from .polynomial import *
from .solvers import *
from .symbolic import *
from .trajectories import *
# Submodules.
from .common.all import *
from .geometry.all import *
# - `.gym` is an optional dependency, so is excluded from `all`.
# - `.examples` does not offer public Drake library symbols.
from .multibody.all import *
from .systems.all import *
from .visualization import *
# Preferred Ordering.
# Please note this will *re*import some modules.
# To view what collisions may occur, please run:
# - Ensure .math imports win over less capable .symbolic or .autodiffutils
# overloads.
from .math import *
# - Ensure symbolic.Polynomial wins (#18353).
from .symbolic import Polynomial
# Ensure that the command-line modules appear in the pydrake API reference.
import pydrake.visualization.meldis
import pydrake.visualization.model_visualizer
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/trajectories_py.cc | #include "pybind11/eval.h"
#include "drake/bindings/pydrake/common/default_scalars_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/polynomial_types_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/polynomial.h"
#include "drake/common/trajectories/bezier_curve.h"
#include "drake/common/trajectories/bspline_trajectory.h"
#include "drake/common/trajectories/composite_trajectory.h"
#include "drake/common/trajectories/derivative_trajectory.h"
#include "drake/common/trajectories/exponential_plus_piecewise_polynomial.h"
#include "drake/common/trajectories/path_parameterized_trajectory.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/common/trajectories/piecewise_pose.h"
#include "drake/common/trajectories/piecewise_quaternion.h"
#include "drake/common/trajectories/stacked_trajectory.h"
#include "drake/common/trajectories/trajectory.h"
namespace drake {
namespace pydrake {
namespace {
using trajectories::Trajectory;
// Binds PiecewisePolynomial<double>::Serialize().
// We cannot use DefAttributesUsingSerialize() for this because the Serialize
// function transforms the data (rather than providing pointers to the member
// fields as would be typical), so we must bind the attributes manually.
template <typename PyClass>
void BindPiecewisePolynomialSerialize(PyClass* cls) {
using Class = trajectories::PiecewisePolynomial<double>;
// The C++ types of the serialized fields.
using Breaks = std::vector<double>;
using Polynomials = std::vector<MatrixX<Eigen::VectorXd>>;
// An adapter to get and/or set the serialized fields.
struct Archive {
void Visit(const NameValue<Breaks>& nv) {
if (set_breaks) {
*nv.value() = std::move(breaks);
} else {
breaks = *nv.value();
}
}
void Visit(const NameValue<Polynomials>& nv) {
if (set_polynomials) {
*nv.value() = std::move(polynomials);
} else {
polynomials = *nv.value();
}
}
bool set_breaks{false};
Breaks breaks;
bool set_polynomials{false};
Polynomials polynomials;
};
// Add the same __fields__ that DefAttributesUsingSerialize would have added.
cls->def_property_readonly_static("__fields__", [](py::object /* cls */) {
auto ndarray = py::module::import("numpy").attr("ndarray");
auto make_namespace = py::module::import("types").attr("SimpleNamespace");
auto breaks = make_namespace();
py::setattr(breaks, "name", py::str("breaks"));
py::setattr(breaks, "type", ndarray);
auto polynomials = make_namespace();
py::setattr(polynomials, "name", py::str("polynomials"));
py::setattr(polynomials, "type", ndarray);
py::list fields;
fields.append(breaks);
fields.append(polynomials);
return py::tuple(fields);
});
// Given the __fields__ above, yaml_load_typed will try to setattr on "breaks"
// and "polynomials". However, we don't want to expose those properties to
// users so we'll respell the name during setattr to add a leading underscore,
// and bind the properties using the private name.
cls->def("__setattr__", [](Class& self, py::str name, py::object value) {
if (std::string(name) == "breaks") {
name = py::str("_breaks");
} else if (std::string(name) == "polynomials") {
name = py::str("_polynomials");
}
py::eval("object.__setattr__")(self, name, value);
});
// Define a property setter for "_breaks" (the getter is never called).
// Setting the breaks resets all of the polynomials; this is fine because
// deserialization matches __fields__ order, which has "breaks" come first
// followed by setting the "polynomials" afterward.
cls->def_property("_breaks", nullptr, [](Class& self, const Breaks& breaks) {
const size_t num_poly = breaks.empty() ? 0 : breaks.size() - 1;
const MatrixX<Eigen::VectorXd> empty_poly;
Archive archive{.set_breaks = true,
.breaks = breaks,
.set_polynomials = true,
.polynomials = Polynomials(num_poly, empty_poly)};
self.Serialize(&archive);
});
// Define a property setter for "_polynomials" (the getter is never called).
// We bind it as private: only yaml_load_typed should call it, not users.
// The property accepts a 4D ndarray and converts it to C++'s convention of
// vector-of-matrix-of-coeffs storage.
cls->def_property("_polynomials", nullptr,
[](Class& self, const py::array_t<double>& polynomials) {
Polynomials cxx_poly;
if (polynomials.size() > 0) {
DRAKE_THROW_UNLESS(polynomials.ndim() == 4);
const int num_poly = polynomials.shape(0);
const int num_rows = polynomials.shape(1);
const int num_cols = polynomials.shape(2);
const int num_coeffs = polynomials.shape(3);
cxx_poly.resize(num_poly);
for (int i = 0; i < num_poly; ++i) {
cxx_poly[i].resize(num_rows, num_cols);
for (int j = 0; j < num_rows; ++j) {
for (int k = 0; k < num_cols; ++k) {
cxx_poly[i](j, k).resize(num_coeffs);
for (int c = 0; c < num_coeffs; ++c) {
cxx_poly[i](j, k)(c) = polynomials.at(i, j, k, c);
}
}
}
}
}
Archive archive{
.set_polynomials = true, .polynomials = std::move(cxx_poly)};
self.Serialize(&archive);
});
}
// Provides a templated 'namespace'.
template <typename T>
struct Impl {
// For bindings that want a `const vector<VectorX<T>>&` but are bound
// via a `const vector<vector<T>>&` for overloading priority,
// this function converts the input. A numpy matrix is row-major, so a 2x3
// samples numpy array (unfortunately) turns into a std::vector with 2
// elements, each a vector of 3 elements; we'll transpose that.
static std::vector<MatrixX<T>> MakeEigenFromRowMajorVectors(
const std::vector<std::vector<T>>& in) {
if (in.size() == 0) {
return std::vector<MatrixX<T>>();
}
std::vector<MatrixX<T>> vec(in[0].size(), Eigen::VectorXd(in.size()));
for (int row = 0; row < static_cast<int>(in.size()); ++row) {
DRAKE_THROW_UNLESS(in[row].size() == in[0].size());
for (int col = 0; col < static_cast<int>(in[row].size()); ++col) {
vec[col](row, 0) = in[row][col];
}
}
return vec;
}
class TrajectoryPublic : public Trajectory<T> {
public:
using Base = Trajectory<T>;
TrajectoryPublic() = default;
// Virtual methods, for explicit bindings.
using Base::Clone;
using Base::cols;
using Base::do_has_derivative;
using Base::DoEvalDerivative;
using Base::DoMakeDerivative;
using Base::end_time;
using Base::rows;
using Base::start_time;
using Base::value;
};
class PyTrajectory : public py::wrapper<TrajectoryPublic> {
public:
using Base = py::wrapper<TrajectoryPublic>;
using Base::Base;
// Trampoline virtual methods.
MatrixX<T> value(const T& t) const override {
PYBIND11_OVERLOAD_PURE(MatrixX<T>, Trajectory<T>, value, t);
}
T start_time() const override {
PYBIND11_OVERLOAD_PURE(T, Trajectory<T>, start_time);
}
T end_time() const override {
PYBIND11_OVERLOAD_PURE(T, Trajectory<T>, end_time);
}
Eigen::Index rows() const override {
PYBIND11_OVERLOAD_PURE(Eigen::Index, Trajectory<T>, rows);
}
Eigen::Index cols() const override {
PYBIND11_OVERLOAD_PURE(Eigen::Index, Trajectory<T>, cols);
}
bool do_has_derivative() const override {
PYBIND11_OVERLOAD_INT(bool, Trajectory<T>, "do_has_derivative");
// If the macro did not return, use default functionality.
return Base::do_has_derivative();
}
MatrixX<T> DoEvalDerivative(
const T& t, int derivative_order) const override {
PYBIND11_OVERLOAD_INT(
MatrixX<T>, Trajectory<T>, "DoEvalDerivative", t, derivative_order);
// If the macro did not return, use default functionality.
return Base::DoEvalDerivative(t, derivative_order);
}
std::unique_ptr<Trajectory<T>> DoMakeDerivative(
int derivative_order) const override {
PYBIND11_OVERLOAD_INT(std::unique_ptr<Trajectory<T>>, Trajectory<T>,
"DoMakeDerivative", derivative_order);
// If the macro did not return, use default functionality.
return Base::DoMakeDerivative(derivative_order);
}
std::unique_ptr<Trajectory<T>> Clone() const override {
PYBIND11_OVERLOAD_PURE(
std::unique_ptr<Trajectory<T>>, Trajectory<T>, Clone);
}
};
static void DoScalarDependentDefinitions(py::module m) {
py::tuple param = GetPyParam<T>();
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::trajectories;
constexpr auto& doc = pydrake_doc.drake.trajectories;
{
using Class = Trajectory<T>;
constexpr auto& cls_doc = doc.Trajectory;
auto cls = DefineTemplateClassWithDefault<Class, PyTrajectory>(
m, "Trajectory", param, cls_doc.doc);
cls // BR
.def(py::init<>())
.def("value", &Class::value, py::arg("t"), cls_doc.value.doc)
.def("vector_values",
overload_cast_explicit<MatrixX<T>, const std::vector<T>&>(
&Class::vector_values),
py::arg("t"), cls_doc.vector_values.doc)
.def("has_derivative", &Class::has_derivative,
cls_doc.has_derivative.doc)
.def("EvalDerivative", &Class::EvalDerivative, py::arg("t"),
py::arg("derivative_order") = 1, cls_doc.EvalDerivative.doc)
.def("MakeDerivative", &Class::MakeDerivative,
py::arg("derivative_order") = 1, cls_doc.MakeDerivative.doc)
.def("start_time", &Class::start_time, cls_doc.start_time.doc)
.def("end_time", &Class::end_time, cls_doc.end_time.doc)
.def("rows", &Class::rows, cls_doc.rows.doc)
.def("cols", &Class::cols, cls_doc.cols.doc);
}
{
using Class = BezierCurve<T>;
constexpr auto& cls_doc = doc.BezierCurve;
auto cls = DefineTemplateClassWithDefault<Class, Trajectory<T>>(
m, "BezierCurve", param, cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<double, double, const Eigen::Ref<const MatrixX<T>>&>(),
py::arg("start_time"), py::arg("end_time"),
py::arg("control_points"), cls_doc.ctor.doc_3args)
.def("order", &Class::order, cls_doc.order.doc)
.def("BernsteinBasis", &Class::BernsteinBasis, py::arg("i"),
py::arg("time"), py::arg("order") = std::nullopt,
cls_doc.BernsteinBasis.doc)
.def("control_points", &Class::control_points,
cls_doc.control_points.doc)
.def("AsLinearInControlPoints", &Class::AsLinearInControlPoints,
py::arg("derivative_order") = 1,
cls_doc.AsLinearInControlPoints.doc)
.def("GetExpression", &Class::GetExpression,
py::arg("time") = symbolic::Variable("t"),
cls_doc.GetExpression.doc)
.def("ElevateOrder", &Class::ElevateOrder, cls_doc.ElevateOrder.doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = BsplineTrajectory<T>;
constexpr auto& cls_doc = doc.BsplineTrajectory;
auto cls = DefineTemplateClassWithDefault<Class, Trajectory<T>>(
m, "BsplineTrajectory", param, cls_doc.doc);
cls // BR
.def(py::init<>())
// This overload will match 2d numpy arrays before
// std::vector<MatrixX<T>>. We want each column of the numpy array as
// a MatrixX of control points, but the std::vectors here are
// associated with the rows in numpy.
.def(py::init([](math::BsplineBasis<T> basis,
std::vector<std::vector<T>> control_points) {
return Class(basis, MakeEigenFromRowMajorVectors(control_points));
}),
py::arg("basis"), py::arg("control_points"), cls_doc.ctor.doc)
.def(py::init<math::BsplineBasis<T>, std::vector<MatrixX<T>>>(),
py::arg("basis"), py::arg("control_points"), cls_doc.ctor.doc)
.def("Clone", &Class::Clone, cls_doc.Clone.doc)
.def("num_control_points", &Class::num_control_points,
cls_doc.num_control_points.doc)
.def("control_points", &Class::control_points,
cls_doc.control_points.doc)
.def("InitialValue", &Class::InitialValue, cls_doc.InitialValue.doc)
.def("FinalValue", &Class::FinalValue, cls_doc.FinalValue.doc)
.def("basis", &Class::basis, cls_doc.basis.doc)
.def("InsertKnots", &Class::InsertKnots, py::arg("additional_knots"),
cls_doc.InsertKnots.doc)
.def("CopyBlock", &Class::CopyBlock, py::arg("start_row"),
py::arg("start_col"), py::arg("block_rows"),
py::arg("block_cols"), cls_doc.CopyBlock.doc)
.def("CopyHead", &Class::CopyHead, py::arg("n"), cls_doc.CopyHead.doc)
.def(py::pickle(
[](const Class& self) {
return std::make_pair(self.basis(), self.control_points());
},
[](std::pair<math::BsplineBasis<T>, std::vector<MatrixX<T>>>
args) {
return Class(std::get<0>(args), std::get<1>(args));
}));
DefCopyAndDeepCopy(&cls);
}
{
using Class = DerivativeTrajectory<T>;
constexpr auto& cls_doc = doc.DerivativeTrajectory;
auto cls = DefineTemplateClassWithDefault<Class, Trajectory<T>>(
m, "DerivativeTrajectory", param, cls_doc.doc);
cls // BR
.def(py::init<const Trajectory<T>&, int>(), py::arg("nominal"),
py::arg("derivative_order") = 1, cls_doc.ctor.doc)
.def("Clone", &Class::Clone, cls_doc.Clone.doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = PathParameterizedTrajectory<T>;
constexpr auto& cls_doc = doc.PathParameterizedTrajectory;
auto cls = DefineTemplateClassWithDefault<Class, Trajectory<T>>(
m, "PathParameterizedTrajectory", param, cls_doc.doc);
cls // BR
.def(py::init<const Trajectory<T>&, const Trajectory<T>&>(),
py::arg("path"), py::arg("time_scaling"), cls_doc.ctor.doc)
.def("Clone", &Class::Clone, cls_doc.Clone.doc)
.def("path", &Class::path, py_rvp::reference_internal,
cls_doc.path.doc)
.def("time_scaling", &Class::time_scaling, py_rvp::reference_internal,
cls_doc.time_scaling.doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = PiecewiseTrajectory<T>;
constexpr auto& cls_doc = doc.PiecewiseTrajectory;
auto cls = DefineTemplateClassWithDefault<Class, Trajectory<T>>(
m, "PiecewiseTrajectory", param, cls_doc.doc);
cls // BR
.def("get_number_of_segments", &Class::get_number_of_segments,
cls_doc.get_number_of_segments.doc)
.def("start_time", overload_cast_explicit<T, int>(&Class::start_time),
py::arg("segment_index"), cls_doc.start_time.doc)
.def("end_time", overload_cast_explicit<T, int>(&Class::end_time),
py::arg("segment_index"), cls_doc.end_time.doc)
.def("duration", &Class::duration, py::arg("segment_index"),
cls_doc.duration.doc)
// N.B. We must redefine these two overloads, as we cannot use the
// base classes' overloads. See:
// https://github.com/pybind/pybind11/issues/974
.def("start_time", overload_cast_explicit<T>(&Class::start_time),
cls_doc.start_time.doc)
.def("end_time", overload_cast_explicit<T>(&Class::end_time),
cls_doc.end_time.doc)
.def("is_time_in_range", &Class::is_time_in_range, py::arg("t"),
cls_doc.is_time_in_range.doc)
.def("get_segment_index", &Class::get_segment_index, py::arg("t"),
cls_doc.get_segment_index.doc)
.def("get_segment_times", &Class::get_segment_times,
cls_doc.get_segment_times.doc);
}
{
using Class = PiecewisePolynomial<T>;
constexpr auto& cls_doc = doc.PiecewisePolynomial;
auto cls = DefineTemplateClassWithDefault<Class, PiecewiseTrajectory<T>>(
m, "PiecewisePolynomial", param, cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const Eigen::Ref<const MatrixX<T>>&>(),
cls_doc.ctor.doc_1args_constEigenMatrixBase)
.def(py::init<std::vector<MatrixX<Polynomial<T>>> const&,
std::vector<T> const&>(),
cls_doc.ctor.doc_2args_polynomials_matrix_breaks)
.def(py::init<std::vector<Polynomial<T>> const&,
std::vector<T> const&>(),
cls_doc.ctor.doc_2args_polynomials_breaks)
.def("Clone", &Class::Clone, cls_doc.Clone.doc)
.def_static(
"ZeroOrderHold",
// This serves the same purpose as the C++
// ZeroOrderHold(VectorX<T>, MatrixX<T>) method. For 2d numpy
// arrays, pybind apparently matches vector<vector<T>> then
// vector<MatrixX<T>> then MatrixX<T>.
[](const std::vector<T>& breaks,
const std::vector<std::vector<T>>& samples) {
return Class::ZeroOrderHold(
breaks, MakeEigenFromRowMajorVectors(samples));
},
py::arg("breaks"), py::arg("samples"),
cls_doc.ZeroOrderHold.doc_vector)
.def_static("ZeroOrderHold",
py::overload_cast<const std::vector<T>&,
const std::vector<MatrixX<T>>&>(&Class::ZeroOrderHold),
py::arg("breaks"), py::arg("samples"),
cls_doc.ZeroOrderHold.doc_matrix)
.def_static(
"FirstOrderHold",
[](const std::vector<T>& breaks,
const std::vector<std::vector<T>>& samples) {
return Class::FirstOrderHold(
breaks, MakeEigenFromRowMajorVectors(samples));
},
py::arg("breaks"), py::arg("samples"),
cls_doc.FirstOrderHold.doc_vector)
.def_static("FirstOrderHold",
py::overload_cast<const std::vector<T>&,
const std::vector<MatrixX<T>>&>(&Class::FirstOrderHold),
py::arg("breaks"), py::arg("samples"),
cls_doc.FirstOrderHold.doc_matrix)
.def_static(
"CubicShapePreserving",
[](const std::vector<T>& breaks,
const std::vector<std::vector<T>>& samples,
bool zero_end_point_derivatives) {
return Class::CubicShapePreserving(breaks,
MakeEigenFromRowMajorVectors(samples),
zero_end_point_derivatives);
},
py::arg("breaks"), py::arg("samples"),
py::arg("zero_end_point_derivatives") = false,
cls_doc.CubicShapePreserving.doc_vector)
.def_static("CubicShapePreserving",
py::overload_cast<const std::vector<T>&,
const std::vector<MatrixX<T>>&, bool>(
&Class::CubicShapePreserving),
py::arg("breaks"), py::arg("samples"),
py::arg("zero_end_point_derivatives") = false,
cls_doc.CubicShapePreserving.doc_matrix)
.def_static(
"CubicWithContinuousSecondDerivatives",
[](const std::vector<T>& breaks,
const std::vector<std::vector<T>>& samples,
const MatrixX<T>& sample_dot_at_start,
const MatrixX<T>& sample_dot_at_end) {
return PiecewisePolynomial<
T>::CubicWithContinuousSecondDerivatives(breaks,
MakeEigenFromRowMajorVectors(samples), sample_dot_at_start,
sample_dot_at_end);
},
py::arg("breaks"), py::arg("samples"),
py::arg("sample_dot_at_start"), py::arg("sample_dot_at_end"),
cls_doc.CubicWithContinuousSecondDerivatives.doc_4args_vector)
.def_static("CubicWithContinuousSecondDerivatives",
py::overload_cast<const std::vector<T>&,
const std::vector<MatrixX<T>>&, const MatrixX<T>&,
const MatrixX<T>&>(
&Class::CubicWithContinuousSecondDerivatives),
py::arg("breaks"), py::arg("samples"),
py::arg("sample_dot_at_start"), py::arg("sample_dot_at_end"),
cls_doc.CubicWithContinuousSecondDerivatives.doc_4args_matrix)
.def_static(
"CubicHermite",
[](const std::vector<T>& breaks,
const std::vector<std::vector<T>>& samples,
const std::vector<std::vector<T>>& samples_dot) {
return Class::CubicHermite(breaks,
MakeEigenFromRowMajorVectors(samples),
MakeEigenFromRowMajorVectors(samples_dot));
},
py::arg("breaks"), py::arg("samples"), py::arg("samples_dot"),
cls_doc.CubicHermite.doc_vector)
.def_static("CubicHermite",
py::overload_cast<const std::vector<T>&,
const std::vector<MatrixX<T>>&,
const std::vector<MatrixX<T>>&>(&Class::CubicHermite),
py::arg("breaks"), py::arg("samples"), py::arg("samples_dot"),
cls_doc.CubicHermite.doc_matrix)
.def_static(
"CubicWithContinuousSecondDerivatives",
[](const std::vector<T>& breaks,
const std::vector<std::vector<T>>& samples,
bool periodic_end_condition) {
return PiecewisePolynomial<
T>::CubicWithContinuousSecondDerivatives(breaks,
MakeEigenFromRowMajorVectors(samples),
periodic_end_condition);
},
py::arg("breaks"), py::arg("samples"),
py::arg("periodic_end_condition") = false,
cls_doc.CubicWithContinuousSecondDerivatives.doc_3args_vector)
.def_static("CubicWithContinuousSecondDerivatives",
py::overload_cast<const std::vector<T>&,
const std::vector<MatrixX<T>>&, bool>(
&Class::CubicWithContinuousSecondDerivatives),
py::arg("breaks"), py::arg("samples"), py::arg("periodic_end"),
cls_doc.CubicWithContinuousSecondDerivatives.doc_3args_matrix)
.def_static(
"LagrangeInterpolatingPolynomial",
[](const std::vector<T>& breaks,
const std::vector<std::vector<T>>& samples) {
return Class::LagrangeInterpolatingPolynomial(
breaks, MakeEigenFromRowMajorVectors(samples));
},
py::arg("times"), py::arg("samples"),
cls_doc.LagrangeInterpolatingPolynomial.doc_vector)
.def_static("LagrangeInterpolatingPolynomial",
py::overload_cast<const std::vector<T>&,
const std::vector<MatrixX<T>>&>(
&Class::LagrangeInterpolatingPolynomial),
py::arg("times"), py::arg("samples"),
cls_doc.LagrangeInterpolatingPolynomial.doc_matrix)
.def("derivative", &Class::derivative,
py::arg("derivative_order") = 1, cls_doc.derivative.doc)
.def("getPolynomialMatrix", &Class::getPolynomialMatrix,
py::arg("segment_index"), cls_doc.getPolynomialMatrix.doc)
.def("getPolynomial", &Class::getPolynomial, py::arg("segment_index"),
py::arg("row") = 0, py::arg("col") = 0, cls_doc.getPolynomial.doc)
.def("getSegmentPolynomialDegree", &Class::getSegmentPolynomialDegree,
py::arg("segment_index"), py::arg("row") = 0, py::arg("col") = 0,
cls_doc.getSegmentPolynomialDegree.doc)
.def("isApprox", &Class::isApprox, py::arg("other"), py::arg("tol"),
py::arg("tol_type") = drake::ToleranceType::kRelative,
cls_doc.isApprox.doc)
.def("Reshape", &Class::Reshape, py::arg("rows"), py::arg("cols"),
cls_doc.Reshape.doc)
.def("Transpose", &Class::Transpose, cls_doc.Transpose.doc)
.def("Block", &Class::Block, py::arg("start_row"),
py::arg("start_col"), py::arg("block_rows"),
py::arg("block_cols"), cls_doc.Block.doc)
.def("ConcatenateInTime", &Class::ConcatenateInTime, py::arg("other"),
cls_doc.ConcatenateInTime.doc)
.def("AppendCubicHermiteSegment", &Class::AppendCubicHermiteSegment,
py::arg("time"), py::arg("sample"), py::arg("sample_dot"),
cls_doc.AppendCubicHermiteSegment.doc)
.def("AppendFirstOrderSegment", &Class::AppendFirstOrderSegment,
py::arg("time"), py::arg("sample"),
cls_doc.AppendFirstOrderSegment.doc)
.def("RemoveFinalSegment", &Class::RemoveFinalSegment,
cls_doc.RemoveFinalSegment.doc)
.def("ReverseTime", &Class::ReverseTime, cls_doc.ReverseTime.doc)
.def("ScaleTime", &Class::ScaleTime, py::arg("scale"),
cls_doc.ScaleTime.doc)
.def("slice", &Class::slice, py::arg("start_segment_index"),
py::arg("num_segments"), cls_doc.slice.doc)
.def("shiftRight", &Class::shiftRight, py::arg("offset"),
cls_doc.shiftRight.doc)
.def(py::self + py::self)
.def("setPolynomialMatrixBlock", &Class::setPolynomialMatrixBlock,
py::arg("replacement"), py::arg("segment_index"),
py::arg("row_start") = 0, py::arg("col_start") = 0,
cls_doc.setPolynomialMatrixBlock.doc);
DefCopyAndDeepCopy(&cls);
if constexpr (std::is_same_v<T, double>) {
BindPiecewisePolynomialSerialize(&cls);
}
}
{
using Class = CompositeTrajectory<T>;
constexpr auto& cls_doc = doc.CompositeTrajectory;
auto cls = DefineTemplateClassWithDefault<Class, PiecewiseTrajectory<T>>(
m, "CompositeTrajectory", param, cls_doc.doc);
cls // BR
.def(py::init([](std::vector<const Trajectory<T>*> py_segments) {
std::vector<copyable_unique_ptr<Trajectory<T>>> segments;
segments.reserve(py_segments.size());
for (const Trajectory<T>* py_segment : py_segments) {
segments.emplace_back(py_segment ? py_segment->Clone() : nullptr);
}
return std::make_unique<CompositeTrajectory<T>>(
std::move(segments));
}),
py::arg("segments"), cls_doc.ctor.doc)
.def("segment", &Class::segment, py::arg("segment_index"),
py_rvp::reference_internal, cls_doc.segment.doc);
DefCopyAndDeepCopy(&cls);
}
if constexpr (std::is_same_v<T, double>) {
using Class = ExponentialPlusPiecewisePolynomial<T>;
constexpr auto& cls_doc = doc.ExponentialPlusPiecewisePolynomial;
auto cls = DefineTemplateClassWithDefault<Class, PiecewiseTrajectory<T>>(
m, "ExponentialPlusPiecewisePolynomial", param, cls_doc.doc);
cls // BR
.def(
py::init(
[](const Eigen::MatrixX<T>& K, const Eigen::MatrixX<T>& A,
const Eigen::MatrixX<T>& alpha,
const PiecewisePolynomial<T>& piecewise_polynomial_part) {
return Class(K, A, alpha, piecewise_polynomial_part);
}),
py::arg("K"), py::arg("A"), py::arg("alpha"),
py::arg("piecewise_polynomial_part"), cls_doc.ctor.doc)
.def("Clone", &Class::Clone, cls_doc.Clone.doc)
.def("shiftRight", &Class::shiftRight, py::arg("offset"),
cls_doc.shiftRight.doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = PiecewiseQuaternionSlerp<T>;
constexpr auto& cls_doc = doc.PiecewiseQuaternionSlerp;
auto cls = DefineTemplateClassWithDefault<Class, PiecewiseTrajectory<T>>(
m, "PiecewiseQuaternionSlerp", param, cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const std::vector<T>&,
const std::vector<Quaternion<T>>&>(),
py::arg("breaks"), py::arg("quaternions"),
cls_doc.ctor.doc_2args_breaks_quaternions)
.def(
py::init<const std::vector<T>&, const std::vector<Matrix3<T>>&>(),
py::arg("breaks"), py::arg("rotation_matrices"),
cls_doc.ctor.doc_2args_breaks_rotation_matrices)
.def(py::init<const std::vector<T>&,
const std::vector<math::RotationMatrix<T>>&>(),
py::arg("breaks"), py::arg("rotation_matrices"),
cls_doc.ctor.doc_2args_breaks_rotation_matrices)
.def(py::init<const std::vector<T>&,
const std::vector<AngleAxis<T>>&>(),
py::arg("breaks"), py::arg("angle_axes"),
cls_doc.ctor.doc_2args_breaks_angle_axes)
.def("Append",
py::overload_cast<const T&, const Quaternion<T>&>(&Class::Append),
py::arg("time"), py::arg("quaternion"),
cls_doc.Append.doc_2args_time_quaternion)
.def("Append",
py::overload_cast<const T&, const math::RotationMatrix<T>&>(
&Class::Append),
py::arg("time"), py::arg("rotation_matrix"),
cls_doc.Append.doc_2args_time_rotation_matrix)
.def("Append",
py::overload_cast<const T&, const AngleAxis<T>&>(&Class::Append),
py::arg("time"), py::arg("angle_axis"),
cls_doc.Append.doc_2args_time_angle_axis)
.def("orientation", &Class::orientation, py::arg("time"),
cls_doc.orientation.doc)
.def("angular_velocity", &Class::angular_velocity, py::arg("time"),
cls_doc.angular_velocity.doc)
.def("angular_acceleration", &Class::angular_acceleration,
py::arg("time"), cls_doc.angular_acceleration.doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = PiecewisePose<T>;
constexpr auto& cls_doc = doc.PiecewisePose;
auto cls = DefineTemplateClassWithDefault<Class, PiecewiseTrajectory<T>>(
m, "PiecewisePose", param, cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const PiecewisePolynomial<T>&,
const PiecewiseQuaternionSlerp<T>&>(),
py::arg("position_trajectory"), py::arg("orientation_trajectory"),
cls_doc.ctor.doc_2args)
.def_static("MakeLinear", &Class::MakeLinear, py::arg("times"),
py::arg("poses"), cls_doc.MakeLinear.doc)
.def_static("MakeCubicLinearWithEndLinearVelocity",
&Class::MakeCubicLinearWithEndLinearVelocity, py::arg("times"),
py::arg("poses"),
py::arg("start_vel") = Vector3<T>::Zero().eval(),
py::arg("end_vel") = Vector3<T>::Zero().eval(),
cls_doc.MakeCubicLinearWithEndLinearVelocity.doc)
.def("GetPose", &Class::GetPose, py::arg("time"), cls_doc.GetPose.doc)
.def("GetVelocity", &Class::GetVelocity, py::arg("time"),
cls_doc.GetVelocity.doc)
.def("GetAcceleration", &Class::GetAcceleration, py::arg("time"),
cls_doc.GetAcceleration.doc)
.def("IsApprox", &Class::IsApprox, py::arg("other"), py::arg("tol"),
cls_doc.IsApprox.doc)
.def("get_position_trajectory", &Class::get_position_trajectory,
cls_doc.get_position_trajectory.doc)
.def("get_orientation_trajectory", &Class::get_orientation_trajectory,
cls_doc.get_orientation_trajectory.doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = StackedTrajectory<T>;
constexpr auto& cls_doc = doc.StackedTrajectory;
auto cls = DefineTemplateClassWithDefault<Class, Trajectory<T>>(
m, "StackedTrajectory", param, cls_doc.doc);
cls // BR
.def(py::init<bool>(), py::arg("rowwise") = true, cls_doc.ctor.doc)
.def("Clone", &Class::Clone, cls_doc.Clone.doc)
.def("Append",
py::overload_cast<const Trajectory<T>&>(&Class::Append),
/* N.B. We choose to omit any py::arg name here. */
cls_doc.Append.doc);
DefCopyAndDeepCopy(&cls);
}
}
};
} // namespace
PYBIND11_MODULE(trajectories, m) {
py::module::import("pydrake.autodiffutils");
py::module::import("pydrake.common");
py::module::import("pydrake.polynomial");
py::module::import("pydrake.symbolic");
// Do templated instantiations of system types.
auto bind_common_scalar_types = [m](auto dummy) {
using T = decltype(dummy);
Impl<T>::DoScalarDependentDefinitions(m);
};
type_visit(bind_common_scalar_types, CommonScalarPack{});
ExecuteExtraPythonCode(m);
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/BUILD.bazel | load("//bindings/pydrake:pydrake.bzl", "add_lint_tests_pydrake")
load("//bindings/pydrake:stubgen.bzl", "generate_python_stubs")
load("//tools/install:install.bzl", "install")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_googletest",
"drake_cc_library",
)
load(
"//tools/skylark:drake_py.bzl",
"drake_py_binary",
"drake_py_library",
"drake_py_unittest",
)
load(
"//tools/skylark:pybind.bzl",
"drake_pybind_cc_googletest",
"drake_pybind_library",
"generate_pybind_documentation_header",
"get_drake_py_installs",
"get_pybind_package_info",
)
load("//tools/workspace:generate_file.bzl", "generate_file")
package(default_visibility = [
"//bindings:__subpackages__",
])
exports_files([
".clang-format",
])
# This determines how `PYTHONPATH` is configured, and how to install the
# bindings.
PACKAGE_INFO = get_pybind_package_info(base_package = "//bindings")
# This target provides the following Python modules:
# - pydrake
# - pydrake.autodiffutils
# - pydrake.common (and all of its sub-modules)
# - pydrake.math
# - pydrake.symbolic
# Refer to bindings/pydrake/common/module_cycle.md for details.
drake_py_library(
name = "module_py",
srcs = [
"__init__.py",
],
deps = [
"//bindings:bazel_workaround_4594_libdrake_py",
"//bindings/pydrake/common:_init_py",
],
)
generate_pybind_documentation_header(
name = "generate_pybind_documentation_header",
out = "documentation_pybind.h",
# Anonymous namespace and deduction guides both confuse pybind.
exclude_hdr_patterns = ["drake/common/overloaded.h"],
root_name = "pydrake_doc",
targets = [
"//tools/install/libdrake:drake_headers",
],
)
drake_cc_library(
name = "documentation_pybind",
hdrs = ["documentation_pybind.h"],
declare_installed_headers = 0,
tags = ["nolint"],
)
drake_cc_library(
name = "pydrake_pybind",
hdrs = ["pydrake_pybind.h"],
declare_installed_headers = 0,
visibility = ["//visibility:public"],
)
drake_cc_library(
name = "test_util_pybind",
testonly = 1,
hdrs = ["test/test_util_pybind.h"],
declare_installed_headers = 0,
visibility = ["//visibility:public"],
)
drake_cc_library(
name = "autodiff_types_pybind",
hdrs = ["autodiff_types_pybind.h"],
declare_installed_headers = 0,
visibility = ["//visibility:public"],
deps = ["//:drake_shared_library"],
)
drake_py_library(
name = "forwarddiff_py",
srcs = [
"forwarddiff.py",
],
deps = [
":module_py",
],
)
drake_pybind_library(
name = "lcm_py",
cc_deps = [
":documentation_pybind",
"//bindings/pydrake/common:deprecation_pybind",
"//bindings/pydrake/common:serialize_pybind",
],
cc_srcs = ["lcm_py.cc"],
package_info = PACKAGE_INFO,
py_deps = [
":module_py",
],
py_srcs = ["_lcm_extra.py"],
)
drake_cc_library(
name = "math_operators_pybind",
hdrs = ["math_operators_pybind.h"],
declare_installed_headers = 0,
deps = ["//:drake_shared_library"],
)
drake_pybind_library(
name = "perception_py",
cc_deps = [
":documentation_pybind",
"//bindings/pydrake/common:value_pybind",
],
cc_srcs = ["perception_py.cc"],
package_info = PACKAGE_INFO,
py_deps = [
":module_py",
"//bindings/pydrake/systems:sensors_py",
],
)
drake_cc_library(
name = "polynomial_types_pybind",
hdrs = ["polynomial_types_pybind.h"],
declare_installed_headers = 0,
visibility = ["//visibility:public"],
deps = ["//:drake_shared_library"],
)
drake_pybind_library(
name = "polynomial_py",
cc_deps = [
":documentation_pybind",
":polynomial_types_pybind",
"//bindings/pydrake/common:default_scalars_pybind",
],
cc_srcs = ["polynomial_py.cc"],
package_info = PACKAGE_INFO,
py_deps = [
":module_py",
],
)
drake_cc_library(
name = "symbolic_types_pybind",
hdrs = ["symbolic_types_pybind.h"],
declare_installed_headers = 0,
visibility = ["//visibility:public"],
deps = [
":documentation_pybind",
"//:drake_shared_library",
],
)
drake_pybind_library(
name = "trajectories_py",
cc_deps = [
":documentation_pybind",
":polynomial_types_pybind",
"//bindings/pydrake/common:default_scalars_pybind",
"//bindings/pydrake/common:deprecation_pybind",
],
cc_srcs = ["trajectories_py.cc"],
package_info = PACKAGE_INFO,
py_deps = [
":module_py",
":polynomial_py",
],
py_srcs = [
"_trajectories_extra.py",
],
)
drake_py_library(
name = "tutorials_py",
srcs = [
"tutorials.py",
],
deps = [
":module_py",
],
)
PY_LIBRARIES_WITH_INSTALL = [
":lcm_py",
":perception_py",
":polynomial_py",
":trajectories_py",
"//bindings/pydrake/common",
"//bindings/pydrake/examples",
"//bindings/pydrake/examples/gym",
"//bindings/pydrake/examples/multibody",
"//bindings/pydrake/geometry",
"//bindings/pydrake/gym",
"//bindings/pydrake/manipulation",
"//bindings/pydrake/multibody",
"//bindings/pydrake/planning",
"//bindings/pydrake/solvers",
"//bindings/pydrake/systems",
"//bindings/pydrake/visualization",
]
PY_LIBRARIES = [
":forwarddiff_py",
":module_py",
":tutorials_py",
]
# Symbol roll-up (for user ease).
drake_py_library(
name = "all_py",
srcs = [
"_all_everything.py",
"all.py",
],
deps = PY_LIBRARIES_WITH_INSTALL + PY_LIBRARIES,
)
# Package roll-up (for Bazel dependencies).
drake_py_library(
name = "pydrake",
visibility = ["//visibility:public"],
deps = [":all_py"],
)
# Roll-up for publicly accessible testing utilities (for development with
# workflows like drake-external-examples/drake_bazel_external).
drake_py_library(
name = "test_utilities_py",
testonly = 1,
visibility = ["//visibility:public"],
deps = [
# N.B. We depend on pydrake so as to keep symmetry with the currently
# offered public targets (rollup only, no granular access).
":pydrake",
"//bindings/pydrake/common/test_utilities",
],
)
drake_cc_googletest(
name = "documentation_pybind_test",
deps = [
":documentation_pybind",
],
)
# N.B. Due to dependency on `common` (#7912), this is not a fully isolated /
# decoupled test.
drake_pybind_cc_googletest(
name = "pydrake_pybind_test",
cc_deps = [":test_util_pybind"],
py_deps = [":module_py"],
py_srcs = ["test/_pydrake_pybind_test_extra.py"],
)
drake_py_binary(
name = "print_symbol_collisions",
testonly = 1,
srcs = ["test/print_symbol_collisions.py"],
add_test_rule = 1,
deps = [":all_py"],
)
drake_py_unittest(
name = "all_test",
timeout = "moderate",
data = ["//examples/pendulum:models"],
deps = [
":all_py",
],
)
drake_py_unittest(
name = "all_each_import_test",
shard_count = 8,
deps = [
":all_py",
"//bindings/pydrake/common/test_utilities:meta_py",
],
)
# Test ODR (One Definition Rule).
drake_pybind_library(
name = "odr_test_module_py",
testonly = 1,
add_install = False,
cc_deps = [
":documentation_pybind",
":symbolic_types_pybind",
],
cc_so_name = "test/odr_test_module",
cc_srcs = ["test/odr_test_module_py.cc"],
package_info = PACKAGE_INFO,
py_srcs = ["test/__init__.py"],
visibility = ["//visibility:private"],
)
drake_py_unittest(
name = "odr_test",
deps = [
":odr_test_module_py",
"//bindings/pydrake:module_py",
],
)
drake_py_library(
name = "mock_torch_py",
testonly = 1,
srcs = ["test/mock_torch/torch.py"],
imports = ["test/mock_torch"],
)
drake_py_unittest(
name = "rtld_global_warning_test",
deps = [
":mock_torch_py",
":module_py",
],
)
drake_py_unittest(
name = "forward_diff_test",
deps = [
":forwarddiff_py",
"//bindings/pydrake/common/test_utilities",
],
)
drake_py_unittest(
name = "lcm_test",
deps = [
":lcm_py",
"//lcmtypes:lcmtypes_drake_py",
],
)
drake_py_unittest(
name = "perception_test",
deps = [
":perception_py",
],
)
drake_py_unittest(
name = "polynomial_test",
deps = [
":polynomial_py",
"//bindings/pydrake/common/test_utilities:numpy_compare_py",
],
)
drake_py_unittest(
name = "trajectories_test",
deps = [
":trajectories_py",
"//bindings/pydrake/common/test_utilities:numpy_compare_py",
"//bindings/pydrake/common/test_utilities:pickle_compare_py",
"//bindings/pydrake/common/test_utilities:scipy_stub_py",
],
)
drake_py_unittest(
name = "parse_models_test",
deps = [":pydrake"],
)
drake_py_unittest(
name = "dot_clang_format_test",
data = [
":.clang-format",
"//:.clang-format",
],
tags = ["lint"],
)
drake_py_binary(
name = "stubgen",
srcs = ["stubgen.py"],
deps = [
":all_py",
"@mypy_internal//:mypy",
"@stable_baselines3_internal//:stable_baselines3",
],
)
# TODO(jwnimmer-tri): It would be convenient if this could be automatically
# generated. For now, we have stubgen.py that will fail-fast when this goes
# out of date.
PYI_FILES = [
"pydrake/autodiffutils.pyi",
"pydrake/common/__init__.pyi",
"pydrake/common/eigen_geometry.pyi",
"pydrake/common/schema.pyi",
"pydrake/common/value.pyi",
"pydrake/examples.pyi",
"pydrake/geometry/__init__.pyi",
"pydrake/geometry/all.pyi",
"pydrake/geometry/optimization.pyi",
"pydrake/lcm.pyi",
"pydrake/manipulation.pyi",
"pydrake/math.pyi",
"pydrake/multibody/benchmarks/__init__.pyi",
"pydrake/multibody/benchmarks/acrobot.pyi",
"pydrake/multibody/benchmarks/all.pyi",
"pydrake/multibody/fem.pyi",
"pydrake/multibody/inverse_kinematics.pyi",
"pydrake/multibody/math.pyi",
"pydrake/multibody/meshcat.pyi",
"pydrake/multibody/optimization.pyi",
"pydrake/multibody/parsing.pyi",
"pydrake/multibody/plant.pyi",
"pydrake/multibody/rational.pyi",
"pydrake/multibody/tree.pyi",
"pydrake/perception.pyi",
"pydrake/planning.pyi",
"pydrake/polynomial.pyi",
"pydrake/solvers.pyi",
"pydrake/symbolic.pyi",
"pydrake/systems/analysis.pyi",
"pydrake/systems/controllers.pyi",
"pydrake/systems/framework.pyi",
"pydrake/systems/lcm.pyi",
"pydrake/systems/primitives.pyi",
"pydrake/systems/rendering.pyi",
"pydrake/systems/sensors.pyi",
"pydrake/trajectories.pyi",
"pydrake/visualization.pyi",
]
# TODO(mwoehlke-kitware): genrule inappropriately gives execute permission to
# all its outputs; see https://github.com/bazelbuild/bazel/issues/3359.
# (Applies to both :pydrake_pyi and, below, :pydrake_typed.)
generate_python_stubs(
name = "pydrake_pyi",
outs = PYI_FILES,
tool = ":stubgen",
)
# PEP 561 marker file; tells tools that type information is available.
genrule(
name = "pydrake_typed",
srcs = [],
outs = ["pydrake/py.typed"],
cmd = "echo '# Marker file for PEP 561.' > $@",
)
generate_file(
name = "_pyi_files",
content = "\n".join(PYI_FILES),
visibility = ["//visibility:private"],
)
drake_py_unittest(
name = "stubgen_test",
data = [
":_pyi_files",
":pydrake_pyi",
":pydrake_typed",
],
deps = [
"@mypy_internal//:mypy",
"@rules_python//python/runfiles",
],
)
install(
name = "install",
install_tests = [
":test/all_install_test.py",
":test/common_install_test.py",
],
targets = PY_LIBRARIES + [":all_py"],
py_dest = PACKAGE_INFO.py_dest,
data = [
":pydrake_pyi",
":pydrake_typed",
],
data_dest = "@PYTHON_SITE_PACKAGES@",
visibility = ["//visibility:public"],
deps = get_drake_py_installs(PY_LIBRARIES_WITH_INSTALL) + [
# These three modules are a special case.
# Refer to bindings/pydrake/common/module_cycle.md for details.
"//bindings/pydrake/autodiffutils:install",
"//bindings/pydrake/math:install",
"//bindings/pydrake/symbolic:install",
],
)
add_lint_tests_pydrake(
python_lint_extra_srcs = [
":test/all_install_test.py",
":test/common_install_test.py",
],
)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/pydrake_pybind.h | #pragma once
#include <utility>
// Here we include a lot of the pybind11 API, to ensure that all code in pydrake
// sees the same definitions ("One Definition Rule") for template types intended
// for specialization. Any pybind11 headers with `type_caster<>` specializations
// must be included here (e.g., eigen.h, functional.h, numpy.h, stl.h) as well
// as ADL headers (e.g., operators.h). Headers that are unused by pydrake
// (e.g., complex.h) are omitted, as are headers that do not specialize anything
// (e.g., eval.h).
#include "pybind11/eigen.h"
#include "pybind11/functional.h"
#include "pybind11/numpy.h"
#include "pybind11/operators.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "pybind11/stl/filesystem.h"
namespace drake {
/// For more high-level information, see the @ref python_bindings
/// "Python Bindings" technical notes.
///
/// Drake developers should prefer any aliases defined here over their full
/// spellings in `pybind11`.
///
/// `namespace py` is a shorthand alias to `pybind11` for consistency. (This
/// symbol cannot be exposed directly in Doxygen.)
///
/// @note Downstream users should avoid `using namespace drake::pydrake`, as
/// this may create ambiguous aliases (especially for GCC). Instead, consider
/// using your own alias directly to the `pybind11` namespace.
namespace pydrake {
// Note: Doxygen apparently doesn't process comments for namespace aliases. If
// you put Doxygen comments here they will apply instead to py_rvp.
namespace py = pybind11;
/// Shortened alias for py::return_value_policy. For more information, see
/// the @ref PydrakeReturnValuePolicy "Return Value Policy" section.
using py_rvp = py::return_value_policy;
// Implementation for `overload_cast_explicit`. We must use this structure so
// that we can constrain what is inferred. Otherwise, the ambiguity confuses
// the compiler.
template <typename Return, typename... Args>
struct overload_cast_impl {
auto operator()(Return (*func)(Args...)) const { return func; }
template <typename Class>
auto operator()(Return (Class::*method)(Args...)) const {
return method;
}
template <typename Class>
auto operator()(Return (Class::*method)(Args...) const) const {
return method;
}
};
/// Provides option to provide explicit signature when
/// `py::overload_cast<Args...>` fails to infer the Return argument.
template <typename Return, typename... Args>
constexpr auto overload_cast_explicit = overload_cast_impl<Return, Args...>{};
/// Binds Pythonic `__copy__` and `__deepcopy__` using class's copy
/// constructor.
/// @note Do not use this if the class's copy constructor does not imply a deep
/// copy.
template <typename PyClass>
void DefCopyAndDeepCopy(PyClass* ppy_class) {
using Class = typename PyClass::type;
PyClass& py_class = *ppy_class;
py_class.def("__copy__", [](const Class* self) { return Class{*self}; })
.def("__deepcopy__",
[](const Class* self, py::dict /* memo */) { return Class{*self}; });
}
/// Binds Pythonic `__copy__` and `__deepcopy__` for a class, as well as
/// `Clone` method, using class's `Clone` method rather than the copy
/// constructor.
template <typename PyClass>
void DefClone(PyClass* ppy_class) {
using Class = typename PyClass::type;
PyClass& py_class = *ppy_class;
py_class // BR
.def("Clone", &Class::Clone)
.def("__copy__", &Class::Clone)
.def("__deepcopy__",
[](const Class* self, py::dict /* memo */) { return self->Clone(); });
}
/// Returns a constructor for creating an instance of Class and initializing
/// parameters (bound using `def_readwrite`).
/// This provides an alternative to manually enumerating each
/// parameter as an argument using `py::init<...>` and `py::arg(...)`, and is
/// useful when the C++ class only has a default constructor. Example:
/// @code
/// using Class = ExampleClass;
/// py::class_<Class>(m, "ExampleClass") // BR
/// .def(ParamInit<Class>());
/// @endcode
///
/// @tparam Class The C++ class. Must have a default constructor.
template <typename Class>
auto ParamInit() {
return py::init([](py::kwargs kwargs) {
// N.B. We use `Class` here because `pybind11` strongly requires that we
// return the instance itself, not just `py::object`.
// TODO(eric.cousineau): This may hurt `keep_alive` behavior, as this
// reference may evaporate by the time the true holding pybind11 record is
// constructed. Would be alleviated using old-style pybind11 init :(
Class obj{};
py::object py_obj = py::cast(&obj, py_rvp::reference);
py::module::import("pydrake").attr("_setattr_kwargs")(py_obj, kwargs);
return obj;
});
}
/// Executes Python code to introduce additional symbols for a given module.
/// For a module with local name `{name}` and use_subdir=False, the code
/// executed will be `_{name}_extra.py`; with use_subdir=True, it will be
/// `{name}/_{name}_extra.py`. See #9599 for relevant background.
inline void ExecuteExtraPythonCode(py::module m, bool use_subdir = false) {
py::module::import("pydrake").attr("_execute_extra_python_code")(
m, use_subdir);
}
// The following works around pybind11 modules getting reconstructed /
// reimported in Python3. See pybind/pybind11#1559 for more details.
// Use this ONLY when necessary (e.g. when using a utility method which imports
// the module, within the module itself).
// TODO(eric.cousineau): Unfold cyclic references, and remove the need for this
// macro (see #11868 for rationale).
#define PYDRAKE_PREVENT_PYTHON3_MODULE_REIMPORT(variable) \
{ \
static py::handle variable##_original; \
if (variable##_original) { \
variable##_original.inc_ref(); \
variable = py::reinterpret_borrow<py::module>(variable##_original); \
return; \
} else { \
variable##_original = variable; \
} \
}
} // namespace pydrake
} // namespace drake
#define DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE(Type) \
PYBIND11_NUMPY_OBJECT_DTYPE(Type)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/_trajectories_extra.py | from pydrake.common import _MangledName
def __getattr__(name):
"""Rewrites requests for Foo[bar] into their mangled form, for backwards
compatibility with unpickling.
"""
return _MangledName.module_getattr(
module_name=__name__, module_globals=globals(), name=name)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/stubgen.py | """Command-line tool to generate Drake's Python Interface files (.pyi)."""
import importlib
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from mypy import stubgen
def _pydrake_modules():
"""Returns the list[str] of all pydrake module names."""
# This import should (as a side effect) load all pydrake modules. We have
# it as a function-local import because we don't want `_wrapper_main` to
# pay the expense of importing this.
importlib.__import__("pydrake._all_everything")
# Scrape sys.modules for pydrake modules, but excluding private modules.
result = [
"pydrake",
]
for name in sys.modules:
if not name.startswith("pydrake."):
continue
if "._" in name:
continue
result.append(name)
# Return a deterministic order to our caller.
return sorted(result)
def _pyi_generated(directory: Path):
"""Returns a list[Path] of all *.pyi files in the given directory and its
subdirectories. The directory should only contains *.pyi files; anything
else is an error.
"""
result = []
for dirpath, dirnames, filenames in os.walk(directory):
for one_filename in filenames:
assert Path(one_filename).suffix == ".pyi"
full = Path(dirpath) / one_filename
result.append(full.relative_to(directory))
# Return a deterministic order to our caller.
return sorted(result)
def _copy_pyi(pyi_generated, output_root, pyi_outputs):
"""Copies pyi_generated to pyi_outputs, with cross-checking."""
# Check for too few *.pyi files.
missing_pyi = [
x
for x in pyi_outputs
if x not in pyi_generated
]
if missing_pyi:
raise RuntimeError(
"The PYI_FILES = ... in the BUILD.bazel file specified that the "
f"{missing_pyi} should have been created, but they were not. "
"Possibly PYI_FILES should not have listed those items, or there "
"are missing imports in all.py or _all_everything.py.")
# Check for too many *.pyi files.
extra_pyi = [
x
for x in pyi_generated
if x not in pyi_outputs
]
if extra_pyi:
raise RuntimeError(
"The PYI_FILES = ... in the BUILD.bazel file did not specify "
f"that {extra_pyi} would be created, but they were. "
"Possibly PYI_FILES should list those items.")
# Just right. The lists are identical.
for pyi in pyi_outputs:
shutil.copyfile(pyi, output_root / pyi)
def _actual_main():
# Our arguments are the list of *.pyi outputs wanted from stubgen.bzl
# (which currently come from the `PYI_FILES = ...` defined in BUILD.bazel).
# They are probably relative paths, which we'll convert to an absolute
# output_root path for where "pydrake/foo.pyi" should appear, and then a
# list of relative paths under that. We must use rsplit because "pydrake"
# might appear multiple times and we want to match the final one.
output_root_str = sys.argv[1].rsplit("/pydrake/", maxsplit=1)[0]
output_root = Path(output_root_str).absolute()
pyi_outputs = sorted([
Path(path).absolute().relative_to(output_root)
for path in sys.argv[1:]
])
# Find all native modules in pydrake (i.e., excluding pure python modules).
native_modules = _pydrake_modules()
for name in native_modules[:]:
source = getattr(sys.modules[name], "__file__", "")
if source.endswith(".py"):
native_modules.remove(name)
# Run stubgen. It writes junk in the current directory, so we need to run
# it from a safe place.
with tempfile.TemporaryDirectory(prefix="drake_stubgen_") as temp:
os.chdir(temp)
args = [
"--output=."
] + [
f"--module={name}"
for name in native_modules
]
returncode = stubgen.main(args=args) or 0
assert returncode == 0, returncode
# The generation was successful. Copy the *.pyi files to output.
pyi_generated = _pyi_generated(Path(temp))
_copy_pyi(pyi_generated, output_root, pyi_outputs)
def _wrapper_main():
# By default, any console output from build actions is passed along to the
# user (in contrast with tests, whose output is muted when they succeed).
# However, it's difficult to teach mypy how to be quiet when successful, so
# we'll use a subprocess to buffer the output until we know whether or not
# there's been an error.
hint = "--inner_process"
if hint not in sys.argv:
# Call ourself again with a new argument as a hint.
completed = subprocess.run(
[sys.executable, "-B"] + sys.argv + [hint],
encoding="utf-8",
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
if completed.returncode != 0:
sys.stderr.write(completed.stdout)
return completed.returncode
else:
# We're the inner process. Ditch the argument hint and proceed.
sys.argv.remove(hint)
return _actual_main()
if __name__ == "__main__":
sys.exit(_wrapper_main())
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/lcm_py.cc | #include <cstring>
#include "drake/bindings/pydrake/common/deprecation_pybind.h"
#include "drake/bindings/pydrake/common/serialize_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/lcm/drake_lcm.h"
#include "drake/lcm/drake_lcm_interface.h"
namespace drake {
namespace pydrake {
PYBIND11_MODULE(lcm, m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::lcm;
constexpr auto& doc = pydrake_doc.drake.lcm;
py::module::import("pydrake.common");
// Use `py::bytes` as a mid-point between C++ LCM (`void* + int` /
// `vector<uint8_t>`) and Python LCM (`str`).
using PyHandlerFunction = std::function<void(py::bytes)>;
using PyMultichannelHandlerFunction =
std::function<void(std::string_view, py::bytes)>;
{
using Class = DrakeLcmInterface;
constexpr auto& cls_doc = doc.DrakeLcmInterface;
py::class_<Class>(m, "DrakeLcmInterface", cls_doc.doc)
.def("get_lcm_url", &DrakeLcmInterface::get_lcm_url,
cls_doc.get_lcm_url.doc)
.def(
"Publish",
[](Class* self, const std::string& channel, py::bytes buffer,
std::optional<double> time_sec) {
// TODO(eric.cousineau): See if there is a way to extra the raw
// bytes from `buffer` without copying.
std::string str = buffer;
self->Publish(channel, str.data(), str.size(), time_sec);
},
py::arg("channel"), py::arg("buffer"),
py::arg("time_sec") = py::none(), cls_doc.Publish.doc)
.def(
"Subscribe",
[](Class* self, const std::string& channel,
PyHandlerFunction handler) {
auto subscription = self->Subscribe(
channel, [handler](const void* data, int size) {
handler(py::bytes(static_cast<const char*>(data), size));
});
DRAKE_DEMAND(subscription != nullptr);
// This is already the default, but for clarity we'll repeat it.
subscription->set_unsubscribe_on_delete(false);
},
py::arg("channel"), py::arg("handler"), cls_doc.Subscribe.doc)
.def(
"SubscribeMultichannel",
[](Class* self, const std::string& regex,
PyMultichannelHandlerFunction handler) {
auto subscription = self->SubscribeMultichannel(
regex, [handler](std::string_view channel, const void* data,
int size) {
handler(channel,
py::bytes(static_cast<const char*>(data), size));
});
DRAKE_DEMAND(subscription != nullptr);
// This is already the default, but for clarity we'll repeat it.
subscription->set_unsubscribe_on_delete(false);
},
py::arg("regex"), py::arg("handler"),
cls_doc.SubscribeMultichannel.doc)
.def(
"SubscribeAllChannels",
[](Class* self, PyMultichannelHandlerFunction handler) {
auto subscription =
self->SubscribeAllChannels([handler](std::string_view channel,
const void* data, int size) {
handler(channel,
py::bytes(static_cast<const char*>(data), size));
});
DRAKE_DEMAND(subscription != nullptr);
// This is already the default, but for clarity we'll repeat it.
subscription->set_unsubscribe_on_delete(false);
},
py::arg("handler"), cls_doc.SubscribeAllChannels.doc)
.def("HandleSubscriptions", &DrakeLcmInterface::HandleSubscriptions,
py::arg("timeout_millis"), cls_doc.HandleSubscriptions.doc);
}
{
using Class = DrakeLcmParams;
constexpr auto& cls_doc = doc.DrakeLcmParams;
py::class_<Class> cls(m, "DrakeLcmParams", cls_doc.doc);
cls // BR
.def(ParamInit<Class>());
DefAttributesUsingSerialize(&cls, cls_doc);
DefReprUsingSerialize(&cls);
DefCopyAndDeepCopy(&cls);
}
{
using Class = DrakeLcm;
constexpr auto& cls_doc = doc.DrakeLcm;
py::class_<Class, DrakeLcmInterface> cls(m, "DrakeLcm", cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<std::string>(), py::arg("lcm_url"),
cls_doc.ctor.doc_1args_lcm_url)
.def(py::init<DrakeLcmParams>(), py::arg("params"),
cls_doc.ctor.doc_1args_params);
}
ExecuteExtraPythonCode(m);
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/math_operators_pybind.h | #pragma once
#include <algorithm>
#include <cmath>
#include <type_traits>
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/drake_bool.h"
namespace drake {
namespace pydrake {
namespace internal {
/* Returns X.inverse() but with special casing for symbolic types. */
template <typename T>
MatrixX<T> CalcMatrixInverse(const MatrixX<T>& X) {
constexpr bool is_symbolic_algebra = !scalar_predicate<T>::is_bool;
if (is_symbolic_algebra) {
const int N = X.rows();
// Note that MatrixX<Expression>.inverse() will fail for symbolic matrices
// that contain variables. We'll special case the sizes shown to work in
// `expression_matrix_test.cc`.
if (N == X.cols()) {
switch (N) {
case 1:
return Eigen::Matrix<T, 1, 1>(X).inverse();
case 2:
return Eigen::Matrix<T, 2, 2>(X).inverse();
case 3:
return Eigen::Matrix<T, 3, 3>(X).inverse();
case 4:
return Eigen::Matrix<T, 4, 4>(X).inverse();
}
}
}
return X.inverse();
}
// TODO(eric.cousineau): Deprecate these methods once we support proper NumPy
// UFuncs.
/* Adds math function overloads (ADL free functions) for the given class `T`.
This is used for both NumPy methods and `pydrake.math` module functions.
@param obj If this is py::class_, this is intended to register class methods on
to overload NumPy's math methods. If this is py::module_, this is intended to
register the overloads in `pydrake.math`. */
template <typename T, typename PyObject>
void BindMathOperators(PyObject* obj) {
// Prepare for ADL in case T is `double`.
using std::abs;
using std::acos;
using std::asin;
using std::atan;
using std::atan2;
using std::ceil;
using std::cos;
using std::cosh;
using std::exp;
using std::floor;
using std::isnan;
using std::log;
using std::max;
using std::min;
using std::pow;
using std::sin;
using std::sinh;
using std::sqrt;
using std::tan;
using std::tanh;
// A few functions differ for module vs class bindings.
constexpr bool is_module = std::is_same_v<PyObject, py::module_>;
// When binding certain types (e.g., symbolic::Variable), operations return
// a type other than the argument type.
using Promoted = decltype(std::declval<T>() + std::declval<T>());
// Add functions that exist both on the class and in the module.
(*obj) // BR
.def("abs", [](const T& x) { return abs(x); })
.def("acos", [](const T& x) { return acos(x); })
.def("arccos", [](const T& x) { return acos(x); })
.def("asin", [](const T& x) { return asin(x); })
.def("arcsin", [](const T& x) { return asin(x); })
.def("atan", [](const T& x) { return atan(x); })
.def("arctan", [](const T& x) { return atan(x); })
.def("ceil", [](const T& x) { return ceil(x); })
.def("cos", [](const T& x) { return cos(x); })
.def("cosh", [](const T& x) { return cosh(x); })
.def("exp", [](const T& x) { return exp(x); })
.def("floor", [](const T& x) { return floor(x); })
.def("log", [](const T& x) { return log(x); })
.def("max",
[](const T& x, const T& y) {
if constexpr (std::is_same_v<T, Promoted>) {
return max(x, y);
} else {
// For types that use promotion, we need to promote prior to
// calling the operator, to avoid ADL confusion with std::max.
return max(Promoted{x}, Promoted{y});
}
})
.def("min",
[](const T& x, const T& y) {
if constexpr (std::is_same_v<T, Promoted>) {
return min(x, y);
} else {
// For types that use promotion, we need to promote prior to
// calling the operator, to avoid ADL confusion with std::max.
return min(Promoted{x}, Promoted{y});
}
})
.def("pow", [](const T& x, double y) { return pow(x, y); })
.def("sin", [](const T& x) { return sin(x); })
.def("sinh", [](const T& x) { return sinh(x); })
.def("sqrt", [](const T& x) { return sqrt(x); })
.def("tan", [](const T& x) { return tan(x); })
.def("tanh", [](const T& x) { return tanh(x); });
// For symbolic types (only), the `pow` exponent can also be an Expression.
if constexpr (!scalar_predicate<T>::is_bool) {
obj->def("pow", [](const T& x, const Promoted& y) { return pow(x, y); });
}
// For atan2 the named arguments change for the module function vs the method.
{
auto func = [](const T& y, const T& x) { return atan2(y, x); };
if constexpr (is_module) {
obj->def("atan2", func, py::arg("y"), py::arg("x"));
obj->def("arctan2", func, py::arg("y"), py::arg("x"));
} else {
obj->def("atan2", func, py::arg("x"),
"Uses ``self`` for ``y`` in ``atan2(y, x)``.");
obj->def("arctan2", func, py::arg("x"),
"Uses ``self`` for ``y`` in ``arctan2(y, x)``.");
}
}
// Add functions specific to either the class or the module.
if constexpr (is_module) {
auto& m = *obj;
m // BR
.def("inv",
[](const MatrixX<T>& X) {
if constexpr (std::is_same_v<T, Promoted>) {
return CalcMatrixInverse(X);
} else {
return CalcMatrixInverse(X.template cast<Promoted>().eval());
}
})
.def(
"isnan", [](const T& x) { return isnan(x); }, py::arg("x"));
} else {
auto& cls = *obj;
cls // BR
.def("__abs__", [](const T& x) { return abs(x); })
.def("__ceil__", [](const T& x) { return ceil(x); })
.def("__floor__", [](const T& x) { return floor(x); });
}
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/.clang-format | # -*- yaml -*-
# This file determines clang-format's style settings; for details, refer to
# http://clang.llvm.org/docs/ClangFormatStyleOptions.html
BasedOnStyle: Google
Language: Cpp
# Force pointers to the type for C++.
DerivePointerAlignment: false
PointerAlignment: Left
# Compress functions onto a single line (when they fit) iff they are defined
# inline (inside a of class) or are empty.
AllowShortFunctionsOnASingleLine: Inline
# Specify the #include statement order. This implements the order mandated by
# the Google C++ Style Guide: related header, C headers, C++ headers, library
# headers, and finally the project headers.
#
# To obtain updated lists of system headers used in the below expressions, see:
# http://stackoverflow.com/questions/2027991/list-of-standard-header-files-in-c-and-c/2029106#2029106.
IncludeCategories:
# Spacers used by drake/tools/formatter.py.
- Regex: '^<clang-format-priority-15>$'
Priority: 15
- Regex: '^<clang-format-priority-25>$'
Priority: 25
- Regex: '^<clang-format-priority-35>$'
Priority: 35
- Regex: '^<clang-format-priority-45>$'
Priority: 45
# C system headers. The header_dependency_test.py contains a copy of this
# list; be sure to update that test anytime this list changes.
- Regex: '^[<"](aio|arpa/inet|assert|complex|cpio|ctype|curses|dirent|dlfcn|errno|fcntl|fenv|float|fmtmsg|fnmatch|ftw|glob|grp|iconv|inttypes|iso646|langinfo|libgen|limits|locale|math|monetary|mqueue|ndbm|netdb|net/if|netinet/in|netinet/tcp|nl_types|poll|pthread|pwd|regex|sched|search|semaphore|setjmp|signal|spawn|stdalign|stdarg|stdatomic|stdbool|stddef|stdint|stdio|stdlib|stdnoreturn|string|strings|stropts|sys/ipc|syslog|sys/mman|sys/msg|sys/resource|sys/select|sys/sem|sys/shm|sys/socket|sys/stat|sys/statvfs|sys/time|sys/times|sys/types|sys/uio|sys/un|sys/utsname|sys/wait|tar|term|termios|tgmath|threads|time|trace|uchar|ulimit|uncntrl|unistd|utime|utmpx|wchar|wctype|wordexp)\.h[">]$'
Priority: 20
# C++ system headers (as of C++23). The header_dependency_test.py contains a
# copy of this list; be sure to update that test anytime this list changes.
- Regex: '^[<"](algorithm|any|array|atomic|barrier|bit|bitset|cassert|ccomplex|cctype|cerrno|cfenv|cfloat|charconv|chrono|cinttypes|ciso646|climits|clocale|cmath|codecvt|compare|complex|concepts|condition_variable|coroutine|csetjmp|csignal|cstdalign|cstdarg|cstdbool|cstddef|cstdint|cstdio|cstdlib|cstring|ctgmath|ctime|cuchar|cwchar|cwctype|deque|exception|execution|expected|filesystem|flat_map|flat_set|format|forward_list|fstream|functional|future|generator|initializer_list|iomanip|ios|iosfwd|iostream|istream|iterator|latch|limits|list|locale|map|mdspan|memory|memory_resource|mutex|new|numbers|numeric|optional|ostream|print|queue|random|ranges|ratio|regex|scoped_allocator|semaphore|set|shared_mutex|source_location|span|spanstream|sstream|stack|stacktrace|stdexcept|stdfloat|stop_token|streambuf|string|string_view|strstream|syncstream|system_error|thread|tuple|type_traits|typeindex|typeinfo|unordered_map|unordered_set|utility|valarray|variant|vector|version)[">]$'
Priority: 30
# Other libraries' h files (with angles).
- Regex: '^<'
Priority: 40
# Your project's h files.
- Regex: '^"drake'
Priority: 50
# Other libraries' h files (with quotes).
- Regex: '^"'
Priority: 40
# -----------------------------------------------------------------------------
# Hereafter are the pydrake-specific override settings.
# -----------------------------------------------------------------------------
# Avoid widening out code horizontally a lot.
AlignAfterOpenBracket: DontAlign
# Compress lambdas as much as possible.
AllowShortLambdasOnASingleLine: All
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/pydrake.bzl | load("//tools/lint:lint.bzl", "add_lint_tests")
def add_lint_tests_pydrake(**kwargs):
data = kwargs.pop("cpplint_data", [])
data.append("//bindings/pydrake:CPPLINT.cfg")
data.append("//bindings/pydrake:.clang-format")
kwargs["cpplint_data"] = data
add_lint_tests(**kwargs)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/__init__.py | """
Python bindings for
`Drake: Model-Based Design and Verification for Robotics
<https://drake.mit.edu/>`_.
This Python API documentation is a work in progress. Most of it is generated
automatically from the C++ API documentation, and thus may have some
C++-specific artifacts. For general overview and API documentation, please see
the `Doxygen C++ Documentation
<https://drake.mit.edu/doxygen_cxx/index.html>`_.
For examples and tutorials that tie in and use this API, please see
`here <https://drake.mit.edu/#tutorials-and-examples>`_.
"""
import functools
import os
import sys
import warnings
# When importing `pydrake` as an external under Bazel, Bazel will use a shared
# library whose relative RPATHs are incorrect for `libdrake.so`, and thus will
# fail to load; this issue is captured in bazelbuild/bazel#4594. As a
# workaround, we can use a library that properly links to `libdrake.so`, but in
# `{runfiles}/{workspace}/external/drake` rather than `{runfiles}/drake`.
# Once this is loaded, all of the Python C-extension libraries
# that depend on it (and its dependencies) will load properly.
# Please note that this workaround is only important when running under the
# Bazel runfiles tree. Installed `pydrake` should not have this issue.
# N.B. We do not import `external.drake.bindings.pydrake` as this may cause
# duplicate classes to be loaded (#8810). This will not be a problem once #7912
# is resolved.
try:
import external.drake.bindings.bazel_workaround_4594_libdrake
except ImportError:
pass
def getDrakePath():
# Compatibility alias.
return os.path.abspath(common.GetDrakePath())
def _execute_extra_python_code(m, use_subdir: bool = False):
# See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and
# rationale.
if m.__name__ not in sys.modules:
# N.B. This is necessary for C++ extensions in Python 3.
sys.modules[m.__name__] = m
module_path = m.__name__.split(".")
if len(module_path) == 1:
raise RuntimeError((
"ExecuteExtraPythonCode cannot be used with the top-level "
"module `{}`. If you are writing modules in a downstream "
"project, please review this thread and ensure your import is "
"correct: https://stackoverflow.com/a/57858822/7829525"
).format(m.__name__))
top_module_name = module_path[0]
top_module_dir = os.path.dirname(sys.modules[top_module_name].__file__)
if use_subdir:
mid_module_names = module_path[1:]
else:
mid_module_names = module_path[1:-1]
base_module_name = module_path[-1]
if base_module_name.startswith("_"):
# Do not repeat leading `_`.
extra_module_name = f"{base_module_name}_extra.py"
else:
extra_module_name = f"_{base_module_name}_extra.py"
extra_path = [top_module_dir] + mid_module_names + [extra_module_name]
extra_filename = os.path.join(*extra_path)
with open(extra_filename) as f:
_code = compile(f.read(), extra_filename, 'exec')
exec(_code, m.__dict__, m.__dict__)
def _setattr_kwargs(obj, kwargs):
# For `ParamInit` in `pydrake_pybind.h`.
for name, value in kwargs.items():
setattr(obj, name, value)
def _import_cc_module_vars(
cc_module,
py_module_name,
*,
include_private=False,
):
# Imports the cc_module's public symbols into the named py module
# (py_module_name), resetting their __module__ to be the py module in the
# process.
# Returns a list[str] of the public symbol names imported.
py_module = sys.modules[py_module_name]
var_list = []
for name, value in cc_module.__dict__.items():
if name.startswith("_") and not include_private:
continue
if name.startswith("__"):
continue
if getattr(value, "__module__", None) == cc_module.__name__:
value.__module__ = py_module_name
setattr(py_module, name, value)
var_list.append(name)
return var_list
@functools.lru_cache
def _is_building_documentation():
"""Returns True iff pydrake is being imported by the website documentation
build process (i.e., Sphinx). We use this to adjust our code to be more
documentation-suitable if so.
"""
return "DRAKE_IS_BUILDING_DOCUMENTATION" in os.environ
class _DrakeImportWarning(Warning):
pass
_RTLD_GLOBAL_WARNING = r"""
You may have already (directly or indirectly) imported `torch` which uses
`RTLD_GLOBAL`. Using `RTLD_GLOBAL` may cause symbol collisions which manifest
themselves in bugs like "free(): invalid pointer". Please consider importing
`pydrake` (and related C++-wrapped libraries like `cv2`, `open3d`, etc.)
*before* importing `torch`. For more details, see:
https://github.com/pytorch/pytorch/issues/3059#issuecomment-534676459
"""
def _check_for_rtld_global_usages():
# Naively check if `torch` is using RTLD_GLOBAL. For more information, see
# the above _RTLD_GLOBAL_WARNING message, #12073, and #13707.
torch = sys.modules.get("torch")
if torch is None:
return False
# This symbol was introduced in v1.5.0 (pytorch@ddff4efa2).
# N.B. Per investigation in #13707, it seems like torch==1.4.0 also plays
# better with pydrake. However, we will keep our warning conservative.
using_rtld_global = getattr(torch, "USE_RTLD_GLOBAL_WITH_LIBTORCH", True)
if not using_rtld_global:
return False
init_file = getattr(torch, "__file__")
if init_file.endswith(".pyc"):
init_file = init_file[:-1]
if not init_file.endswith(".py"):
return False
with open(init_file) as f:
init_source = f.read()
return "sys.setdlopenflags(_dl_flags.RTLD_GLOBAL" in init_source
if _check_for_rtld_global_usages():
warnings.warn(
_RTLD_GLOBAL_WARNING, category=_DrakeImportWarning, stacklevel=3)
# We specifically load `common` prior to loading any other pydrake modules,
# in order to a) get assertion configuration done as early as possible, and b)
# detect whether we are able to load the shared libraries. But importantly,
# we need to do this *after* defining the pure Python helper functions, above,
# since they are called while loading `pydrake.common` and things it loads.
try:
from . import common
except ImportError as e:
if ('cannot open shared object file' in (e.msg or '')
and '/pydrake/' in (e.path or '')):
message = f'''
Drake failed to load a required library. This could indicate an installation
problem, or that your system is missing required distro-provided packages.
Please refer to the installation instructions to ensure that all required
dependencies are installed.
'''
# For wheel builds, we have a file with additional advice.
wheel_doc = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'INSTALLATION')
if os.path.exists(wheel_doc):
with open(wheel_doc) as f:
message += f.read()
message += '''
For more information, please see https://drake.mit.edu/installation.html
'''
print(message)
raise
__all__ = ['common', 'getDrakePath']
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/symbolic_types_pybind.h | #pragma once
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/symbolic/expression.h"
#include "drake/common/symbolic/polynomial.h"
#include "drake/common/symbolic/rational_function.h"
// Whenever we want to cast any array / matrix type of `T` in C++ (e.g.,
// `Eigen::MatrixX<T>`) to a NumPy array, we should have it in the following
// list.
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::symbolic::Expression)
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::symbolic::Formula)
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::symbolic::Monomial)
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::symbolic::Polynomial)
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::symbolic::RationalFunction)
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::symbolic::Variable)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/pydrake_doxygen.h | /** @file
Doxygen-only documentation for @ref python_bindings. */
/** @defgroup python_bindings Python Bindings
@ingroup technical_notes
@brief Details on implementing python bindings for the C++ code.
# Overview
Drake uses [pybind11](http://pybind11.readthedocs.io/en/stable/) for binding
its C++ API to Python.
At present, a fork of `pybind11` is used which permits bindings matrices with
`dtype=object`, passing `unique_ptr` objects, and prevents aliasing for Python
classes derived from `pybind11` classes.
Before delving too deep into this, please first review the user-facing
documentation about
[What's Available from Python](https://drake.mit.edu/python_bindings.html#what-s-available-from-python).
## Module Organization
<!--
TODO(eric.cousineau): Migrate the header -> module mapping to user docs.
-->
The structure of the bindings generally follow the *directory structure*, not
the namespace structure. As an example, the following code in C++:
```{.cc}
#include <drake/multibody/parsing/parser.h>
#include <drake/multibody/plant/multibody_plant.h>
using drake::multibody::MultibodyPlant;
using drake::multibody::Parser;
```
will look similar in Python, but you won't use the header file's name:
```{.py}
from pydrake.multibody.parsing import Parser
from pydrake.multibody.plant import MultibodyPlant
```
In general, you can find where a symbol is bound by searching for the symbol's
name in quotes underneath the directory `drake/bindings/pydrake`.
For example, you should search for `"MultibodyPlant"`, `"Parser"`, etc. To
elaborate, the binding of `Parser` is found in
`.../pydrake/multibody/parsing_py.cc`, and looks like this:
```{.cc}
using Class = Parser;
py::class_<Class>(m, "Parser", ...)
```
and binding of `MultibodyPlant` template instantiations are in
`.../pydrake/multibody/plant_py.cc` and look like this:
```{.cc}
using Class = MultibodyPlant<T>;
DefineTemplateClassWithDefault<Class, systems::LeafSystem<T>>(
m, "MultibodyPlant", ...)
```
where the function containing this definition is templated on type `T` and
invoked for the scalar types mentioned in `drake/common/default_scalars.h`.
Some (but not all) exceptions to the above rules:
- `drake/common/autodiff.h` symbols live in `pydrake.autodiffutils`.
- `drake/common/symbolic.h` symbols live in `pydrake.symbolic`.
- `drake/common/value.h` symbols live in `pydrake.common.value`.
- `drake/systems/framework/*.h` symbols live in `pydrake.systems.framework`
(per the rule) and the bindings are ultimately linked via
`pydrake/systems/framework_py.cc`, but for compilation speed the binding
definitions themselves are split into
`./framework_py_{semantics,systems,values}.cc`.
## `pybind11` Tips
### Python Types
Throughout the Drake code, Python types provided by `pybind11` are used, such
as `py::handle`, `py::object`, `py::module`, `py::str`, `py::list`, etc.
For an overview, see the
[pybind11 reference](http://pybind11.readthedocs.io/en/stable/reference.html).
All of these are effectively thin wrappers around `PyObject*`, and thus can be
cheaply copied.
Mutating the referred-to object also does not require passing by reference, so
you can always pass the object by value for functions, but you should document
your method if it mutates the object in a non-obvious fashion.
### Python Type Conversions
You can implicit convert between `py::object` and its derived classes (such
as `py::list`, `py::class_`, etc.), assuming the actual Python types agree.
You may also implicitly convert from `py::object` (and its derived classes) to
`py::handle`.
If you wish to convert a `py::handle` (or `PyObject*`) to `py::object` or a
derived class, you should use
[`py::reinterpret_borrow<>`](http://pybind11.readthedocs.io/en/stable/reference.html#_CPPv218reinterpret_borrow6handle).
# Conventions
## API
Any Python bindings of C++ code will maintain C++ naming conventions, as well
as Python code that is directly related to C++ symbols (e.g. shims, wrappers,
or extensions on existing bound classes).
All other Python code be Pythonic and use PEP 8 naming conventions.
For binding functions or methods, argument names should be provided that
correspond exactly to the C++ signatures using `py::arg("arg_name")`. This
permits the C++ documentation to be relevant to the Sphinx-generated
@ref PydrakeDoc "documentation", and allows for the keyword-arguments to be
used in Python.
For binding functions, methods, properties, and classes, docstrings should be
provided. These should be provided as described @ref PydrakeDoc "here".
## Testing
In general, since the Python bindings wrap tested C++ code, you do not (and
should not) repeat intricate testing logic done in C++. Instead, ensure you
exercise the Pythonic portion of the API, using kwargs when appropriate.
When testing the values of NumPy matrices, please review the documentation in
`pydrake.common.test_utilities.numpy_compare` for guidance.
## Target Conventions
### Names
- `*_py`: A Python library (can be pure Python or pybind)
- File Names: `*.py`, `*_py.cc`
- Each `*_py.cc` file should only define one package (a module; optionally
with multiple submodules under it).
- `*_pybind`: A C++ library for adding pybind-specific utilities to be consumed
by C++.
- File Names: `*_pybind.{h,cc}`
File names should follow form with their respective target.
### Visibility
- All Python libraries should generally be private, as `pydrake` will
be consumed as one encapsulated target.
- All C++ `*_pybind` libraries for binding utilities should be public to aide
downstream Bazel projects. If the API is unstable, consider making it private
with a TODO to make public once it stabilizes.
### Bazel
Given that `libdrake.so` relies on static linking for components,
any common headers should be robust against ODR violations. This can
be normally achieved by using header-only libraries.
For upstream dependencies of these libraries, do NOT depend on the direct
targets (e.g. `//common:essential`), because this will introduce runtime ODR
violations for objects that have static storage (UID counters, etc.).
Instead, you must temporarily violate IWYU because it will be satisfied by
`drake_pybind_library`, which will incorporate `libdrake.so` and the transitive
headers.
If singletons are required (e.g. for `util/cpp_param_pybind`), consider storing
the singleton values using Python.
If you are developing bindings for a small portion of Drake and would like to
avoid rebuilding a large number of components when testing, consider editing
`//tools/install/libdrake:build_components.bzl` to reduce the number of
components being built.
@anchor PydrakeModuleDefinitions
## pybind Module Definitions
- Module bindings must always be split into parts (to avoid large files that
would bloat our compile times). The easiest way to understand this pattern is
probably to look at an existing module that follows the convention (e.g.,
`pydrake/geometry/**` or `pydrake/visualization/**`), but here's a summary of
the rules:
- foo_py.h: provides function signatures for the various "Define..." helper
functions that comprise the module. In general, splitting into more
(smaller) helper functions is better than fewer (larger) helper functions.
- foo_py.cc: uses PYBIND11_MODULE to define the package or module, by
importing other dependent modules, calling the "Define..." helper functions,
and possibly defining submodules. Must not itself add bindings; it must
always call helpers that add them.
- foo_py_bar.cc: the definition for the "DefineBar" helper function.
- foo_py_quux.cc: the definition for the "DefineQuux" helper function.
- ... etc.
- Modules should be defined within the drake::pydrake namespace. Please review
this namespace for available helper methods / classes.
- Any Drake pybind module should include `pydrake_pybind.h`.
- `PYBIND_MODULE` should be used to define modules.
- The alias `namespace py = pybind11` is defined as `drake::pydrake::py`. Drake
modules should not re-define this alias at global scope.
- If a certain namespace is being bound (e.g. `drake::systems::sensors`), you
may use `using namespace drake::systems::sensors` within functions or
anonymous namespaces. Avoid `using namespace` directives otherwise.
- Any symbol referenced in a module binding (even as function/method parameters)
must either be *bound* in that compilation unit (with the binding evaluated
before to the reference), or the module must import the pydrake module in which
it is bound (e.g., `py::module::import("pydrake.foo"))`). Failure to do so can
cause errors (unable to cast unregistered types from Python to C++) and can
cause the generated docstring from pybind11 to render these types by their C++
`typeid` rather than the Python type name.
- If a module depends on the *bindings* for another module, then you should do
the following:
- Ensure that the dependent bindings module is listed in the `py_deps`
attribute for the `drake_pybind_library()` target.
- Inside the `_py.cc`, ensure that you tell Python to import dependency
bindings. This is important to load the bindings at the right time (for
documentation), and ensure the dependent bindings are executed so that users
can import that module in isolation and still have it work. This is important
when your type signatures use dependency bindings, or a class declares its
inheritance, etc.
- As an example:
# .../my_component.h
#include "drake/geometry/meshcat.h"
void MyMethod(std::shared_ptr<Meshcat> meshcat);
# bindings/.../BUILD.bazel
drake_pybind_library(
name = "my_method_py",
...
py_deps = [
...
"//bindings/pydrake/geometry",
],
...
)
# bindings/.../my_method_py.cc
PYBIND_MODULE(my_method, m) {
py::module::import("pydrake.geometry");
m.def("MyMethod", &MyMethod, ...);
}
@anchor PydrakeDoc
## Documentation
Drake uses a modified version of `mkdoc.py` from `pybind11`, where `libclang`
Python bindings are used to generate C++ docstrings accessible to the C++
binding code.
These docstrings are available within `constexpr struct ... pydrake_doc`
as `const char*` values . When these are not available or not suitable for
Python documentation, provide custom strings. If this custom string is long,
consider placing them in a heredoc string.
An example of incorporating docstrings from `pydrake_doc`:
```{.cc}
#include "drake/bindings/pydrake/documentation_pybind.h"
PYBIND11_MODULE(math, m) {
using namespace drake::math;
constexpr auto& doc = pydrake_doc.drake.math;
using T = double;
py::class_<RigidTransform<T>>(m, "RigidTransform", doc.RigidTransform.doc)
.def(py::init(), doc.RigidTransform.ctor.doc_0args)
...
.def(py::init<const RotationMatrix<T>&>(), py::arg("R"),
doc.RigidTransform.ctor.doc_1args_R)
.def(py::init<const Eigen::Quaternion<T>&, const Vector3<T>&>(),
py::arg("quaternion"), py::arg("p"),
doc.RigidTransform.ctor.doc_2args_quaternion_p)
...
.def("set_rotation", &RigidTransform<T>::set_rotation, py::arg("R"),
doc.RigidTransform.set_rotation.doc)
...
}
```
An example of supplying custom strings:
```{.cc}
constexpr char another_helper_doc[] = R"""(
Another helper docstring. This is really long.
And has multiple lines.
)""";
PYBIND11_MODULE(example, m) {
m.def("helper", []() { return 42; }, "My helper method");
m.def("another_helper", []() { return 10; }, another_helper_doc);
}
```
@note Consider using scoped aliases to abbreviate both the usage of bound types
and the docstring structures. Borrowing from above:
```{.cc}
{
using Class = RigidTransform<T>;
constexpr auto& cls_doc = doc.RigidTransform;
py::class_<Class>(m, "RigidTransform", cls_doc.doc)
.def(py::init(), cls_doc.ctor.doc_0args)
...
}
```
To view the documentation rendered in Sphinx:
bazel run //doc/pydrake:serve_sphinx [-- --browser=false]
@note Drake's online Python documentation is generated on Ubuntu Jammy, and it
is suggested to preview documentation using this platform. Other platforms may
have slightly different generated documentation.
To browse the generated documentation strings that are available for use (or
especially, to find out the names for overloaded functions' documentation),
generate and open the docstring header:
bazel build //bindings/pydrake:documentation_pybind.h
$EDITOR bazel-bin/bindings/pydrake/documentation_pybind.h
Search the comments for the symbol of interest, e.g.,
`drake::math::RigidTransform::RigidTransform<T>`, and view the include file and
line corresponding to the symbol that the docstring was pulled from.
@note This file may be large, on the order of ~100K lines; be sure to use an
efficient editor!
@note If you are debugging a certain file and want quicker generation and a
smaller generated file, you can hack `mkdoc.py` to focus only on your include
file of chioce. As an example, debugging `mathematical_program.h`:
```{.py}
...
assert len(include_files) > 0 # Existing code.
include_files = ["drake/solvers/mathematical_program.h"] # HACK
```
This may break the bindings themselves, and should only be used for inspecting
the output.
For more detail:
- Each docstring is stored in `documentation_pybind.h` in the nested structure
`pydrake_doc`.
- The docstring for a symbol without any overloads will be accessible via
`pydrake_doc.drake.{namespace...}.{symbol}.doc`.
- The docstring for an overloaded symbol will be `.doc_something` instead of
just `.doc`, where the `_something` suffix conveys some information about the
overload. Browse the documentation_pybind.h (described above) for details.
Most commonly, the names will be `doc_1args`, `doc_3args`, etc. Be sure that
the pydrake binding's signature is consistent with the docstring argument
count.
- If two or more docstrings are the same, only one new symbol is introduced.
- To suppress a Doxygen comment from mkdoc, add the custom Doxygen command
@c \@exclude_from_pydrake_mkdoc{Explanation} to the API comment text.
This is useful to help dismiss unbound overloads, so that mkdoc's choice of
`_something` name suffix is simpler for the remaining overloads, especially if
you see the symbol `.doc_was_unable_to_choose_unambiguous_names` in the
generated documentation.
- To manually specify the `.doc_foobar` identifier name, add the line
@c \@pydrake_mkdoc_identifier{foobar} to the Doxygen comment.
- The docstring for a method that is marked as deprecated in C++ Doxygen will
be named `.doc_deprecated...` instead of just `.doc...`.
@anchor PydrakeDeprecation
## Deprecation
Decorators and utilities for deprecation in pure Python are available in
[`pydrake.common.deprecation`](https://drake.mit.edu/pydrake/pydrake.common.deprecation.html).
Deprecations for Python bindings in C++ are available in
[`drake/bindings/pydrake/common/deprecation_pybind.h`](https://drake.mit.edu/doxygen_cxx/deprecation__pybind_8h.html).
For examples of how to use the deprecations and what side effects they will
have, please see:
- [`drake/bindings/.../deprecation_example/`](https://github.com/RobotLocomotion/drake/tree/master/bindings/pydrake/common/test/deprecation_example)
- [`drake/bindings/.../deprecation_utility_test.py`](https://github.com/RobotLocomotion/drake/blob/master/bindings/pydrake/common/test/deprecation_utility_test.py)
@note All deprecations in Drake should ultimately use the
[Python `warnings` module](https://docs.python.org/3.6/library/warnings.html),
and the
[`DrakeDeprecationWarning`](https://drake.mit.edu/pydrake/pydrake.common.deprecation.html#pydrake.common.deprecation.DrakeDeprecationWarning)
class. The utilities mentioned above use them.
@anchor PydrakeKeepAlive
## Keep Alive Behavior
`py::keep_alive<Nurse, Patient>()` is used heavily throughout this code. Please
first review [the pybind11 documentation](
http://pybind11.readthedocs.io/en/stable/advanced/functions.html#keep-alive).
`py::keep_alive` decorations should be added after all `py::arg`s are
specified. Terse comments should be added above these decorations to indicate
the relationship between the Nurse and the Patient and decode the meaning of
the Nurse and Patient integers by spelling out either the `py::arg` name (for
named arguments), `return` for index 0, or `self` (not `this`) for index 1 when
dealing with methods / members. The primary relationships:
- "Keep alive, ownership" implies that a Patient owns the Nurse (or vice
versa).
- "Keep alive, reference" implies a Patient that is referred to by the Nurse.
If there is an indirect / transitive relationship (storing a reference to
an argument's member or a transfer of ownership, as with
`DiagramBuilder.Build()`), append `(tr.)` to the relationship.
Some example comments:
```
// Keep alive, reference: `self` keeps `context` alive.
// Keep alive, ownership (tr.): `return` keeps `self` alive.
```
@anchor PydrakeReturnValuePolicy
## Return Value Policy
For more information about `pybind11` return value policies, see [the pybind11
documentation](
https://pybind11.readthedocs.io/en/stable/advanced/functions.html#return-value-policies).
`pydrake` offers the @ref drake::pydrake::py_rvp "py_rvp" alias to help with
shortened usage of `py::return_value_policy`. The most used (non-default)
policies in `pydrake` are `reference` and `reference_internal` due to the usage
of raw pointers / references in the public C++ API (rather than
`std::shared_ptr<>`).
@note While `py_rvp::reference_internal` effectively implies
`py_rvp::reference` and `py::keep_alive<0, 1>()`, we choose to only use it when
`self` is the intended patient (i.e. the bound item is a class method). For
static / free functions, we instead explicitly spell out `py_rvp::reference`
and `py::keep_alive<0, 1>()`.
@anchor PydrakeOverloads
## Function Overloads
To bind function overloads, please try the following (in order):
- `py::overload_cast<Args>(func)`: See [the pybind11
documentation](http://pybind11.readthedocs.io/en/stable/classes.html#overloaded-methods).
This works about 80% of the time.
- `pydrake::overload_cast_explicit<Return, Args...>(func)`: When
`py::overload_cast` does not work (not always guaranteed to work).
- `static_cast`, as mentioned in the pybind11 documentation.
- Lambdas, e.g. `[](Args... args) -> auto&& { return func(args...); }`
(using perfect forwarding when appropriate).
### Mutable vs. `const` Method Overloads
C++ has the ability to distinguish `T` and `const T` for both function arguments
and class methods. However, Python does not have a native mechanism for this. It
is possible to provide a feature like this in Python (see discussion and
prototypes in [#7793](https://github.com/RobotLocomotion/drake/issues/7793));
however, its pros (similarity to C++) have not yet outweighted the cons (awkward
non-Pythonic types and workflows).
When a function is overloaded only by its `const`-ness, choose to bind the
mutable overload, not the `const` overload.
We do this because `pybind11` evaluates overloads in the order they are bound,
and is not possible for a user to "reach" any overloads that can only be
disambiguated by const-ness.
Examples of functions to bind and not bind:
<!--
WARNING: Adding {.cc} for syntax coloring seems to cause Doxygen to break
(#15439).
-->
```
// N.B. The two free functions below aren't necessarily great in terms of coding
// and the GSG; however, we use them for illustrative purposes.
// BIND: Should be exposed.
void MyFunction(MyClass* mutable_value);
// DO NOT BIND: Identical to above mutable overload, may constrain user.
void MyFunction(const MyClass& value);
// Disambiguating an accessor solely based on `const`-ness of `this`. In
// general, you may want to avoid this.
class MyOtherClassDispreferred {
public:
...
// BIND: Even though more costly, this ensure the user has access to the
// "maximum" amount of functionality.
MyClass& value();
// DO NOT BIND: Identical to above mutable overload.
const MyClass& value() const;
};
class MyOtherClassPreferred {
public:
...
// BIND: Unambiguous.
MyClass& mutable_value();
// BIND: Unambiguous.
const MyValue& value() const;
};
```
### Public C++ API Considerations for Function and Method Templates
The motivation behind this section can be found under the
"C++ Function and Method Template Instantiations in Python" section in
`doc/python_bindings.rst`.
In general, Drake uses techniques like parameter packs and type erasure to
create sugar functions. These functions map their inputs to parameters of some
concrete, under-the-hood method that actually does the work, and is devoid of
such tricks. To facilitate python bindings, this underlying function should
also be exposed in the public API.
As an example for parameter packs,
`MultibodyPlant<T>::AddJoint<JointType, Args...>(...)`
([code permalink](https://git.io/JfqhI))
is a C++ sugar method
that uses parameter packs and ultimately passes the result to
`MultibodyPlant<T>::AddJoint<JointType>(unique_ptr<JointType>)`
([code permalink](https://git.io/JfqhU)), and only the
`unique_ptr` function is bound ([code permalink](https://git.io/Jfqie)):
```
using Class = MultibodyPlant<T>;
...
.def("AddJoint",
[](Class* self, std::unique_ptr<Joint<T>> joint) -> auto& {
return self->AddJoint(std::move(joint));
},
py::arg("joint"), py_rvp::reference_internal, cls_doc.AddJoint.doc_1args)
...
```
As an example for parameter packs,
`GeometryProperties::AddProperty<ValueType>`
([code permalink](https://git.io/JfqhL)) is a C++ sugar method that uses
type erasure and ultimately passes the result to
`GeometryProperties::AddPropertyAbstract`
([code permalink](https://git.io/Jfqhm)), and only the `AddPropertyAbstract`
flavor is used in the bindings, but in such a way that it is similar to the C++
API for `AddProperty` ([code permalink](https://git.io/JfqiT)):
```
using Class = GeometryProperties;
py::handle abstract_value_cls =
py::module::import("pydrake.systems.framework").attr("AbstractValue");
...
.def("AddProperty",
[abstract_value_cls](Class* self, const std::string& group_name,
const std::string& name, py::object value) {
py::object abstract = abstract_value_cls.attr("Make")(value);
self->AddPropertyAbstract(
group_name, name, abstract.cast<const AbstractValue&>());
},
py::arg("group_name"), py::arg("name"), py::arg("value"),
cls_doc.AddProperty.doc)
...
```
### Matrix-multiplication-like Methods
For objects that may be represented by matrices or vectors (e.g.
RigidTransform, RotationMatrix), the `*` operator (via `__mul__`) should *not*
be bound because the `*` operator in NumPy implies elemnt-wise multiplication
for arrays.
For simplicity, we instead bind the explicitly named `.multiply()` method, and
alias the `__matmul__` operator `@` to this function.
### Clone Methods
If you wish to bind a `Clone()` method, please use `DefClone()` so that
`__copy__()` and `__deepcopy__()` will also be defined. (It is simplest to do
these things together.)
@anchor PydrakeReturnVectorsOrMatrices
#### Returning Vectors or Matrices
Certain bound methods, like `RigidTransform.multiply()`, will have overloads
that can multiply and return (a) other `RigidTransform` instances, (b) vectors,
or (c) matrices (representing a list of vectors).
In the cases of (a) and (c), `pybind11` provides sufficient mechanisms to
provide an unambiguous output return type. However, for (b), `pybind11` will
return `ndarray` with shape `(3,)`. This can cause an issue when users pass
a vector of shape `(3, 1)` as input. Nominally, pybind11 will return a `(3,)`
array, but the user may expect `(3, 1)` as an output. To accommodate this, you
should use the drake::pydrake::WrapToMatchInputShape function.
@sa https://github.com/RobotLocomotion/drake/issues/13885
## Python Subclassing of C++ Classes
In general, minimize the amount in which users may subclass C++ classes in
Python. When you do wish to do this, ensure that you use a trampoline class
in `pybind`, and ensure that the trampoline class inherits from the
`py::wrapper<>` class specific to our fork of `pybind`. This ensures that no
slicing happens with the subclassed instances.
@anchor PydrakeBazelDebug
# Interactive Debugging with Bazel
If you are debugging a unitest, first try running the test with `--trace=user`
to see where the code is failing. This should cover most cases where you need
to debug C++ bits. Example:
bazel run //bindings/pydrake/systems:py/lifetime_test -- --trace=user
If you need to debug further while using Bazel, it is suggested to use
`gdbserver` for simplicity. Example:
```
# Terminal 1 - Host process.
cd drake
bazel run -c dbg \
--run_under='gdbserver localhost:9999' \
//bindings/pydrake/systems:py/lifetime_test -- \
--trace=user
# Terminal 2 - Client debugger.
cd drake
gdb -ex "dir ${PWD}/bazel-drake" \
-ex "target remote localhost:9999" \
-ex "set sysroot" \
-ex "set breakpoint pending on"
# In the GDB terminal:
(gdb) break drake::systems::Simulator<double>::Simulator
(gdb) continue
```
`set sysroot` is important for using `gdbserver`, `set breakpoint pending on`
allows you set the breakpoints before loading `libdrake.so`, and `dir ...` adds
source directories. It is also suggested that you
[enable readline history](https://stackoverflow.com/a/3176802) in `~/.gdbinit`
for ease of use.
If using CLion, you can still connect to the `gdbserver` instance.
There are analogs for `lldb` / `lldbserver` but for brevity, only GDB is
covered.
*/
// TODO(eric.cousineau): If it ever stops redirecting stdin, use
// `bazel run --run_under='gdb --args python' --script_path=...`.
/**
@addtogroup environment_variables
@{
@defgroup pydrake_python_logging DRAKE_PYTHON_LOGGING
By default, pydrake will redirect spdlog logging (from C++) to Python's
`logging` module. However, if this environment variable is set to "0",
then logging will not be redirected.
For example, to disable logging redirect, you can set the following in
your terminal before you run your process that uses pydrake:
```
export DRAKE_PYTHON_LOGGING=0
```
See also <a href="/pydrake/pydrake.common.html#pydrake.common.use_native_cpp_logging">pydrake.common.use_native_cpp_logging</a>.
@} */
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/_all_everything.py | """This (private) module is like pydrake.all, but with an even wider charter.
The pydrake.all module merges all of Drake's _stable_ modules (e.g., it does
not incorporate any of the `pydrake.examples.*`).
On the other hand, this module imports all of Drake's _public_ modules (which
are a superset of the stable modules). Importing all modules is a prerequisite
of generating our website docs, *.pyi type stub files, etc.
Anytime pydrake gains a new public module, that module needs to be added to
either pydrake.all or this file.
TODO(jwnimmer-tri) Nobody ever remembers to add their module to the lists.
We need some kind of automated cross-check to enforce the rule.
"""
import importlib
# Start with all of the stable modules.
importlib.__import__("pydrake.all")
# Add the remaining public modules.
importlib.__import__("pydrake.common.cpp_param")
importlib.__import__("pydrake.common.cpp_template")
importlib.__import__("pydrake.examples")
importlib.__import__("pydrake.examples.gym.play_cart_pole")
importlib.__import__("pydrake.examples.gym.train_cart_pole")
importlib.__import__("pydrake.gym")
importlib.__import__("pydrake.tutorials")
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/autodiff_types_pybind.h | #pragma once
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/autodiff.h"
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::AutoDiffXd)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/polynomial_types_pybind.h | #pragma once
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/polynomial.h"
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::Polynomial<double>)
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::Polynomial<drake::AutoDiffXd>)
DRAKE_PYBIND11_NUMPY_OBJECT_DTYPE( // NOLINT
drake::Polynomial<drake::symbolic::Expression>)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/tutorials.py | """Drake offers Python tutorials that can be previewed and executed as Jupyter
notebooks online with no need for local installation. To run Drake's tutorials
online, refer to the `Drake Tutorials <https://drake.mit.edu/>`_ website.
Alternatively, to run Drake's tutorials locally from an
`installed <https://drake.mit.edu/installation.html>`_ copy of Drake,
run ``python3 -m pydrake.tutorials`` to launch a Jupyter browser.
Be sure your ``PYTHONPATH`` has been set per the installation instructions,
e.g., via ``source env/bin/activate`` in the
`pip instructions <https://drake.mit.edu/pip.html>`_.
If you haven't done so already, you'll also need to install the Jupyter
notebook package on your system:
- For pip or macOS, use: ``pip install notebook``.
- For Ubuntu, use ``sudo apt-get install jupyter-notebook``.
"""
def __main():
import sys
import pydrake
sys.argv = ["notebook", f"{pydrake.getDrakePath()}/tutorials/index.ipynb"]
imported = False
try:
# Try the Jupyter >= 7 spelling first.
from notebook import app
imported = True
except ImportError:
pass
if not imported:
try:
# Try the Jupyter < 7 spelling as a fallback.
from notebook import notebookapp as app
imported = True
except ImportError:
pass
if not imported:
print("ERROR: the Jupyter notebook runtime is not installed!")
print()
print(__doc__)
sys.exit(1)
app.launch_new_instance()
if __name__ == "__main__":
__main()
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/polynomial_py.cc | #include "drake/bindings/pydrake/common/default_scalars_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/polynomial_types_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/polynomial.h"
namespace drake {
namespace pydrake {
namespace {
template <typename T>
void DoScalarDependentDefinitions(py::module m, T) {
py::tuple param = GetPyParam<T>();
using Class = Polynomial<T>;
constexpr auto& cls_doc = pydrake_doc.drake.Polynomial;
auto cls = DefineTemplateClassWithDefault<Class>(
m, "Polynomial", param, cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const T&>(), cls_doc.ctor.doc_1args_scalar)
.def(py::init<const Eigen::Ref<const Eigen::VectorXd>&>(),
py::arg("coefficients"), cls_doc.ctor.doc_1args_constEigenMatrixBase)
.def("GetNumberOfCoefficients", &Class::GetNumberOfCoefficients,
cls_doc.GetNumberOfCoefficients.doc)
.def("GetDegree", &Class::GetDegree, cls_doc.GetDegree.doc)
.def("IsAffine", &Class::IsAffine, cls_doc.IsAffine.doc)
.def("GetCoefficients", &Class::GetCoefficients,
cls_doc.GetCoefficients.doc)
.def(
"EvaluateUnivariate",
[](const Class* self, const T& x, int derivative_order) {
return self->EvaluateUnivariate(x, derivative_order);
},
py::arg("x"), py::arg("derivative_order") = 0,
cls_doc.EvaluateUnivariate.doc)
.def("Derivative", &Class::Derivative, py::arg("derivative_order") = 1,
cls_doc.Derivative.doc)
.def("Integral", &Class::Integral, py::arg("integration_constant") = 0.0,
cls_doc.Integral.doc)
.def("CoefficientsAlmostEqual", &Class::CoefficientsAlmostEqual,
py::arg("other"), py::arg("tol") = 0.0,
py::arg("tol_type") = ToleranceType::kAbsolute,
cls_doc.CoefficientsAlmostEqual.doc)
// Arithmetic
.def(-py::self)
.def(py::self + py::self)
.def(py::self + double())
.def(double() + py::self)
.def(py::self - py::self)
.def(py::self - double())
.def(double() - py::self)
.def(py::self * py::self)
.def(py::self * double())
.def(double() * py::self)
.def(py::self / double())
// Logical comparison
.def(py::self == py::self);
}
} // namespace
PYBIND11_MODULE(polynomial, m) {
py::module::import("pydrake.autodiffutils");
py::module::import("pydrake.common");
py::module::import("pydrake.symbolic");
type_visit([m](auto dummy) { DoScalarDependentDefinitions(m, dummy); },
CommonScalarPack{});
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/stubgen.bzl | def _impl(ctx):
ctx.actions.run(
mnemonic = "GenerateMypyStubs",
executable = ctx.executable.tool,
arguments = [x.path for x in ctx.outputs.outs],
outputs = ctx.outputs.outs,
)
return [DefaultInfo(
files = depset(ctx.outputs.outs),
data_runfiles = ctx.runfiles(files = ctx.outputs.outs),
)]
generate_python_stubs = rule(
implementation = _impl,
attrs = {
"tool": attr.label(
mandatory = True,
executable = True,
# We use "target" config so that we will use the to-be-installed
# pydrake binaries in order to populate the pyi stubs.
cfg = "target",
),
"outs": attr.output_list(mandatory = True),
},
)
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/perception_py.cc | #include "drake/bindings/pydrake/common/cpp_param_pybind.h"
#include "drake/bindings/pydrake/common/value_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/perception/depth_image_to_point_cloud.h"
#include "drake/perception/point_cloud.h"
#include "drake/perception/point_cloud_to_lcm.h"
namespace drake {
namespace pydrake {
namespace {
// TODO(eric.cousineau): At present, these bindings expose a minimal subset of
// features (e.g. no descriptors exposed, skipping performance-based args
// (like `skip_initialization`)). Bind these if they are useful.
void init_pc_flags(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::perception::pc_flags;
constexpr auto& doc = pydrake_doc.drake.perception.pc_flags;
{
using Class = BaseField;
constexpr auto& cls_doc = doc.BaseField;
py::enum_<Class>(m, "BaseField", py::arithmetic(), cls_doc.doc)
.value("kNone", Class::kNone, cls_doc.kNone.doc)
.value("kXYZs", Class::kXYZs, cls_doc.kXYZs.doc)
.value("kNormals", Class::kNormals, cls_doc.kNormals.doc)
.value("kRGBs", Class::kRGBs, cls_doc.kRGBs.doc);
}
{
using Class = Fields;
constexpr auto& cls_doc = doc.Fields;
py::class_<Class>(m, "Fields", cls_doc.doc)
.def(py::init<BaseFieldT>(), py::arg("base_fields"), cls_doc.ctor.doc)
.def("base_fields", &Class::base_fields, cls_doc.base_fields.doc)
.def("has_base_fields", &Class::has_base_fields,
cls_doc.has_base_fields.doc)
.def(py::self | py::self)
.def(py::self & py::self)
.def(py::self == py::self)
.def(py::self != py::self)
.def("__repr__", [](const Class& self) {
return py::str("Fields(base_fields={})").format(self.base_fields());
});
}
}
void init_perception(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::perception;
constexpr auto& doc = pydrake_doc.drake.perception;
using systems::LeafSystem;
using systems::sensors::CameraInfo;
using systems::sensors::PixelType;
py::module::import("pydrake.systems.framework");
py::module::import("pydrake.systems.sensors");
{
using Class = PointCloud;
constexpr auto& cls_doc = doc.PointCloud;
py::class_<Class> cls(m, "PointCloud", cls_doc.doc);
cls.attr("T") = GetPyParam<Class::T>()[0];
cls.attr("C") = GetPyParam<Class::C>()[0];
cls.attr("D") = GetPyParam<Class::D>()[0];
// N.B. Workaround linking error for `constexpr` bits.
cls.attr("kDefaultValue") = Class::T{Class::kDefaultValue};
cls.def_static("IsDefaultValue", &Class::IsDefaultValue, py::arg("value"),
cls_doc.IsDefaultValue.doc)
.def_static("IsInvalidValue", &Class::IsInvalidValue, py::arg("value"),
cls_doc.IsInvalidValue.doc)
.def(py::init<int, pc_flags::Fields>(), py::arg("new_size") = 0,
py::arg("fields") = pc_flags::Fields(pc_flags::kXYZs),
cls_doc.ctor.doc_3args)
.def(py::init<const PointCloud&>(), py::arg("other"),
cls_doc.ctor.doc_copy)
.def("fields", &Class::fields, cls_doc.fields.doc)
.def("size", &Class::size, cls_doc.size.doc)
.def(
"resize",
[](PointCloud* self, int new_size) { self->resize(new_size); },
py::arg("new_size"), cls_doc.resize.doc)
// XYZs
.def("has_xyzs", &Class::has_xyzs, cls_doc.has_xyzs.doc)
.def("xyzs", &Class::xyzs, py_rvp::reference_internal, cls_doc.xyzs.doc)
.def("mutable_xyzs", &Class::mutable_xyzs, py_rvp::reference_internal,
cls_doc.mutable_xyzs.doc)
.def("xyz", &Class::xyz, py::arg("i"), cls_doc.xyz.doc)
.def("mutable_xyz", &Class::mutable_xyz, py::arg("i"),
py_rvp::reference_internal, cls_doc.mutable_xyz.doc)
// Normals
.def("has_normals", &Class::has_normals, cls_doc.has_normals.doc)
.def("normals", &Class::normals, py_rvp::reference_internal,
cls_doc.normals.doc)
.def("mutable_normals", &Class::mutable_normals,
py_rvp::reference_internal, cls_doc.mutable_normals.doc)
.def("normal", &Class::normal, py::arg("i"), cls_doc.normal.doc)
.def("mutable_normal", &Class::mutable_normal, py::arg("i"),
py_rvp::reference_internal, cls_doc.mutable_normal.doc)
// RGBs
.def("has_rgbs", &Class::has_rgbs, cls_doc.has_rgbs.doc)
.def("rgbs", &Class::rgbs, py_rvp::reference_internal, cls_doc.rgbs.doc)
.def("mutable_rgbs", &Class::mutable_rgbs, py_rvp::reference_internal,
cls_doc.mutable_rgbs.doc)
.def("rgb", &Class::rgb, py::arg("i"), cls_doc.rgb.doc)
.def("mutable_rgb", &Class::mutable_rgb, py::arg("i"),
py_rvp::reference_internal, cls_doc.mutable_rgb.doc)
// Mutators.
.def(
"SetFrom",
[](PointCloud* self, const PointCloud& other) {
self->SetFrom(other);
},
py::arg("other"), cls_doc.SetFrom.doc)
.def("SetFields", &Class::SetFields, py::arg("new_fields"),
py::arg("skip_initialize") = false, cls_doc.SetFields.doc)
.def("Crop", &Class::Crop, py::arg("lower_xyz"), py::arg("upper_xyz"),
cls_doc.Crop.doc)
.def("FlipNormalsTowardPoint", &Class::FlipNormalsTowardPoint,
py::arg("p_CP"), cls_doc.FlipNormalsTowardPoint.doc)
.def("VoxelizedDownSample", &Class::VoxelizedDownSample,
py::arg("voxel_size"), py::arg("parallelize") = false,
py::call_guard<py::gil_scoped_release>(),
cls_doc.VoxelizedDownSample.doc)
.def("EstimateNormals", &Class::EstimateNormals, py::arg("radius"),
py::arg("num_closest"), py::arg("parallelize") = false,
py::call_guard<py::gil_scoped_release>(),
cls_doc.EstimateNormals.doc);
}
AddValueInstantiation<PointCloud>(m);
m.def("Concatenate", &Concatenate, py::arg("clouds"), doc.Concatenate.doc);
{
using Class = DepthImageToPointCloud;
constexpr auto& cls_doc = doc.DepthImageToPointCloud;
py::class_<Class, LeafSystem<double>>(
m, "DepthImageToPointCloud", cls_doc.doc)
.def(py::init<const CameraInfo&, PixelType, float,
pc_flags::BaseFieldT>(),
py::arg("camera_info"),
py::arg("pixel_type") = PixelType::kDepth32F,
py::arg("scale") = 1.0, py::arg("fields") = pc_flags::kXYZs,
cls_doc.ctor.doc)
.def("depth_image_input_port", &Class::depth_image_input_port,
py_rvp::reference_internal, cls_doc.depth_image_input_port.doc)
.def("color_image_input_port", &Class::color_image_input_port,
py_rvp::reference_internal, cls_doc.color_image_input_port.doc)
.def("camera_pose_input_port", &Class::camera_pose_input_port,
py_rvp::reference_internal, cls_doc.camera_pose_input_port.doc)
.def("point_cloud_output_port", &Class::point_cloud_output_port,
py_rvp::reference_internal, cls_doc.point_cloud_output_port.doc);
}
{
using Class = PointCloudToLcm;
constexpr auto& cls_doc = doc.PointCloudToLcm;
py::class_<Class, LeafSystem<double>>(m, "PointCloudToLcm", cls_doc.doc)
.def(py::init<std::string>(), py::arg("frame_name") = std::string(),
cls_doc.ctor.doc);
}
}
PYBIND11_MODULE(perception, m) {
m.doc() = "Python bindings for //perception";
py::module::import("pydrake.common");
// N.B. To stick to directory structure, we do not define this in a
// `pc_flags` submodule.
init_pc_flags(m);
init_perception(m);
}
} // namespace
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/CPPLINT.cfg | # Disable whitespace warnings. Within bindings/pydrake, we rely on
# clang-format to govern our formatting.
filter=-whitespace/line_length
filter=-whitespace/parens
| 0 |
/home/johnshepherd/drake/bindings | /home/johnshepherd/drake/bindings/pydrake/_lcm_extra.py | # See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and
# rationale.
# This is a python reimplementation of drake::lcm::Subscriber. We reimplement
# (rather than bind) the C++ class because we want message() to be a python LCM
# message, not a C++ object.
class Subscriber:
"""Subscribes to and stores a copy of the most recent message on a given
channel, for some message type. This class does NOT provide any mutex
behavior for multi-threaded locking; it should only be used in cases where
the governing DrakeLcmInterface.HandleSubscriptions is called from the same
thread that owns all copies of this object.
"""
def __init__(self, lcm, channel, lcm_type):
"""Creates a subscriber and subscribes to `channel` on `lcm`.
Args:
lcm: LCM service instance (a pydrake.lcm.DrakeLcmInterface).
channel: LCM channel name.
lcm_type: Python class generated by lcmgen.
"""
self.lcm_type = lcm_type
self.clear()
lcm.Subscribe(channel=channel, handler=self._handler)
def clear(self):
self.count = 0
self.raw = []
self.message = self.lcm_type()
def _handler(self, raw):
self.count += 1
self.raw = raw
self.message = self.lcm_type.decode(raw)
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py.h | #pragma once
/* This file declares the functions that bind the drake::examples namespace.
These functions form a complete partition of the drake::examples bindings.
The implementations of these functions are parceled out into various *.cc
files as indicated in each function's documentation. */
#include "drake/bindings/pydrake/pydrake_pybind.h"
namespace drake {
namespace pydrake {
namespace internal {
/* Defines bindings per examples_py_acrobot.cc. */
void DefineExamplesAcrobot(py::module m);
/* Defines bindings per examples_py_compass_gait.cc. */
void DefineExamplesCompassGait(py::module m);
/* Defines bindings per examples_py_manipulation_station.cc. */
void DefineExamplesManipulationStation(py::module m);
/* Defines bindings per examples_py_pendulum.cc. */
void DefineExamplesPendulum(py::module m);
/* Defines bindings per examples_py_quadrotor.cc. */
void DefineExamplesQuadrotor(py::module m);
/* Defines bindings per examples_py_rimless_wheel.cc. */
void DefineExamplesRimlessWheel(py::module m);
/* Defines bindings per examples_py_van_der_pol.cc. */
void DefineExamplesVanDerPol(py::module m);
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py_rimless_wheel.cc | #include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/examples/examples_py.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/examples/rimless_wheel/rimless_wheel.h"
#include "drake/examples/rimless_wheel/rimless_wheel_continuous_state.h"
#include "drake/examples/rimless_wheel/rimless_wheel_geometry.h"
#include "drake/examples/rimless_wheel/rimless_wheel_params.h"
namespace drake {
namespace pydrake {
namespace internal {
void DefineExamplesRimlessWheel(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::systems;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::examples::rimless_wheel;
constexpr auto& doc = pydrake_doc.drake.examples.rimless_wheel;
// TODO(eric.cousineau): At present, we only bind doubles.
// In the future, we will bind more scalar types, and enable scalar
// conversion.
using T = double;
py::class_<RimlessWheel<T>, LeafSystem<T>>(
m, "RimlessWheel", doc.RimlessWheel.doc)
.def(py::init<>(), doc.RimlessWheel.ctor.doc)
.def("get_minimal_state_output_port",
&RimlessWheel<T>::get_minimal_state_output_port,
py_rvp::reference_internal,
doc.RimlessWheel.get_minimal_state_output_port.doc)
.def("get_floating_base_state_output_port",
&RimlessWheel<T>::get_floating_base_state_output_port,
py_rvp::reference_internal,
doc.RimlessWheel.get_floating_base_state_output_port.doc)
.def_static("calc_alpha", &RimlessWheel<T>::calc_alpha, py::arg("params"),
doc.RimlessWheel.calc_alpha.doc);
py::class_<RimlessWheelParams<T>, BasicVector<T>>(
m, "RimlessWheelParams", doc.RimlessWheelParams.doc)
.def(py::init<>(), doc.RimlessWheelParams.ctor.doc)
.def(
"mass", &RimlessWheelParams<T>::mass, doc.RimlessWheelParams.mass.doc)
.def("length", &RimlessWheelParams<T>::length,
doc.RimlessWheelParams.length.doc)
.def("gravity", &RimlessWheelParams<T>::gravity,
doc.RimlessWheelParams.gravity.doc)
.def("number_of_spokes", &RimlessWheelParams<T>::number_of_spokes,
doc.RimlessWheelParams.number_of_spokes.doc)
.def("slope", &RimlessWheelParams<T>::slope,
doc.RimlessWheelParams.slope.doc)
.def("set_mass", &RimlessWheelParams<T>::set_mass,
doc.RimlessWheelParams.set_mass.doc)
.def("set_length", &RimlessWheelParams<T>::set_length,
doc.RimlessWheelParams.set_length.doc)
.def("set_gravity", &RimlessWheelParams<T>::set_gravity,
doc.RimlessWheelParams.set_gravity.doc)
.def("set_number_of_spokes", &RimlessWheelParams<T>::set_number_of_spokes,
doc.RimlessWheelParams.set_number_of_spokes.doc)
.def("set_slope", &RimlessWheelParams<T>::set_slope,
doc.RimlessWheelParams.set_slope.doc);
py::class_<RimlessWheelContinuousState<T>, BasicVector<T>>(
m, "RimlessWheelContinuousState", doc.RimlessWheelContinuousState.doc)
.def(py::init<>(), doc.RimlessWheelContinuousState.ctor.doc)
.def("theta", &RimlessWheelContinuousState<T>::theta,
doc.RimlessWheelContinuousState.theta.doc)
.def("thetadot", &RimlessWheelContinuousState<T>::thetadot,
doc.RimlessWheelContinuousState.thetadot.doc)
.def("set_theta", &RimlessWheelContinuousState<T>::set_theta,
doc.RimlessWheelContinuousState.set_theta.doc)
.def("set_thetadot", &RimlessWheelContinuousState<T>::set_thetadot,
doc.RimlessWheelContinuousState.set_thetadot.doc);
py::class_<RimlessWheelGeometry, LeafSystem<double>>(
m, "RimlessWheelGeometry", doc.RimlessWheelGeometry.doc)
.def_static("AddToBuilder",
py::overload_cast<systems::DiagramBuilder<double>*,
const systems::OutputPort<double>&,
const RimlessWheelParams<double>&, geometry::SceneGraph<double>*>(
&RimlessWheelGeometry::AddToBuilder),
py::arg("builder"), py::arg("floating_base_state_port"),
py::arg("rimless_wheel_params"), py::arg("scene_graph"),
// Keep alive, ownership: `return` keeps `builder` alive.
py::keep_alive<0, 1>(),
// See #11531 for why `py_rvp::reference` is needed.
py_rvp::reference, doc.RimlessWheelGeometry.AddToBuilder.doc_4args)
.def_static("AddToBuilder",
py::overload_cast<systems::DiagramBuilder<double>*,
const systems::OutputPort<double>&,
geometry::SceneGraph<double>*>(
&RimlessWheelGeometry::AddToBuilder),
py::arg("builder"), py::arg("floating_base_state_port"),
py::arg("scene_graph"),
// Keep alive, ownership: `return` keeps `builder` alive.
py::keep_alive<0, 1>(),
// See #11531 for why `py_rvp::reference` is needed.
py_rvp::reference, doc.RimlessWheelGeometry.AddToBuilder.doc_3args);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py_quadrotor.cc | #include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/examples/examples_py.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/examples/quadrotor/quadrotor_geometry.h"
#include "drake/examples/quadrotor/quadrotor_plant.h"
#include "drake/systems/primitives/affine_system.h"
namespace drake {
namespace pydrake {
namespace internal {
void DefineExamplesQuadrotor(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::systems;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::examples::quadrotor;
constexpr auto& doc = pydrake_doc.drake.examples.quadrotor;
// TODO(eric.cousineau): At present, we only bind doubles.
// In the future, we will bind more scalar types, and enable scalar
// conversion. Issue #7660.
using T = double;
py::class_<QuadrotorPlant<T>, LeafSystem<T>>(
m, "QuadrotorPlant", doc.QuadrotorPlant.doc)
.def(py::init<>(), doc.QuadrotorPlant.ctor.doc)
.def(py::init<double, double, const Eigen::Matrix3d&, double, double>(),
py::arg("m_arg"), py::arg("L_arg"), py::arg("I_arg"),
py::arg("kF_arg"), py::arg("kM_arg"), doc.QuadrotorPlant.ctor.doc)
.def("m", &QuadrotorPlant<T>::m, doc.QuadrotorPlant.m.doc)
.def("g", &QuadrotorPlant<T>::g, doc.QuadrotorPlant.g.doc)
.def("length", &QuadrotorPlant<T>::length, doc.QuadrotorPlant.length.doc)
.def("force_constant", &QuadrotorPlant<T>::force_constant,
doc.QuadrotorPlant.force_constant.doc)
.def("moment_constant", &QuadrotorPlant<T>::moment_constant,
doc.QuadrotorPlant.moment_constant.doc)
.def("inertia", &QuadrotorPlant<T>::inertia, py_rvp::reference_internal,
doc.QuadrotorPlant.inertia.doc);
py::class_<QuadrotorGeometry, LeafSystem<double>>(
m, "QuadrotorGeometry", doc.QuadrotorGeometry.doc)
.def("get_frame_id", &QuadrotorGeometry::get_frame_id,
doc.QuadrotorGeometry.get_frame_id.doc)
.def_static("AddToBuilder", &QuadrotorGeometry::AddToBuilder,
py::arg("builder"), py::arg("quadrotor_state_port"),
py::arg("scene_graph"), py::return_value_policy::reference,
// Keep alive, ownership: `return` keeps `builder` alive.
py::keep_alive<0, 1>(), doc.QuadrotorGeometry.AddToBuilder.doc);
m.def("StabilizingLQRController", &StabilizingLQRController,
py::arg("quadrotor_plant"), py::arg("nominal_position"),
doc.StabilizingLQRController.doc);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/BUILD.bazel | load("//bindings/pydrake:pydrake.bzl", "add_lint_tests_pydrake")
load("//tools/install:install.bzl", "install")
load(
"//tools/skylark:drake_py.bzl",
"drake_py_library",
"drake_py_unittest",
)
load(
"//tools/skylark:pybind.bzl",
"drake_pybind_library",
"get_drake_py_installs",
"get_pybind_package_info",
)
package(default_visibility = [
"//bindings/pydrake:__subpackages__",
])
# This determines how `PYTHONPATH` is configured, and how to install the
# bindings.
PACKAGE_INFO = get_pybind_package_info("//bindings")
drake_pybind_library(
name = "examples",
cc_deps = [
"//bindings/pydrake:documentation_pybind",
"//bindings/pydrake/common:deprecation_pybind",
],
cc_so_name = "__init__",
cc_srcs = [
"examples_py.h",
"examples_py.cc",
"examples_py_acrobot.cc",
"examples_py_compass_gait.cc",
"examples_py_manipulation_station.cc",
"examples_py_pendulum.cc",
"examples_py_quadrotor.cc",
"examples_py_rimless_wheel.cc",
"examples_py_van_der_pol.cc",
],
package_info = PACKAGE_INFO,
py_deps = [
"//bindings/pydrake/systems",
],
py_srcs = [
"_examples_extra.py",
],
)
PY_LIBRARIES_WITH_INSTALL = [
":examples",
"//bindings/pydrake/examples/gym",
"//bindings/pydrake/examples/multibody",
]
install(
name = "install",
py_dest = PACKAGE_INFO.py_dest,
deps = get_drake_py_installs(PY_LIBRARIES_WITH_INSTALL),
)
drake_py_unittest(
name = "acrobot_test",
deps = [
":examples",
],
)
drake_py_unittest(
name = "compass_gait_test",
deps = [
":examples",
],
)
drake_py_unittest(
name = "manipulation_station_test",
deps = [
":examples",
"//bindings/pydrake/common/test_utilities",
"//bindings/pydrake/multibody:parsing_py",
"//bindings/pydrake/multibody:plant_py",
],
)
drake_py_unittest(
name = "pendulum_test",
deps = [
":examples",
],
)
drake_py_unittest(
name = "quadrotor_test",
deps = [
":examples",
],
)
drake_py_unittest(
name = "rimless_wheel_test",
deps = [
":examples",
],
)
drake_py_unittest(
name = "van_der_pol_test",
deps = [
":examples",
],
)
add_lint_tests_pydrake()
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/_examples_extra.py | # See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and
# rationale.
import numpy as np
from pydrake.math import RigidTransform, RollPitchYaw
def _xyz_rpy_deg(xyz, rpy_deg):
return RigidTransform(RollPitchYaw(np.asarray(rpy_deg) * np.pi / 180), xyz)
def CreateManipulationClassYcbObjectList():
"""Creates a list of (model_file, pose) pairs to add five YCB objects to a
ManipulationStation with the ManipulationClass setup.
"""
ycb_object_pairs = []
# The cracker box pose
X_WCracker = _xyz_rpy_deg([0.35, 0.14, 0.09], [0, -90, 230])
ycb_object_pairs.append(
("drake_models/ycb/003_cracker_box.sdf", X_WCracker))
# The sugar box pose.
X_WSugar = _xyz_rpy_deg([0.28, -0.17, 0.03], [0, 90, 180])
ycb_object_pairs.append(
("drake_models/ycb/004_sugar_box.sdf", X_WSugar))
# The tomato soup can pose.
X_WSoup = _xyz_rpy_deg([0.40, -0.07, 0.03], [-90, 0, 180])
ycb_object_pairs.append(
("drake_models/ycb/005_tomato_soup_can.sdf", X_WSoup))
# The mustard bottle pose.
X_WMustard = _xyz_rpy_deg([0.44, -0.16, 0.09], [-90, 0, 190])
ycb_object_pairs.append(
("drake_models/ycb/006_mustard_bottle.sdf",
X_WMustard))
# The potted meat can pose.
X_WMeat = _xyz_rpy_deg([0.35, -0.32, 0.03], [-90, 0, 145])
ycb_object_pairs.append(
("drake_models/ycb/010_potted_meat_can.sdf", X_WMeat))
return ycb_object_pairs
def CreateClutterClearingYcbObjectList():
"""Creates a list of (model_file, pose) pairs to add six YCB objects to a
ManipulationStation with the ClutterClearing setup.
"""
ycb_object_pairs = []
# The cracker box pose.
X_WCracker = _xyz_rpy_deg([-0.3, -0.55, 0.2], [-90, 0, 170])
ycb_object_pairs.append(
("drake_models/ycb/003_cracker_box.sdf", X_WCracker))
# The sugar box pose.
X_WSugar = _xyz_rpy_deg([-0.3, -0.7, 0.17], [90, 90, 0])
ycb_object_pairs.append(
("drake_models/ycb/004_sugar_box.sdf", X_WSugar))
# The tomato soup can pose.
X_WSoup = _xyz_rpy_deg([-0.03, -0.57, 0.15], [-90, 0, 180])
ycb_object_pairs.append(
("drake_models/ycb/005_tomato_soup_can.sdf", X_WSoup))
# The mustard bottle pose.
X_WMustard = _xyz_rpy_deg([0.05, -0.66, 0.19], [-90, 0, 190])
ycb_object_pairs.append(
("drake_models/ycb/006_mustard_bottle.sdf",
X_WMustard))
# The gelatin box pose.
X_WGelatin = _xyz_rpy_deg([-0.15, -0.62, 0.22], [-90, 0, 210])
ycb_object_pairs.append(
("drake_models/ycb/009_gelatin_box.sdf", X_WGelatin))
# The potted meat can pose.
X_WMeat = _xyz_rpy_deg([-0.15, -0.62, 0.14], [-90, 0, 145])
ycb_object_pairs.append(
("drake_models/ycb/010_potted_meat_can.sdf", X_WMeat))
return ycb_object_pairs
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py_acrobot.cc | #include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/examples/examples_py.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/examples/acrobot/acrobot_geometry.h"
#include "drake/examples/acrobot/acrobot_input.h"
#include "drake/examples/acrobot/acrobot_params.h"
#include "drake/examples/acrobot/acrobot_plant.h"
#include "drake/examples/acrobot/acrobot_state.h"
#include "drake/examples/acrobot/spong_controller.h"
#include "drake/examples/acrobot/spong_controller_params.h"
using std::make_unique;
using std::unique_ptr;
using std::vector;
namespace drake {
namespace pydrake {
namespace internal {
void DefineExamplesAcrobot(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::systems;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::examples::acrobot;
constexpr auto& doc = pydrake_doc.drake.examples.acrobot;
// TODO(eric.cousineau): At present, we only bind doubles.
// In the future, we will bind more scalar types, and enable scalar
// conversion. Issue #7660.
using T = double;
py::class_<AcrobotPlant<T>, LeafSystem<T>>(
m, "AcrobotPlant", doc.AcrobotPlant.doc)
.def(py::init<>(), doc.AcrobotPlant.ctor.doc)
.def("DynamicsBiasTerm", &AcrobotPlant<T>::DynamicsBiasTerm,
doc.AcrobotPlant.DynamicsBiasTerm.doc)
.def("SetMitAcrobotParameters", &AcrobotPlant<T>::SetMitAcrobotParameters,
doc.AcrobotPlant.SetMitAcrobotParameters.doc)
.def("MassMatrix", &AcrobotPlant<T>::MassMatrix,
doc.AcrobotPlant.MassMatrix.doc)
.def_static("get_state",
py::overload_cast<const Context<T>&>(&AcrobotPlant<T>::get_state),
py::arg("context"),
// Keey alive, ownership: `return` keeps `context` alive
py::keep_alive<0, 1>(), doc.AcrobotPlant.get_state.doc)
.def_static("get_mutable_state",
py::overload_cast<Context<T>*>(&AcrobotPlant<T>::get_mutable_state),
py::arg("context"),
// Keep alive, ownership: `return` keeps `context` alive
py::keep_alive<0, 1>(), doc.AcrobotPlant.get_mutable_state.doc)
.def("get_parameters", &AcrobotPlant<T>::get_parameters,
py_rvp::reference_internal, py::arg("context"),
doc.AcrobotPlant.get_parameters.doc)
.def("get_mutable_parameters", &AcrobotPlant<T>::get_mutable_parameters,
py_rvp::reference_internal, py::arg("context"),
doc.AcrobotPlant.get_mutable_parameters.doc);
py::class_<AcrobotSpongController<T>, LeafSystem<T>>(
m, "AcrobotSpongController", doc.AcrobotSpongController.doc)
.def(py::init<>(), doc.AcrobotSpongController.ctor.doc)
.def("get_parameters", &AcrobotSpongController<T>::get_parameters,
py_rvp::reference, py::arg("context"),
// Keep alive, ownership: `return` keeps `context` alive.
py::keep_alive<0, 2>(), doc.AcrobotSpongController.get_parameters.doc)
.def("get_mutable_parameters",
&AcrobotSpongController<T>::get_mutable_parameters, py_rvp::reference,
py::arg("context"),
// Keep alive, ownership: `return` keeps `context` alive.
py::keep_alive<0, 2>(),
doc.AcrobotSpongController.get_mutable_parameters.doc);
py::class_<AcrobotInput<T>, BasicVector<T>>(
m, "AcrobotInput", doc.AcrobotInput.doc)
.def(py::init<>(), doc.AcrobotInput.ctor.doc)
.def("tau", &AcrobotInput<T>::tau, doc.AcrobotInput.tau.doc)
.def("set_tau", &AcrobotInput<T>::set_tau, doc.AcrobotInput.set_tau.doc);
py::class_<AcrobotParams<T>, BasicVector<T>>(
m, "AcrobotParams", doc.AcrobotParams.doc)
.def(py::init<>(), doc.AcrobotParams.ctor.doc)
.def("m1", &AcrobotParams<T>::m1, doc.AcrobotParams.m1.doc)
.def("m2", &AcrobotParams<T>::m2, doc.AcrobotParams.m2.doc)
.def("l1", &AcrobotParams<T>::l1, doc.AcrobotParams.l1.doc)
.def("lc1", &AcrobotParams<T>::lc1, doc.AcrobotParams.lc1.doc)
.def("lc2", &AcrobotParams<T>::lc2, doc.AcrobotParams.lc2.doc)
.def("Ic1", &AcrobotParams<T>::Ic1, doc.AcrobotParams.Ic1.doc)
.def("Ic2", &AcrobotParams<T>::Ic2, doc.AcrobotParams.Ic2.doc)
.def("b1", &AcrobotParams<T>::b1, doc.AcrobotParams.b1.doc)
.def("b2", &AcrobotParams<T>::b2, doc.AcrobotParams.b2.doc)
.def("gravity", &AcrobotParams<T>::gravity, doc.AcrobotParams.gravity.doc)
.def("set_m1", &AcrobotParams<T>::set_m1, doc.AcrobotParams.set_m1.doc)
.def("set_m2", &AcrobotParams<T>::set_m2, doc.AcrobotParams.set_m2.doc)
.def("set_l1", &AcrobotParams<T>::set_l1, doc.AcrobotParams.set_l1.doc)
.def("set_lc1", &AcrobotParams<T>::set_lc1, doc.AcrobotParams.set_lc1.doc)
.def("set_lc2", &AcrobotParams<T>::set_lc2, doc.AcrobotParams.set_lc2.doc)
.def("set_Ic1", &AcrobotParams<T>::set_Ic1, doc.AcrobotParams.set_Ic1.doc)
.def("set_Ic2", &AcrobotParams<T>::set_Ic2, doc.AcrobotParams.set_Ic2.doc)
.def("set_b1", &AcrobotParams<T>::set_b1, doc.AcrobotParams.set_b1.doc)
.def("set_b2", &AcrobotParams<T>::set_b2, doc.AcrobotParams.set_b2.doc)
.def("set_gravity", &AcrobotParams<T>::set_gravity,
doc.AcrobotParams.set_gravity.doc);
py::class_<AcrobotState<T>, BasicVector<T>>(
m, "AcrobotState", doc.AcrobotState.doc)
.def(py::init<>(), doc.AcrobotState.ctor.doc)
.def("theta1", &AcrobotState<T>::theta1, doc.AcrobotState.theta1.doc)
.def("theta1dot", &AcrobotState<T>::theta1dot,
doc.AcrobotState.theta1dot.doc)
.def("theta2", &AcrobotState<T>::theta2, doc.AcrobotState.theta2.doc)
.def("theta2dot", &AcrobotState<T>::theta2dot,
doc.AcrobotState.theta2dot.doc)
.def("set_theta1", &AcrobotState<T>::set_theta1,
doc.AcrobotState.set_theta1.doc)
.def("set_theta1dot", &AcrobotState<T>::set_theta1dot,
doc.AcrobotState.set_theta1dot.doc)
.def("set_theta2", &AcrobotState<T>::set_theta2,
doc.AcrobotState.set_theta2.doc)
.def("set_theta2dot", &AcrobotState<T>::set_theta2dot,
doc.AcrobotState.set_theta2dot.doc);
py::class_<SpongControllerParams<T>, BasicVector<T>>(
m, "SpongControllerParams", doc.AcrobotParams.doc)
.def(py::init<>(), doc.SpongControllerParams.ctor.doc)
.def("k_e", &SpongControllerParams<T>::k_e,
doc.SpongControllerParams.k_e.doc)
.def("k_p", &SpongControllerParams<T>::k_p,
doc.SpongControllerParams.k_p.doc)
.def("k_d", &SpongControllerParams<T>::k_d,
doc.SpongControllerParams.k_d.doc)
.def("balancing_threshold",
&SpongControllerParams<T>::balancing_threshold,
doc.SpongControllerParams.balancing_threshold.doc)
.def("set_k_e", &SpongControllerParams<T>::set_k_e,
doc.SpongControllerParams.set_k_e.doc)
.def("set_k_p", &SpongControllerParams<T>::set_k_p,
doc.SpongControllerParams.set_k_p.doc)
.def("set_k_d", &SpongControllerParams<T>::set_k_d,
doc.SpongControllerParams.set_k_d.doc)
.def("set_balancing_threshold",
&SpongControllerParams<T>::set_balancing_threshold,
doc.SpongControllerParams.set_balancing_threshold.doc);
py::class_<AcrobotGeometry, LeafSystem<double>>(
m, "AcrobotGeometry", doc.AcrobotGeometry.doc)
.def_static("AddToBuilder",
py::overload_cast<systems::DiagramBuilder<double>*,
const systems::OutputPort<double>&, const AcrobotParams<double>&,
geometry::SceneGraph<double>*>(&AcrobotGeometry::AddToBuilder),
py::arg("builder"), py::arg("acrobot_state_port"),
py::arg("acrobot_params"), py::arg("scene_graph"),
// Keep alive, ownership: `return` keeps `builder` alive.
py::keep_alive<0, 1>(),
// See #11531 for why `py_rvp::reference` is needed.
py_rvp::reference, doc.AcrobotGeometry.AddToBuilder.doc_4args)
.def_static("AddToBuilder",
py::overload_cast<systems::DiagramBuilder<double>*,
const systems::OutputPort<double>&,
geometry::SceneGraph<double>*>(&AcrobotGeometry::AddToBuilder),
py::arg("builder"), py::arg("acrobot_state_port"),
py::arg("scene_graph"),
// Keep alive, ownership: `return` keeps `builder` alive.
py::keep_alive<0, 1>(),
// See #11531 for why `py_rvp::reference` is needed.
py_rvp::reference, doc.AcrobotGeometry.AddToBuilder.doc_3args);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py_pendulum.cc | #include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/examples/examples_py.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/examples/pendulum/pendulum_geometry.h"
#include "drake/examples/pendulum/pendulum_input.h"
#include "drake/examples/pendulum/pendulum_params.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/examples/pendulum/pendulum_state.h"
using std::make_unique;
using std::unique_ptr;
using std::vector;
namespace drake {
namespace pydrake {
namespace internal {
void DefineExamplesPendulum(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::systems;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::examples::pendulum;
constexpr auto& doc = pydrake_doc.drake.examples.pendulum;
// TODO(eric.cousineau): At present, we only bind doubles.
// In the future, we will bind more scalar types, and enable scalar
// conversion.
using T = double;
py::class_<PendulumPlant<T>, LeafSystem<T>>(
m, "PendulumPlant", doc.PendulumPlant.doc)
.def(py::init<>(), doc.PendulumPlant.ctor.doc)
.def("get_state_output_port", &PendulumPlant<T>::get_state_output_port,
py_rvp::reference_internal,
doc.PendulumPlant.get_state_output_port.doc)
.def_static("get_state",
py::overload_cast<const Context<T>&>(&PendulumPlant<T>::get_state),
py::arg("context"),
// Keey alive, ownership: `return` keeps `context` alive
py::keep_alive<0, 1>(), doc.PendulumPlant.get_state.doc)
.def_static("get_mutable_state",
py::overload_cast<Context<T>*>(&PendulumPlant<T>::get_mutable_state),
py::arg("context"),
// Keey alive, ownership: `return` keeps `context` alive
py::keep_alive<0, 1>(), doc.PendulumPlant.get_mutable_state.doc)
.def("get_parameters", &PendulumPlant<T>::get_parameters,
py_rvp::reference_internal, py::arg("context"),
doc.PendulumPlant.get_parameters.doc)
.def("get_mutable_parameters", &PendulumPlant<T>::get_mutable_parameters,
py_rvp::reference_internal, py::arg("context"),
doc.PendulumPlant.get_mutable_parameters.doc);
py::class_<PendulumInput<T>, BasicVector<T>>(
m, "PendulumInput", doc.PendulumInput.doc)
.def(py::init<>(), doc.PendulumInput.ctor.doc)
.def("tau", &PendulumInput<T>::tau, doc.PendulumInput.tau.doc)
.def("set_tau", &PendulumInput<T>::set_tau, py::arg("tau"),
doc.PendulumInput.set_tau.doc)
.def("with_tau", &PendulumInput<T>::with_tau, py::arg("tau"),
doc.PendulumInput.with_tau.doc);
py::class_<PendulumParams<T>, BasicVector<T>>(
m, "PendulumParams", doc.PendulumParams.doc)
.def(py::init<>(), doc.PendulumParams.ctor.doc)
.def("mass", &PendulumParams<T>::mass, doc.PendulumParams.mass.doc)
.def("length", &PendulumParams<T>::length, doc.PendulumParams.length.doc)
.def("damping", &PendulumParams<T>::damping,
doc.PendulumParams.damping.doc)
.def("gravity", &PendulumParams<T>::gravity,
doc.PendulumParams.gravity.doc)
.def("set_mass", &PendulumParams<T>::set_mass, py::arg("mass"),
doc.PendulumParams.set_mass.doc)
.def("set_length", &PendulumParams<T>::set_length, py::arg("length"),
doc.PendulumParams.set_length.doc)
.def("set_damping", &PendulumParams<T>::set_damping, py::arg("damping"),
doc.PendulumParams.set_damping.doc)
.def("set_gravity", &PendulumParams<T>::set_gravity, py::arg("gravity"),
doc.PendulumParams.set_gravity.doc)
.def("with_mass", &PendulumParams<T>::with_mass, py::arg("mass"),
doc.PendulumParams.with_mass.doc)
.def("with_length", &PendulumParams<T>::with_length, py::arg("length"),
doc.PendulumParams.with_length.doc)
.def("with_damping", &PendulumParams<T>::with_damping, py::arg("damping"),
doc.PendulumParams.with_damping.doc)
.def("with_gravity", &PendulumParams<T>::with_gravity, py::arg("gravity"),
doc.PendulumParams.with_gravity.doc);
py::class_<PendulumState<T>, BasicVector<T>>(
m, "PendulumState", doc.PendulumState.doc)
.def(py::init<>(), doc.PendulumState.ctor.doc)
.def("theta", &PendulumState<T>::theta, doc.PendulumState.theta.doc)
.def("thetadot", &PendulumState<T>::thetadot,
doc.PendulumState.thetadot.doc)
.def("set_theta", &PendulumState<T>::set_theta, py::arg("theta"),
doc.PendulumState.set_theta.doc)
.def("set_thetadot", &PendulumState<T>::set_thetadot, py::arg("thetadot"),
doc.PendulumState.set_thetadot.doc)
.def("with_theta", &PendulumState<T>::with_theta, py::arg("theta"),
doc.PendulumState.with_theta.doc)
.def("with_thetadot", &PendulumState<T>::with_thetadot,
py::arg("thetadot"), doc.PendulumState.with_thetadot.doc);
py::class_<PendulumGeometry, LeafSystem<double>>(
m, "PendulumGeometry", doc.PendulumGeometry.doc)
.def_static("AddToBuilder", &PendulumGeometry::AddToBuilder,
py::arg("builder"), py::arg("pendulum_state_port"),
py::arg("scene_graph"),
// Keep alive, ownership: `return` keeps `builder` alive.
py::keep_alive<0, 1>(),
// See #11531 for why `py_rvp::reference` is needed.
py_rvp::reference, doc.PendulumGeometry.AddToBuilder.doc);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py_compass_gait.cc | #include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/examples/examples_py.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/examples/compass_gait/compass_gait.h"
#include "drake/examples/compass_gait/compass_gait_continuous_state.h"
#include "drake/examples/compass_gait/compass_gait_geometry.h"
#include "drake/examples/compass_gait/compass_gait_params.h"
namespace drake {
namespace pydrake {
namespace internal {
void DefineExamplesCompassGait(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::systems;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::examples::compass_gait;
constexpr auto& doc = pydrake_doc.drake.examples.compass_gait;
// TODO(eric.cousineau): At present, we only bind doubles.
// In the future, we will bind more scalar types, and enable scalar
// conversion.
using T = double;
py::class_<CompassGait<T>, LeafSystem<T>>(
m, "CompassGait", doc.CompassGait.doc)
.def(py::init<>(), doc.CompassGait.ctor.doc)
.def("get_minimal_state_output_port",
&CompassGait<T>::get_minimal_state_output_port,
py_rvp::reference_internal,
doc.CompassGait.get_minimal_state_output_port.doc)
.def("get_floating_base_state_output_port",
&CompassGait<T>::get_floating_base_state_output_port,
py_rvp::reference_internal,
doc.CompassGait.get_floating_base_state_output_port.doc);
py::class_<CompassGaitParams<T>, BasicVector<T>>(
m, "CompassGaitParams", doc.CompassGaitParams.doc)
.def(py::init<>(), doc.CompassGaitParams.ctor.doc)
.def("mass_hip", &CompassGaitParams<T>::mass_hip,
doc.CompassGaitParams.mass_hip.doc)
.def("mass_leg", &CompassGaitParams<T>::mass_leg,
doc.CompassGaitParams.mass_leg.doc)
.def("length_leg", &CompassGaitParams<T>::length_leg,
doc.CompassGaitParams.length_leg.doc)
.def("center_of_mass_leg", &CompassGaitParams<T>::center_of_mass_leg,
doc.CompassGaitParams.center_of_mass_leg.doc)
.def("gravity", &CompassGaitParams<T>::gravity,
doc.CompassGaitParams.gravity.doc)
.def("slope", &CompassGaitParams<T>::slope,
doc.CompassGaitParams.slope.doc)
.def("set_mass_hip", &CompassGaitParams<T>::set_mass_hip,
doc.CompassGaitParams.set_mass_hip.doc)
.def("set_mass_leg", &CompassGaitParams<T>::set_mass_leg,
doc.CompassGaitParams.set_mass_leg.doc)
.def("set_length_leg", &CompassGaitParams<T>::set_length_leg,
doc.CompassGaitParams.set_length_leg.doc)
.def("set_center_of_mass_leg",
&CompassGaitParams<T>::set_center_of_mass_leg,
doc.CompassGaitParams.set_center_of_mass_leg.doc)
.def("set_gravity", &CompassGaitParams<T>::set_gravity,
doc.CompassGaitParams.set_gravity.doc)
.def("set_slope", &CompassGaitParams<T>::set_slope,
doc.CompassGaitParams.set_slope.doc);
py::class_<CompassGaitContinuousState<T>, BasicVector<T>>(
m, "CompassGaitContinuousState", doc.CompassGaitContinuousState.doc)
.def(py::init<>(), doc.CompassGaitContinuousState.ctor.doc)
.def("stance", &CompassGaitContinuousState<T>::stance,
doc.CompassGaitContinuousState.stance.doc)
.def("swing", &CompassGaitContinuousState<T>::swing,
doc.CompassGaitContinuousState.swing.doc)
.def("stancedot", &CompassGaitContinuousState<T>::stancedot,
doc.CompassGaitContinuousState.stancedot.doc)
.def("swingdot", &CompassGaitContinuousState<T>::swingdot,
doc.CompassGaitContinuousState.swingdot.doc)
.def("set_stance", &CompassGaitContinuousState<T>::set_stance,
doc.CompassGaitContinuousState.set_stance.doc)
.def("set_swing", &CompassGaitContinuousState<T>::set_swing,
doc.CompassGaitContinuousState.set_swing.doc)
.def("set_stancedot", &CompassGaitContinuousState<T>::set_stancedot,
doc.CompassGaitContinuousState.set_stancedot.doc)
.def("set_swingdot", &CompassGaitContinuousState<T>::set_swingdot,
doc.CompassGaitContinuousState.set_swingdot.doc);
py::class_<CompassGaitGeometry, LeafSystem<double>>(
m, "CompassGaitGeometry", doc.CompassGaitGeometry.doc)
.def_static("AddToBuilder",
py::overload_cast<systems::DiagramBuilder<double>*,
const systems::OutputPort<double>&,
const CompassGaitParams<double>&, geometry::SceneGraph<double>*>(
&CompassGaitGeometry::AddToBuilder),
py::arg("builder"), py::arg("floating_base_state_port"),
py::arg("compass_gait_params"), py::arg("scene_graph"),
// Keep alive, ownership: `return` keeps `builder` alive.
py::keep_alive<0, 1>(),
// See #11531 for why `py_rvp::reference` is needed.
py_rvp::reference, doc.CompassGaitGeometry.AddToBuilder.doc_4args)
.def_static("AddToBuilder",
py::overload_cast<systems::DiagramBuilder<double>*,
const systems::OutputPort<double>&,
geometry::SceneGraph<double>*>(
&CompassGaitGeometry::AddToBuilder),
py::arg("builder"), py::arg("floating_base_state_port"),
py::arg("scene_graph"),
// Keep alive, ownership: `return` keeps `builder` alive.
py::keep_alive<0, 1>(),
// See #11531 for why `py_rvp::reference` is needed.
py_rvp::reference, doc.CompassGaitGeometry.AddToBuilder.doc_3args);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py_van_der_pol.cc | #include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/examples/examples_py.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/examples/van_der_pol/van_der_pol.h"
namespace drake {
namespace pydrake {
namespace internal {
void DefineExamplesVanDerPol(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::systems;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::examples::van_der_pol;
constexpr auto& doc = pydrake_doc.drake.examples.van_der_pol;
// TODO(eric.cousineau): At present, we only bind doubles.
// In the future, we will bind more scalar types, and enable scalar
// conversion.
using T = double;
py::class_<VanDerPolOscillator<T>, LeafSystem<T>>(
m, "VanDerPolOscillator", doc.VanDerPolOscillator.doc)
.def(py::init<>(), doc.VanDerPolOscillator.ctor.doc)
.def("get_position_output_port",
&VanDerPolOscillator<T>::get_position_output_port,
py_rvp::reference_internal,
doc.VanDerPolOscillator.get_position_output_port.doc)
.def("get_full_state_output_port",
&VanDerPolOscillator<T>::get_full_state_output_port,
py_rvp::reference_internal,
doc.VanDerPolOscillator.get_full_state_output_port.doc)
.def_static("CalcLimitCycle", &VanDerPolOscillator<T>::CalcLimitCycle,
doc.VanDerPolOscillator.CalcLimitCycle.doc);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py_manipulation_station.cc | #include "drake/bindings/pydrake/common/deprecation_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/examples/examples_py.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/examples/manipulation_station/manipulation_station.h"
#include "drake/examples/manipulation_station/manipulation_station_hardware_interface.h" // noqa
using std::make_unique;
using std::unique_ptr;
using std::vector;
namespace drake {
namespace pydrake {
namespace internal {
void DefineExamplesManipulationStation(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::systems;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::examples::manipulation_station;
constexpr auto& doc = pydrake_doc.drake.examples.manipulation_station;
// ManipulationStation currently only supports double.
using T = double;
py::enum_<IiwaCollisionModel>(
m, "IiwaCollisionModel", doc.IiwaCollisionModel.doc)
.value("kNoCollision", IiwaCollisionModel::kNoCollision,
doc.IiwaCollisionModel.kNoCollision.doc)
.value("kBoxCollision", IiwaCollisionModel::kBoxCollision,
doc.IiwaCollisionModel.kBoxCollision.doc)
.export_values();
py::enum_<SchunkCollisionModel>(
m, "SchunkCollisionModel", doc.SchunkCollisionModel.doc)
.value(
"kBox", SchunkCollisionModel::kBox, doc.SchunkCollisionModel.kBox.doc)
.value("kBoxPlusFingertipSpheres",
SchunkCollisionModel::kBoxPlusFingertipSpheres,
doc.SchunkCollisionModel.kBoxPlusFingertipSpheres.doc)
.export_values();
{
using Class = ManipulationStation<T>;
const auto& cls_doc = doc.ManipulationStation;
py::class_<Class, Diagram<T>> cls(m, "ManipulationStation", cls_doc.doc);
cls // BR
.def(py::init<double>(), py::arg("time_step") = 0.002, cls_doc.ctor.doc)
.def("SetupManipulationClassStation",
&Class::SetupManipulationClassStation,
py::arg("collision_model") = IiwaCollisionModel::kNoCollision,
py::arg("schunk_model") = SchunkCollisionModel::kBox,
cls_doc.SetupManipulationClassStation.doc)
.def("SetupClutterClearingStation", &Class::SetupClutterClearingStation,
py::arg("X_WCameraBody") = std::nullopt,
py::arg("collision_model") = IiwaCollisionModel::kNoCollision,
py::arg("schunk_model") = SchunkCollisionModel::kBox,
cls_doc.SetupClutterClearingStation.doc)
.def("SetupPlanarIiwaStation", &Class::SetupPlanarIiwaStation,
py::arg("schunk_model") = SchunkCollisionModel::kBox,
cls_doc.SetupPlanarIiwaStation.doc)
.def("AddManipulandFromFile", &Class::AddManipulandFromFile,
py::arg("model_file"), py::arg("X_WObject"),
cls_doc.AddManipulandFromFile.doc)
.def("RegisterIiwaControllerModel", &Class::RegisterIiwaControllerModel,
cls_doc.RegisterIiwaControllerModel.doc)
.def("RegisterRgbdSensor",
py::overload_cast<const std::string&, const multibody::Frame<T>&,
const math::RigidTransform<double>&,
const geometry::render::DepthRenderCamera&>(
&Class::RegisterRgbdSensor),
cls_doc.RegisterRgbdSensor.doc_single_camera)
.def("RegisterRgbdSensor",
py::overload_cast<const std::string&, const multibody::Frame<T>&,
const math::RigidTransform<double>&,
const geometry::render::ColorRenderCamera&,
const geometry::render::DepthRenderCamera&>(
&Class::RegisterRgbdSensor),
cls_doc.RegisterRgbdSensor.doc_dual_camera)
.def("RegisterWsgControllerModel", &Class::RegisterWsgControllerModel,
cls_doc.RegisterWsgControllerModel.doc)
.def("Finalize", py::overload_cast<>(&Class::Finalize),
cls_doc.Finalize.doc_0args)
.def("num_iiwa_joints", &Class::num_iiwa_joints,
cls_doc.num_iiwa_joints.doc)
.def("get_multibody_plant", &Class::get_multibody_plant,
py_rvp::reference_internal, cls_doc.get_multibody_plant.doc)
.def("get_mutable_multibody_plant", &Class::get_mutable_multibody_plant,
py_rvp::reference_internal, cls_doc.get_mutable_multibody_plant.doc)
.def("get_scene_graph", &Class::get_scene_graph,
py_rvp::reference_internal, cls_doc.get_scene_graph.doc)
.def("get_mutable_scene_graph", &Class::get_mutable_scene_graph,
py_rvp::reference_internal, cls_doc.get_mutable_scene_graph.doc)
.def("get_controller_plant", &Class::get_controller_plant,
py_rvp::reference_internal, cls_doc.get_controller_plant.doc)
.def("GetIiwaPosition", &Class::GetIiwaPosition,
cls_doc.GetIiwaPosition.doc)
.def("SetIiwaPosition",
overload_cast_explicit<void, systems::Context<T>*,
const Eigen::Ref<const VectorX<T>>&>(&Class::SetIiwaPosition),
py::arg("station_context"), py::arg("q"),
cls_doc.SetIiwaPosition.doc_2args)
.def("GetIiwaVelocity", &Class::GetIiwaVelocity,
cls_doc.GetIiwaVelocity.doc)
.def("SetIiwaVelocity",
overload_cast_explicit<void, systems::Context<T>*,
const Eigen::Ref<const VectorX<T>>&>(&Class::SetIiwaVelocity),
py::arg("station_context"), py::arg("v"),
cls_doc.SetIiwaVelocity.doc_2args)
.def("GetWsgPosition", &Class::GetWsgPosition,
cls_doc.GetWsgPosition.doc)
.def("SetWsgPosition",
overload_cast_explicit<void, systems::Context<T>*, const T&>(
&Class::SetWsgPosition),
py::arg("station_context"), py::arg("q"),
cls_doc.SetWsgPosition.doc_2args)
.def("GetWsgVelocity", &Class::GetWsgVelocity,
cls_doc.GetWsgVelocity.doc)
.def("SetWsgVelocity",
overload_cast_explicit<void, systems::Context<T>*, const T&>(
&Class::SetWsgVelocity),
py::arg("station_context"), py::arg("v"),
cls_doc.SetWsgVelocity.doc_2args)
.def("GetStaticCameraPosesInWorld", &Class::GetStaticCameraPosesInWorld,
py_rvp::reference_internal, cls_doc.GetStaticCameraPosesInWorld.doc)
.def("get_camera_names", &Class::get_camera_names,
cls_doc.get_camera_names.doc)
.def("SetWsgGains", &Class::SetWsgGains, cls_doc.SetWsgGains.doc)
.def("SetIiwaPositionGains", &Class::SetIiwaPositionGains,
cls_doc.SetIiwaPositionGains.doc)
.def("SetIiwaVelocityGains", &Class::SetIiwaVelocityGains,
cls_doc.SetIiwaVelocityGains.doc)
.def("SetIiwaIntegralGains", &Class::SetIiwaIntegralGains,
cls_doc.SetIiwaIntegralGains.doc);
}
py::class_<ManipulationStationHardwareInterface, Diagram<double>>(m,
"ManipulationStationHardwareInterface",
doc.ManipulationStationHardwareInterface.doc)
.def(py::init<const std::vector<std::string>>(),
py::arg("camera_names") = std::vector<std::string>{},
doc.ManipulationStationHardwareInterface.ctor.doc)
.def("Connect", &ManipulationStationHardwareInterface::Connect,
py::arg("wait_for_cameras") = true,
doc.ManipulationStationHardwareInterface.Connect.doc)
.def("get_controller_plant",
&ManipulationStationHardwareInterface::get_controller_plant,
py_rvp::reference_internal,
doc.ManipulationStationHardwareInterface.get_controller_plant.doc)
.def("get_camera_names",
&ManipulationStationHardwareInterface::get_camera_names,
py_rvp::reference_internal,
doc.ManipulationStationHardwareInterface.get_camera_names.doc)
.def("num_iiwa_joints",
&ManipulationStationHardwareInterface::num_iiwa_joints,
doc.ManipulationStationHardwareInterface.num_iiwa_joints.doc);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/examples/examples_py.cc | #include "drake/bindings/pydrake/examples/examples_py.h"
namespace drake {
namespace pydrake {
PYBIND11_MODULE(examples, m) {
PYDRAKE_PREVENT_PYTHON3_MODULE_REIMPORT(m);
m.doc() = R"""(
Provides bindings of existing C++ example library code as well as a few pure
Python examples.
)""";
py::module::import("pydrake.geometry");
py::module::import("pydrake.multibody.plant");
py::module::import("pydrake.systems.framework");
py::module::import("pydrake.systems.primitives");
py::module::import("pydrake.systems.sensors");
// These are in alphabetical order; the modules do not depend on each other.
internal::DefineExamplesAcrobot(m);
internal::DefineExamplesCompassGait(m);
internal::DefineExamplesManipulationStation(m);
internal::DefineExamplesPendulum(m);
internal::DefineExamplesQuadrotor(m);
internal::DefineExamplesRimlessWheel(m);
internal::DefineExamplesVanDerPol(m);
const bool use_subdir = true;
ExecuteExtraPythonCode(m, use_subdir);
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/gym/play_cart_pole.py | """
Play a policy for //bindings/pydrake/examples/gym/envs:cart_pole.
"""
import argparse
import warnings
import gymnasium as gym
import stable_baselines3
from stable_baselines3.common.env_checker import check_env
from pydrake.geometry import StartMeshcat
from pydrake.examples.gym._bazel_cwd_helpers import bazel_chdir
def _run_playing(args):
if args.log_path is None:
log = args.log_path
else:
log = "./rl/tmp/CartPole/play_runs/"
# Make a version of the env with meshcat.
meshcat = StartMeshcat()
print(f"For visualization, "
f"open the url {meshcat.web_url()} in your browser.")
env = gym.make(
"DrakeCartPole-v0",
meshcat=meshcat,
time_limit=7,
debug=args.debug,
obs_noise=True,
add_disturbances=True)
if args.test:
check_env(env)
rate = 1.0 if not args.test else 0.0
env.simulator.set_target_realtime_rate(rate)
max_steps = 1e5 if not args.test else 5e1
if not args.test:
assert "drake_internal" not in stable_baselines3.__version__
from stable_baselines3 import PPO
model = PPO.load(args.model_path, env, verbose=1, tensorboard_log=log)
obs, _ = env.reset()
for _ in range(int(max_steps)):
if args.test:
# Plays a random policy.
action = env.action_space.sample()
else:
action, _states = model.predict(obs, deterministic=True)
obs, reward, terminated, truncated, info = env.step(action)
if args.debug:
# This will play the policy step by step.
input("Press Enter to continue...")
env.render()
if terminated or truncated:
if args.debug:
input("The environment will reset. Press Enter to continue...")
obs, _ = env.reset()
def _main():
bazel_chdir()
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--test', action='store_true')
parser.add_argument('--debug', action='store_true')
parser.add_argument('--model_path', help="path to the policy zip file.")
parser.add_argument('--log_path', help="path to the logs directory.")
args = parser.parse_args()
if not args.debug:
warnings.filterwarnings("ignore")
gym.envs.register(id="DrakeCartPole-v0",
entry_point="pydrake.examples.gym.envs.cart_pole:DrakeCartPoleEnv") # noqa
_run_playing(args)
if __name__ == '__main__':
_main()
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/gym/_bazel_cwd_helpers.py | import os
def bazel_chdir():
"""When using `bazel run`, the current working directory ("cwd") of the
program is set to a deeply-nested runfiles directory, not the actual cwd.
In case relative paths are given on the command line, we need to restore
the original cwd so that those paths resolve correctly.
"""
if 'BUILD_WORKSPACE_DIRECTORY' in os.environ:
os.chdir(os.environ['BUILD_WORKSPACE_DIRECTORY'])
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/gym/BUILD.bazel | load("@python//:version.bzl", "PYTHON_VERSION")
load("//bindings/pydrake:pydrake.bzl", "add_lint_tests_pydrake")
load("//tools/install:install.bzl", "install")
load(
"//tools/skylark:drake_py.bzl",
"drake_py_binary",
"drake_py_library",
"drake_py_test",
)
load(
"//tools/skylark:pybind.bzl",
"get_pybind_package_info",
)
package(default_visibility = [
"//bindings/pydrake:__subpackages__",
])
# This determines how `PYTHONPATH` is configured, and how to install the
# bindings.
PACKAGE_INFO = get_pybind_package_info("//bindings")
drake_py_library(
name = "module_py",
srcs = ["__init__.py"],
deps = [
"//bindings/pydrake/examples",
],
)
drake_py_library(
name = "named_view_helpers_py",
srcs = ["named_view_helpers.py"],
deps = [
":module_py",
"//bindings/pydrake/multibody",
],
)
drake_py_library(
name = "bazel_cwd_helpers_py",
srcs = ["_bazel_cwd_helpers.py"],
deps = [
":module_py",
],
)
drake_py_library(
name = "cart_pole_py",
srcs = ["envs/cart_pole.py"],
data = [
"models/cartpole_BSA.sdf",
],
deps = [
":module_py",
":named_view_helpers_py",
"//bindings/pydrake/geometry",
"//bindings/pydrake/gym",
"//bindings/pydrake/multibody",
"//bindings/pydrake/systems",
],
)
drake_py_library(
name = "cart_pole_binaries",
srcs = [
"play_cart_pole.py",
"train_cart_pole.py",
],
deps = [
":bazel_cwd_helpers_py",
":cart_pole_py",
":module_py",
"//bindings/pydrake/geometry",
],
)
drake_py_binary(
name = "train_cart_pole",
srcs = ["train_cart_pole.py"],
deps = [
":cart_pole_binaries",
],
)
drake_py_binary(
name = "play_cart_pole",
srcs = ["play_cart_pole.py"],
deps = [
":cart_pole_binaries",
],
)
# Get some test coverage on the example; `--test` limits its time
# and CPU budget.
drake_py_test(
name = "train_cart_pole_test",
srcs = ["train_cart_pole.py"],
args = ["--test"],
main = "train_cart_pole.py",
# DrakeGym is only supported for Python >= 3.10.
tags = ["manual"] if PYTHON_VERSION in [
"3.8",
"3.9",
] else [],
deps = [
":cart_pole_binaries",
"@gymnasium_py",
"@stable_baselines3_internal//:stable_baselines3",
],
)
drake_py_test(
name = "play_cart_pole_test",
srcs = ["play_cart_pole.py"],
args = ["--test"],
main = "play_cart_pole.py",
# DrakeGym is only supported for Python >= 3.10.
tags = ["manual"] if PYTHON_VERSION in [
"3.8",
"3.9",
] else [],
deps = [
":cart_pole_binaries",
"@gymnasium_py",
"@stable_baselines3_internal//:stable_baselines3",
],
)
PY_LIBRARIES = [
":cart_pole_binaries",
":cart_pole_py",
":named_view_helpers_py",
]
# Package roll-up (for Bazel dependencies).
# N.B. `examples` packages do not have `all` modules.
drake_py_library(
name = "gym",
imports = PACKAGE_INFO.py_imports,
deps = PY_LIBRARIES,
)
install(
name = "install",
targets = PY_LIBRARIES,
py_dest = PACKAGE_INFO.py_dest,
)
add_lint_tests_pydrake()
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/gym/README.md | Examples for Drake Gym
======================
This directory contains some simple examples using drake_gym. For more detail
see the documentation for [drake_gym itself](/bindings/pydrake/gym/README.md).
THIS FEATURE IS EXPERIMENTAL. Development is ongoing and no guarantees against deprecation are provided for any file under this directory.
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/gym/__init__.py | """Provides examples of using ``pydrake.gym``.
"""
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/gym/named_view_helpers.py | """
The following functions provide a convenient method
to print and access vectors by state or actuator name.
"""
from pydrake.common.containers import namedview
from pydrake.multibody.tree import (
JointIndex,
)
def MakeNamedViewActuation(plant, view_name):
names = [None] * plant.get_actuation_input_port().size()
for ind in plant.GetJointActuatorIndices():
actuator = plant.get_joint_actuator(ind)
assert actuator.num_inputs() == 1
names[actuator.input_start()] = actuator.name()
return namedview(view_name, names)
# Adapted from https://github.com/RussTedrake/manipulation/blob/master/manipulation/utils.py # noqa
# TODO(russt): consider making a version with model_instance
def MakeNamedViewPositions(plant,
view_name,
add_suffix_if_single_position=False):
names = [None] * plant.num_positions()
for ind in plant.GetJointIndices():
joint = plant.get_joint(JointIndex(ind))
if joint.num_positions() == 1 and not add_suffix_if_single_position:
names[joint.position_start()] = joint.name()
else:
for i in range(joint.num_positions()):
names[joint.position_start() + i] = \
f"{joint.name()}_{joint.position_suffix(i)}"
for ind in plant.GetFloatingBaseBodies():
body = plant.get_body(ind)
start = body.floating_positions_start()
for i in range(7):
names[start
+ i] = f"{body.name()}_{body.floating_position_suffix(i)}"
return namedview(view_name, names)
def MakeNamedViewVelocities(plant,
view_name,
add_suffix_if_single_velocity=False):
names = [None] * plant.num_velocities()
for ind in plant.GetJointIndices():
joint = plant.get_joint(JointIndex(ind))
if joint.num_velocities() == 1 and not add_suffix_if_single_velocity:
names[joint.velocity_start()] = joint.name()
else:
for i in range(joint.num_velocities()):
names[joint.velocity_start() + i] = \
f"{joint.name()}_{joint.velocity_suffix(i)}"
for ind in plant.GetFloatingBaseBodies():
body = plant.get_body(ind)
start = body.floating_velocities_start_in_v()
for i in range(6):
names[start
+ i] = f"{body.name()}_{body.floating_velocity_suffix(i)}"
return namedview(view_name, names)
def MakeNamedViewState(plant, view_name):
# TODO(russt): this could become a nested named view, pending
# https://github.com/RobotLocomotion/drake/pull/14973
pview = MakeNamedViewPositions(plant, f"{view_name}_pos", True)
vview = MakeNamedViewVelocities(plant, f"{view_name}_vel", True)
return namedview(view_name, pview.get_fields() + vview.get_fields())
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/gym/train_cart_pole.py | """
Train a policy for //bindings/pydrake/examples/envs:cart_pole
"""
import argparse
import gymnasium as gym
import stable_baselines3
from stable_baselines3.common.env_checker import check_env
from pydrake.geometry import StartMeshcat
from pydrake.examples.gym._bazel_cwd_helpers import bazel_chdir
_full_sb3_available = False
if "drake_internal" not in stable_baselines3.__version__:
from stable_baselines3 import PPO
from stable_baselines3.common.callbacks import EvalCallback
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.vec_env import (
DummyVecEnv,
SubprocVecEnv,
VecVideoRecorder,
)
import torch as th
_full_sb3_available = True
def _run_training(config, args):
env_name = config["env_name"]
num_env = config["num_workers"]
time_limit = config["env_time_limit"]
log_dir = config["local_log_dir"]
policy_type = config["policy_type"]
total_timesteps = config["total_timesteps"]
policy_kwargs = config["policy_kwargs"]
eval_freq = config["model_save_freq"]
obs_noise = config["observation_noise"]
add_disturbances = config["disturbances"]
if not args.train_single_env:
env = make_vec_env(env_name,
n_envs=num_env,
seed=0,
vec_env_cls=SubprocVecEnv,
env_kwargs={
'time_limit': time_limit,
'obs_noise': obs_noise,
'add_disturbances': add_disturbances,
})
else:
meshcat = StartMeshcat()
env = gym.make(env_name,
meshcat=meshcat,
time_limit=time_limit,
debug=args.debug,
obs_noise=obs_noise,
)
check_env(env)
input("Open meshcat (optional). Press Enter to continue...")
if args.test:
model = PPO(policy_type, env, n_steps=4, n_epochs=2,
batch_size=8, policy_kwargs=policy_kwargs)
else:
tensorboard_log = f"{log_dir}runs/test"
model = PPO(
policy_type, env, n_steps=int(2048/num_env), n_epochs=10,
# In SB3, this is the mini-batch size.
# https://github.com/DLR-RM/stable-baselines3/blob/master/docs/modules/ppo.rst
batch_size=64*num_env,
verbose=1,
tensorboard_log=tensorboard_log,
policy_kwargs=policy_kwargs)
print("Open tensorboard (optional) via "
f"`tensorboard --logdir {tensorboard_log}` "
"in another terminal.")
# Separate evaluation env.
eval_env = gym.make(env_name,
time_limit=time_limit,
obs_noise=obs_noise,
monitoring_camera=True,
)
eval_env = DummyVecEnv([lambda: eval_env])
# Record a video every n evaluation rollouts.
n = 1
eval_env = VecVideoRecorder(
eval_env,
log_dir+f"videos/test",
record_video_trigger=lambda x: x % n == 0,
video_length=100)
# Use deterministic actions for evaluation.
eval_callback = EvalCallback(
eval_env,
best_model_save_path=log_dir+f'eval_logs/test',
log_path=log_dir+f'eval_logs/test',
eval_freq=eval_freq,
deterministic=True,
render=False)
model.learn(
total_timesteps=total_timesteps,
callback=eval_callback,
)
eval_env.close()
def _main():
bazel_chdir()
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--test', action='store_true')
parser.add_argument('--train_single_env', action='store_true')
parser.add_argument('--debug', action='store_true')
parser.add_argument('--log_path', help="path to the logs directory.",
default="./rl/tmp/DrakeCartPole/")
args = parser.parse_args()
if not _full_sb3_available:
print("stable_baselines3 found, but was drake internal")
return 0 if args.test else 1
if args.test:
num_env = 2
elif args.train_single_env:
num_env = 1
else:
num_env = 10
config = {
"policy_type": "MlpPolicy",
"total_timesteps": 5e5 if not args.test else 5,
"env_name": "DrakeCartPole-v0",
"num_workers": num_env,
"env_time_limit": 7 if not args.test else 0.5,
"local_log_dir": args.log_path,
"model_save_freq": 1e4,
"policy_kwargs": {'activation_fn': th.nn.ReLU,
'net_arch': {'pi': [64, 64, 64],
'vf': [64, 64, 64]}},
"observation_noise": True,
"disturbances": True,
}
_run_training(config, args)
gym.envs.register(
id="DrakeCartPole-v0",
entry_point=(
"pydrake.examples.gym.envs.cart_pole:DrakeCartPoleEnv"))
if __name__ == '__main__':
_main()
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples/gym | /home/johnshepherd/drake/bindings/pydrake/examples/gym/models/cartpole_BSA.sdf | <?xml version="1.0"?>
<sdf version='1.7'>
<model name='CartPoleBSA'>
<!-- This sdf file produces a model based on Barto, Sutton, and Anderson
in “Neuronlike Adaptive Elements That Can Solve Difficult Learning
Control Problem”.
It is a copy of //examples/multibody/cart_pole:cart_pole.sdf
with nicer visuals and added joint limits.
-->
<link name='Cart'>
<pose>0 0 0 0 0 0</pose>
<inertial>
<mass>1.0</mass>
<inertia>
<ixx>1.0e-20</ixx><iyy>1.0e-20</iyy><izz>1.0e-20</izz>
<ixy>0</ixy><ixz>0</ixz><iyz>0</iyz>
</inertia>
</inertial>
<visual name='cart_visual'>
<pose>0 0 0 0 0 0</pose>
<geometry>
<box>
<size>0.3 0.2 0.2</size>
</box>
</geometry>
<material>
<diffuse>0 0 0.1 1</diffuse>
</material>
</visual>
</link>
<link name='Pole'>
<!-- The pole is modeled as a point mass at the middle of a pole. -->
<!-- The length of the pole is 1.0 meters. -->
<pose>0 0 0.5 0 0 0</pose>
<inertial>
<mass>0.1</mass>
<inertia>
<ixx>1.0e-20</ixx><iyy>1.0e-20</iyy><izz>1.0e-20</izz>
<ixy>0</ixy><ixz>0</ixz><iyz>0</iyz>
</inertia>
</inertial>
<visual name='pole_point_mass'>
<pose>0 0 0 0 0 0</pose>
<geometry>
<sphere>
<radius>0.05</radius>
</sphere>
</geometry>
<material>
<diffuse>0.4 1 0.1 1</diffuse>
</material>
</visual>
<visual name='pole_rod'>
<pose>0 0 0 0 0 0</pose>
<geometry>
<cylinder>
<radius>0.025</radius>
<length>1.0</length>
</cylinder>
</geometry>
<material>
<diffuse>0.4 0.1 0.1 1</diffuse>
</material>
</visual>
</link>
<joint name='CartSlider' type='prismatic'>
<parent>world</parent>
<child>Cart</child>
<axis>
<xyz>1.0 0.0 0.0</xyz>
<limit>
<!-- This joint is actuated. -->
<effort>10.0</effort>
<lower>-4.8</lower>
<upper>4.8</upper>
</limit>
</axis>
</joint>
<joint name='PolePin' type='revolute'>
<!-- Pose of the joint frame in the pole's frame (located at the COM) -->
<pose>0 0 -0.5 0 0 0</pose>
<parent>Cart</parent>
<child>Pole</child>
<axis>
<xyz>0.0 -1.0 0.0</xyz>
<limit>
<!-- This joint is not actuated. -->
<effort>-1.0</effort>
</limit>
</axis>
</joint>
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples/gym | /home/johnshepherd/drake/bindings/pydrake/examples/gym/envs/cart_pole.py | import gymnasium as gym
import matplotlib.pyplot as plt
import numpy as np
from pydrake.common import FindResourceOrThrow
from pydrake.common.cpp_param import List
from pydrake.common.value import Value
from pydrake.examples.gym.named_view_helpers import (
MakeNamedViewActuation,
MakeNamedViewPositions,
MakeNamedViewState,
)
from pydrake.geometry import (
ClippingRange,
ColorRenderCamera,
DepthRange,
DepthRenderCamera,
MakeRenderEngineVtk,
MeshcatVisualizer,
RenderCameraCore,
RenderEngineVtkParams,
)
from pydrake.gym import DrakeGymEnv
from pydrake.math import RigidTransform, RollPitchYaw
from pydrake.multibody.math import SpatialForce
from pydrake.multibody.parsing import Parser
from pydrake.multibody.plant import (
AddMultibodyPlant,
ExternallyAppliedSpatialForce_,
MultibodyPlant,
MultibodyPlantConfig,
)
from pydrake.systems.analysis import Simulator
from pydrake.systems.drawing import plot_graphviz, plot_system_graphviz
from pydrake.systems.framework import (
DiagramBuilder,
EventStatus,
LeafSystem,
PublishEvent,
)
from pydrake.systems.primitives import (
ConstantVectorSource,
Multiplexer,
PassThrough,
)
from pydrake.systems.sensors import CameraInfo, RgbdSensor
# Gym parameters.
sim_time_step = 0.01
gym_time_step = 0.05
controller_time_step = 0.01
gym_time_limit = 5
drake_contact_models = ['point', 'hydroelastic_with_fallback']
contact_model = drake_contact_models[0]
drake_contact_approximations = ['sap', 'tamsi', 'similar', 'lagged']
contact_approximation = drake_contact_approximations[0]
def AddAgent(plant):
parser = Parser(plant)
model_file = FindResourceOrThrow(
"drake/bindings/pydrake/examples/gym/models/cartpole_BSA.sdf")
agent, = parser.AddModels(model_file)
return agent
def make_sim(meshcat=None,
time_limit=5,
debug=False,
obs_noise=False,
monitoring_camera=False,
add_disturbances=False):
builder = DiagramBuilder()
multibody_plant_config = MultibodyPlantConfig(
time_step=sim_time_step,
contact_model=contact_model,
discrete_contact_approximation=contact_approximation,
)
plant, scene_graph = AddMultibodyPlant(multibody_plant_config, builder)
# Add assets to the plant.
agent = AddAgent(plant)
plant.Finalize()
plant.set_name("plant")
# Add assets to the controller plant.
controller_plant = MultibodyPlant(time_step=controller_time_step)
AddAgent(controller_plant)
if meshcat:
MeshcatVisualizer.AddToBuilder(builder, scene_graph, meshcat)
# Finalize the plant.
controller_plant.Finalize()
controller_plant.set_name("controller_plant")
# Extract the controller plant information.
ns = controller_plant.num_multibody_states()
nv = controller_plant.num_velocities()
na = controller_plant.num_actuators()
nj = controller_plant.num_joints()
npos = controller_plant.num_positions()
# Make NamedViews
state_view = MakeNamedViewState(controller_plant, "States")
position_view = MakeNamedViewPositions(controller_plant, "Position")
actuation_view = MakeNamedViewActuation(controller_plant, "Actuation")
if debug:
print(f'\nNumber of position: {npos},',
f'Number of velocities: {nv},',
f'Number of actuators: {na},',
f'Number of joints: {nj},',
f'Number of multibody states: {ns}')
print("State view: ", state_view(np.ones(ns)))
print("Position view: ", position_view(np.ones(npos)))
print("Actuation view: ", actuation_view(np.ones(na)), '\n')
# Visualize the plant.
plt.figure()
plot_graphviz(plant.GetTopologyGraphvizString())
plt.plot(1)
plt.show(block=False)
# Actions are positions sent to plant.
actuation = builder.AddSystem(Multiplexer([1, 1]))
prismatic_actuation_force = builder.AddSystem(PassThrough(1))
# Zero torque to the revolute joint --it is underactuated.
revolute_actuation_torque = builder.AddSystem(ConstantVectorSource([0]))
builder.Connect(revolute_actuation_torque.get_output_port(),
actuation.get_input_port(1))
builder.Connect(prismatic_actuation_force.get_output_port(),
actuation.get_input_port(0))
builder.Connect(actuation.get_output_port(),
plant.get_actuation_input_port(agent))
builder.ExportInput(prismatic_actuation_force.get_input_port(), "actions")
class ObservationPublisher(LeafSystem):
def __init__(self, noise=False):
LeafSystem.__init__(self)
self.ns = plant.num_multibody_states()
self.DeclareVectorInputPort("plant_states", self.ns)
self.DeclareVectorOutputPort("observations", self.ns, self.CalcObs)
self.noise = noise
def CalcObs(self, context, output):
plant_state = self.get_input_port(0).Eval(context)
if self.noise:
plant_state += np.random.uniform(low=-0.01,
high=0.01,
size=self.ns)
output.set_value(plant_state)
obs_pub = builder.AddSystem(ObservationPublisher(noise=obs_noise))
builder.Connect(plant.get_state_output_port(), obs_pub.get_input_port(0))
builder.ExportOutput(obs_pub.get_output_port(), "observations")
class RewardSystem(LeafSystem):
def __init__(self):
LeafSystem.__init__(self)
# The state port is not used.
ns = plant.num_multibody_states()
self.DeclareVectorInputPort("state", ns)
self.DeclareVectorOutputPort("reward", 1, self.CalcReward)
def CalcReward(self, context, output):
reward = 1
output[0] = reward
reward = builder.AddSystem(RewardSystem())
builder.Connect(plant.get_state_output_port(agent),
reward.get_input_port(0))
builder.ExportOutput(reward.get_output_port(), "reward")
if monitoring_camera:
# Adds an overhead camera.
# This is useful for logging videos of rollout evaluation.
scene_graph.AddRenderer(
"renderer", MakeRenderEngineVtk(RenderEngineVtkParams()))
color_camera = ColorRenderCamera(
RenderCameraCore(
"renderer",
CameraInfo(
width=640,
height=480,
fov_y=np.pi/4),
ClippingRange(0.01, 10.0),
RigidTransform()
), False)
depth_camera = DepthRenderCamera(color_camera.core(),
DepthRange(0.01, 10.0))
X_PB = RigidTransform(RollPitchYaw(-np.pi/2, 0, 0),
np.array([0, -2.5, 0.4]))
rgbd_camera = builder.AddSystem(
RgbdSensor(parent_id=scene_graph.world_frame_id(),
X_PB=X_PB,
color_camera=color_camera,
depth_camera=depth_camera))
builder.Connect(scene_graph.get_query_output_port(),
rgbd_camera.query_object_input_port())
builder.ExportOutput(
rgbd_camera.color_image_output_port(), "color_image")
class DisturbanceGenerator(LeafSystem):
def __init__(self, plant, force_mag, period, duration):
# Applies a random force [-force_mag, force_mag] at
# the COM of the Pole body in the x direction every
# period seconds for a given duration.
LeafSystem.__init__(self)
forces_cls = Value[List[ExternallyAppliedSpatialForce_[float]]]
self.DeclareAbstractOutputPort("spatial_forces",
lambda: forces_cls(),
self.CalcDisturbances)
self.plant = plant
self.pole_body = self.plant.GetBodyByName("Pole")
self.force_mag = force_mag
assert period > duration, (
f"period: {period} must be larger than duration: {duration}")
self.period = period
self.duration = duration
def CalcDisturbances(self, context, spatial_forces_vector):
# Apply a force at COM of the Pole body.
force = ExternallyAppliedSpatialForce_[float]()
force.body_index = self.pole_body.index()
force.p_BoBq_B = self.pole_body.default_com()
y = context.get_time() % self.period
if not ((y >= 0) and (y <= (self.period - self.duration))):
spatial_force = SpatialForce(
tau=[0, 0, 0],
f=[np.random.uniform(
low=-self.force_mag,
high=self.force_mag),
0, 0])
else:
spatial_force = SpatialForce(
tau=[0, 0, 0],
f=[0, 0, 0])
force.F_Bq_W = spatial_force
spatial_forces_vector.set_value([force])
if add_disturbances:
# Applies a force of 1N every 1s
# for 0.1s at the COM of the Pole body.
disturbance_generator = builder.AddSystem(
DisturbanceGenerator(
plant=plant, force_mag=1,
period=1, duration=0.1))
builder.Connect(disturbance_generator.get_output_port(),
plant.get_applied_spatial_force_input_port())
diagram = builder.Build()
simulator = Simulator(diagram)
simulator.Initialize()
def monitor(context, state_view=state_view):
'''
Monitors the simulation for episode end conditions.
'''
plant_context = plant.GetMyContextFromRoot(context)
state = plant.GetOutputPort("state").Eval(plant_context)
s = state_view(state)
# Truncation: the episode duration reaches the time limit.
if context.get_time() > time_limit:
if debug:
print("Episode reached time limit.")
return EventStatus.ReachedTermination(
diagram,
"time limit")
# Termination: The pole angle exceeded +-0.2 rad.
if abs(s.PolePin_q) > 0.2:
if debug:
print("Pole angle exceeded +-0.2 rad.")
return EventStatus.ReachedTermination(
diagram,
"pole angle exceeded +-0.2 rad")
# Termination: Cart position exceeded +-2.4 m.
if abs(s.CartSlider_x) > 2.4:
if debug:
print("Cart position exceeded +-2.4 m.")
return EventStatus.ReachedTermination(
diagram,
"cart position exceeded +-2.4 m")
return EventStatus.Succeeded()
simulator.set_monitor(monitor)
if debug:
# Visualize the controller plant and diagram.
plt.figure()
plot_graphviz(controller_plant.GetTopologyGraphvizString())
plt.figure()
plot_system_graphviz(diagram, max_depth=2)
plt.plot(1)
plt.show(block=False)
return simulator
def reset_handler(simulator, diagram_context, seed):
'''
Provides an easy method for domain randomization.
'''
# Set the seed.
np.random.seed(seed)
# Randomize the initial position of the joints.
home_positions = [
('CartSlider', np.random.uniform(low=-.1, high=0.1)),
('PolePin', np.random.uniform(low=-.15, high=0.15)),
]
# Randomize the initial velocities of the PolePin joint.
home_velocities = [
('PolePin', np.random.uniform(low=-.1, high=0.1))
]
# Randomize the mass of the Pole by adding a mass offset.
home_body_mass_offset = [
('Pole', np.random.uniform(low=-0.05, high=0.05))
]
diagram = simulator.get_system()
plant = diagram.GetSubsystemByName("plant")
plant_context = diagram.GetMutableSubsystemContext(plant,
diagram_context)
# Ensure the positions are within the joint limits.
for pair in home_positions:
joint = plant.GetJointByName(pair[0])
if joint.type_name() == "revolute":
joint.set_angle(plant_context,
np.clip(pair[1],
joint.position_lower_limit(),
joint.position_upper_limit()
)
)
if joint.type_name() == "prismatic":
joint.set_translation(plant_context,
np.clip(pair[1],
joint.position_lower_limit(),
joint.position_upper_limit()
)
)
for pair in home_velocities:
joint = plant.GetJointByName(pair[0])
if joint.type_name() == "revolute":
joint.set_angular_rate(plant_context,
np.clip(pair[1],
joint.velocity_lower_limit(),
joint.velocity_upper_limit()
)
)
for pair in home_body_mass_offset:
body = plant.GetBodyByName(pair[0])
mass = body.get_mass(plant.CreateDefaultContext())
body.SetMass(plant_context, mass+pair[1])
def DrakeCartPoleEnv(
meshcat=None,
time_limit=gym_time_limit,
debug=False,
obs_noise=False,
monitoring_camera=False,
add_disturbances=False):
# Make simulation.
simulator = make_sim(meshcat=meshcat,
time_limit=time_limit,
debug=debug,
obs_noise=obs_noise,
monitoring_camera=monitoring_camera,
add_disturbances=add_disturbances)
plant = simulator.get_system().GetSubsystemByName("plant")
# Define Action space.
na = 1
low_a = plant.GetEffortLowerLimits()[:na]
high_a = plant.GetEffortUpperLimits()[:na]
action_space = gym.spaces.Box(low=np.asarray(low_a, dtype="float32"),
high=np.asarray(high_a, dtype="float32"),
dtype=np.float32)
# Define observation space.
low = np.concatenate(
(plant.GetPositionLowerLimits(), plant.GetVelocityLowerLimits()))
high = np.concatenate(
(plant.GetPositionUpperLimits(), plant.GetVelocityUpperLimits()))
observation_space = gym.spaces.Box(low=np.asarray(low),
high=np.asarray(high),
dtype=np.float64)
env = DrakeGymEnv(
simulator=simulator,
time_step=gym_time_step,
action_space=action_space,
observation_space=observation_space,
reward="reward",
action_port_id="actions",
observation_port_id="observations",
reset_handler=reset_handler,
render_rgb_port_id="color_image" if monitoring_camera else None)
# Expose parameters that could be useful for learning.
env.time_step = gym_time_step
env.sim_time_step = sim_time_step
return env
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/multibody/pendulum_lqr_monte_carlo_analysis.py | # -*- coding: utf-8 -*-
"""
This example demonstrates using Monte Carlo verification to analyze task
performance, for the task of stabilizing an inverted torque-limited pendulum
with LQR.
"""
import argparse
import numpy as np
from pydrake.common import RandomGenerator
from pydrake.multibody.parsing import Parser
from pydrake.multibody.plant import MultibodyPlant
from pydrake.symbolic import (
Expression,
Variable
)
from pydrake.systems.analysis import (
MonteCarloSimulation,
RandomSimulationResult,
RandomSimulation,
Simulator
)
from pydrake.systems.controllers import LinearQuadraticRegulator
from pydrake.systems.framework import (
Context,
Diagram,
DiagramBuilder
)
from pydrake.systems.primitives import (
ConstantVectorSource,
Linearize,
Saturation
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--num_samples", type=int, default=50,
help="Number of Monte Carlo samples to use to estimate performance.")
parser.add_argument(
"--torque_limit", type=float, default=2.0,
help="Torque limit of the pendulum.")
args = parser.parse_args()
if args.torque_limit < 0:
raise ValueError("Please supply a nonnegative torque limit.")
# Assemble the Pendulum plant.
builder = DiagramBuilder()
pendulum = builder.AddSystem(MultibodyPlant(0.0))
Parser(pendulum).AddModelsFromUrl(
url="package://drake/examples/pendulum/Pendulum.urdf")
pendulum.Finalize()
# Set the pendulum to start at uniformly random
# positions (but always zero velocity).
elbow = pendulum.GetMutableJointByName("theta")
upright_theta = np.pi
theta_expression = Variable(
name="theta",
type=Variable.Type.RANDOM_UNIFORM)*2.*np.pi
elbow.set_random_angle_distribution(theta_expression)
# Set up LQR, with high position gains to try to ensure the
# ROA is close to the theoretical torque-limited limit.
Q = np.diag([100., 1.])
R = np.identity(1)*0.01
linearize_context = pendulum.CreateDefaultContext()
linearize_context.SetContinuousState(
np.array([upright_theta, 0.]))
actuation_port = pendulum.get_actuation_input_port()
actuation_port.FixValue(linearize_context, 0)
controller = builder.AddSystem(
LinearQuadraticRegulator(
pendulum, linearize_context, Q, R,
np.zeros(0), actuation_port.get_index()))
# Apply the torque limit.
torque_limit = args.torque_limit
torque_limiter = builder.AddSystem(
Saturation(min_value=np.array([-torque_limit]),
max_value=np.array([torque_limit])))
builder.Connect(controller.get_output_port(0),
torque_limiter.get_input_port(0))
builder.Connect(torque_limiter.get_output_port(0),
pendulum.get_actuation_input_port())
builder.Connect(pendulum.get_state_output_port(),
controller.get_input_port(0))
diagram = builder.Build()
# Perform the Monte Carlo simulation.
def make_simulator(generator):
''' Create a simulator for the system
using the given generator. '''
simulator = Simulator(diagram)
simulator.set_target_realtime_rate(0)
simulator.Initialize()
return simulator
def calc_wrapped_error(system, context):
''' Given a context from the end of the simulation,
calculate an error -- which for this stabilizing
task is the distance from the
fixed point. '''
state = diagram.GetSubsystemContext(
pendulum, context).get_continuous_state_vector()
error = state.GetAtIndex(0) - upright_theta
# Wrap error to [-pi, pi].
return (error + np.pi) % (2*np.pi) - np.pi
num_samples = args.num_samples
results = MonteCarloSimulation(
make_simulator=make_simulator, output=calc_wrapped_error,
final_time=1.0, num_samples=num_samples, generator=RandomGenerator())
# Compute results.
# The "success" region is fairly large since some "stabilized" trials
# may still be oscillating around the fixed point. Failed examples are
# consistently much farther from the fixed point than this.
binary_results = np.array([abs(res.output) < 0.1 for res in results])
passing_ratio = float(sum(binary_results)) / len(results)
# 95% confidence interval for the passing ratio.
passing_ratio_var = 1.96 * np.sqrt(
passing_ratio*(1. - passing_ratio)/len(results))
print("Monte-Carlo estimated performance across %d samples: "
"%.2f%% +/- %0.2f%%" %
(num_samples, passing_ratio*100, passing_ratio_var*100))
# Analytically compute the best possible ROA, for comparison, but
# calculating where the torque needed to lift the pendulum exceeds
# the torque limit.
arm_radius = 0.5
arm_mass = 1.0
# torque = r x f = r * (m * 9.81 * sin(theta))
# theta = asin(torque / (r * m))
if torque_limit <= (arm_radius * arm_mass * 9.81):
roa_half_width = np.arcsin(torque_limit
/ (arm_radius * arm_mass * 9.81))
else:
roa_half_width = np.pi
roa_as_fraction_of_state_space = roa_half_width / np.pi
print("Max possible ROA = %0.2f%% of state space, which should"
" match with the above estimate." % (
100 * roa_as_fraction_of_state_space))
if __name__ == "__main__":
main()
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/multibody/BUILD.bazel | load("//bindings/pydrake:pydrake.bzl", "add_lint_tests_pydrake")
load("//tools/install:install.bzl", "install")
load(
"//tools/skylark:drake_py.bzl",
"drake_py_binary",
"drake_py_library",
)
load(
"//tools/skylark:pybind.bzl",
"get_drake_py_installs",
"get_pybind_package_info",
)
package(default_visibility = [
"//bindings/pydrake:__subpackages__",
])
# This determines how `PYTHONPATH` is configured, and how to install the
# bindings.
PACKAGE_INFO = get_pybind_package_info("//bindings")
drake_py_library(
name = "module_py",
srcs = ["__init__.py"],
deps = [
"//bindings/pydrake/examples",
],
)
drake_py_library(
name = "cart_pole_passive_simulation_py",
srcs = ["cart_pole_passive_simulation.py"],
data = [
"//examples/multibody/cart_pole:models",
],
deps = [
":module_py",
"//bindings/pydrake:lcm_py",
"//bindings/pydrake/multibody:parsing_py",
"//bindings/pydrake/multibody:plant_py",
"//bindings/pydrake/systems:analysis_py",
"//bindings/pydrake/visualization",
],
)
drake_py_binary(
name = "cart_pole_passive_simulation",
srcs = ["cart_pole_passive_simulation.py"],
add_test_rule = 1,
test_rule_args = [
"--target_realtime_rate=0",
"--simulation_time=0.1",
],
visibility = ["//visibility:public"],
deps = [
":cart_pole_passive_simulation_py",
],
)
drake_py_library(
name = "pendulum_lqr_monte_carlo_analysis_py",
srcs = ["pendulum_lqr_monte_carlo_analysis.py"],
data = ["//examples/pendulum:models"],
deps = [
":module_py",
"//bindings/pydrake/multibody",
"//bindings/pydrake/systems",
],
)
drake_py_binary(
name = "pendulum_lqr_monte_carlo_analysis",
srcs = ["pendulum_lqr_monte_carlo_analysis.py"],
add_test_rule = 1,
test_rule_args = [
"--num_samples=10",
"--torque_limit=2.0",
],
visibility = ["//visibility:public"],
deps = [
":pendulum_lqr_monte_carlo_analysis_py",
],
)
drake_py_library(
name = "run_planar_scenegraph_visualizer_py",
srcs = ["run_planar_scenegraph_visualizer.py"],
data = ["//examples/pendulum:models"],
deps = [
":module_py",
"//bindings/pydrake/examples",
"//bindings/pydrake/multibody",
"//bindings/pydrake/systems",
],
)
drake_py_binary(
name = "run_planar_scenegraph_visualizer",
srcs = ["run_planar_scenegraph_visualizer.py"],
add_test_rule = 1,
visibility = ["//visibility:public"],
deps = [
":run_planar_scenegraph_visualizer_py",
],
)
PY_LIBRARIES = [
":cart_pole_passive_simulation_py",
":pendulum_lqr_monte_carlo_analysis_py",
":run_planar_scenegraph_visualizer_py",
]
# Package roll-up (for Bazel dependencies).
# N.B. `examples` packages do not have `all` modules.
drake_py_library(
name = "multibody",
imports = PACKAGE_INFO.py_imports,
deps = PY_LIBRARIES,
)
install(
name = "install",
targets = PY_LIBRARIES,
py_dest = PACKAGE_INFO.py_dest,
)
add_lint_tests_pydrake()
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/multibody/cart_pole_passive_simulation.py | """Provides an example translation of `cart_pole_passive_simluation.cc`."""
import argparse
from pydrake.multibody.plant import AddMultibodyPlantSceneGraph
from pydrake.multibody.parsing import Parser
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.analysis import Simulator
from pydrake.visualization import AddDefaultVisualization
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--target_realtime_rate", type=float, default=1.0,
help="Desired rate relative to real time. See documentation for "
"Simulator::set_target_realtime_rate() for details.")
parser.add_argument(
"--simulation_time", type=float, default=10.0,
help="Desired duration of the simulation in seconds.")
parser.add_argument(
"--time_step", type=float, default=0.,
help="If greater than zero, the plant is modeled as a system with "
"discrete updates and period equal to this time_step. "
"If 0, the plant is modeled as a continuous system.")
args = parser.parse_args()
builder = DiagramBuilder()
cart_pole, scene_graph = AddMultibodyPlantSceneGraph(
builder=builder, time_step=args.time_step)
Parser(plant=cart_pole).AddModelsFromUrl(
url="package://drake/examples/multibody/cart_pole/cart_pole.sdf")
cart_pole.Finalize()
AddDefaultVisualization(builder=builder)
diagram = builder.Build()
diagram_context = diagram.CreateDefaultContext()
cart_pole_context = cart_pole.GetMyMutableContextFromRoot(diagram_context)
cart_pole.get_actuation_input_port().FixValue(cart_pole_context, 0)
cart_slider = cart_pole.GetJointByName("CartSlider")
pole_pin = cart_pole.GetJointByName("PolePin")
cart_slider.set_translation(context=cart_pole_context, translation=0.)
pole_pin.set_angle(context=cart_pole_context, angle=2.)
simulator = Simulator(diagram, diagram_context)
simulator.set_publish_every_time_step(False)
simulator.set_target_realtime_rate(args.target_realtime_rate)
simulator.Initialize()
simulator.AdvanceTo(args.simulation_time)
if __name__ == "__main__":
main()
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/multibody/run_planar_scenegraph_visualizer.py | """
Run examples of PlanarSceneGraphVisualizer, e.g. to visualize a pendulum.
Usage demo: load a URDF, rig it up with a constant torque input, and draw it.
"""
import argparse
import numpy as np
from pydrake.common import temp_directory
from pydrake.examples import ManipulationStation
from pydrake.multibody.parsing import Parser
from pydrake.multibody.plant import AddMultibodyPlantSceneGraph
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.planar_scenegraph_visualizer import (
ConnectPlanarSceneGraphVisualizer)
def run_pendulum_example(args):
builder = DiagramBuilder()
plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)
parser = Parser(plant)
parser.AddModelsFromUrl(
url="package://drake/examples/pendulum/Pendulum.urdf")
plant.Finalize()
T_VW = np.array([[1., 0., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
visualizer = ConnectPlanarSceneGraphVisualizer(
builder, scene_graph, T_VW=T_VW, xlim=[-1.2, 1.2], ylim=[-1.2, 1.2])
if args.playback:
visualizer.start_recording()
diagram = builder.Build()
simulator = Simulator(diagram)
simulator.Initialize()
simulator.set_target_realtime_rate(1.0)
# Fix the input port to zero.
plant_context = diagram.GetMutableSubsystemContext(
plant, simulator.get_mutable_context())
plant.get_actuation_input_port().FixValue(
plant_context, np.zeros(plant.num_actuators()))
plant_context.SetContinuousState([0.5, 0.1])
simulator.AdvanceTo(args.duration)
if args.playback:
visualizer.stop_recording()
ani = visualizer.get_recording_as_animation()
# Playback the recording and save the output.
ani.save("{}/pend_playback.mp4".format(temp_directory()), fps=30)
def run_manipulation_example(args):
builder = DiagramBuilder()
station = builder.AddSystem(ManipulationStation(time_step=0.005))
station.SetupManipulationClassStation()
station.Finalize()
plant = station.get_multibody_plant()
scene_graph = station.get_scene_graph()
query_object_output_port = station.GetOutputPort("geometry_query")
# Side-on view of the station.
T_VW = np.array([[1., 0., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
visualizer = ConnectPlanarSceneGraphVisualizer(
builder, scene_graph, query_object_output_port, T_VW=T_VW,
xlim=[-0.5, 1.0], ylim=[-1.2, 1.2], draw_period=0.1)
if args.playback:
visualizer.start_recording()
diagram = builder.Build()
simulator = Simulator(diagram)
simulator.Initialize()
simulator.set_target_realtime_rate(1.0)
# Fix the control inputs to zero.
station_context = diagram.GetMutableSubsystemContext(
station, simulator.get_mutable_context())
station.GetInputPort("iiwa_position").FixValue(
station_context, station.GetIiwaPosition(station_context))
station.GetInputPort("iiwa_feedforward_torque").FixValue(
station_context, np.zeros(7))
station.GetInputPort("wsg_position").FixValue(
station_context, np.zeros(1))
station.GetInputPort("wsg_force_limit").FixValue(
station_context, [40.0])
simulator.AdvanceTo(args.duration)
if args.playback:
visualizer.stop_recording()
ani = visualizer.get_recording_as_animation()
# Playback the recording and save the output.
ani.save("{}/manip_playback.mp4".format(temp_directory()), fps=30)
def main():
np.set_printoptions(precision=5, suppress=True)
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("-T", "--duration",
type=float,
help="Duration to run sim in seconds.",
default=1.0)
parser.add_argument("-m", "--models",
type=str,
nargs="*",
help="Models to run, at least one of [pend, manip]",
default=["pend"])
parser.add_argument("-p", "--playback",
type=bool,
help="Whether to record and playback the animation",
default=False)
args = parser.parse_args()
for model in args.models:
if model == "pend":
run_pendulum_example(args)
elif model == "manip":
run_manipulation_example(args)
else:
print("Unrecognized model %s." % model)
parser.print_usage()
exit(1)
if __name__ == "__main__":
main()
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/multibody/__init__.py | """Provides multibody-specific Python examples and C++ example bindings for
Python.
"""
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/test/compass_gait_test.py | import unittest
from pydrake.examples import (
CompassGait,
CompassGaitContinuousState,
CompassGaitGeometry,
CompassGaitParams,
)
from pydrake.geometry import SceneGraph
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
class TestCompassGait(unittest.TestCase):
def test_compass_gait(self):
plant = CompassGait()
# Confirm the spelling on the output ports.
plant.get_minimal_state_output_port()
plant.get_floating_base_state_output_port()
def test_params(self):
params = CompassGaitParams()
params.set_mass_hip(1.)
params.set_mass_leg(2.)
params.set_length_leg(3.)
params.set_center_of_mass_leg(4.)
params.set_gravity(5.)
params.set_slope(.15)
self.assertEqual(params.mass_hip(), 1.)
self.assertEqual(params.mass_leg(), 2.)
self.assertEqual(params.length_leg(), 3.)
self.assertEqual(params.center_of_mass_leg(), 4.)
self.assertEqual(params.gravity(), 5.)
self.assertEqual(params.slope(), .15)
def test_state(self):
state = CompassGaitContinuousState()
state.set_stance(1.)
state.set_swing(2.)
state.set_stancedot(3.)
state.set_swingdot(4.)
self.assertEqual(state.stance(), 1.)
self.assertEqual(state.swing(), 2.)
self.assertEqual(state.stancedot(), 3.)
self.assertEqual(state.swingdot(), 4.)
def test_geometry(self):
builder = DiagramBuilder()
plant = builder.AddSystem(CompassGait())
scene_graph = builder.AddSystem(SceneGraph())
geom = CompassGaitGeometry.AddToBuilder(
builder=builder,
floating_base_state_port=plant.get_floating_base_state_output_port(), # noqa
scene_graph=scene_graph)
# Confirming that the resulting diagram builds.
builder.Build()
self.assertIsInstance(geom, CompassGaitGeometry)
def test_geometry_with_params(self):
builder = DiagramBuilder()
plant = builder.AddSystem(CompassGait())
scene_graph = builder.AddSystem(SceneGraph())
geom = CompassGaitGeometry.AddToBuilder(
builder=builder,
floating_base_state_port=plant.get_floating_base_state_output_port(), # noqa
compass_gait_params=CompassGaitParams(), scene_graph=scene_graph)
# Confirming that the resulting diagram builds.
builder.Build()
self.assertIsInstance(geom, CompassGaitGeometry)
def test_simulation(self):
# Basic compass_gait simulation.
compass_gait = CompassGait()
# Create the simulator.
simulator = Simulator(compass_gait)
context = simulator.get_mutable_context()
context.SetAccuracy(1e-8)
# Zero the input
compass_gait.get_input_port(0).FixValue(context, 0.0)
# Set the initial state.
state = context.get_mutable_continuous_state_vector()
state.set_stance(0.)
state.set_swing(0.)
state.set_stancedot(0.4)
state.set_swingdot(-2.0)
# Simulate (and make sure the state actually changes).
initial_state = state.CopyToVector()
simulator.AdvanceTo(1.0)
self.assertFalse((state.CopyToVector() == initial_state).any())
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/test/pendulum_test.py | import unittest
from pydrake.examples import (
PendulumGeometry,
PendulumInput,
PendulumParams,
PendulumPlant,
PendulumState,
)
from pydrake.geometry import SceneGraph
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
class TestPendulum(unittest.TestCase):
def test_plant(self):
pendulum = PendulumPlant()
self.assertEqual(pendulum.get_input_port(), pendulum.get_input_port(0))
self.assertEqual(pendulum.get_state_output_port(),
pendulum.get_output_port(0))
context = pendulum.CreateDefaultContext()
self.assertIsInstance(pendulum.get_state(context=context),
PendulumState)
self.assertIsInstance(pendulum.get_mutable_state(context=context),
PendulumState)
self.assertIsInstance(pendulum.get_parameters(context=context),
PendulumParams)
self.assertIsInstance(pendulum.get_mutable_parameters(context=context),
PendulumParams)
def test_input(self):
input = PendulumInput()
input.set_tau(tau=1.)
self.assertEqual(input.tau(), 1.)
input_tau = input.with_tau(tau=2.)
self.assertEqual(input_tau.tau(), 2.)
def test_params(self):
params = PendulumParams()
params.set_mass(mass=1.)
params.set_length(length=2.)
params.set_damping(damping=3.)
params.set_gravity(gravity=4.)
self.assertEqual(params.mass(), 1.)
self.assertEqual(params.length(), 2.)
self.assertEqual(params.damping(), 3.)
self.assertEqual(params.gravity(), 4.)
params_mass = params.with_mass(mass=5.)
params_length = params.with_length(length=6.)
params_damping = params.with_damping(damping=7.)
params_gravity = params.with_gravity(gravity=8.)
self.assertEqual(params_mass.mass(), 5.)
self.assertEqual(params_length.length(), 6.)
self.assertEqual(params_damping.damping(), 7.)
self.assertEqual(params_gravity.gravity(), 8.)
def test_state(self):
state = PendulumState()
state.set_theta(theta=1.)
state.set_thetadot(thetadot=2.)
self.assertEqual(state.theta(), 1.)
self.assertEqual(state.thetadot(), 2.)
state_theta = state.with_theta(theta=3.)
state_thetadot = state.with_thetadot(thetadot=4.)
self.assertEqual(state_theta.theta(), 3.)
self.assertEqual(state_thetadot.thetadot(), 4.)
def test_geometry(self):
builder = DiagramBuilder()
plant = builder.AddSystem(PendulumPlant())
scene_graph = builder.AddSystem(SceneGraph())
geom = PendulumGeometry.AddToBuilder(
builder=builder, pendulum_state_port=plant.get_output_port(0),
scene_graph=scene_graph)
builder.Build()
self.assertIsInstance(geom, PendulumGeometry)
def test_simulation(self):
# Basic constant-torque pendulum simulation.
pendulum = PendulumPlant()
# Create the simulator.
simulator = Simulator(pendulum)
context = simulator.get_mutable_context()
# Set an input torque.
input = PendulumInput()
input.set_tau(1.)
pendulum.get_input_port().FixValue(context, input)
# Set the initial state.
state = context.get_mutable_continuous_state_vector()
state.set_theta(1.)
state.set_thetadot(0.)
# Simulate (and make sure the state actually changes).
initial_state = state.CopyToVector()
simulator.AdvanceTo(1.0)
self.assertFalse((state.CopyToVector() == initial_state).any())
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/test/van_der_pol_test.py | import unittest
import numpy as np
from pydrake.examples import VanDerPolOscillator
from pydrake.systems.analysis import Simulator
class TestVanDerPol(unittest.TestCase):
def test_simulation(self):
van_der_pol = VanDerPolOscillator()
# Create the simulator.
simulator = Simulator(van_der_pol)
context = simulator.get_mutable_context()
# Set the initial state.
state = context.get_mutable_continuous_state_vector()
state.SetFromVector([0., 2.])
# Simulate (and make sure the state actually changes).
initial_state = state.CopyToVector()
simulator.AdvanceTo(1.0)
self.assertFalse((state.CopyToVector() == initial_state).any())
def test_ports(self):
vdp = VanDerPolOscillator()
self.assertTrue(vdp.get_position_output_port().get_index().is_valid())
self.assertTrue(
vdp.get_full_state_output_port().get_index().is_valid())
def test_limit_cycle(self):
cycle = VanDerPolOscillator.CalcLimitCycle()
np.testing.assert_almost_equal(cycle[:, 0], cycle[:, -1], 2)
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/test/quadrotor_test.py | import unittest
import numpy as np
from pydrake.geometry import SceneGraph
from pydrake.examples import (
QuadrotorGeometry,
QuadrotorPlant,
StabilizingLQRController,
)
from pydrake.systems.framework import DiagramBuilder
class TestQuadrotor(unittest.TestCase):
def test_basics(self):
# call default constructor
QuadrotorPlant()
quadrotor = QuadrotorPlant(m_arg=1, L_arg=2, I_arg=np.eye(3),
kF_arg=1., kM_arg=1.)
self.assertEqual(quadrotor.m(), 1)
self.assertEqual(quadrotor.g(), 9.81)
self.assertEqual(quadrotor.length(), 2)
self.assertEqual(quadrotor.force_constant(), 1)
self.assertEqual(quadrotor.moment_constant(), 1.)
np.testing.assert_array_equal(quadrotor.inertia(), np.eye(3))
StabilizingLQRController(quadrotor, np.zeros(3))
def test_geometry(self):
builder = DiagramBuilder()
quadrotor = builder.AddSystem(QuadrotorPlant())
scene_graph = builder.AddSystem(SceneGraph())
state_port = quadrotor.get_output_port(0)
geom = QuadrotorGeometry.AddToBuilder(builder, state_port, scene_graph)
self.assertTrue(geom.get_frame_id().is_valid())
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/test/acrobot_test.py | import unittest
from pydrake.examples import (
AcrobotGeometry,
AcrobotInput,
AcrobotParams,
AcrobotPlant,
AcrobotSpongController,
AcrobotState,
SpongControllerParams,
)
from pydrake.geometry import SceneGraph
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
class TestAcrobot(unittest.TestCase):
def test_input(self):
input = AcrobotInput()
input.set_tau(1.)
self.assertEqual(input.tau(), 1.)
def test_params(self):
params = AcrobotParams()
params.set_m1(1.)
params.set_m2(2.)
params.set_l1(3.)
params.set_Ic1(4.)
params.set_Ic2(5.)
params.set_b1(6.)
params.set_b2(7.)
params.set_gravity(8.)
self.assertEqual(params.m1(), 1.)
self.assertEqual(params.m2(), 2.)
self.assertEqual(params.l1(), 3.)
self.assertEqual(params.Ic1(), 4.)
self.assertEqual(params.Ic2(), 5.)
self.assertEqual(params.b1(), 6.)
self.assertEqual(params.b2(), 7.)
self.assertEqual(params.gravity(), 8.)
def test_state(self):
state = AcrobotState()
state.set_theta1(1.)
state.set_theta1dot(2.)
state.set_theta2(3.)
state.set_theta2dot(4.)
self.assertEqual(state.theta1(), 1.)
self.assertEqual(state.theta1dot(), 2.)
self.assertEqual(state.theta2(), 3.)
self.assertEqual(state.theta2dot(), 4.)
def test_geometry(self):
builder = DiagramBuilder()
plant = builder.AddSystem(AcrobotPlant())
scene_graph = builder.AddSystem(SceneGraph())
geom = AcrobotGeometry.AddToBuilder(
builder=builder, acrobot_state_port=plant.get_output_port(0),
scene_graph=scene_graph)
builder.Build()
self.assertIsInstance(geom, AcrobotGeometry)
def test_geometry_with_params(self):
builder = DiagramBuilder()
plant = builder.AddSystem(AcrobotPlant())
scene_graph = builder.AddSystem(SceneGraph())
geom = AcrobotGeometry.AddToBuilder(
builder=builder, acrobot_state_port=plant.get_output_port(0),
acrobot_params=AcrobotParams(), scene_graph=scene_graph)
builder.Build()
self.assertIsInstance(geom, AcrobotGeometry)
def test_simulation(self):
# Basic constant-torque acrobot simulation.
acrobot = AcrobotPlant()
# Create the simulator.
simulator = Simulator(acrobot)
context = simulator.get_mutable_context()
# Set an input torque.
input = AcrobotInput()
input.set_tau(1.)
acrobot.GetInputPort("elbow_torque").FixValue(context, input)
# Set the initial state.
state = context.get_mutable_continuous_state_vector()
state.set_theta1(1.)
state.set_theta1dot(0.)
state.set_theta2(0.)
state.set_theta2dot(0.)
self.assertIsInstance(acrobot.get_state(context=context), AcrobotState)
self.assertIsInstance(acrobot.get_mutable_state(context=context),
AcrobotState)
self.assertIsInstance(acrobot.get_parameters(context=context),
AcrobotParams)
self.assertIsInstance(acrobot.get_mutable_parameters(context=context),
AcrobotParams)
self.assertTrue(acrobot.DynamicsBiasTerm(context).shape == (2,))
self.assertTrue(acrobot.MassMatrix(context).shape == (2, 2))
initial_total_energy = acrobot.EvalPotentialEnergy(context) + \
acrobot.EvalKineticEnergy(context)
# Simulate (and make sure the state actually changes).
initial_state = state.CopyToVector()
simulator.AdvanceTo(1.0)
self.assertLessEqual(acrobot.EvalPotentialEnergy(context)
+ acrobot.EvalKineticEnergy(context),
initial_total_energy)
class TestAcrobotSpongController(unittest.TestCase):
def test_default_parameters(self):
controller = AcrobotSpongController()
context = controller.CreateDefaultContext()
expected_parameters = SpongControllerParams()
actual_parameters = controller.get_parameters(context)
self.assertEqual(actual_parameters.k_e(), expected_parameters.k_e())
self.assertEqual(actual_parameters.k_p(), expected_parameters.k_p())
self.assertEqual(actual_parameters.k_d(), expected_parameters.k_d())
self.assertEqual(actual_parameters.balancing_threshold(),
expected_parameters.balancing_threshold())
def test_param_accessors(self):
controller = AcrobotSpongController()
context = controller.CreateDefaultContext()
controller.get_mutable_parameters(context).set_k_e(1.)
actual_parameters = controller.get_parameters(context)
self.assertEqual(actual_parameters.k_e(), 1.)
class TestSpongControllerParams(unittest.TestCase):
def test_param_accessors(self):
params = SpongControllerParams()
params.set_k_e(1.)
params.set_k_p(2.)
params.set_k_d(3.)
params.set_balancing_threshold(4.)
self.assertEqual(params.k_e(), 1.)
self.assertEqual(params.k_p(), 2.)
self.assertEqual(params.k_d(), 3.)
self.assertEqual(params.balancing_threshold(), 4.)
def test_param_defaults(self):
params = SpongControllerParams()
self.assertEqual(params.k_e(), 5.)
self.assertEqual(params.k_p(), 50.)
self.assertEqual(params.k_d(), 5.)
self.assertEqual(params.balancing_threshold(), 1000.)
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/test/rimless_wheel_test.py | import unittest
import numpy as np
from pydrake.examples import (
RimlessWheel,
RimlessWheelContinuousState,
RimlessWheelGeometry,
RimlessWheelParams,
)
from pydrake.geometry import SceneGraph
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
class TestRimlessWheel(unittest.TestCase):
def test_rimless_wheel(self):
plant = RimlessWheel()
# Confirm the spelling on the output ports.
plant.get_minimal_state_output_port()
plant.get_floating_base_state_output_port()
def test_params(self):
params = RimlessWheelParams()
params.set_mass(1.)
params.set_length(2.)
params.set_gravity(4.)
params.set_number_of_spokes(7)
params.set_slope(.15)
self.assertEqual(params.mass(), 1.)
self.assertEqual(params.length(), 2.)
self.assertEqual(params.gravity(), 4.)
self.assertEqual(params.number_of_spokes(), 7)
self.assertEqual(params.slope(), .15)
self.assertEqual(
RimlessWheel.calc_alpha(params=params),
np.pi / params.number_of_spokes())
def test_state(self):
state = RimlessWheelContinuousState()
state.set_theta(1.)
state.set_thetadot(2.)
self.assertEqual(state.theta(), 1.)
self.assertEqual(state.thetadot(), 2.)
def test_geometry(self):
builder = DiagramBuilder()
plant = builder.AddSystem(RimlessWheel())
scene_graph = builder.AddSystem(SceneGraph())
geom = RimlessWheelGeometry.AddToBuilder(
builder=builder,
floating_base_state_port=plant.get_floating_base_state_output_port(), # noqa
scene_graph=scene_graph)
# Confirming that the resulting diagram builds.
builder.Build()
self.assertIsInstance(geom, RimlessWheelGeometry)
def test_geometry_with_params(self):
builder = DiagramBuilder()
plant = builder.AddSystem(RimlessWheel())
scene_graph = builder.AddSystem(SceneGraph())
geom = RimlessWheelGeometry.AddToBuilder(
builder=builder,
floating_base_state_port=plant.get_floating_base_state_output_port(), # noqa
rimless_wheel_params=RimlessWheelParams(), scene_graph=scene_graph)
# Confirming that the resulting diagram builds.
builder.Build()
self.assertIsInstance(geom, RimlessWheelGeometry)
def test_simulation(self):
# Basic rimless_wheel simulation.
rimless_wheel = RimlessWheel()
# Create the simulator.
simulator = Simulator(rimless_wheel)
context = simulator.get_mutable_context()
context.SetAccuracy(1e-8)
# Set the initial state.
state = context.get_mutable_continuous_state_vector()
state.set_theta(0.)
state.set_thetadot(4.)
# Simulate (and make sure the state actually changes).
initial_state = state.CopyToVector()
simulator.AdvanceTo(1.0)
self.assertFalse((state.CopyToVector() == initial_state).any())
| 0 |
/home/johnshepherd/drake/bindings/pydrake/examples | /home/johnshepherd/drake/bindings/pydrake/examples/test/manipulation_station_test.py | import unittest
import numpy as np
from pydrake.examples import (
CreateClutterClearingYcbObjectList,
CreateManipulationClassYcbObjectList,
IiwaCollisionModel,
ManipulationStation,
ManipulationStationHardwareInterface,
)
from pydrake.geometry import (
ClippingRange,
ColorRenderCamera,
DepthRange,
DepthRenderCamera,
RenderCameraCore,
)
from pydrake.math import RigidTransform, RollPitchYaw
from pydrake.multibody.plant import MultibodyPlant
from pydrake.multibody.tree import ModelInstanceIndex
from pydrake.multibody.parsing import (
PackageMap,
Parser,
)
from pydrake.systems.sensors import CameraInfo
class TestManipulationStation(unittest.TestCase):
def test_manipulation_station(self):
# Just check the spelling.
station = ManipulationStation(time_step=0.001)
station.SetupManipulationClassStation()
station.SetWsgGains(0.1, 0.1)
station.SetIiwaPositionGains(np.ones(7))
station.SetIiwaVelocityGains(np.ones(7))
station.SetIiwaIntegralGains(np.ones(7))
station.Finalize()
station.get_multibody_plant()
station.get_mutable_multibody_plant()
station.get_scene_graph()
station.get_mutable_scene_graph()
station.get_controller_plant()
# Check the setters/getters.
context = station.CreateDefaultContext()
q = np.linspace(0.04, 0.6, num=7)
v = np.linspace(-2.3, 0.5, num=7)
station.SetIiwaPosition(context, q)
np.testing.assert_array_equal(q, station.GetIiwaPosition(context))
station.SetIiwaVelocity(context, v)
np.testing.assert_array_equal(v, station.GetIiwaVelocity(context))
q = 0.0423
v = 0.0851
station.SetWsgPosition(context, q)
self.assertEqual(q, station.GetWsgPosition(context))
station.SetWsgVelocity(context, v)
self.assertEqual(v, station.GetWsgVelocity(context))
station.GetStaticCameraPosesInWorld()["0"]
self.assertEqual(len(station.get_camera_names()), 3)
def test_manipulation_station_add_iiwa_and_wsg_explicitly(self):
station = ManipulationStation()
parser = Parser(station.get_mutable_multibody_plant(),
station.get_mutable_scene_graph())
plant = station.get_mutable_multibody_plant()
# Add models for iiwa and wsg
iiwa_model_file = PackageMap().ResolveUrl(
"package://drake_models/iiwa_description/sdf/"
"iiwa7_no_collision.sdf")
(iiwa,) = parser.AddModels(iiwa_model_file)
X_WI = RigidTransform.Identity()
plant.WeldFrames(plant.world_frame(),
plant.GetFrameByName("iiwa_link_0", iiwa),
X_WI)
wsg_model_file = PackageMap().ResolveUrl(
"package://drake_models/wsg_50_description/sdf/"
"schunk_wsg_50.sdf")
(wsg,) = parser.AddModels(wsg_model_file)
X_7G = RigidTransform.Identity()
plant.WeldFrames(
plant.GetFrameByName("iiwa_link_7", iiwa),
plant.GetFrameByName("body", wsg),
X_7G)
# Register models for the controller.
station.RegisterIiwaControllerModel(
iiwa_model_file, iiwa, plant.world_frame(),
plant.GetFrameByName("iiwa_link_0", iiwa), X_WI)
station.RegisterWsgControllerModel(
wsg_model_file, wsg,
plant.GetFrameByName("iiwa_link_7", iiwa),
plant.GetFrameByName("body", wsg), X_7G)
# Finalize
station.Finalize()
self.assertEqual(station.num_iiwa_joints(), 7)
# This WSG gripper model has 2 independent dof, and the IIWA model
# has 7.
self.assertEqual(plant.num_positions(), 9)
self.assertEqual(plant.num_velocities(), 9)
def test_clutter_clearing_setup(self):
station = ManipulationStation(time_step=0.001)
station.SetupClutterClearingStation()
num_station_bodies = (
station.get_multibody_plant().num_model_instances())
ycb_objects = CreateClutterClearingYcbObjectList()
for model_file, X_WObject in ycb_objects:
station.AddManipulandFromFile(model_file, X_WObject)
station.Finalize()
self.assertEqual(station.num_iiwa_joints(), 7)
context = station.CreateDefaultContext()
q = np.linspace(0.04, 0.6, num=7)
v = np.linspace(-2.3, 0.5, num=7)
station.SetIiwaPosition(context, q)
np.testing.assert_array_equal(q, station.GetIiwaPosition(context))
station.SetIiwaVelocity(context, v)
np.testing.assert_array_equal(v, station.GetIiwaVelocity(context))
q = 0.0423
v = 0.0851
station.SetWsgPosition(context, q)
self.assertEqual(q, station.GetWsgPosition(context))
station.SetWsgVelocity(context, v)
self.assertEqual(v, station.GetWsgVelocity(context))
self.assertEqual(len(station.get_camera_names()), 1)
self.assertEqual(station.get_multibody_plant().num_model_instances(),
num_station_bodies + len(ycb_objects))
def test_planar_iiwa_setup(self):
station = ManipulationStation(time_step=0.001)
station.SetupPlanarIiwaStation()
station.Finalize()
self.assertEqual(station.num_iiwa_joints(), 3)
context = station.CreateDefaultContext()
q = np.linspace(0.04, 0.6, num=3)
v = np.linspace(-2.3, 0.5, num=3)
station.SetIiwaPosition(context, q)
np.testing.assert_array_equal(q, station.GetIiwaPosition(context))
station.SetIiwaVelocity(context, v)
np.testing.assert_array_equal(v, station.GetIiwaVelocity(context))
q = 0.0423
v = 0.0851
station.SetWsgPosition(context, q)
self.assertEqual(q, station.GetWsgPosition(context))
station.SetWsgVelocity(context, v)
self.assertEqual(v, station.GetWsgVelocity(context))
def test_iiwa_collision_model(self):
# Check that all of the elements of the enum were spelled correctly.
IiwaCollisionModel.kNoCollision
IiwaCollisionModel.kBoxCollision
def test_manipulation_station_hardware_interface(self):
station = ManipulationStationHardwareInterface(
camera_names=["123", "456"])
# Don't actually call Connect here, since it would block.
station.get_controller_plant()
self.assertEqual(len(station.get_camera_names()), 2)
self.assertEqual(station.num_iiwa_joints(), 7)
def test_ycb_object_creation(self):
ycb_objects = CreateClutterClearingYcbObjectList()
self.assertEqual(len(ycb_objects), 6)
ycb_objects = CreateManipulationClassYcbObjectList()
self.assertEqual(len(ycb_objects), 5)
def test_rgbd_sensor_registration(self):
X_PC = RigidTransform(p=[1, 2, 3])
station = ManipulationStation(time_step=0.001)
station.SetupManipulationClassStation()
plant = station.get_multibody_plant()
color_camera = ColorRenderCamera(
RenderCameraCore("renderer", CameraInfo(10, 10, np.pi/4),
ClippingRange(0.1, 10.0), RigidTransform()),
False)
depth_camera = DepthRenderCamera(color_camera.core(),
DepthRange(0.1, 9.5))
station.RegisterRgbdSensor("single_sensor", plant.world_frame(), X_PC,
depth_camera)
station.RegisterRgbdSensor("dual_sensor", plant.world_frame(), X_PC,
color_camera, depth_camera)
station.Finalize()
camera_poses = station.GetStaticCameraPosesInWorld()
# The three default cameras plus the two just added.
self.assertEqual(len(camera_poses), 5)
self.assertTrue("single_sensor" in camera_poses)
self.assertTrue("dual_sensor" in camera_poses)
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/module_py.cc | #include "pybind11/eval.h"
#include "drake/bindings/pydrake/autodiff_types_pybind.h"
#include "drake/bindings/pydrake/autodiffutils/autodiffutils_py.h"
#include "drake/bindings/pydrake/common/cpp_template_pybind.h"
#include "drake/bindings/pydrake/common/submodules_py.h"
#include "drake/bindings/pydrake/common/text_logging_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/math/math_py.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/bindings/pydrake/symbolic/symbolic_py.h"
#include "drake/common/constants.h"
#include "drake/common/drake_assert.h"
#include "drake/common/drake_assertion_error.h"
#include "drake/common/drake_path.h"
#include "drake/common/find_resource.h"
#include "drake/common/nice_type_name.h"
#include "drake/common/nice_type_name_override.h"
#include "drake/common/parallelism.h"
#include "drake/common/random.h"
#include "drake/common/temp_directory.h"
#include "drake/common/text_logging.h"
namespace drake {
namespace pydrake {
using drake::internal::type_erased_ptr;
// This function is defined in drake/common/drake_assert_and_throw.cc.
extern "C" void drake_set_assertion_failure_to_throw_exception();
namespace {
void trigger_an_assertion_failure() {
DRAKE_DEMAND(false);
}
// Resolves to a Python handle given a type erased pointer. If the instance or
// lowest-level RTTI type are unregistered, returns an empty handle.
py::handle ResolvePyObject(const type_erased_ptr& ptr) {
auto py_type_info = py::detail::get_type_info(ptr.info);
return py::detail::get_object_handle(ptr.raw, py_type_info);
}
// Override for SetNiceTypeNamePtrOverride, to ensure that instances that are
// registered (along with their types) can use their Python class's name.
std::string PyNiceTypeNamePtrOverride(const type_erased_ptr& ptr) {
DRAKE_DEMAND(ptr.raw != nullptr);
const std::string cc_name = NiceTypeName::Get(ptr.info);
if (cc_name.find("pydrake::") != std::string::npos) {
py::handle obj = ResolvePyObject(ptr);
if (obj) {
py::handle cls = obj.get_type();
const bool use_qualname = true;
return py::str("{}.{}").format(
cls.attr("__module__"), internal::PrettyClassName(cls, use_qualname));
}
}
return cc_name;
}
namespace testing {
// Registered type. Also a base class for UnregisteredDerivedType.
class RegisteredType {
public:
virtual ~RegisteredType() {}
};
// Completely unregistered type.
class UnregisteredType {};
// Unregistered type, but with a registered base.
class UnregisteredDerivedType : public RegisteredType {};
void def_testing(py::module m) {
py::class_<RegisteredType>(m, "RegisteredType").def(py::init());
// See comments in `module_test.py`.
m.def("get_nice_type_name_cc_registered_instance",
[](const RegisteredType& obj) { return NiceTypeName::Get(obj); });
m.def("get_nice_type_name_cc_unregistered_instance",
[]() { return NiceTypeName::Get(RegisteredType()); });
m.def("get_nice_type_name_cc_typeid",
[](const RegisteredType& obj) { return NiceTypeName::Get(typeid(obj)); });
m.def("get_nice_type_name_cc_unregistered_type",
[]() { return NiceTypeName::Get(UnregisteredType()); });
m.def("make_cc_unregistered_derived_type", []() {
return std::unique_ptr<RegisteredType>(new UnregisteredDerivedType());
});
}
} // namespace testing
namespace {
// We put the work of PYBIND11_MODULE into a function so that we can easily
// catch exceptions.
void InitLowLevelModules(py::module m) {
m.doc() = "Bindings for //common:common";
PYDRAKE_PREVENT_PYTHON3_MODULE_REIMPORT(m);
constexpr auto& doc = pydrake_doc.drake;
// Morph any DRAKE_ASSERT and DRAKE_DEMAND failures into SystemExit exceptions
// instead of process aborts. See RobotLocomotion/drake#5268.
drake_set_assertion_failure_to_throw_exception();
// TODO(jwnimmer-tri) Split out the bindings for functions and classes into
// their own separate files, so that this file is only an orchestrator.
// WARNING: Deprecations for this module can be *weird* because of stupid
// cyclic dependencies (#7912). If you need functions that immediately import
// `pydrake.common.deprecation` (e.g. DeprecateAttribute, WrapDeprecated),
// please ping @EricCousineau-TRI.
m.attr("_HAVE_SPDLOG") = logging::kHaveSpdlog;
// Python users should not touch the C++ level; thus, we bind this privately.
m.def("_set_log_level", &logging::set_log_level, py::arg("level"),
doc.logging.set_log_level.doc);
internal::MaybeRedirectPythonLogging();
m.def("_use_native_cpp_logging", &internal::UseNativeCppLogging);
ExecuteExtraPythonCode(m, true);
{
using Class = Parallelism;
constexpr auto& cls_doc = doc.Parallelism;
py::class_<Class> cls(m, "Parallelism", cls_doc.doc);
py::implicitly_convertible<bool, Class>();
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<bool>(), py::arg("parallelize").noconvert(),
cls_doc.ctor.doc_1args_parallelize)
.def(py::init<int>(), py::arg("num_threads").noconvert(),
cls_doc.ctor.doc_1args_num_threads)
// Note that we can't bind Parallelism::None(), because `None`
// is a reserved word in Python.
.def_static("Max", &Class::Max, cls_doc.Max.doc)
.def("num_threads", &Class::num_threads, cls_doc.num_threads.doc);
DefCopyAndDeepCopy(&cls);
}
py::enum_<drake::ToleranceType>(m, "ToleranceType", doc.ToleranceType.doc)
.value("kAbsolute", drake::ToleranceType::kAbsolute,
doc.ToleranceType.kAbsolute.doc)
.value("kRelative", drake::ToleranceType::kRelative,
doc.ToleranceType.kRelative.doc);
py::enum_<drake::RandomDistribution>(
m, "RandomDistribution", doc.RandomDistribution.doc)
.value("kUniform", drake::RandomDistribution::kUniform,
doc.RandomDistribution.kUniform.doc)
.value("kGaussian", drake::RandomDistribution::kGaussian,
doc.RandomDistribution.kGaussian.doc)
.value("kExponential", drake::RandomDistribution::kExponential,
doc.RandomDistribution.kExponential.doc);
m.def("CalcProbabilityDensity", &CalcProbabilityDensity<double>,
py::arg("distribution"), py::arg("x"), doc.CalcProbabilityDensity.doc)
.def("CalcProbabilityDensity", &CalcProbabilityDensity<AutoDiffXd>,
py::arg("distribution"), py::arg("x"),
doc.CalcProbabilityDensity.doc);
// Adds a binding for drake::RandomGenerator.
py::class_<RandomGenerator> random_generator_cls(m, "RandomGenerator",
(std::string(doc.RandomGenerator.doc) + R"""(
Note: For many workflows in drake, we aim to have computations that are fully
deterministic given a single random seed. This is accomplished by passing a
RandomGenerator object. To generate random numbers in numpy that are
deterministic given the C++ random seed (see drake issue #12632 for the
discussion), use e.g.
.. code-block:: python
generator = pydrake.common.RandomGenerator()
random_state = numpy.random.RandomState(generator())
my_random_value = random_state.uniform()
...
)""")
.c_str());
random_generator_cls // BR
.def(py::init<>(), doc.RandomGenerator.ctor.doc_0args)
.def(py::init<RandomGenerator::result_type>(), py::arg("seed"),
doc.RandomGenerator.ctor.doc_1args)
.def(
"__call__", [](RandomGenerator& self) { return self(); },
"Generates a pseudo-random value.");
// Turn DRAKE_ASSERT and DRAKE_DEMAND exceptions into native SystemExit.
// Admittedly, it's unusual for a python library like pydrake to raise
// SystemExit, but for now its better than C++ ::abort() taking down the
// whole interpreter with a worse diagnostic message.
py::register_exception_translator([](std::exception_ptr p) {
try {
if (p) {
std::rethrow_exception(p);
}
} catch (const drake::internal::assertion_error& e) {
PyErr_SetString(PyExc_SystemExit, e.what());
}
});
// Convenient wrapper for querying FindResource(resource_path).
m.def("FindResourceOrThrow", &FindResourceOrThrow,
"Attempts to locate a Drake resource named by the given path string. "
"The path refers to the relative path within the Drake repository, "
"e.g., drake/examples/pendulum/Pendulum.urdf. Raises an exception "
"if the resource was not found.",
py::arg("resource_path"), doc.FindResourceOrThrow.doc);
m.def("temp_directory", &temp_directory,
"Returns a directory location suitable for temporary files that is "
"the value of the environment variable TEST_TMPDIR if defined or "
"otherwise ${TMPDIR:-/tmp}/robotlocomotion_drake_XXXXXX where each X "
"is replaced by a character from the portable filename character set. "
"Any trailing / will be stripped from the output.",
doc.temp_directory.doc);
// The pydrake function named GetDrakePath is residue from when there used to
// be a C++ method named drake::GetDrakePath(). For backward compatibility,
// we'll keep the pydrake function name intact even though there's no
// matching C++ method anymore.
m.def(
"GetDrakePath",
[]() {
py::object result;
if (auto optional_result = MaybeGetDrakePath()) {
result = py::str(*optional_result);
}
return result;
},
doc.MaybeGetDrakePath.doc);
// These are meant to be called internally by pydrake; not by users.
m.def("trigger_an_assertion_failure", &trigger_an_assertion_failure,
"Trigger a Drake C++ assertion failure");
m.attr("kDrakeAssertIsArmed") = kDrakeAssertIsArmed;
// Make nice_type_name use Python type info when available.
drake::internal::SetNiceTypeNamePtrOverride(PyNiceTypeNamePtrOverride);
// =========================================================================
// Now we'll starting defining other modules.
// The following needs to proceed in topological dependency order.
// =========================================================================
// Define `_testing` submodule.
py::module pydrake_top = py::eval("sys.modules['pydrake']");
py::module pydrake_common = py::eval("sys.modules['pydrake.common']");
py::module testing = pydrake_common.def_submodule("_testing");
testing::def_testing(testing);
// Install NumPy warning filters.
// N.B. This may interfere with other code, but until that is a confirmed
// issue, we should aggressively try to avoid these warnings.
py::module::import("pydrake.common.deprecation")
.attr("install_numpy_warning_filters")();
// Install NumPy formatters patch.
py::module::import("pydrake.common.compatibility")
.attr("maybe_patch_numpy_formatters")();
// Define `autodiffutils` top-level module.
py::module autodiffutils = pydrake_top.def_submodule("autodiffutils");
autodiffutils.doc() = "Bindings for Eigen AutoDiff Scalars";
internal::DefineAutodiffutils(autodiffutils);
ExecuteExtraPythonCode(autodiffutils, true);
// Define `symbolic` top-level module.
py::module symbolic = pydrake_top.def_submodule("symbolic");
symbolic.doc() =
"Symbolic variable, variables, monomial, expression, polynomial, and "
"formula";
internal::DefineSymbolicMonolith(symbolic);
ExecuteExtraPythonCode(symbolic, true);
// Define `value` submodule.
py::module value = pydrake_common.def_submodule("value");
value.doc() = "Bindings for //common:value";
internal::DefineModuleValue(value);
// Define `eigen_geometry` submodule.
py::module eigen_geometry = pydrake_common.def_submodule("eigen_geometry");
eigen_geometry.doc() = "Bindings for Eigen geometric types.";
internal::DefineModuleEigenGeometry(eigen_geometry);
ExecuteExtraPythonCode(eigen_geometry, false);
// Define `math` top-level module.
py::module math = pydrake_top.def_submodule("math");
// N.B. Docstring contained in `_math_extra.py`.
internal::DefineMathOperators(math);
internal::DefineMathMatmul(math);
internal::DefineMathMonolith(math);
ExecuteExtraPythonCode(math, true);
// Define `schema` submodule.
py::module schema = pydrake_common.def_submodule("schema");
schema.doc() = "Bindings for the common.schema package.";
internal::DefineModuleSchema(schema);
}
} // namespace
PYBIND11_MODULE(common, m) {
try {
InitLowLevelModules(m);
} catch (const std::exception& e) {
drake::log()->critical("Could not initialize pydrake: {}", e.what());
throw;
}
}
} // namespace
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/all.py | from . import *
from .compatibility import *
from .containers import *
# - `cpp_param` does not offer public Drake symbols.
# - `cpp_template` does not offer public Drake symbols.
# - `deprecation` does not offer public Drake symbols.
from .eigen_geometry import *
from .schema import *
from .yaml import *
from .value import *
# N.B. Since this is generic and relatively scoped, we import the module as a
# symbol.
from . import pybind11_version
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/yaml.py | import collections.abc
import copy
import dataclasses
import math
import functools
import types
import typing
import numpy as np
import yaml
from pydrake.common import pretty_class_name
class _SchemaLoader(yaml.loader.SafeLoader):
"""Customizes SafeLoader for the purposes of this module."""
@staticmethod
def _handle_multi_variant(loader, tag, node):
"""Parses a variant-like YAML node (akin to std::variant<> in C++).
Returns a dict with the inner mapping, plus one extra item with key
`_tag` that holds the YAML tag.
For example, a !Gaussian YAML node is returned as:
{
"_tag": "!Gaussian",
"mean": 2.0,
"std": 4.0,
}.
"""
assert type(loader) is _SchemaLoader, loader
result = loader.construct_mapping(node)
result.update({"_tag": tag})
return result
_SchemaLoader.add_multi_constructor("", _SchemaLoader._handle_multi_variant)
def yaml_load_data(data, *, private=False):
"""Loads and returns the given `data` str as a yaml object, while also
accounting for variant-like type tags. Any tags are reported as an
extra "_tag" field in the returned dictionary.
(Alternatively, `data` may be a file-like stream instead of a str.)
By default, removes any root-level keys that begin with an underscore, so
that yaml anchors and templates are invisibly easy to use. Callers that
wish to receive the private data may pass `private=True`.
This function returns the raw, untyped data (dict, list, str, float, etc.)
without any schema checking nor default values. To load with respect to
a schema with defaults, see ``yaml_load_typed()``.
"""
result = yaml.load(data, Loader=_SchemaLoader)
if not private:
try:
all_keys = list(result.keys())
except AttributeError:
all_keys = []
for key in all_keys:
if key.startswith("_"):
del result[key]
return result
def yaml_load_file(filename, *, private=False):
"""Loads and returns the given `filename` as a yaml object, while also
accounting for variant-like type tags.
See yaml_load_data for full details; this function differs only by reading
the yaml data from a file instead of memory.
"""
with open(filename, "r") as data:
return yaml_load_data(data, private=private)
def yaml_load(*, data=None, filename=None, private=False):
"""Loads either a `data` str xor a `filename` (exactly one must be
specified) and returns the value as a yaml object.
This is sugar for calling either yaml_load_data or yaml_load_file;
refer to those functions for additional details.
This function returns the raw, untyped data (dict, list, str, float, etc.)
without any schema checking nor default values. To load with respect to
a schema with defaults, see ``yaml_load_typed()``.
"""
has_data = data is not None
has_filename = filename is not None
if has_data and has_filename:
raise RuntimeError(
"Exactly one of `data=...` or `filename=...` must be provided, "
"but both were non-None")
if not has_data and not has_filename:
raise RuntimeError(
"Exactly one of `data=...` or `filename=...` must be provided, "
"but both were None")
if data:
return yaml_load_data(data, private=private)
else:
return yaml_load_file(filename, private=private)
# This is a magic tribool value described at
# https://github.com/yaml/pyyaml/pull/256
# and must be set this way for post- and pre- pyyaml#256 yaml dumpers to give
# the same output.
_FLOW_STYLE = None
class _SchemaDumper(yaml.dumper.SafeDumper):
"""Customizes SafeDumper for the purposes of this module."""
class ExplicitScalar(typing.NamedTuple):
"""Wrapper type used when dumping a document. When this type is dumped,
it will always emit the tag, e.g., `!!int 10`. (By default, tags for
scalars are not emitted by pyyaml.)
"""
value: typing.Union[bool, int, float, str]
def _represent_explicit_scalar(self, explicit_scalar):
assert isinstance(explicit_scalar, _SchemaDumper.ExplicitScalar)
value = explicit_scalar.value
node = self.yaml_representers[type(value)](self, value)
# Encourage pyyaml to emit the secondary tag, e.g., `!!int`.
# This does not work for strings.
node.style = "'"
return node
def _represent_dict(self, data):
"""Permits a reverse of _SchemaLoader."""
if "_tag" in data:
tag = data["_tag"]
data = copy.copy(data)
del data["_tag"]
return self.represent_mapping(tag, data)
else:
return super().represent_dict(data)
_SchemaDumper.add_representer(dict, _SchemaDumper._represent_dict)
_SchemaDumper.add_representer(
_SchemaDumper.ExplicitScalar,
_SchemaDumper._represent_explicit_scalar)
class _DrakeFlowSchemaDumper(_SchemaDumper):
"""Implements the 'drake flow' emitter styling, which follows the
conventions from yaml_write_archive.cc:
- For sequences: if all children are scalars, then formats the sequence
onto a single line; otherwise, format as a bulleted list. This exact
logic is already implemented in PyYAML when using _DEFAULT_FLOW_STYLE.
- For mappings: If there are no children, then formats this map onto a
single line; otherwise, format over multiple lines.
"""
def serialize_node(self, node, parent, index):
if isinstance(node, yaml.MappingNode):
node.flow_style = len(node.value) == 0
return super().serialize_node(node, parent, index)
def yaml_dump(data, *, filename=None):
"""Dumps a yaml object to a string or `filename` (if specified).
This is the counterpart to `yaml_load(..., private=True)`, and will permit
re-expressing the same tagged data.
"""
if filename is not None:
with open(filename, "w") as f:
yaml.dump(data, f, Dumper=_SchemaDumper,
default_flow_style=_FLOW_STYLE)
else:
return yaml.dump(data, Dumper=_SchemaDumper,
default_flow_style=_FLOW_STYLE)
_LoadYamlOptions = collections.namedtuple("LoadYamlOptions", [
"allow_yaml_with_no_schema",
"allow_schema_with_no_yaml",
"retain_map_defaults",
])
def _enumerate_field_types(schema):
"""Returns a Mapping[str, type] of the schema-based field names and types
of the given type `schema`.
"""
assert isinstance(schema, type)
# Dataclasses offer a public API for introspection.
if dataclasses.is_dataclass(schema):
return dict([
(field.name, field.type)
for field in dataclasses.fields(schema)])
# Drake's DefAttributesUsingSerialize offers (hidden) introspection.
fields = getattr(schema, "__fields__", None)
if fields is not None:
return dict([
(field.name, field.type)
for field in fields])
# Detect when the user forgot to use DefAttributesUsingSerialize.
if getattr(type(schema), "__name__", None) == "pybind11_type":
raise NotImplementedError(
f"The bound C++ type {schema} cannot be used as a schema because"
f" it lacks a __fields__ attribute."
f" Use DefAttributesUsingSerialize to add that attribute.")
raise NotImplementedError(
f"Schema objects of type {schema} are not yet supported")
def _is_union(generic_base):
"""Given a generic_base type (from typing.get_origin), returns True iff it
is a sum type (i.e., a Union).
"""
return generic_base in [typing.Union, types.UnionType]
def _get_nested_optional_type(schema):
"""If the given schema (i.e., type) is equivalent to an Optional[Foo], then
returns Foo. Otherwise, returns None.
"""
generic_base = typing.get_origin(schema)
if _is_union(generic_base):
generic_args = typing.get_args(schema)
NoneType = type(None)
if len(generic_args) == 2 and generic_args[-1] == NoneType:
(nested_type, _) = generic_args
return nested_type
return None
def _create_from_schema(*, schema, forthcoming_value):
"""Given a schema (i.e., a type), returns a default-constructed instance
of that schema type, modulo a few exceptional cases that are specific to
our parsing semantics as detailed below.
When schema is a sum type (e.g., typing.Union[...]), returns None.
When schema is a numpy type, returns a 1-d ndarray with the same size as
the ``forthcoming_value`` if provided, otherwise an empty array.
"""
if _is_union(typing.get_origin(schema)):
return None
if schema == np.ndarray:
size = len(forthcoming_value)
return np.array([math.nan] * size)
return schema()
# For details, see:
# https://yaml.org/spec/1.2.2/#scalars
# https://yaml.org/spec/1.2.2/#json-schema
_PRIMITIVE_YAML_TYPES = (bool, int, float, str)
def _merge_yaml_dict_item_into_target(*, options, name, yaml_value,
target, value_schema):
"""Parses the given `yaml_value` into an object of type `value_schema`,
writing the result to the field named `name` of the given `target` object.
"""
# The target can be either a dictionary or a dataclass.
assert target is not None
if isinstance(target, collections.abc.Mapping):
getter = functools.partial(target.__getitem__, name)
setter = functools.partial(target.__setitem__, name)
else:
getter = functools.partial(getattr, target, name)
setter = functools.partial(setattr, target, name)
# Handle all of the plain YAML scalars:
# https://yaml.org/spec/1.2.2/#scalars
# https://yaml.org/spec/1.2.2/#json-schema
if value_schema in _PRIMITIVE_YAML_TYPES:
if type(yaml_value) in (list, dict):
raise RuntimeError(
f"Expected a {value_schema} value for '{name}' but instead got"
f" non-scalar yaml data of type {type(yaml_value)}")
new_value = value_schema(yaml_value)
setter(new_value)
return
# Handle nullable types (std::optional<T> or typing.Optional[T]).
nested_optional_type = _get_nested_optional_type(value_schema)
if nested_optional_type is not None:
# If the yaml was null, the Python field will be None.
if yaml_value is None:
setter(None)
return
# Create a non-null default value, if necessary.
old_value = getter()
if old_value is None:
setter(_create_from_schema(
schema=nested_optional_type,
forthcoming_value=yaml_value))
# Now we can parse Optional[Foo] like a plain Foo.
_merge_yaml_dict_item_into_target(
options=options, name=name, yaml_value=yaml_value, target=target,
value_schema=nested_optional_type)
return
# Handle NumPy types.
if value_schema == np.ndarray:
new_value = np.array(yaml_value, dtype=float)
setter(new_value)
return
# Check if the field is generic like list[str]; if yes, the generic_base
# will be, e.g., `list` and generic_args will be, e.g., `[str]`.
generic_base = typing.get_origin(value_schema)
generic_args = typing.get_args(value_schema)
# Handle YAML sequences:
# https://yaml.org/spec/1.2.2/#sequence
#
# In Drake's YamlLoad convention, merging a sequence denotes *overwriting*
# what was there.
if generic_base in (list, typing.List):
(value_type,) = generic_args
new_value = []
for sub_yaml_value in yaml_value:
sub_target = {"_": _create_from_schema(
schema=value_type,
forthcoming_value=sub_yaml_value)}
_merge_yaml_dict_item_into_target(
options=options, name="_", yaml_value=sub_yaml_value,
target=sub_target, value_schema=value_type)
new_value.append(sub_target["_"])
setter(new_value)
return
# Handle YAML maps:
# https://yaml.org/spec/1.2.2/#mapping
#
# In Drake's YamlLoad convention, merging a mapping denotes *updating*
# what was there iff retain_map_defaults was set.
if generic_base in (dict, collections.abc.Mapping):
(key_type, value_type) = generic_args
# This requirement matches what we have in C++. Allowing sequences
# or maps as keys would mean we're no longer JSON-compatible.
assert key_type == str
if options.retain_map_defaults:
old_value = getter()
new_value = copy.deepcopy(old_value)
else:
new_value = dict()
for sub_key, sub_yaml_value in yaml_value.items():
# In case the sub_key does not exist in the map, insert it.
if sub_key not in new_value:
new_value[sub_key] = _create_from_schema(
schema=value_type,
forthcoming_value=sub_yaml_value)
_merge_yaml_dict_item_into_target(
options=options, name=sub_key, yaml_value=sub_yaml_value,
target=new_value, value_schema=value_type)
setter(new_value)
return
# Handle schema sum types (std::variant<...> or typing.Union[...]).
if _is_union(generic_base):
# The YAML data might be a scalar value (as opposed to a mapping).
yaml_value_type = type(yaml_value)
if yaml_value_type in list(_PRIMITIVE_YAML_TYPES) + [type(None)]:
if yaml_value_type not in generic_args:
raise RuntimeError(
f"The schema sum type for '{name}' cannot accept a yaml "
f"value '{yaml_value}' of type {yaml_value_type}; only "
f"one of {generic_args} are acceptable")
setter(yaml_value)
return
# A mapping can optionally specify a type tag to choose which Union[]
# type to parse into. When none is provided, the default is to use the
# first option listed in the sum type (to match what C++ does).
if yaml_value is not None and "_tag" in yaml_value:
# Pop the type tag out of the yaml_value dictionary.
refined_yaml_value = copy.copy(yaml_value)
_tag = refined_yaml_value.pop("_tag")
assert _tag.startswith("!"), yaml_value
tag = _tag[1:]
# Find which Union[] type argument matches the tag.
refined_value_schema = None
for candidate in generic_args:
candidate_name = pretty_class_name(candidate)
if "[" in candidate_name:
# When matching vs template type, compare the base name.
candidate_name = candidate_name.split("[", 1)[0]
if candidate_name == tag:
refined_value_schema = candidate
break
else:
raise RuntimeError(
f"The yaml type tag value '{tag}' did not match any of the"
f" allowed type options for '{name}' ({generic_args})")
else:
refined_yaml_value = yaml_value
refined_value_schema = generic_args[0]
# Self-call, but now with an updated value and type.
refined_value_schema_origin = typing.get_origin(refined_value_schema)
if refined_value_schema_origin is None:
refined_value_schema_origin = refined_value_schema
if not isinstance(getter(), refined_value_schema_origin):
setter(_create_from_schema(
schema=refined_value_schema_origin,
forthcoming_value=yaml_value))
_merge_yaml_dict_item_into_target(
options=options, name=name, yaml_value=refined_yaml_value,
target=target, value_schema=refined_value_schema)
return
# By this point, we've handled all known cases of generic types.
if generic_base is not None:
raise NotImplementedError(
f"The generic type {generic_base} of {value_schema} is "
"not yet supported")
# If the value_schema is neither primitive nor generic, then we'll assume
# it's a directly-nested subclass.
old_value = getter()
new_value = copy.deepcopy(old_value)
_merge_yaml_dict_into_target(
options=options, yaml_dict=yaml_value,
target=new_value, target_schema=value_schema)
setter(new_value)
def _merge_yaml_dict_into_target(*, options, yaml_dict,
target, target_schema):
"""Merges the given yaml_dict into the given target (of given type).
The target must be an instance of some dataclass or pybind11 class.
The yaml_dict must be typed like the result of calling yaml_load (i.e.,
raw strings, dictionaries, lists, etc.).
"""
assert isinstance(yaml_dict, collections.abc.Mapping), yaml_dict
assert target is not None
static_field_map = _enumerate_field_types(target_schema)
schema_names = list(static_field_map.keys())
schema_optionals = set([
name for name, sub_schema in static_field_map.items()
if _get_nested_optional_type(sub_schema) is not None
])
yaml_names = list(yaml_dict.keys())
extra_yaml_names = [
name for name in yaml_names
if name not in schema_names
]
missing_yaml_names = [
name for name, sub_schema in static_field_map.items()
if name not in yaml_names and name not in schema_optionals
]
if extra_yaml_names and not options.allow_yaml_with_no_schema:
raise RuntimeError(
f"The fields {extra_yaml_names} were unknown to the schema")
if missing_yaml_names and not options.allow_schema_with_no_yaml:
raise RuntimeError(
f"The fields {missing_yaml_names} were missing in the yaml data")
for name, sub_schema in static_field_map.items():
if name in yaml_dict:
sub_value = yaml_dict[name]
elif name in schema_optionals:
# For Optional fields that are missing from the yaml data, we must
# match the C++ heuristic: when "allow no yaml" is set, we'll leave
# the existing value unchanged. Otherwise, we need to affirmatively
# to set the target to the None value.
if options.allow_schema_with_no_yaml:
continue
sub_value = None
else:
# Errors for non-Optional missing yaml data have already been
# implemented above (see "missing_yaml_names"), so we should just
# skip over those fields here. They will remain unchanged.
continue
_merge_yaml_dict_item_into_target(
options=options, name=name, yaml_value=sub_value,
target=target, value_schema=sub_schema)
def yaml_load_typed(*, schema=None,
data=None,
filename=None,
child_name=None,
defaults=None,
allow_yaml_with_no_schema=False,
allow_schema_with_no_yaml=True,
retain_map_defaults=True):
"""Loads either a ``data`` str or a ``filename`` against the given
``schema`` type and returns an instance of that type.
This mimics the C++ function ``drake::common::yaml::LoadYamlFile``.
This is the complementary operation to ``yaml_dump_typed``.
Args:
schema: The type to load as. This either must be a ``dataclass``, a C++
class bound using pybind11 and ``DefAttributesUsingSerialize``, or
a ``Mapping[str, ...]`` where the mapping's value type is one of
those two categories. If a non-None ``defaults`` is provided, then
``schema`` can be ``None`` and will use ``type(defaults)`` in that
case.
data: The string of YAML data to be loaded. Exactly one of either
``data`` or ``filename`` must be provided.
filename: The filename of YAML data to be loaded. Exactly one of either
``data`` or ``filename`` must be provided.
child_name: If provided, loads data from given-named child of the
document's root instead of the root itself.
defaults: If provided, then the object being read into will be
initialized using this value instead of the schema's default
constructor.
allow_yaml_with_no_schema: Allows yaml Maps to have extra key-value
pairs that are specified by the schema being parsed into. In other
words, the schema argument provides only an incomplete schema for
the YAML data. This allows for parsing only a subset of the YAML
data.
allow_schema_with_no_yaml: Allows the schema to provide more key-value
pairs than are present in the YAML data. In other words, objects
can have default values that are left intact unless the YAML data
provides a value.
retain_map_defaults: If set to true, when parsing a Mapping the loader
will merge the YAML data into the destination, instead of replacing
the dict contents entirely. In other words, a Mapping field in a
schema can have default values that are left intact unless the YAML
data provides a value *for that specific key*.
"""
# Infer the schema when possible.
if schema is None:
if defaults is None:
raise ValueError(
"At least one of schema= and defaults= must be provided")
schema = type(defaults)
# Choose the allow/retain setting in case none were provided.
options = _LoadYamlOptions(
allow_yaml_with_no_schema=allow_yaml_with_no_schema,
allow_schema_with_no_yaml=allow_schema_with_no_yaml,
retain_map_defaults=retain_map_defaults)
# Create the result object.
if defaults is not None:
result = copy.deepcopy(defaults)
else:
result = schema()
# Parse the YAML document.
document = yaml_load(data=data, filename=filename)
if child_name is not None:
root_node = document[child_name]
else:
root_node = document
if not isinstance(root_node, collections.abc.Mapping):
raise RuntimeError(
f"YAML root was a {type(root_node)} but should have been a dict")
# Merge the document into the result.
_merge_yaml_dict_into_target(
options=options, yaml_dict=root_node,
target=result, target_schema=schema)
return result
def _yaml_dump_typed_item(*, obj, schema):
"""Given an object ``obj`` and its type ``schema``, returns the plain YAML
object that should be serialized. Objects that are already primitive types
(str, float, etc.) are returned unchanged. Bare collection types (List and
Mapping) are processed recursively. Structs (dataclasses) are processed
using their schema. The result is "plain" in the sense that's it's always
just a tree of primitives, lists, and dicts -- no user-defined types.
"""
assert schema is not None
# Handle all of the plain YAML scalars:
# https://yaml.org/spec/1.2.2/#scalars
# https://yaml.org/spec/1.2.2/#json-schema
if schema in _PRIMITIVE_YAML_TYPES:
return schema(obj)
# Check if the field is generic like list[str]; if yes, the generic_base
# will be, e.g., `list` and generic_args will be, e.g., `[str]`.
generic_base = typing.get_origin(schema)
generic_args = typing.get_args(schema)
# Handle YAML sequences:
# https://yaml.org/spec/1.2.2/#sequence
if generic_base in (list, typing.List):
(item_schema,) = generic_args
return [
_yaml_dump_typed_item(obj=item, schema=item_schema)
for item in obj
]
# Handle YAML maps:
# https://yaml.org/spec/1.2.2/#mapping
if generic_base in (dict, collections.abc.Mapping):
(key_schema, value_schema) = generic_args
if key_schema != str:
# This requirement matches what we have in C++. Allowing sequences
# or maps as keys would mean we're no longer JSON-compatible.
raise RuntimeError(f"Dict keys must be strings, not {key_schema}")
result = dict()
for key in sorted(obj):
value = obj[key]
value_plain = _yaml_dump_typed_item(obj=value, schema=value_schema)
result[key] = value_plain
return result
# Handle nullable types (std::optional<T> or typing.Optional[T]).
optional_schema = _get_nested_optional_type(schema)
if optional_schema is not None:
if obj is None:
return None
return _yaml_dump_typed_item(obj=obj, schema=optional_schema)
# Handle schema sum types (std::variant<...> or typing.Union[...]).
if _is_union(generic_base):
if obj is None:
if type(None) in generic_args:
return None
raise RuntimeError(f"The {schema} does not allow None as a value")
match = None
for i, one_schema in enumerate(generic_args):
one_schema_origin = typing.get_origin(one_schema)
if one_schema_origin is None:
one_schema_origin = one_schema
if isinstance(obj, one_schema_origin):
match = i
break
if match is None:
raise RuntimeError(
f"A value of type {type(obj)} did not match any {schema}")
union_schema = generic_args[i]
result = _yaml_dump_typed_item(obj=obj, schema=union_schema)
if i != 0:
if union_schema in _PRIMITIVE_YAML_TYPES:
result = _SchemaDumper.ExplicitScalar(result)
else:
class_name_with_args = pretty_class_name(union_schema)
class_name = class_name_with_args.split("[", 1)[0]
result["_tag"] = "!" + class_name
return result
# Handle NumPy types.
if schema == np.ndarray:
# TODO(jwnimmer-tri) We should use the numpy.typing module here to
# statically specify a shape and/or dtype in the schema. For now,
# we only support floats with no restrictions on the shape.
assert obj.dtype == np.dtype(np.float64)
list_value = obj.tolist()
list_schema = float
for _ in obj.shape:
list_schema = typing.List[list_schema]
return _yaml_dump_typed_item(obj=list_value, schema=list_schema)
# If no special case matched, then we'll assume it's a nested class and
# dump its fields one by one.
result = dict()
for name, item_schema in _enumerate_field_types(schema).items():
item_obj = getattr(obj, name)
item_plain = _yaml_dump_typed_item(obj=item_obj, schema=item_schema)
if item_plain is None:
if _get_nested_optional_type(item_schema) is not None:
# When an Optional member field is set to None, then don't emit
# "{name}: null"; instead, just skip it entirely.
continue
result[name] = item_plain
return result
def _erase_matching_maps(*, node, defaults):
"""This logic mimics the C++ YamlWriteArchive function of the same name."""
# Remove from `node` any key-value pair that is identical within both
# `node` and `defaults`.
keys_to_prune = []
for key in node:
if key not in defaults:
# Don't prune and don't recurse.
continue
sub_node = node[key]
sub_defaults = defaults[key]
if sub_node is sub_defaults or sub_node == sub_defaults:
# Found a match. Prune and don't recurse. (We check both 'is' and
# '==' because `math.nan` does not compare equal to itself.)
keys_to_prune.append(key)
continue
if not isinstance(sub_node, dict):
continue
if sub_node.get("_tag") != sub_defaults.get("_tag"):
# The maps are tagged differently, so we should not subtract their
# children, since they may have different semantics.
continue
# Recurse into children with the same key name.
_erase_matching_maps(node=sub_node, defaults=sub_defaults)
for key in keys_to_prune:
del node[key]
def yaml_dump_typed(data,
*,
filename=None,
schema=None,
child_name=None,
defaults=None):
"""Dumps an object to a YAML string or ``filename`` (if specified), using
the ``schema`` in order to support non-primitive types.
This mimics the C++ function ``drake::common::yaml::SaveYamlFile``.
This is the complementary operation to ``yaml_load_typed``.
Args:
data: The object to be dumped.
filename: If provided, the YAML filename to be written to. When None,
this function will return a YAML string instead of writing to a
file.
schema: If provided, the type to dump as. When None, the default is
``type(data)``. This either must be a ``dataclass``, a C++ class
bound using pybind11 and ``DefAttributesUsingSerialize``, or a
``Mapping[str, ...]`` where the mapping's value type is one of
those two categories.
child_name: If provided, dumps using given name as the document root,
with the ``data`` nested underneath.
defaults: If provided, then only data that differs from the given
``defaults`` will be dumped.
"""
# Sanity checks.
assert data is not None
if child_name is not None:
if type(child_name) not in _PRIMITIVE_YAML_TYPES:
raise RuntimeError("The child_name must be a primitive type, "
f"not a {type(child_name)}")
# If no schema was provided, then choose one.
if schema is None:
schema = type(data)
# Convert to a tree of primitives, lists, and dicts.
root = _yaml_dump_typed_item(obj=data, schema=schema)
# If a baseline value was provided, then subtract it from the result.
if defaults is not None:
plain_defaults = _yaml_dump_typed_item(obj=defaults, schema=schema)
_erase_matching_maps(node=root, defaults=plain_defaults)
# If a child_name was provided, then weave it into the root.
if child_name is not None:
root = {child_name: root}
# To align with the capabilities of yaml_load_typed, we limit the root to
# be a mapping node (not scalar nor list).
if not isinstance(root, collections.abc.Mapping):
raise RuntimeError(
f"YAML root was a {type(root)} but should have been a dict")
# Write the data to disk xor return a string, based on the presence of a
# filename. Use layout options to match the C++ (SaveYamlFile) style.
dump_func = functools.partial(
yaml.dump,
Dumper=_DrakeFlowSchemaDumper,
default_flow_style=_FLOW_STYLE,
sort_keys=False,
)
if filename is not None:
with open(filename, "w", encoding="utf-8") as f:
dump_func(root, f)
else:
return dump_func(root)
__all__ = [
"yaml_dump",
"yaml_dump_typed",
"yaml_load",
"yaml_load_data",
"yaml_load_file",
"yaml_load_typed",
]
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/value_py.cc | #include <string>
#include "pybind11/eval.h"
#include "drake/bindings/pydrake/common/cpp_param_pybind.h"
#include "drake/bindings/pydrake/common/value_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
namespace drake {
namespace pydrake {
namespace internal {
namespace {
// Local specialization of C++ implementation for `Value[object]`
// instantiation.
// TODO(eric.cousineau): Per discussion in #18655, should consider enforcing
// value semantics (always deepcopy, even on `set_value()`).
class PyObjectValue : public drake::Value<Object> {
public:
using Base = Value<Object>;
using Base::Base;
// Override `Clone()` to perform a deep copy on the object.
std::unique_ptr<AbstractValue> Clone() const override {
py::gil_scoped_acquire guard;
return std::make_unique<PyObjectValue>(get_value().Clone());
}
// Override `SetFrom()` to perform a deep copy on the object.
void SetFrom(const AbstractValue& other) override {
py::gil_scoped_acquire guard;
get_mutable_value() = other.get_value<Object>().Clone();
}
};
// Add instantiations of primitive types on an as-needed basis; please be
// conservative.
void AddPrimitiveValueInstantiations(py::module m) {
AddValueInstantiation<std::string>(m); // Value[str]
AddValueInstantiation<bool>(m); // Value[bool]
AddValueInstantiation<double>(m); // Value[float]
AddValueInstantiation<Object, PyObjectValue>(m); // Value[object]
}
} // namespace
void DefineModuleValue(py::module m) {
constexpr auto& doc = pydrake_doc.drake;
// `AddValueInstantiation` will define methods specific to `T` for
// `Value<T>`. Since Python is nominally dynamic, these methods are
// effectively "virtual".
auto abstract_stub = [](const std::string& method) {
return [method](const AbstractValue* self, py::args, py::kwargs) {
std::string type_name = NiceTypeName::Get(*self);
throw std::runtime_error(fmt::format(
"This C++ derived class of `AbstractValue`, `{}`, is not known to "
"Python, so `AbstractValue.{}` cannot be called. One likely source "
"of this problem is a missing `import` statement. Or, if the binding "
"truly doesn't exist in any module, see `AddValueInstantiation` for "
"how to bind it.",
type_name, method));
};
};
py::class_<AbstractValue> abstract_value(m, "AbstractValue");
DefClone(&abstract_value);
abstract_value // BR
.def("SetFrom", &AbstractValue::SetFrom, doc.AbstractValue.SetFrom.doc)
.def("get_value", abstract_stub("get_value"),
doc.AbstractValue.get_value.doc)
.def("get_mutable_value", abstract_stub("get_mutable_value"),
doc.AbstractValue.get_mutable_value.doc)
.def("set_value", abstract_stub("set_value"),
doc.AbstractValue.set_value.doc);
// Add value instantiations for nominal data types.
AddPrimitiveValueInstantiations(m);
ExecuteExtraPythonCode(m);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/BUILD.bazel | load("//bindings/pydrake:pydrake.bzl", "add_lint_tests_pydrake")
load("//tools/install:install.bzl", "install")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_googletest",
"drake_cc_library",
)
load(
"//tools/skylark:drake_py.bzl",
"drake_py_binary",
"drake_py_library",
"drake_py_unittest",
)
load(
"//tools/skylark:pybind.bzl",
"drake_pybind_cc_googletest",
"drake_pybind_library",
"generate_pybind_documentation_header",
"get_drake_py_installs",
"get_pybind_package_info",
)
load(
"//tools/workspace/pybind11:repository.bzl",
"generate_pybind11_version_py_file",
)
package(default_visibility = ["//visibility:private"])
# This determines how `PYTHONPATH` is configured, and how to install the
# bindings.
PACKAGE_INFO = get_pybind_package_info("//bindings")
drake_py_library(
name = "common",
imports = PACKAGE_INFO.py_imports,
visibility = [
"//bindings/pydrake:__pkg__",
"//bindings/pydrake/common/test_utilities:__pkg__",
],
deps = [
# This `_init_py` is redundant since `pydrake:module_py` uses it, but
# it is placed here for clarity.
":_init_py",
"//bindings/pydrake:module_py",
],
)
# We've carved this `_init_py` out of `common` to avoid dependency cycles with
# `pydrake:module_py`.
drake_pybind_library(
name = "_init_py",
cc_deps = [
":cpp_template_pybind",
":default_scalars_pybind",
":eigen_pybind",
":serialize_pybind",
":type_pack",
":value_pybind",
"//bindings/pydrake:autodiff_types_pybind",
"//bindings/pydrake:documentation_pybind",
"//bindings/pydrake:math_operators_pybind",
"//bindings/pydrake:symbolic_types_pybind",
"//bindings/pydrake/autodiffutils:autodiffutils_py",
"//bindings/pydrake/math:math_py",
"//bindings/pydrake/symbolic:symbolic_py",
"//common:nice_type_name_override_header",
],
cc_so_name = "__init__",
cc_srcs = [
"module_py.cc",
"text_logging_pybind.h",
"text_logging_pybind.cc",
"eigen_geometry_py.cc",
"schema_py.cc",
"submodules_py.h",
"value_py.cc",
],
package_info = PACKAGE_INFO,
py_deps = [
"//bindings/pydrake/autodiffutils:autodiffutils_extra",
"//bindings/pydrake/math:math_extra",
"//bindings/pydrake/symbolic:symbolic_extra",
],
py_srcs = [
"_common_extra.py",
"_eigen_geometry_extra.py",
"_value_extra.py",
"all.py",
"compatibility.py",
"containers.py",
"cpp_param.py",
"cpp_template.py",
"deprecation.py",
"jupyter.py",
"pybind11_version.py",
"yaml.py",
],
visibility = [
"//bindings/pydrake:__pkg__",
],
)
generate_pybind11_version_py_file(
name = "pybind11_version.py",
)
# Our Jupyter tooling needs to import this file directly. This is sound only
# because `deprecation.py` depends on the Python standard library and nothing
# else. (Note that the source file is also already listed as part of the
# sources of `_init_py`; this library target is only used for the Jupyter
# launcher, not as part of the nominal pydrake build.)
drake_py_library(
name = "deprecation_py",
srcs = ["deprecation.py"],
imports = PACKAGE_INFO.py_imports,
visibility = [
"//tools/jupyter:__pkg__",
],
)
# ========================== FOO_pybind.h helpers ==========================
# ODR does not matter, because the singleton will be stored in Python.
drake_cc_library(
name = "cpp_param_pybind",
srcs = ["cpp_param_pybind.cc"],
hdrs = ["cpp_param_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
":type_pack",
":wrap_pybind",
"//bindings/pydrake:pydrake_pybind",
"@pybind11",
],
)
drake_cc_library(
name = "cpp_template_pybind",
hdrs = ["cpp_template_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
":cpp_param_pybind",
"//bindings/pydrake:pydrake_pybind",
"@pybind11",
],
)
drake_cc_library(
name = "default_scalars_pybind",
hdrs = ["default_scalars_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
":cpp_template_pybind",
":type_pack",
"//:drake_shared_library",
"//bindings/pydrake:autodiff_types_pybind",
"//bindings/pydrake:pydrake_pybind",
"//bindings/pydrake:symbolic_types_pybind",
],
)
drake_cc_library(
name = "deprecation_pybind",
hdrs = ["deprecation_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
":wrap_function",
"//bindings/pydrake:pydrake_pybind",
],
)
drake_cc_library(
name = "eigen_pybind",
hdrs = ["eigen_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
"//:drake_shared_library",
"//bindings/pydrake:pydrake_pybind",
],
)
drake_cc_library(
name = "identifier_pybind",
hdrs = ["identifier_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
"//:drake_shared_library",
"//bindings/pydrake:documentation_pybind",
],
)
drake_cc_library(
name = "serialize_pybind",
hdrs = ["serialize_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
":cpp_template_pybind",
"//:drake_shared_library",
"//bindings/pydrake:pydrake_pybind",
],
)
drake_cc_library(
name = "sorted_pair_pybind",
hdrs = ["sorted_pair_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = ["//:drake_shared_library"],
)
drake_cc_library(
name = "type_pack",
hdrs = ["type_pack.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
)
drake_cc_library(
name = "type_safe_index_pybind",
hdrs = ["type_safe_index_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
":value_pybind",
"//:drake_shared_library",
"//bindings/pydrake:documentation_pybind",
],
)
# N.B. Any C++ libraries that include this must include `cpp_template_py` when
# being used in Python.
drake_cc_library(
name = "value_pybind",
hdrs = ["value_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
":cpp_template_pybind",
"//:drake_shared_library",
],
)
drake_cc_library(
name = "wrap_function",
hdrs = ["wrap_function.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
)
drake_cc_library(
name = "wrap_pybind",
hdrs = ["wrap_pybind.h"],
declare_installed_headers = False,
visibility = ["//visibility:public"],
deps = [
":wrap_function",
"//:drake_shared_library",
],
)
# ========================== Pure Python submodules ==========================
PY_LIBRARIES_WITH_INSTALL = [
":_init_py",
]
# Symbol roll-up (for user ease).
drake_py_library(
name = "all_py",
deps = PY_LIBRARIES_WITH_INSTALL,
)
install(
name = "install",
py_dest = PACKAGE_INFO.py_dest,
visibility = [
"//bindings/pydrake:__pkg__",
],
deps = get_drake_py_installs(PY_LIBRARIES_WITH_INSTALL),
)
# ========================== Tests and test helpers ==========================
drake_pybind_library(
name = "compatibility_test_util_py",
testonly = True,
add_install = False,
cc_srcs = ["test/compatibility_test_util_py.cc"],
package_info = PACKAGE_INFO,
)
drake_py_unittest(
name = "compatibility_test",
deps = [
":common",
":compatibility_test_util_py",
],
)
drake_py_unittest(
name = "containers_test",
deps = [
":common",
],
)
drake_py_unittest(
name = "cpp_param_test",
deps = [
":common",
],
)
drake_pybind_cc_googletest(
name = "cpp_param_pybind_test",
cc_deps = [
":cpp_param_pybind",
"//bindings/pydrake:test_util_pybind",
],
py_deps = [
":common",
],
)
drake_py_unittest(
name = "cpp_template_test",
deps = [
":common",
"//bindings/pydrake/common/test_utilities",
],
)
drake_pybind_cc_googletest(
name = "cpp_template_pybind_test",
cc_deps = [
":cpp_template_pybind",
"//bindings/pydrake:test_util_pybind",
"//common:nice_type_name",
"//common/test_utilities:expect_throws_message",
],
py_deps = [":common"],
)
drake_cc_library(
name = "deprecation_example_class",
testonly = True,
srcs = ["test/deprecation_example/example_class.cc"],
hdrs = ["test/deprecation_example/example_class.h"],
deps = [
"//:drake_shared_library",
],
)
drake_pybind_library(
name = "eigen_geometry_test_util_py",
testonly = True,
add_install = False,
cc_so_name = "test/eigen_geometry_test_util",
cc_srcs = ["test/eigen_geometry_test_util_py.cc"],
package_info = PACKAGE_INFO,
)
drake_py_unittest(
name = "eigen_geometry_test",
deps = [
":common",
":eigen_geometry_test_util_py",
"//bindings/pydrake/common/test_utilities",
],
)
drake_pybind_library(
name = "eigen_pybind_test_util_py",
testonly = True,
add_install = False,
cc_deps = [":eigen_pybind"],
cc_so_name = "test/eigen_pybind_test_util",
cc_srcs = ["test/eigen_pybind_test_util_py.cc"],
package_info = PACKAGE_INFO,
)
drake_py_unittest(
name = "eigen_pybind_test",
deps = [
":eigen_pybind_test_util_py",
],
)
generate_pybind_documentation_header(
name = "deprecation_example_class_documentation_genrule",
testonly = True,
out = "test/deprecation_example/example_class_documentation.h",
targets = [":deprecation_example_class"],
)
drake_cc_library(
name = "deprecation_example_class_documentation",
testonly = True,
hdrs = ["test/deprecation_example/example_class_documentation.h"],
tags = ["nolint"],
)
drake_pybind_library(
name = "deprecation_example_cc_module_py",
testonly = True,
add_install = False,
cc_deps = [
":deprecation_example_class",
":deprecation_example_class_documentation",
":deprecation_pybind",
],
cc_so_name = "test/deprecation_example/cc_module",
cc_srcs = [
"test/deprecation_example/cc_module_py.cc",
],
package_info = PACKAGE_INFO,
py_deps = [
":common",
],
)
drake_py_library(
name = "deprecation_example",
testonly = True,
srcs = glob(["test/deprecation_example/*.py"]),
imports = ["test"],
deps = [
":common",
":deprecation_example_cc_module_py",
],
)
# Note: This target tests the low-level deprecation API.
# See `deprecation_utility_test` for a unittest on higher-level deprecation
# API.
drake_py_unittest(
name = "deprecation_test",
tags = ["no_kcov"], # kcov messes with module ref counts.
deps = [
":common",
":deprecation_example",
],
)
# Note: This target tests autocompletion for the low-level deprecation API.
# See source for an explanation why this is separate from `deprecation_test`.
drake_py_unittest(
name = "deprecation_autocomplete_test",
deps = [
":common",
":deprecation_example",
],
)
# Provides a unittest for high-level deprecation API.
drake_py_unittest(
name = "deprecation_utility_test",
deps = [
":deprecation_example",
"//bindings/pydrake/common/test_utilities:deprecation_py",
],
)
drake_py_unittest(
name = "module_test",
data = ["//examples/acrobot:models"],
num_threads = 2,
deps = [
":common",
],
)
drake_py_unittest(
name = "numpy_compare_test",
deps = [
"//bindings/pydrake/common/test_utilities:numpy_compare_py",
],
)
drake_py_unittest(
name = "pybind11_version_test",
deps = [
":common",
],
)
drake_py_unittest(
name = "schema_test",
deps = [
":common",
],
)
drake_py_unittest(
name = "schema_serialization_test",
deps = [
":common",
],
)
drake_pybind_library(
name = "serialize_test_foo_py",
testonly = True,
add_install = False,
cc_deps = [":serialize_pybind"],
cc_so_name = "test/serialize_test_foo",
cc_srcs = [
"test/serialize_test_foo_py.cc",
"test/serialize_test_foo_py.h",
],
package_info = PACKAGE_INFO,
py_deps = [
":common",
],
)
drake_pybind_library(
name = "serialize_test_bar_py",
testonly = True,
add_install = False,
cc_deps = [":serialize_pybind"],
cc_so_name = "test/serialize_test_bar",
cc_srcs = [
"test/serialize_test_bar_py.cc",
"test/serialize_test_foo_py.h",
],
package_info = PACKAGE_INFO,
py_deps = [
":common",
],
)
drake_py_unittest(
name = "serialize_import_failure_test",
deps = [
":serialize_test_bar_py",
":serialize_test_foo_py",
],
)
drake_pybind_library(
name = "serialize_test_util_py",
testonly = True,
add_install = False,
cc_deps = [
":cpp_template_pybind",
":serialize_pybind",
],
cc_so_name = "test/serialize_test_util",
cc_srcs = ["test/serialize_test_util_py.cc"],
package_info = PACKAGE_INFO,
py_deps = [
":common",
],
)
drake_py_unittest(
name = "serialize_pybind_test",
deps = [
":serialize_test_util_py",
],
)
drake_pybind_cc_googletest(
name = "sorted_pair_pybind_test",
cc_deps = [
":sorted_pair_pybind",
"//bindings/pydrake:test_util_pybind",
],
)
drake_pybind_library(
name = "text_logging_test_helpers_py",
testonly = True,
add_install = False,
cc_so_name = "test/text_logging_test_helpers",
cc_srcs = ["test/text_logging_test_helpers_py.cc"],
package_info = PACKAGE_INFO,
)
drake_py_binary(
name = "text_logging_example",
testonly = True,
srcs = ["test/text_logging_example.py"],
deps = [
":common",
":text_logging_test_helpers_py",
],
)
drake_py_unittest(
name = "text_logging_test",
data = [
":text_logging_example",
],
shard_count = 16,
deps = [
"//bindings/pydrake/common/test_utilities:meta_py",
],
)
drake_py_unittest(
name = "text_logging_gil_test",
tags = [
"cpu:2",
],
deps = [
":common",
":text_logging_test_helpers_py",
],
)
drake_py_unittest(
name = "text_logging_threading_direct_to_stderr_test",
deps = [
":common",
":text_logging_test_helpers_py",
],
)
drake_py_unittest(
name = "text_logging_threading_with_gil_release_test",
deps = [
":common",
":text_logging_test_helpers_py",
],
)
drake_cc_googletest(
name = "type_pack_test",
deps = [
":type_pack",
"//common:nice_type_name",
],
)
drake_pybind_cc_googletest(
name = "type_safe_index_pybind_test",
cc_deps = [
":type_safe_index_pybind",
"//bindings/pydrake:test_util_pybind",
],
py_deps = [
":common",
],
)
drake_pybind_library(
name = "value_test_util_py",
testonly = True,
add_install = False,
cc_deps = [":value_pybind"],
cc_so_name = "test/value_test_util",
cc_srcs = ["test/value_test_util_py.cc"],
package_info = PACKAGE_INFO,
)
drake_py_unittest(
name = "value_test",
deps = [
":common",
":value_test_util_py",
],
)
drake_cc_googletest(
name = "wrap_function_test",
deps = [
":wrap_function",
],
)
drake_pybind_library(
name = "wrap_test_util_py",
testonly = True,
add_install = False,
cc_deps = [":wrap_pybind"],
cc_so_name = "test/wrap_test_util",
cc_srcs = ["test/wrap_test_util_py.cc"],
package_info = PACKAGE_INFO,
)
drake_py_unittest(
name = "wrap_pybind_test",
deps = [
":wrap_test_util_py",
],
)
drake_py_unittest(
name = "yaml_test",
deps = [
":common",
],
)
drake_py_unittest(
name = "yaml_typed_test",
data = [
"//common/yaml:test/yaml_io_test_input_1.yaml",
],
deps = [
":common",
":serialize_test_util_py",
"//bindings/pydrake/common/test_utilities:meta_py",
],
)
add_lint_tests_pydrake()
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/value_pybind.h | #pragma once
/// @file
/// Helpers for defining instantiations of drake::Value<>.
#include <string>
#include <fmt/format.h>
#include "drake/bindings/pydrake/common/cpp_param_pybind.h"
#include "drake/bindings/pydrake/common/cpp_template_pybind.h"
#include "drake/bindings/pydrake/common/wrap_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/drake_throw.h"
#include "drake/common/value.h"
namespace drake {
namespace pydrake {
/// Defines an instantiation of `pydrake.common.value.Value[...]`. This is only
/// meant to bind `Value<T>` (or specializations thereof).
/// @prereq `T` must have already been exposed to `pybind11`.
/// @param scope Parent scope.
/// @tparam T Inner parameter of `Value<T>`.
/// @tparam Class Class to be bound. By default, `Value<T>` is used.
/// @returns Reference to the registered Python type.
template <typename T, typename Class = drake::Value<T>>
py::class_<Class, drake::AbstractValue> AddValueInstantiation(
py::module scope) {
static_assert(!py::detail::is_pyobject<T>::value, "See docs for GetPyParam");
py::module py_common = py::module::import("pydrake.common.value");
py::class_<Class, drake::AbstractValue> py_class(
scope, TemporaryClassName<Class>().c_str());
// Register instantiation.
py::tuple param = GetPyParam<T>();
AddTemplateClass(py_common, "Value", py_class, param);
// Only use copy (clone) construction.
// Ownership with `unique_ptr<T>` has some annoying caveats, and some are
// simplified by always copying.
// See docstring for `set_value` for presently unavoidable caveats.
py_class.def(py::init<const T&>());
// Define emplace constructor.
py::object py_T = param[0];
py_class.def(py::init([py_T](py::args args, py::kwargs kwargs) {
// Use Python constructor for the bound type.
py::object py_v = py_T(*args, **kwargs);
// TODO(eric.cousineau): Use `unique_ptr` for custom types if it's ever a
// performance concern.
// Use `type_caster` so that we are not forced to copy T, which is not
// possible for non-movable types. This can be avoided if we bind a
// `cpp_function` accepting a reference. However, that may cause the Python
// instance to be double-initialized.
py::detail::type_caster<T> caster;
DRAKE_THROW_UNLESS(caster.load(py_v, false));
const T& v = caster; // Use implicit conversion from `type_caster<>`.
return new Class(v);
}));
// If the type is registered via `py::class_`, or is of type `Object`
// (`py::object`), then we can obtain a mutable view into the value.
constexpr bool has_get_mutable_value =
internal::is_generic_pybind_v<T> || std::is_same_v<T, Object>;
if constexpr (has_get_mutable_value) {
py::return_value_policy return_policy = py_rvp::reference_internal;
if (std::is_same_v<T, Object>) {
// N.B. This implies that `Object` will be copied by value; however, it
// is only a shallow copy of the pointer, not a deep copy of the object.
return_policy = py::return_value_policy::copy;
}
std::string set_value_docstring = "Replaces stored value with a new one.";
if (!std::is_copy_constructible_v<T>) {
set_value_docstring += R"""(
@note The value type for this class is non-copyable.
You should ensure that you do not have any dangling references to previous
values returned by `get_value` or `get_mutable_value`, because this memory
will
be destroyed when it is replaced, since it is stored using `unique_ptr<>`.
)""";
}
py_class // BR
.def("get_value", &Class::get_value, return_policy)
.def("get_mutable_value", &Class::get_mutable_value, return_policy)
.def("set_value", &Class::set_value, set_value_docstring.c_str());
} else {
py_class // BR
.def("get_value", &Class::get_value)
.def("get_mutable_value",
[py_T](const Class&) {
throw std::logic_error(
fmt::format("Cannot get mutable value (or reference) for a "
"type-conversion type: {}",
py::str(py_T).cast<std::string>()));
})
.def("set_value", &Class::set_value);
}
return py_class;
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/schema_py.cc | #include <memory>
#include <vector>
#include "pybind11/eval.h"
#include "drake/bindings/pydrake/common/cpp_template_pybind.h"
#include "drake/bindings/pydrake/common/serialize_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/bindings/pydrake/symbolic_types_pybind.h"
#include "drake/common/schema/rotation.h"
#include "drake/common/schema/stochastic.h"
#include "drake/common/schema/transform.h"
namespace drake {
namespace pydrake {
namespace internal {
void DefineModuleSchema(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::schema;
constexpr auto& doc = pydrake_doc.drake.schema;
// Bindings for stochastic.h.
{
using Class = Distribution;
constexpr auto& cls_doc = doc.Distribution;
py::class_<Class>(m, "Distribution", cls_doc.doc)
.def("Sample", &Class::Sample, py::arg("generator"), cls_doc.Sample.doc)
.def("Mean", &Class::Mean, cls_doc.Mean.doc)
.def("ToSymbolic", &Class::ToSymbolic, cls_doc.ToSymbolic.doc);
}
{
using Class = Deterministic;
constexpr auto& cls_doc = doc.Deterministic;
py::class_<Class, Distribution> cls(m, "Deterministic", cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<double>(), py::arg("value"), cls_doc.ctor.doc);
DefAttributesUsingSerialize(&cls, cls_doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = Gaussian;
constexpr auto& cls_doc = doc.Gaussian;
py::class_<Class, Distribution> cls(m, "Gaussian", cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<double, double>(), py::arg("mean"), py::arg("stddev"),
cls_doc.ctor.doc);
DefAttributesUsingSerialize(&cls, cls_doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = Uniform;
constexpr auto& cls_doc = doc.Uniform;
py::class_<Class, Distribution> cls(m, "Uniform", cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<double, double>(), py::arg("min"), py::arg("max"),
cls_doc.ctor.doc);
DefAttributesUsingSerialize(&cls, cls_doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = UniformDiscrete;
constexpr auto& cls_doc = doc.UniformDiscrete;
py::class_<Class, Distribution> cls(m, "UniformDiscrete", cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<std::vector<double>>(), py::arg("values"),
cls_doc.ctor.doc);
DefAttributesUsingSerialize(&cls, cls_doc);
DefCopyAndDeepCopy(&cls);
}
{
m // BR
.def("ToDistribution",
pydrake::overload_cast_explicit<std::unique_ptr<Distribution>,
const DistributionVariant&>(ToDistribution),
py::arg("var"), doc.ToDistribution.doc)
.def("Sample",
pydrake::overload_cast_explicit<double, const DistributionVariant&,
drake::RandomGenerator*>(Sample),
py::arg("var"), py::arg("generator"),
doc.Sample.doc_2args_var_generator)
.def("Mean",
pydrake::overload_cast_explicit<double, const DistributionVariant&>(
Mean),
py::arg("var"), doc.Mean.doc_1args_var)
.def("ToSymbolic",
pydrake::overload_cast_explicit<drake::symbolic::Expression,
const DistributionVariant&>(ToSymbolic),
py::arg("var"), doc.ToSymbolic.doc_1args_var)
.def("IsDeterministic",
pydrake::overload_cast_explicit<bool, const DistributionVariant&>(
IsDeterministic),
py::arg("var"), doc.IsDeterministic.doc_1args_var)
.def("GetDeterministicValue",
pydrake::overload_cast_explicit<double, const DistributionVariant&>(
GetDeterministicValue),
py::arg("var"), doc.GetDeterministicValue.doc_1args_var);
}
{
// We need to bind these to placate some runtime type checks, but we should
// not expose them to users.
py::class_<schema::internal::InvalidVariantSelection<Deterministic>>(
m, "_InvalidVariantSelectionDeterministic");
py::class_<schema::internal::InvalidVariantSelection<Gaussian>>(
m, "_InvalidVariantSelectionGaussian");
py::class_<schema::internal::InvalidVariantSelection<Uniform>>(
m, "_InvalidVariantSelectionUniform");
}
{
using Class = DistributionVector;
constexpr auto& cls_doc = doc.DistributionVector;
py::class_<Class>(m, "DistributionVector", cls_doc.doc)
.def("Sample", &Class::Sample, py::arg("generator"), cls_doc.Sample.doc)
.def("Mean", &Class::Mean, cls_doc.Mean.doc)
.def("ToSymbolic", &Class::ToSymbolic, cls_doc.ToSymbolic.doc);
}
// Here, we bind all supported values of the 'Size' template argument.
auto bind_distribution_vectors = [&]<int Size>(
std::integral_constant<int, Size>) {
// Prepare our python template argument (i.e., the Size).
// For Eigen::Dynamic, we use None (instead of the magical "-1").
py::tuple py_param;
if constexpr (Size == Eigen::Dynamic) {
py_param = py::make_tuple(py::none());
} else {
py_param = py::make_tuple(Size);
}
{
using Class = DeterministicVector<Size>;
constexpr auto& cls_doc = doc.DeterministicVector;
py::class_<Class, DistributionVector> cls(
m, TemporaryClassName<Class>().c_str(), cls_doc.doc);
AddTemplateClass(m, "DeterministicVector", cls, py_param);
if constexpr (Size == Eigen::Dynamic) {
m.attr("DeterministicVectorX") = cls;
}
cls // BR
.def(py::init<>(), cls_doc.ctor.doc)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<const drake::Vector<double, Size>&>(), py::arg("value"),
cls_doc.ctor.doc);
DefAttributesUsingSerialize(&cls, cls_doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = GaussianVector<Size>;
constexpr auto& cls_doc = doc.GaussianVector;
py::class_<Class, DistributionVector> cls(
m, TemporaryClassName<Class>().c_str(), cls_doc.doc);
AddTemplateClass(m, "GaussianVector", cls, py_param);
if constexpr (Size == Eigen::Dynamic) {
m.attr("GaussianVectorX") = cls;
}
cls // BR
.def(py::init<>(), cls_doc.ctor.doc)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<const drake::Vector<double, Size>&,
const drake::VectorX<double>&>(),
py::arg("mean"), py::arg("stddev"), cls_doc.ctor.doc);
DefAttributesUsingSerialize(&cls, cls_doc);
DefCopyAndDeepCopy(&cls);
}
{
using Class = UniformVector<Size>;
constexpr auto& cls_doc = doc.UniformVector;
py::class_<Class, DistributionVector> cls(
m, TemporaryClassName<Class>().c_str(), cls_doc.doc);
AddTemplateClass(m, "UniformVector", cls, py_param);
if constexpr (Size == Eigen::Dynamic) {
m.attr("UniformVectorX") = cls;
}
cls // BR
.def(py::init<>(), cls_doc.ctor.doc)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<const drake::Vector<double, Size>&,
const drake::Vector<double, Size>&>(),
py::arg("min"), py::arg("max"), cls_doc.ctor.doc);
DefAttributesUsingSerialize(&cls, cls_doc);
DefCopyAndDeepCopy(&cls);
}
{
m // BR
.def("ToDistributionVector",
pydrake::overload_cast_explicit<
std::unique_ptr<DistributionVector>,
const DistributionVectorVariant<Size>&>(ToDistributionVector),
py::arg("vec"), doc.ToDistributionVector.doc)
.def("IsDeterministic",
pydrake::overload_cast_explicit<bool,
const DistributionVectorVariant<Size>&>(IsDeterministic),
py::arg("vec"),
doc.IsDeterministic.doc_1args_constDistributionVectorVariant)
.def("GetDeterministicValue",
pydrake::overload_cast_explicit<Eigen::VectorXd,
const DistributionVectorVariant<Size>&>(
GetDeterministicValue),
py::arg("vec"),
doc.GetDeterministicValue
.doc_1args_constDistributionVectorVariant);
}
}; // NOLINT
bind_distribution_vectors(std::integral_constant<int, Eigen::Dynamic>{});
bind_distribution_vectors(std::integral_constant<int, 1>{});
bind_distribution_vectors(std::integral_constant<int, 2>{});
bind_distribution_vectors(std::integral_constant<int, 3>{});
bind_distribution_vectors(std::integral_constant<int, 4>{});
bind_distribution_vectors(std::integral_constant<int, 5>{});
bind_distribution_vectors(std::integral_constant<int, 6>{});
// Bindings for rotation.h.
{
// To bind nested serializable structs without errors, we declare the outer
// struct first, then bind its inner structs, then bind the outer struct.
using Class = Rotation;
constexpr auto& cls_doc = doc.Rotation;
py::class_<Class> cls(m, "Rotation", cls_doc.doc);
// Inner structs.
{
using Inner = Class::Identity;
py::class_<Inner> inner(cls, "Identity", cls_doc.Identity.doc);
inner.def(py::init<const Inner&>(), py::arg("other"));
inner.def(ParamInit<Inner>());
DefAttributesUsingSerialize(&inner, cls_doc.Identity);
DefReprUsingSerialize(&inner);
DefCopyAndDeepCopy(&inner);
}
{
using Inner = Class::Rpy;
py::class_<Inner> inner(cls, "Rpy", cls_doc.Rpy.doc);
inner.def(py::init<const Inner&>(), py::arg("other"));
inner.def(ParamInit<Inner>());
DefAttributesUsingSerialize(&inner, cls_doc.Rpy);
DefReprUsingSerialize(&inner);
DefCopyAndDeepCopy(&inner);
}
{
using Inner = Class::AngleAxis;
py::class_<Inner> inner(cls, "AngleAxis", cls_doc.AngleAxis.doc);
inner.def(py::init<const Inner&>(), py::arg("other"));
inner.def(ParamInit<Inner>());
DefAttributesUsingSerialize(&inner, cls_doc.AngleAxis);
DefReprUsingSerialize(&inner);
DefCopyAndDeepCopy(&inner);
}
{
using Inner = Class::Uniform;
py::class_<Inner> inner(cls, "Uniform", cls_doc.Uniform.doc);
inner.def(py::init<const Inner&>(), py::arg("other"));
inner.def(ParamInit<Inner>());
DefAttributesUsingSerialize(&inner, cls_doc.Uniform);
DefReprUsingSerialize(&inner);
DefCopyAndDeepCopy(&inner);
}
// Now we can finish binding the outermost struct (Rotation).
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<const math::RotationMatrixd&>(), cls_doc.ctor.doc_1args)
.def(py::init<const math::RollPitchYawd&>(), cls_doc.ctor.doc_1args)
.def(ParamInit<Class>())
.def("IsDeterministic", &Class::IsDeterministic,
cls_doc.IsDeterministic.doc)
.def("GetDeterministicValue", &Class::GetDeterministicValue,
cls_doc.GetDeterministicValue.doc)
.def("ToSymbolic", &Class::ToSymbolic, cls_doc.ToSymbolic.doc)
.def("set_rpy_deg", &Class::set_rpy_deg, py::arg("rpy_deg"),
cls_doc.set_rpy_deg.doc);
DefAttributesUsingSerialize(&cls, cls_doc);
DefReprUsingSerialize(&cls);
DefCopyAndDeepCopy(&cls);
// To support the atypical C++ implementation of Transform::Serialize, we
// need to support attribute operations on Rotation that should actually
// apply to the Rotation::value member field instead. We'll achieve that by
// adding special-cases to getattr and setattr.
cls.def("__getattr__", [](const Class& self, py::str name) -> py::object {
if (std::holds_alternative<Rotation::Rpy>(self.value)) {
const std::string name_cxx = name;
if (name_cxx == "deg") {
py::object self_py = py::cast(self, py_rvp::reference);
return self_py.attr("value").attr(name);
}
}
if (std::holds_alternative<Rotation::AngleAxis>(self.value)) {
const std::string name_cxx = name;
if ((name_cxx == "angle_deg") || (name_cxx == "axis")) {
py::object self_py = py::cast(self, py_rvp::reference);
return self_py.attr("value").attr(name);
}
}
return py::eval("object.__getattr__")(self, name);
});
cls.def("__setattr__", [](Class& self, py::str name, py::object value) {
if (std::holds_alternative<Rotation::Rpy>(self.value)) {
const std::string name_cxx = name;
if (name_cxx == "deg") {
py::object self_py = py::cast(self, py_rvp::reference);
self_py.attr("value").attr(name) = value;
return;
}
}
if (std::holds_alternative<Rotation::AngleAxis>(self.value)) {
const std::string name_cxx = name;
if ((name_cxx == "angle_deg") || (name_cxx == "axis")) {
py::object self_py = py::cast(self, py_rvp::reference);
self_py.attr("value").attr(name) = value;
return;
}
}
py::eval("object.__setattr__")(self, name, value);
});
}
// Bindings for transform.h.
{
using Class = Transform;
constexpr auto& cls_doc = doc.Transform;
py::class_<Class> cls(m, "Transform", cls_doc.doc);
cls // BR
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const Class&>(), py::arg("other"))
.def(py::init<const math::RigidTransformd&>(), cls_doc.ctor.doc_1args)
.def(ParamInit<Class>())
.def("set_rotation_rpy_deg", &Class::set_rotation_rpy_deg,
py::arg("rpy_deg"), cls_doc.set_rotation_rpy_deg.doc)
.def("IsDeterministic", &Class::IsDeterministic,
cls_doc.IsDeterministic.doc)
.def("GetDeterministicValue", &Class::GetDeterministicValue,
cls_doc.GetDeterministicValue.doc)
.def("ToSymbolic", &Class::ToSymbolic, cls_doc.ToSymbolic.doc)
.def("Mean", &Class::Mean, cls_doc.Mean.doc)
.def(
"Sample", &Class::Sample, py::arg("generator"), cls_doc.Sample.doc);
DefAttributesUsingSerialize(&cls);
// The Transform::Serialize does something sketchy for the "rotation" field.
// We'll undo that damage for the attribute getter and setter functions, but
// notably we must leave the __fields__ manifest unchanged to match the C++
// serialization convention and the setter needs to accept either a Rotation
// (the actual type of the property) or any of the allowed Rotation::Variant
// types (which will occur during YAML deserialization).
using RotationOrNestedValue = std::variant<Rotation, Rotation::Identity,
Rotation::Rpy, Rotation::AngleAxis, Rotation::Uniform>;
static_assert(
std::variant_size_v<RotationOrNestedValue> ==
1 /* for Rotation */ + std::variant_size_v<Rotation::Variant>);
cls.def_property(
"rotation",
// The getter is just the usual, no special magic.
[](const Class& self) { return &self.rotation; },
// The setter accepts a more generous allowed set of argument types.
[](Class& self, RotationOrNestedValue value_variant) {
std::visit(
[&self]<typename T>(const T& new_value) {
if constexpr (std::is_same_v<T, Rotation>) {
self.rotation = new_value;
} else {
self.rotation.value = new_value;
}
},
value_variant);
},
py_rvp::reference_internal, cls_doc.rotation.doc);
DefReprUsingSerialize(&cls);
DefCopyAndDeepCopy(&cls);
}
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/deprecation_pybind.h | #pragma once
/// @file
/// Provides access to Python deprecation utilities from C++.
/// For example usages, please see `deprecation_example/cc_module_py.cc`.
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "drake/bindings/pydrake/common/wrap_function.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
namespace drake {
namespace pydrake {
// N.B. We cannot use `py::str date = py::none()` because the pybind Python C++
// API converts `None` to a string.
// See: https://github.com/pybind/pybind11/issues/2361
/// Deprecates an attribute `name` of a class `cls`.
/// This *only* works with class attributes (unbound members or methods) as it
/// is implemented with a Python property descriptor.
inline void DeprecateAttribute(py::object cls, py::str name, py::str message,
std::optional<std::string> date = {}) {
py::object deprecated =
py::module::import("pydrake.common.deprecation").attr("deprecated");
py::object original = cls.attr(name);
cls.attr(name) = deprecated(message, py::arg("date") = date)(original);
}
/// Raises a deprecation warning.
///
/// @note If you are deprecating a class's member or method, please use
/// `DeprecateAttribute` so that the warning is issued immediately when
/// accessed, not only when it is called.
inline void WarnDeprecated(
py::str message, std::optional<std::string> date = {}) {
py::object warn_deprecated =
py::module::import("pydrake.common.deprecation").attr("_warn_deprecated");
warn_deprecated(message, py::arg("date") = date);
}
namespace internal {
template <typename Func, typename Return, typename... Args>
auto WrapDeprecatedImpl(py::str message,
function_info<Func, Return, Args...>&& info,
std::enable_if_t<std::is_same_v<Return, void>, void*> = {}) {
return [info = std::move(info), message](Args... args) {
WarnDeprecated(message);
info.func(std::forward<Args>(args)...);
};
}
// N.B. `decltype(auto)` is used in both places to (easily) achieve perfect
// forwarding of the return type.
template <typename Func, typename Return, typename... Args>
decltype(auto) WrapDeprecatedImpl(py::str message,
function_info<Func, Return, Args...>&& info,
std::enable_if_t<!std::is_same_v<Return, void>, void*> = {}) {
return [info = std::move(info), message](Args... args) -> decltype(auto) {
WarnDeprecated(message);
return info.func(std::forward<Args>(args)...);
};
}
} // namespace internal
/// Wraps any callable (function pointer, method pointer, lambda, etc.) to emit
/// a deprecation message.
template <typename Func>
auto WrapDeprecated(py::str message, Func&& func) {
return internal::WrapDeprecatedImpl(
message, internal::infer_function_info(std::forward<Func>(func)));
}
/// Deprecated wrapping of `py::init<>`.
/// @note Only for `unique_ptr` holders. If using `shared_ptr`, talk to Eric.
template <typename Class, typename... Args>
auto py_init_deprecated(py::str message) {
// N.B. For simplicity, require that Class be passed up front, rather than
// trying to figure out how to pipe code into / mock `py::detail::initimpl`
// classes.
return py::init([message](Args... args) {
WarnDeprecated(message);
return std::make_unique<Class>(std::forward<Args>(args)...);
});
}
/// Deprecated wrapping of `py::init(factory)`.
template <typename Func>
auto py_init_deprecated(py::str message, Func&& func) {
return py::init(WrapDeprecated(message, std::forward<Func>(func)));
}
/// The deprecated flavor of ParamInit<>.
template <typename Class>
auto DeprecatedParamInit(py::str message) {
return py::init(WrapDeprecated(message, [](py::kwargs kwargs) {
// N.B. We use `Class` here because `pybind11` strongly requires that we
// return the instance itself, not just `py::object`.
// TODO(eric.cousineau): This may hurt `keep_alive` behavior, as this
// reference may evaporate by the time the true holding pybind11 record is
// constructed. Would be alleviated using old-style pybind11 init :(
Class obj{};
py::object py_obj = py::cast(&obj, py_rvp::reference);
py::module::import("pydrake").attr("_setattr_kwargs")(py_obj, kwargs);
return obj;
}));
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/_common_extra.py | import collections
import functools
import inspect
import logging as _logging
import sys
import typing
import numpy as np
_root_logger = _logging.getLogger()
_drake_logger = _logging.getLogger("drake")
def _python_level_to_spdlog(level: int):
"""Returns the spdlog string level that enables C++ logging at the given
Python logging level, for use with pydrake.common._set_log_level.
"""
if level >= _logging.CRITICAL:
return "critical"
if level >= _logging.ERROR:
return "err"
if level >= _logging.WARNING:
return "warn"
if level >= _logging.INFO:
return "info"
if level >= _logging.DEBUG:
return "debug"
return "trace"
def _sync_spdlog_level():
"""Updates Drake's C++ spdlog level threshold to match the effective level
of Drake's Python logger. This will either be the Drake Logger's level or
else the root Logger's level in case Drake Logger's level is NOTSET.
This only syncs the "effective" level, not the "enabled for" level. The
"enabled for" level would also incorporate the global "logging.disable"
setting, but we do not reflect that back into C++ spdlog at the moment.
"""
if not _drake_logger._tied_to_spdlog:
return
level = _drake_logger.level or _root_logger.level
_set_log_level(_python_level_to_spdlog(level))
def _monkey_patch_logger_level_events():
"""Adds a hook into Drake's Python Logger object such that changes to
Python logging levels are reflected back into Drake's C++ spdlog level.
"""
# To notice log level changes (whether to the root logger or our logger) we
# intercept calls to our logger's cache-clearing function. Specifically,
# when a user calls `Logger.setLevel(...)`, the logger tells the manager
# singleton to clear its cache ...
#
# https://github.com/python/cpython/blob/c2b57974/Lib/logging/__init__.py#L1457-L1462
#
# ... which asks each Logger in turn to clear its cache.
#
# https://github.com/python/cpython/blob/c2b57974/Lib/logging/__init__.py#L1412-L1423
#
# That notification is triggered for any logger level change, including
# both the root logger and Drake's own logger. Therefore, syncing the C++
# level based on cache-clearing events is sufficient to cover all cases.
#
# This relies on the implementation details of CPython's logging module,
# so we might need to adapt this technique to track CPython changes. Our
# CI testing will inform us in case this technique ever stops working.
class spdlog_syncing_dict(dict):
def clear(self):
super().clear()
_sync_spdlog_level()
_drake_logger._cache = spdlog_syncing_dict()
# Reflect the Python level to C++ level iff the Python sink is fed by spdlog.
if getattr(_drake_logger, "_tied_to_spdlog", False):
_monkey_patch_logger_level_events()
def configure_logging():
"""Convenience function that configures the root Python logging module in
a tasteful way for Drake. Using this function is totally optional; there
is no requirement to call it prior to using Drake or generating messages.
We offer it as a convenience only because Python's logging defaults are
more spartan than Drake's C++ logging format (e.g., Python does not show
message timestamps by default).
Note:
pydrake logs using Python's built-in ``logging`` module. To access
pydrake's ``logging.Logger``, use ``logging.getLogger("drake")``.
You can configure log settings using that object whether or not you
have called ``configure_logging()`` first.
See also:
https://docs.python.org/3/library/logging.html
"""
format = "[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s"
_logging.basicConfig(level=_logging.INFO, format=format)
_drake_logger.setLevel(_logging.NOTSET)
_logging.addLevelName(5, "TRACE")
def use_native_cpp_logging():
"""By default, pydrake's C++ code routes all of its log messages to
Python's ``logging`` module; this function opts-out of that feature.
After this function has been called, pydrake's C++ code will log directly
to stderr, with no interaction with Python. (The Python settings for log
level threshold and message formatting will no longer affect the C++ log
messages.)
This can be useful to avoid C++ logging touching the GIL, e.g., when using
Python's ``threading`` module.
This function is not thread-safe. No other threads should be running when
it is called.
See also the `environment variable
<https://drake.mit.edu/doxygen_cxx/group__environment__variables.html>`_
``DRAKE_PYTHON_LOGGING``, which can also be used to opt-out.
Raises:
RuntimeError: If the reconfiguration is not possible, e.g., if you have
already manually adjusted the C++ logging configuration.
"""
_use_native_cpp_logging()
_drake_logger._tied_to_spdlog = False
def _wrap_to_match_input_shape(f):
# See docstring for `WrapToMatchInputShape` in `eigen_pybind.h` for more
# details.
# N.B. We cannot use `inspect.Signature` due to the fact that pybind11's
# instance method is not inspectable for overloads.
assert callable(f), f
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
# Call the function first to permit it to raise the appropriate
# TypeError from pybind11 if the inputs are not correctly formatted.
out = f(self, *args, **kwargs)
if isinstance(out, np.ndarray):
arg_list = tuple(args) + tuple(kwargs.values())
assert len(arg_list) == 1
(arg,) = arg_list
in_shape = np.asarray(arg).shape
return out.reshape(in_shape)
else:
return out
return wrapper
class _MangledName:
"""Provides recipes for mangling and demangling names for templated code.
For example, the template instantiation expression LeafSystem_[AutoDiffXd]
refers to Python class named LeafSystem_𝓣AutoDiffXd𝓤. We refer to the
former as the "pretty" name and the latter as the "mangled" name.
We need to use name mangling because Python class and function names must
be valid identifiers (i.e., alphanumeric characters, with underscores).
The pretty name LeafSystem_[AutoDiffXd] is a valid *expression* but it is
not a valid *identifier*. In cases where an expression is allowed, we'll
prefer to use the pretty name, but in cases where we must use an identifier
(e.g., when declaring a class), we must use the mangled name.
To make code transformations easier, we'll create a bijection between
pretty names and mangled names. Any disallowed character that might appear
in a pretty name is mapped to an arcane unicode character in the mangled
name. (Refer to the constants below for details.)
See pretty_class_name() below for a demangling function to help display
"pretty" class names to the user.
"""
# This is the mangled substitution for "[" in a pretty name.
# This letter is 'U+1D4E3 MATHEMATICAL BOLD SCRIPT CAPITAL T'.
UNICODE_LEFT_BRACKET = "𝓣"
# This is the mangled substitution for "]" in a pretty name.
# This letter is 'U+1D4E4 MATHEMATICAL BOLD SCRIPT CAPITAL U'.
UNICODE_RIGHT_BRACKET = "𝓤"
# This is the mangled substitution for "," in a pretty name.
# This letter is 'U+1D4EC MATHEMATICAL BOLD SCRIPT SMALL C'.
UNICODE_COMMA = "𝓬"
# This is the mangled substitution for "." in a pretty name.
# This letter is 'U+1D4F9 MATHEMATICAL BOLD SCRIPT SMALL P'.
UNICODE_PERIOD = "𝓹"
@staticmethod
def mangle(name: str) -> str:
"""Given a pretty name (or partially-mangled name), returns the
corresponding fully-mangled name.
For example, ``LeafSystem_[AutoDiffXd]`` as input becomes
``LeafSystem_𝓣AutoDiffXd𝓤`` as the return value.
Names that do not need mangling (i.e., are already valid identifiers)
are returned unchanged.
If part of the name is already partially-mangled, it will remain so.
For example, ``Image[PixelType𝓹kRgba8U]`` as input becomes
``Image𝓣PixelType𝓹kRgba8U𝓤`` as the return value. This implies
that `demangle(mangle(name)) == name` does not always hold true.
"""
name = name.replace("[", _MangledName.UNICODE_LEFT_BRACKET)
name = name.replace("]", _MangledName.UNICODE_RIGHT_BRACKET)
name = name.replace(",", _MangledName.UNICODE_COMMA)
name = name.replace(".", _MangledName.UNICODE_PERIOD)
# Sanity check that all of the characters are alpha-numeric (and
# N.B. ignoring the rule that identifiers cannot start with numbers).
assert ("_" + name).isidentifier(), name
return name
@staticmethod
def demangle(name: str) -> str:
"""Given a mangled name, returns the pretty name.
"""
name = name.replace(_MangledName.UNICODE_LEFT_BRACKET, "[")
name = name.replace(_MangledName.UNICODE_RIGHT_BRACKET, "]")
name = name.replace(_MangledName.UNICODE_COMMA, ",")
name = name.replace(_MangledName.UNICODE_PERIOD, ".")
return name
@staticmethod
def module_getattr(*, module_name: str,
module_globals: typing.Mapping[str, typing.Any],
name: str) -> typing.Any:
"""Looks up a name in a module's globals(), accounting for mangling.
If the name is a pretty name, it's first converted to a mangled name.
Then, the name is looked up in the module_globals.
Unknown names are reported by raising an AttributeError.
This function is intended to help implement __getattr__ on a module
for backwards-compatibility with template unpickling vs prior versions
of Drake.
To make a module backwards-compatible with pickle loading, we place
the following code into each module that contains any pre-v1.12.0
pickled template classes.
def __getattr__(name):
return _MangledName.module_getattr(
module_name=__name__, module_globals=globals(), name=name)
Note that users cannot ``import`` names with, e.g., square brackets
anyway. The renaming only comes into play for calls to ``getattr``,
e.g., by the ``pickle`` module.
"""
name = _MangledName.mangle(name)
if name in module_globals:
return module_globals[name]
float_tag = "_{}float{}".format(
_MangledName.UNICODE_LEFT_BRACKET,
_MangledName.UNICODE_RIGHT_BRACKET)
if name.endswith(float_tag):
shorter_name = name[:-len(float_tag)]
if shorter_name in module_globals:
return module_globals[shorter_name]
raise AttributeError(
f"module {module_name!r} has no attribute {name!r}")
def pretty_class_name(cls: type, *, use_qualname: bool = False) -> str:
"""Given a class, returns its ``cls.__name__`` respelled to be suitable for
display to a user, in particular by respelling C++ template arguments using
their conventional ``FooBar_[AutoDiffXd]`` expression spelling instead of
the mangled unicode name. Note that the returned name might not be a valid
Python identifier, though it should still be a valid Python expression.
If the class is not a template, simply returns ``cls.__name__`` unchanged.
When ``use_qualname`` is true, uses ``cls.__qualname__`` instead of
``cls.__name__``.
"""
if use_qualname:
name = cls.__qualname__
else:
name = cls.__name__
return _MangledName.demangle(name)
# We must be able to do `from pydrake.symbolic import _symbolic_sympy` so we
# need `pydrake.symbolic` to be a Python package, not merely a module. (See
# https://docs.python.org/3/tutorial/modules.html for details.) The way to
# designate something as a package is to define its `__path__` attribute.
__path__ = [sys.modules["pydrake"].__path__[0] + "/common"]
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/submodules_py.h | #pragma once
/* This file declares the functions that populate the sub-modules of
`pydrake.common`. */
#include "drake/bindings/pydrake/pydrake_pybind.h"
namespace drake {
namespace pydrake {
namespace internal {
// For simplicity, these declarations are listed in alphabetical order.
/* Defines `pydrake.common.eigen_geometry` bindings per eigen_geometry_py.cc. */
void DefineModuleEigenGeometry(py::module m);
/* Defines `pydrake.common.schema` bindings per schema_py.cc. */
void DefineModuleSchema(py::module m);
/* Defines `pydrake.common.value` bindings per value_py.cc. */
void DefineModuleValue(py::module m);
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/type_safe_index_pybind.h | #pragma once
#include <string>
#include "drake/bindings/pydrake/common/value_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/type_safe_index.h"
namespace drake {
namespace pydrake {
/// Binds a TypeSafeIndex instantiation along with its Value[Class]
/// type-erasure wrapper.
template <typename Class>
auto BindTypeSafeIndex(
py::module m, const std::string& name, const std::string& class_doc = "") {
py::class_<Class> cls(m, name.c_str(), class_doc.c_str());
cls // BR
.def(py::init<>(), pydrake_doc.drake.TypeSafeIndex.ctor.doc_0args)
.def(
py::init<int>(), pydrake_doc.drake.TypeSafeIndex.ctor.doc_1args_index)
.def("__int__", &Class::operator int)
.def("__index__", &Class::operator int)
.def(py::self == py::self)
.def(py::self == int{})
.def(py::self < py::self)
.def(py::hash(py::self))
// TODO(eric.cousineau): Add more operators.
.def("is_valid", &Class::is_valid,
pydrake_doc.drake.TypeSafeIndex.is_valid.doc)
.def("__repr__", [name](const Class& self) {
return py::str("{}({})").format(name, static_cast<int>(self));
});
AddValueInstantiation<Class>(m);
return cls;
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/sorted_pair_pybind.h | #pragma once
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/sorted_pair.h"
namespace pybind11 {
namespace detail {
// Casts `SortedPair<T>` as `Tuple[T]` comprised of `(first, second)`.
template <typename T>
struct type_caster<drake::SortedPair<T>> {
using Type = drake::SortedPair<T>;
using InnerCaster = make_caster<T>;
// N.B. This macro assumes placement in `pybind11::detail`.
PYBIND11_TYPE_CASTER(Type, _("Tuple[") + type_caster<T>::name + _("]"));
bool load(handle src, bool convert) {
if (!convert && !tuple::check_(src)) {
return false;
}
tuple t = reinterpret_borrow<tuple>(src);
if (t.size() != 2) return false;
InnerCaster first, second;
if (!first.load(t[0], convert) || !second.load(t[1], convert)) {
return false;
}
value = Type(static_cast<T>(first), static_cast<T>(second));
return true;
}
static handle cast(Type src, return_value_policy policy, handle parent) {
object out = make_tuple(InnerCaster::cast(src.first(), policy, parent),
InnerCaster::cast(src.second(), policy, parent));
return out.release();
}
};
} // namespace detail
} // namespace pybind11
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/type_pack.h | #pragma once
/// @file
/// Basic meta-programming utilities for types, focused on template parameter
/// packs.
#include <cstddef>
#include <type_traits>
#include <typeindex>
#include <typeinfo>
#include <utility>
namespace drake {
template <typename... Ts>
struct type_pack;
namespace internal {
// Provides type at given index.
template <size_t N, size_t K, typename T, typename... Ts>
struct type_at_impl {
using type = typename type_at_impl<N, K + 1, Ts...>::type;
};
// Base case.
template <size_t N, typename T, typename... Ts>
struct type_at_impl<N, N, T, Ts...> {
using type = T;
};
// Visits a type given a VisitWith mechanism, templated to permit
// conditional execution.
template <typename VisitWith, typename Visitor>
struct type_visit_impl {
template <typename T, bool execute>
struct runner {
inline static void run(Visitor&& visitor) {
VisitWith::template run<T>(std::forward<Visitor>(visitor));
}
};
template <typename T>
struct runner<T, false> {
inline static void run(Visitor&&) {}
};
};
// Catches non-template types explicitly.
template <typename T>
struct type_pack_extract_impl {
// Defer to show that this is a bad instantiation.
static_assert(!std::is_same_v<T, T>, "Wrong template");
};
template <template <typename... Ts> class Tpl, typename... Ts>
struct type_pack_extract_impl<Tpl<Ts...>> {
using type = type_pack<Ts...>;
};
// Provides type for pack expansion into an initializer list for
// deterministic execution order.
using DummyList = bool[];
template <typename T>
struct assert_default_constructible {
static_assert(
std::is_default_constructible_v<T>, "Must be default constructible");
};
} // namespace internal
/// Extracts the Ith type from a sequence of types.
template <size_t I, typename... Ts>
struct type_at {
static_assert(I >= 0 && I < sizeof...(Ts), "Invalid type index");
using type = typename internal::type_at_impl<I, 0, Ts...>::type;
};
/// Provides a tag to pass a type for ease of inference.
template <typename T>
struct type_tag {
using type = T;
};
/// Provides a tag for single-parameter templates.
/// @note Single-parameter is specialized because `using` aliases are picky
/// about how template parameters are passed.
/// @see https://stackoverflow.com/a/33131008/7829525
/// @note The above issues can be worked around if either (a) inheritance
/// rather than aliasing is used, or (b) the alias uses the *exact* matching
/// form of expansion.
template <template <typename> class Tpl>
struct template_single_tag {
template <typename T>
using type = Tpl<T>;
};
/// Provides a tag to pass a parameter packs for ease of inference.
template <typename... Ts>
struct type_pack {
/// Number of template parameters.
static constexpr int size = sizeof...(Ts);
/// Rebinds parameter pack to a given template.
template <template <typename...> class Tpl>
using bind = Tpl<Ts...>;
/// Extracts the Ith type from this sequence.
template <size_t I>
using type_at = typename drake::type_at<I, Ts...>::type;
};
/// Returns an expression (only to be used in `decltype`) for inferring
/// and binding a parameter pack to a template.
template <template <typename...> class Tpl, typename... Ts>
Tpl<Ts...> type_bind(type_pack<Ts...>);
/// Extracts the inner template arguments (typename only) for a typename which
/// is a template instantiation.
template <typename T>
using type_pack_extract = typename internal::type_pack_extract_impl<T>::type;
/// Visit a type by constructing its default value.
/// Useful for iterating over `type_tag`, `type_pack`, `std::integral_constant`,
/// etc.
struct type_visit_with_default {
template <typename T, typename Visitor>
inline static void run(Visitor&& visitor) {
// TODO(eric.cousineau): Figure out how to make this the only error, without
// wasting more function calls.
(void)internal::assert_default_constructible<T>{};
visitor(T{});
}
};
/// Visits a type by construct a template tag's default value.
template <template <typename> class Tag = type_tag>
struct type_visit_with_tag {
template <typename T, typename Visitor>
inline static void run(Visitor&& visitor) {
visitor(Tag<T>{});
}
};
/// Provides a check which will return true for any type.
template <typename T>
using type_check_always_true = std::true_type;
/// Provides a check which returns whether `T` is different than `U`.
template <typename T>
struct type_check_different_from {
template <typename U>
using type = std::negation<std::is_same<T, U>>;
};
/// Visits each type in a type pack. This effectively implements a
// `constexpr for` loops. See `type_pack_test.cc` for usages.
/// @tparam VisitWith
/// Visit helper. @see `type_visit_with_default`, `type_visit_with_tag`.
/// @tparam Predicate Predicate operating on the type dictated by `VisitWith`.
/// @param visitor Lambda or functor for visiting a type.
template <class VisitWith = type_visit_with_default,
template <typename> class Predicate = type_check_always_true,
typename Visitor = void, typename... Ts>
void type_visit(Visitor&& visitor, type_pack<Ts...> = {},
template_single_tag<Predicate> = {}) {
// clang-format off
(void)internal::DummyList{(
internal::type_visit_impl<VisitWith, Visitor>::
template runner<Ts, Predicate<Ts>::value>::
run(std::forward<Visitor>(visitor)),
true)...};
// clang-format on
}
/// Provides short-hand for hashing a type.
template <typename T>
constexpr size_t type_hash() {
return std::type_index(typeid(T)).hash_code();
}
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/_eigen_geometry_extra.py | from pydrake.common import _MangledName
def __getattr__(name):
"""Rewrites requests for Foo[bar] into their mangled form, for backwards
compatibility with unpickling.
"""
return _MangledName.module_getattr(
module_name=__name__, module_globals=globals(), name=name)
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/cpp_template.py | """Provides containers for tracking instantiations of C++ templates. """
import inspect
import sys
import types
from pydrake import _is_building_documentation
from pydrake.common import _MangledName, pretty_class_name
from pydrake.common.cpp_param import get_param_names, get_param_canonical
from pydrake.common.deprecation import _warn_deprecated
def _get_module_from_stack(frame=2):
# Infers module name from call stack.
return inspect.getmodule(inspect.stack()[frame][0])
def _is_pybind11_type_error(e):
return ("incompatible function arguments" in str(e)
or "incompatible constructor arguments" in str(e))
def get_or_init(scope, name, template_cls, *args, **kwargs):
"""Gets an existing template from a scope if it exists; otherwise, it will
be created and registered.
If `scope` does not have the attribute `name`, then it will be created as
`template_cls(name, *args, **kwargs)`.
(`module_name=...` is also set, but should not be important).
Args:
scope: Scope that contains the template object (this may not
necessarily be the scope of the instantiation).
name: Name of the template object.
template_cls: Class (either `TemplateBase` or a derivative).
args, kwargs: Passed to the template class's constructor.
Returns:
The existing (or newly created) template object.
"""
template = getattr(scope, name, None)
if template is None:
template = template_cls(name, *args, scope=scope, **kwargs)
setattr(scope, name, template)
return template
class _Deprecation:
# Denotes a (message, date) tuple.
def __init__(self, *, message, date):
self.message = message
self.date = date
class TemplateBase:
"""Provides a mechanism to map parameters (types or literals) to
instantiations, following C++ mechanics.
"""
def __init__(self, name, allow_default=True, scope=None):
"""
Args:
name: Name of the template object.
allow_default: Allow a default value (None) to resolve to the
parameters of the instantiation that was first added.
scope: Parent scope for the template object.
"""
self.name = name
self.param_list = []
self._allow_default = allow_default
self._instantiation_map = {}
self._instantiation_alias_map = {}
if scope is None:
scope = _get_module_from_stack()
self._scope = scope
self._instantiation_func = None
self._deprecation_map = {}
self.__doc__ = ""
def __getitem__(self, *param):
"""Gets concrete class associate with the given arguments.
Can be one of the following forms:
template[param0]
template[param0, param1, ...]
template[(param0, param1, ...)]
template[[param0, param1, ...]]
template[None] (first instantiation, if `allow_default` is True)
"""
# For compatibility with Python3.
if len(param) == 1:
param = param[0]
return self.get_instantiation(param)[0]
def __call__(self, *args, **kwargs):
"""Permits pseudo argument deduction for a template. This is intended
for use with pybind11, where any invalid argument raises a TypeError.
This must have arguments passed to it.
Note:
While pybind11 has two passes for checking overloads (once
without and once with conversions), this only passes through the
instantiations once with conversions; therefore, be careful in how
arguments are assigned.
"""
if len(args) == 0 and len(kwargs) == 0:
raise TypeError(
("{}: incompatible function arguments for template: Cannot "
"call without arguments").format(self.name))
result = self._call_internal(*args, **kwargs)
if result is not None:
return result
raise TypeError(
("{}: incompatible function arguments for template: No "
"compatible instantiations").format(self.name))
def _call_internal(self, *args, **kwargs):
"""The implementation of __call__, to allow easy overriding."""
for param in self.param_list:
instantiation = self._instantiation_map[param]
try:
return instantiation(*args, **kwargs)
except TypeError as e:
if not _is_pybind11_type_error(e):
raise e
def get_module_name(self):
"""
Returns module name for this object's parent scope.
Example:
::
>>> pydrake.common.value.Value.get_module_name()
pydrake.common.value
"""
if isinstance(self._scope, types.ModuleType):
return self._scope.__name__
else:
raise RuntimeError(
f"Unable to resolve `get_module_name` for a scope that is not "
f"a module: {self._scope}"
)
# Unique token to signify that this instantiation is deferred when using
# `add_instantiations` or `define`. The instantiation function will not be
# called until the specific instantiation is requested. To illustrate, the
# following example defines a template via `@define`, and refers to
# itself:
#
# @TemplateClass.define("MyTemplate", ((int,), (float,)))
# def MyTemplate(param):
# print(MyTemplate)
# # ... Make and return a class.
#
# If the instantiation were not deferred and the inner function was called
# before the decorator returned, an error would be raised since
# `MyTemplate` is not yet defined. However, since it is deferred, this
# should print out that `MyTemplate` is `<TemplateClass ...MyTemplate>`,
# would only be called when the user requests something such as
# `MyTemplate[float]`.
class _Deferred:
pass
_deferred = _Deferred()
def get_instantiation(self, param=None, throw_error=True):
"""Gets the instantiation for the given parameters.
Args:
param: Can be None, a single parameter, or a tuple/list of
parameters.
Returns:
(instantiation, param), where `param` is the resolved set of
parameters.
"""
param = self._param_resolve(param)
instantiation = self._instantiation_map.get(param)
if instantiation is TemplateBase._deferred:
assert self._instantiation_func is not None
instantiation = self._instantiation_func(param)
self._add_instantiation_internal(param, instantiation,
skip_rename=False)
elif instantiation is None and throw_error:
raise RuntimeError("Invalid instantiation: {}".format(
self._instantiation_name(param)))
deprecation = self._deprecation_map.get(param)
if deprecation is not None:
_warn_deprecated(deprecation.message, date=deprecation.date)
return (instantiation, param)
def add_instantiation(self, param, instantiation, skip_rename=False):
"""Adds a unique instantiation.
Note:
`param` must not have already been added.
"""
# Ensure that we do not already have this tuple.
param = get_param_canonical(self._param_resolve(param))
if param in self._instantiation_map:
raise RuntimeError(
"Parameter instantiation already registered: {}".format(param))
# Register it.
self.param_list.append(param)
self._add_instantiation_internal(param, instantiation, skip_rename)
return param
def _add_instantiation_internal(self, param, instantiation, skip_rename):
# Adds instantiation. Permits overwriting for deferred cases.
assert instantiation is not None
if instantiation is not TemplateBase._deferred:
old = instantiation
instantiation = self._on_add(param, instantiation, skip_rename)
assert instantiation is not None, (self, param, old)
if instantiation is not old:
self._instantiation_alias_map[old] = instantiation
self._instantiation_map[param] = instantiation
def add_instantiations(self, instantiation_func, param_list):
"""Adds a set of instantiations given a function and a list of
parameter sets.
Note:
This method can only be called once.
Args:
instantiation_func: Function of the form `f(template, param)`,
where `template` is the current template and `param` is the
parameter set for the current instantiation.
param_list: Ordered container of parameter sets that these
instantiations should be produced for.
"""
assert instantiation_func is not None
if self._instantiation_func is not None:
raise RuntimeError(
"`add_instantiations` cannot be called multiple times.")
self._instantiation_func = instantiation_func
for param in param_list:
self.add_instantiation(param, TemplateBase._deferred)
def deprecate_instantiation(self, param, message, *, date=None):
"""Deprecates an instantiation for the given set of parameters.
Note:
This method can only be called once for a given instantiation.
Args:
param: Parameters for an instantiation that is already registered.
message: Message to be shown when issuing a deprecation warning.
date: (Optional) String of the form "YYYY-MM-DD".
If supplied, will reformat the message to add the date as is
done with DRAKE_DEPRECATED and its processing in mkdoc.py. This
must be present if ``message`` does not contain the date
itself.
Returns:
(instantiation, param), where ``param`` is the resolved parameters.
"""
param = get_param_canonical(self._param_resolve(param))
if param in self._deprecation_map:
raise RuntimeError(
f"Deprecation already registered: "
f"{self._instantiation_name(param)}")
instantiation, param = self.get_instantiation(param)
self._deprecation_map[param] = _Deprecation(message=message, date=date)
return (instantiation, param)
def get_param_set(self, instantiation):
"""Returns all parameters for a given `instantiation`.
Returns:
A set of instantiations.
"""
param_list = []
for param, check in self._instantiation_map.items():
if check == instantiation:
param_list.append(param)
return set(param_list)
def is_instantiation(self, obj):
"""Determines if an object is an instantion of the given template."""
# Use `get_instantiation` so that we can handled deferred cases.
for param in self.param_list:
instantiation, _ = self.get_instantiation(param)
obj = self._instantiation_alias_map.get(obj, obj)
if instantiation is obj:
return True
return False
def _param_resolve(self, param):
# Resolves to canonical parameters, including default case.
if param is None:
assert self._allow_default
assert len(self.param_list) > 0
param = self.param_list[0]
elif not isinstance(param, tuple):
if not isinstance(param, list):
# Assume scalar.
param = (param,)
else:
param = tuple(param)
return get_param_canonical(param)
def _instantiation_name(self, param, *, mangle=False):
"""When mangle=False (the common case), returns the human-readable
display name for an instantiation of the given ``param``s. This is
typically a Python expression like ``LeafSystem_[AutoDiffXd]``.
When mangle=True, returns the mangled name for an instantition, i.e.,
a valid Python identifier that will be used as __name__ of the class.
"""
if _is_building_documentation():
# When we're building the website, the API docs should always use
# the unmangled names. TODO(jwnimmer-tri) Ideally, we should have
# our Sphinx extension demangle the names (so that we can remove
# this giant hack), but at the moment this is the safest practical
# way to ensure our website API reference displays correctly.
mangle = False
names = get_param_names(self._param_resolve(param), mangle=mangle)
result = '{}[{}]'.format(self.name, ','.join(names))
if mangle:
result = _MangledName.mangle(result)
return result
def _full_name(self):
return "{}.{}".format(self._scope.__name__, self.name)
def __str__(self):
cls_name = pretty_class_name(type(self))
return "<{} {}>".format(cls_name, self._full_name())
def _on_add(self, param, instantiation, skip_rename):
# To be overridden by child classes.
return instantiation
@classmethod
def define(cls, name, param_list, *args, scope=None, **kwargs):
"""Provides a decorator for functions that defines a template using
`name`. The template instantiations are added using
`add_instantiations`, where the instantiation function is the decorated
function.
Args:
name: Name of the template. This should generally match the name
of the object being decorated for clarity.
param_list: Ordered container of parameter sets. For more
information, see `add_instantiations`.
Note:
The name of the inner class will not matter as it will be
overwritten with the template instantiation name. In the below
example, `Impl` will be renamed to `MyTemplate[int]` when
`param=(int,)`.
Example:
::
@TemplateClass.define("MyTemplate",
param_list=[(int,), (float,)])
def MyTemplate(param):
T, = param
class Impl:
def __init__(self):
self.T = T
return Impl
"""
if scope is None:
scope = _get_module_from_stack()
template = cls(name, *args, scope=scope, **kwargs)
def decorator(instantiation_func):
template.add_instantiations(instantiation_func, param_list)
return template
return decorator
class TemplateClass(TemplateBase):
"""Extension of `TemplateBase` for classes."""
def __init__(self, name, *, scope=None, **kwargs):
if scope is None:
scope = _get_module_from_stack()
TemplateBase.__init__(self, name, scope=scope, **kwargs)
def _on_add(self, param, cls, skip_rename):
# Unless this class was a default template instantiation, we need to
# rename it now to describe its template arguments. (Most templated
# C++ classes are bound using the TemporaryClassName() function.)
if not skip_rename:
cls._original_name = cls.__name__
cls._original_qualname = getattr(cls, "__qualname__", cls.__name__)
cls.__name__ = self._instantiation_name(param, mangle=True)
# Define `__qualname__` in Python2 because that's what `pybind11`
# uses when showing function signatures when an overload cannot be
# found.
# TODO(eric.cousineau): When porting to Python3 / six, try to
# ensure this handles nesting.
cls.__qualname__ = cls.__name__
cls.__module__ = self._scope.__name__
# Ensure instantiation is available for pickling... magically...
setattr(self._scope, cls.__name__, cls)
return cls
def is_subclass_of_instantiation(self, obj):
"""Determines if `obj` is a subclass of one of the instantiations.
Returns:
The first instantiation of which `obj` is a subclass.
"""
for param in self.param_list:
instantiation, _ = self.get_instantiation(param)
if issubclass(obj, instantiation):
return instantiation
return None
def _rename_callable(f, scope, name, cls=None):
if isinstance(scope, type):
module = scope.__module__
else:
module = scope.__name__
# Renames a function.
if (f.__module__, f.__name__) == (module, name):
# Short circuit.
return f
if cls is not None:
qualname = cls.__qualname__ + "." + name
else:
qualname = name
# If Python2, we have to wrap instancemethods + built-in functions to spoof
# the metadata.
type_requires_wrap = (
types.MethodType, types.BuiltinMethodType, types.BuiltinFunctionType,)
if isinstance(f, type_requires_wrap):
orig = f
def f(*args, **kwargs): return orig(*args, **kwargs)
f.__module__ = module
f.__name__ = name
f.__qualname__ = qualname
f.__doc__ = orig.__doc__
else:
f.__module__ = module
f.__name__ = name
f.__qualname__ = qualname
return f
class TemplateFunction(TemplateBase):
"""Extension of `TemplateBase` for functions."""
def _on_add(self, param, func, skip_rename):
assert skip_rename is False
new_name = self._instantiation_name(param, mangle=True)
func = _rename_callable(func, self._scope, new_name)
setattr(self._scope, func.__name__, func)
return func
class TemplateMethod(TemplateBase):
"""Extension of `TemplateBase` for class methods."""
def __init__(self, name, cls, scope=None, **kwargs):
if scope is None:
scope = _get_module_from_stack()
TemplateBase.__init__(self, name, scope=scope, **kwargs)
# TODO(eric.cousineau): Merge `cls` into `scope` once we are Python 3
# only.
self._cls = cls
def _on_add(self, param, func, skip_rename):
assert skip_rename is False
new_name = self._instantiation_name(param, mangle=True)
func = _rename_callable(func, self._scope, new_name, self._cls)
setattr(self._cls, func.__name__, func)
return func
def __get__(self, obj, objtype):
"""Provides descriptor accessor."""
if obj is None:
return self
else:
return TemplateMethod._Bound(self, obj)
def __set__(self, obj, value):
raise RuntimeError("Read-only property")
def __str__(self):
return '<unbound TemplateMethod {}>'.format(self._full_name())
def _full_name(self):
return '{}.{}'.format(self._cls.__name__, self.name)
class _Bound:
def __init__(self, template, obj):
self._tpl = template
self._obj = obj
def __getitem__(self, param):
unbound = self._tpl[param]
bound = types.MethodType(unbound, self._obj)
return bound
def __str__(self):
return '<bound TemplateMethod {} of {}>'.format(
self._tpl._full_name(), self._obj)
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/module_cycle.md |
The lowest-level modules in pydrake have a dependency cycle: classes (or
functions) from one module refer to classes (or functions) from other modules
such that there is no ordering of module loading that ensures the referenced
module is loaded before the module that uses needs its classes (or functions).
The following modules are part of the dependency cycle:
- pydrake.autodiffutils
- pydrake.common
- pydrake.common.cpp_template
- pydrake.common.deprecation
- pydrake.common.eigen_geometry
- pydrake.common.schema
- pydrake.common.value
- pydrake.math
- pydrake.symbolic
(There are probably more submodules in python.common that are part of the cycle;
the list is not necessarily complete.)
Therefore, we must merge all of those *logical* modules into a single *physical*
module (one shared library) so the library setup code can incrementally define
symbols one at a time (bouncing between modules) in an order that satisfies all
requirements. That module is `pydrake.common`.
When the user does an `import pydrake`, that `__init__.py` file does `import
pydrake.common` and in that C++ code (our `module_py.cc` code), all of the
necessary modules (pydrake.math, etc) are defined and initialized.
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/deprecation.py | """Provides deprecation warnings and utilities for triggering warnings.
By default, this sets all `DrakeDeprecationWarnings` to be shown `"once"`,
which overrides any `-W` command-line arguments. To change this behavior, you
can do something like:
>>> import warnings
>>> from pydrake.common.deprecation import DrakeDeprecationWarning
>>> warnings.simplefilter("always", DrakeDeprecationWarning)
If you would like to disable all Drake-related warnings, you may use the
`"ignore"` action for `warnings.simplefilter`.
"""
import os
import re
import sys
import traceback
from types import ModuleType
import warnings
# TODO(eric.cousineau): Make autocomplete ignore `ModuleShim` attributes
# (e.g. `install`).
# TODO(eric.cousineau): Remove ModuleShim once Drake requires Python >= 3.7
# (for PEP 562).
class ModuleShim:
"""Provides a shim for automatically resolving extra variables.
This can be used to deprecate import alias in modules to simplify
dependencies.
See Also:
https://stackoverflow.com/a/7668273/7829525
Note:
This is not necessary in Python >= 3.7 due to PEP 562.
Warning:
This will not work if called on a cc module during import (e.g. using
ExecuteExtraPythonCode). Instead, you should rename the module from
`{name}` to `_{name}`, and import the symbols into the new module using
_import_cc_module_vars.
"""
def __init__(self, orig_module, handler):
assert hasattr(orig_module, "__all__"), (
"Please define `__all__` for this module.")
assert isinstance(orig_module, ModuleType), (
"{} must be a module".format(orig_module))
# https://stackoverflow.com/a/16237698/7829525
object.__setattr__(self, '_orig_module', orig_module)
object.__setattr__(self, '_handler', handler)
object.__setattr__(self, '__doc__', orig_module.__doc__)
def __getattr__(self, name):
# Use the original module if possible.
m = self._orig_module
if hasattr(m, name):
return getattr(m, name)
else:
# Otherwise, use the handler, and store the result.
try:
value = self._handler(name)
except AttributeError as e:
if str(e):
raise e
else:
raise AttributeError(
"'module' object has no attribute '{}'".format(name))
setattr(m, name, value)
return value
def __setattr__(self, name, value):
# Redirect writes to the original module.
setattr(self._orig_module, name, value)
def __delattr__(self, name):
# Redirect deletions to the original module.
delattr(self._orig_module, name)
def __repr__(self):
return repr(self._orig_module)
def __dir__(self):
# Implemented to provide a useful subset of completions to
# `rlcompleter`.
return self._orig_module.__all__
@classmethod
def _install(cls, name, handler, *, auto_all=False):
"""Hook into module's attribute accessors and mutators.
Args:
name: Module name. Generally should be __name__.
handler: Function of the form `handler(var)`, where `var` is the
variable name.
auto_all: If True, this will override `__all__` with a listing of
all non-private variables in the module.
Note:
This is private such that `install` does not pollute completion
candidations provided by `rlcompleter` when it iterates through
`__bases__`.
"""
old_module = sys.modules[name]
if auto_all:
old_module.__all__ = [
name
for name in old_module.__dict__
if not name.startswith("_")
]
new_module = cls(old_module, handler)
sys.modules[name] = new_module
class DrakeDeprecationWarning(DeprecationWarning):
"""Extends `DeprecationWarning` to permit Drake-specific warnings to
be filtered by default, without having side effects on other libraries."""
pass
def _format_deprecation_message(message, *, date=None):
assert isinstance(message, str), repr(message)
if date is not None:
assert isinstance(date, str), repr(date)
assert date != "None"
assert _date_pattern.fullmatch(date) is not None, (
f"Date does not match YYYY-MM-DD pattern: {repr(date)}"
)
# N.B. This follows the formatting in `mkdoc.py`.
message = (
f"{message} The deprecated code will be removed from Drake on or "
f"after {date}."
)
assert _date_pattern.search(message) is not None, (
f"Deprecation messages should have a removal date in the form of "
f"YYYY-MM-DD. Consider passing in the kwarg `date='YYYY-MM-DD' to "
f"have a preformatted message.\n"
f"Original message:\n"
f"{message}"
)
return message
def _warn_deprecated(message, *, date=None, stacklevel=2):
# Logs a deprecation warning message. Also used by `deprecation_pybind.h`
# in addition to this file.
warnings.warn(
_format_deprecation_message(message, date=date),
category=DrakeDeprecationWarning,
stacklevel=stacklevel,
)
class _DeprecatedDescriptor:
"""Wraps a descriptor to warn that it is deprecated any time it is
accessed.
"""
def __init__(self, original, message, *, date=None):
assert hasattr(original, '__get__'), (
f"`original` must be a descriptor: {original}"
)
self._original = original
self.__doc__ = self._original.__doc__
self._message = message
self._date = date
def _warn(self):
_warn_deprecated(self._message, date=self._date, stacklevel=4)
def __get__(self, obj, objtype):
self._warn()
return self._original.__get__(obj, objtype)
def __set__(self, obj, value):
self._warn()
self._original.__set__(obj, value)
def __delete__(self, obj):
self._warn()
self._original.__delete__(obj)
def deprecated(message, *, date=None):
"""Decorator that deprecates a member of a class based on access.
Args:
message: Warning message when member is accessed.
date: (Optional) String of the form "YYYY-MM-DD".
If supplied, will reformat the message to add the date as is done
with DRAKE_DEPRECATED and its processing in mkdoc.py. This must be
present if ``message`` does not contain the date itself.
Note:
This differs from other implementations in that it warns on access,
not when the method is called. For other methods, see the examples in
https://stackoverflow.com/a/40301488/7829525.
Use `ModuleShim` for deprecating variables in a module.
"""
# TODO(eric.cousineau): If possible, distinguish between descriptors and
# free functions. See PR #15877 for attempt.
def wrapped(original):
return _DeprecatedDescriptor(original, message, date=date)
return wrapped
def install_numpy_warning_filters(force=False):
"""Install warnings filters specific to NumPy."""
global _installed_numpy_warning_filters
if _installed_numpy_warning_filters and not force:
return
_installed_numpy_warning_filters = True
# Warnings specific to comparison with `dtype=object` should be raised to
# errors (#8315, #8491). Without them, NumPy will swallow the errors and
# make a DeprecationWarning, while returning effectively garbage values
# (e.g. comparison based on object ID): either a scalar bool or an array of
# bools (based on what objects are present and the NumPy version).
# N.B. Using a `module=` regex filter does not work, as the warning is
# raised from C code, and thus inherits the calling module, which may not
# be "numpy\..*" (numpy/numpy#10861).
warnings.filterwarnings(
"error", category=DeprecationWarning, message="numpy equal will not")
warnings.filterwarnings(
"error", category=DeprecationWarning,
message="elementwise == comparison failed")
warnings.filterwarnings(
"error", category=DeprecationWarning,
message="elementwise != comparison failed")
# Error changed in 1.16.0
warnings.filterwarnings(
"error", category=DeprecationWarning,
message="elementwise comparison failed")
# TODO(#17898): This is not a deprecation per se, nor is it promoting the
# deprecation to warning. However, this warning currently does not incur
# a functional penalty, so we suppress the warning to minimize
# distractions. Root-cause investigation pending.
warnings.filterwarnings(
"ignore", category=RuntimeWarning,
message="invalid value encountered in")
def deprecated_callable(message, *, date=None):
"""
Deprecates a callable (a free function or a type/class object) by
wrapping its invocation to emit a deprecation.
When possible, use ModuleShim to ensure that a deprecation warning is
emitted at *import time*, as it can easily be used with pure Python
modules.
However, if you are dealing with a C++ module (and are writing code inside
of `_{module}_extra.py`), you should use this approach.
Example:
::
# As decorator
@deprecated_callable("Please use `func_y` instead", date="2038-01-19") # noqa
def func_x():
...
# As alias
deprecated_alias = deprecated_callable(
"Please use `real_callable` instead", date="2038-01-19"
)(real_callable)
"""
def decorator(original):
def wrapped(*args, **kwargs):
_warn_deprecated(message, date=date, stacklevel=3)
return original(*args, **kwargs)
wrapped.__name__ = original.__name__
wrapped.__qualname__ = original.__name__
warning = _format_deprecation_message(message, date=date)
wrapped.__doc__ = f"Warning:\n\n {warning}"
return wrapped
return decorator
def _forward_callables_as_deprecated(var_dict, m_new, date):
# Forwards public symbols from `m_new` to `var_dict`, while wrapping
# each symbol to emit a deprecation warning when it is called.
# Warning: This assumes all relevant symbols are callable!
all_public = [x for x in m_new.__dict__ if not x.startswith("_")]
symbols = getattr(m_new, "__all__", all_public)
for symbol in symbols:
new = getattr(m_new, symbol)
assert hasattr(new, "__call__")
old_name = var_dict["__name__"]
message = (
f"Please use ``{m_new.__name__}.{symbol}`` instead of "
f"``{old_name}.{symbol}``."
)
old = deprecated_callable(message, date=date)(new)
old.__module__ = old_name
var_dict[symbol] = old
if os.environ.get("_DRAKE_DEPRECATION_IS_ERROR") == "1":
# This is used for testing Jupyter notebooks in `jupyter_bazel`.
# Note that the same literal string name for the environment variable is
# used for both C++ code and Python code, so keep the two in sync.
warnings.simplefilter('error', DrakeDeprecationWarning)
else:
warnings.simplefilter('once', DrakeDeprecationWarning)
_installed_numpy_warning_filters = False
# Used to enforce presence of YYYY-MM-DD timestamp for deprecation.
_date_pattern = re.compile(r"\d\d\d\d\-\d\d\-\d\d")
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/compatibility.py | """Contains routines to monkey patch or provide alternatives to upstream code
which may need changes for compatibility.
"""
import numpy as np
_patches = {
'numpy_formatters': {
'applied': False,
'required': np.lib.NumpyVersion(np.__version__) < '1.13.0',
},
}
def _defer_callable_type(cls):
# Makes a type, which is meant to purely callable, and defers its
# construction until it needs to be called.
class Deferred:
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
self._obj = None
def _get_obj(self):
if self._obj is None:
self._obj = cls(*self._args, **self._kwargs)
return self._obj
def __call__(self, *args, **kwargs):
return self._get_obj().__call__(*args, **kwargs)
return Deferred
def maybe_patch_numpy_formatters():
"""Required to permit printing of symbolic array types in NumPy < 1.13.0.
See #8729 for more information.
"""
# Provides version-dependent monkey-patch which effectively achieves a
# portion of https://github.com/numpy/numpy/pull/8963
patch = _patches['numpy_formatters']
if not patch['required']:
return
if patch['applied']:
return
module = np.core.arrayprint
defer_callable_types = [
'IntegerFormat',
'FloatFormat',
]
for name in defer_callable_types:
original = getattr(module, name)
deferred = _defer_callable_type(original)
setattr(module, name, deferred)
patch['applied'] = True
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/default_scalars_pybind.h | #pragma once
/// @file
/// Helpers for defining scalars and values.
#include "drake/bindings/pydrake/autodiff_types_pybind.h"
#include "drake/bindings/pydrake/common/cpp_template_pybind.h"
#include "drake/bindings/pydrake/common/type_pack.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/bindings/pydrake/symbolic_types_pybind.h"
#include "drake/common/default_scalars.h"
namespace drake {
namespace pydrake {
// N.B. This should be kept in sync with the `*_DEFAULT_SCALARS` macro in
// `default_scalars.h`.
/** Type pack defining common scalar types. */
using CommonScalarPack = type_pack< // BR
double, //
AutoDiffXd, //
symbolic::Expression>;
// N.B. This should be kept in sync with the `*_DEFAULT_NONSYMBOLIC_SCALARS`
// macro in `default_scalars.h`.
/** Type pack for non-symbolic common scalar types. */
using NonSymbolicScalarPack = type_pack< // BR
double, //
AutoDiffXd>;
// TODO(eric.cousineau): Remove `CopyIfNotPodType` functions and
// `return_value_policy_for_scalar_type` once #8116 is resolved.
/** @name Handling special non-POD scalar types.
Because we use dtype=object in NumPy, we cannot alias (share references to) the
data underlying matrix objects when passing data between NumPy and Eigen (see
#8116).
The simple policy these functions help enforce:
- When T is double, allow referencing (do not require copying).
- When T is not double (i.e., AutoDiffXd, Expression), copy data (do not
reference the data).
*/
//@{
/** Permits referencing for builtin dtypes (e.g., T == double), but then
switches to copying for custom dtypes (T ∈ {AutoDiffXd, Expression}). */
template <typename T>
py::return_value_policy return_value_policy_for_scalar_type() {
if (std::is_same_v<T, double>) {
return py::return_value_policy::reference_internal;
} else {
return py::return_value_policy::copy;
}
}
/** A no-op for builtin dtypes (e.g., T == double), but then switches to copying
for custom dtypes (T ∈ {AutoDiffXd, Expression}).
@tparam SomeBlock an Eigen::Block or Eigen::VectorBlock. */
template <typename SomeBlock>
decltype(auto) CopyIfNotPodType(const SomeBlock& x) {
using NestedExpression = typename SomeBlock::NestedExpression;
using T = typename NestedExpression::Scalar;
if constexpr (std::is_same_v<T, double>) {
return x;
} else {
constexpr int RowsAtCompileTime = NestedExpression::RowsAtCompileTime;
constexpr int ColsAtCompileTime = NestedExpression::ColsAtCompileTime;
return Eigen::Matrix<T, RowsAtCompileTime, ColsAtCompileTime>(x);
}
}
//@}
namespace internal {
// For generic types, only permit conversion to the type itself.
// `AutoDiffXd` and `Expression` cannot `static_cast<>` to each other, and
// cannot `static_cast<>` to `double`.
template <typename T>
struct CastUPack {
using Pack = type_pack<T>;
};
// For `double`, permit conversion to any common type.
template <>
struct CastUPack<double> {
using Pack = CommonScalarPack;
};
} // namespace internal
/** Binds `cast<T>()` explicitly. */
template <typename T, typename PyClass,
typename UPack = typename internal::CastUPack<T>::Pack>
void DefCast(PyClass* cls, const char* doc, UPack U_pack = {}) {
using Class = typename PyClass::type;
auto bind_scalar = [cls, doc](auto U_dummy) {
using U = decltype(U_dummy);
AddTemplateMethod(
*cls, "cast", [](const Class& self) { return self.template cast<U>(); },
GetPyParam<U>(), doc);
};
type_visit(bind_scalar, U_pack);
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/cpp_template_pybind.h | #pragma once
#include <string>
#include <utility>
// `GetPyTypes` is implemented specifically for `cpp_template`; to simplify
// dependencies, this is included transitively.
#include "drake/bindings/pydrake/common/cpp_param_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
namespace drake {
namespace pydrake {
namespace internal {
// C++ interface for `pydrake.common.cpp_template.get_or_init`.
// Please see that function for common parameters.
// @param template_cls_name Name of the template class in `cpp_template`,
// resolves to class to be passed as `template_cls`.
inline py::object GetOrInitTemplate( // BR
py::handle scope, const std::string& name,
const std::string& template_cls_name, // BR
py::tuple args = py::tuple(), py::dict kwargs = py::dict()) {
const char module_name[] = "pydrake.common.cpp_template";
py::handle m = py::module::import(module_name);
return m.attr("get_or_init")(
scope, name, m.attr(template_cls_name.c_str()), *args, **kwargs);
}
// Adds instantiation to a Python template.
inline void AddInstantiation(py::handle py_template, py::handle obj,
py::tuple param, bool skip_rename = false) {
py_template.attr("add_instantiation")(param, obj, skip_rename);
}
// Gets name for a given instantiation.
inline std::string GetInstantiationName(
py::handle py_template, py::tuple param, bool mangle = false) {
return py::cast<std::string>(py_template.attr("_instantiation_name")(
param, py::arg("mangle") = mangle));
}
// C++ wrapper around pydrake.common.pretty_class_name.
inline py::object PrettyClassName(py::handle cls, bool use_qualname = false) {
py::handle py_func =
py::module::import("pydrake.common").attr("pretty_class_name");
return py_func(cls, py::arg("use_qualname") = use_qualname);
}
} // namespace internal
/// Provides a temporary, unique name for a class instantiation that
/// will be passed to `AddTemplateClass`.
template <typename T>
std::string TemporaryClassName(const std::string& name = "TemporaryName") {
return "_" + name + "_" + typeid(T).name();
}
/// Adds a template class instantiation.
/// @param scope Parent scope of the template.
/// @param template_name Name of the template.
/// @param py_class Class instantiation to be added.
/// @note The class name should be *unique*. If you would like automatic unique
/// names, consider constructing the class binding as
/// `py::class_<Class, ...>(m, TemporaryClassName<Class>().c_str())`.
/// @param param Parameters for the instantiation.
inline py::object AddTemplateClass( // BR
py::handle scope, const std::string& template_name, py::handle py_class,
py::tuple param, bool skip_rename = false) {
py::object py_template =
internal::GetOrInitTemplate(scope, template_name, "TemplateClass");
internal::AddInstantiation(py_template, py_class, param, skip_rename);
return py_template;
}
/// Provides a convenience wrapper for defining a template class instantiation
/// and a default instantiation (if not already defined).
/// The default instantiation is named `default_name`, while the template is
/// named `default_name + template_suffix`.
/// @return pybind11 class
template <typename Class, typename... Options>
py::class_<Class, Options...> DefineTemplateClassWithDefault( // BR
py::handle scope, const std::string& default_name, py::tuple param,
const char* doc_string = "", const std::string& template_suffix = "_") {
// The default instantiation is immediately assigned its correct class name.
// Other instantiations use a temporary name here that will be overwritten
// by the AddTemplateClass function during registration.
const bool is_default = !py::hasattr(scope, default_name.c_str());
const std::string class_name =
is_default ? default_name : TemporaryClassName<Class>();
const std::string template_name = default_name + template_suffix;
// Define the class.
std::string doc;
if (is_default) {
doc = fmt::format(
"{}\n\nNote:\n\n"
" This class is templated; see :class:`{}`\n"
" for the list of instantiations.",
doc_string, template_name);
} else {
doc = doc_string;
}
py::class_<Class, Options...> py_class(
scope, class_name.c_str(), doc.c_str());
// Register it as a template instantiation.
const bool skip_rename = is_default;
AddTemplateClass(scope, template_name, py_class, param, skip_rename);
return py_class;
}
/// Declares a template function.
/// @param scope Parent scope of the template.
/// @param name Name of the template.
/// @param func Function to be added.
/// @param param Parameters for the instantiation.
/// @param extra... Additional arguments to pass to `py::cpp_function`.
template <typename Func, typename... Extra>
py::object AddTemplateFunction(py::handle scope, const std::string& name,
Func&& func, py::tuple param, Extra&&... extra) {
// TODO(eric.cousineau): Use `py::sibling` if overloads are needed.
py::object py_template =
internal::GetOrInitTemplate(scope, name, "TemplateFunction");
const bool mangle = true;
const std::string instantiation_name =
internal::GetInstantiationName(py_template, param, mangle);
py::object py_func = py::cpp_function(std::forward<Func>(func),
py::name(instantiation_name.c_str()), std::forward<Extra>(extra)...);
internal::AddInstantiation(py_template, py_func, param);
return py_template;
}
/// Declares a template method.
/// @param scope Parent scope of the template. This should be a class.
/// @param name Name of the template.
/// @param method Method to be added.
/// @param param Parameters for the instantiation.
/// @param extra... Additional arguments to pass to `py::cpp_function`.
template <typename Method, typename... Extra>
py::object AddTemplateMethod( // BR
py::handle scope, const std::string& name, Method&& method, py::tuple param,
Extra&&... extra) {
py::object py_template = internal::GetOrInitTemplate(
scope, name, "TemplateMethod", py::make_tuple(scope));
const bool mangle = true;
const std::string instantiation_name =
internal::GetInstantiationName(py_template, param, mangle);
py::object py_func = py::cpp_function(std::forward<Method>(method),
py::name(instantiation_name.c_str()), py::is_method(scope),
std::forward<Extra>(extra)...);
internal::AddInstantiation(py_template, py_func, param);
return py_template;
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/cpp_param_pybind.h | #pragma once
/// @file
/// Provides a mechanism to map C++ types to canonical Python types.
#include <string>
#include <typeinfo>
#include <vector>
#include "drake/bindings/pydrake/common/type_pack.h"
#include "drake/bindings/pydrake/common/wrap_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
namespace drake {
namespace pydrake {
/// Provides a publicly visible, but minimal, re-implementation of `py::object`
/// so that a public type can be used with `drake::Value<T>`, while still
/// maintaining the revelant semantics with its generic implementation (#13207).
/// This should *only* be used in place of `py::object` for public APIs that
/// rely on RTTI (e.g. `typeid`).
/// See implementation of `class object` in pybind11/include/pybind11/pytypes.h.
class Object {
public:
Object() {}
/// Decrements reference count (if pointing to a real object).
~Object();
/// Constructs from raw pointer, incrementing the reference count.
/// @note This does not implement any of the `py::reinterpret_borrow<>`
/// semantics.
explicit Object(::PyObject* ptr);
/// Constructs from another Object, incrementing the reference count.
explicit Object(const Object& other);
/// Steals object (and reference count) from another Object.
Object(Object&& other);
/// Copies object reference and increments reference count.
Object& operator=(const Object& other);
/// Steals object (and reference count) from another Object.
Object& operator=(Object&& other);
/// Accesses raw PyObject pointer (no reference counting).
::PyObject* ptr() const { return ptr_; }
/// Converts to a pybind11 Python type, using py::reinterpret_borrow.
template <typename T>
T to_pyobject() const {
return py::reinterpret_borrow<T>(ptr());
}
/// Converts from a pybind11 Python type, using py::reinterpret_borrow.
template <typename T>
static Object from_pyobject(const T& h) {
return Object(h.ptr());
}
/// Provides a deep copy of the referred-to object.
Object Clone() const;
private:
// Increments reference count. See `py::handle::inc_ref()` for more details.
void inc_ref();
// Decrements reference count. See `py::handle::dec_ref()` for more details.
void dec_ref();
::PyObject* ptr_{};
};
namespace internal {
// Wrapper for Object.
struct wrapper_pydrake_object {
using Type = Object;
static constexpr auto original_name = py::detail::_("pydrake::Object");
using WrappedType = py::object;
static constexpr auto wrapped_name = py::detail::_("object");
static Object unwrap(const py::object& obj) {
return Object::from_pyobject(obj);
}
static py::object wrap(const Object& obj) {
return obj.to_pyobject<py::object>();
}
};
// Gets singleton for type aliases from `cpp_param`.
py::object GetParamAliases();
// Gets Python type object given `std::type_info`.
// @throws std::exception if type is neither aliased nor registered in
// `pybind11`.
py::object GetPyParamScalarImpl(const std::type_info& tinfo);
// Gets Python type for a C++ type (base case).
template <typename T>
inline py::object GetPyParamScalarImpl(type_pack<T> = {}) {
static_assert(!py::detail::is_pyobject<T>::value,
"You cannot use `pybind11` types (e.g. `py::object`). Use a publicly "
"visible replacement type instead (e.g. `drake::pydrake::Object`).");
return GetPyParamScalarImpl(typeid(T));
}
// Gets Python literal for a C++ literal (specialization).
template <typename T, T Value>
inline py::object GetPyParamScalarImpl(
type_pack<std::integral_constant<T, Value>> = {}) {
return py::cast(Value);
}
// Gets Python type for a C++ vector that is not registered using
// PYBIND11_MAKE_OPAQUE.
template <typename T>
inline py::object GetPyParamScalarImpl(type_pack<std::vector<T>> = {}) {
// Get inner type for validation.
py::object py_T = GetPyParamScalarImpl(type_pack<T>{});
if constexpr (!internal::is_generic_pybind_v<std::vector<T>>) {
return py::module::import("pydrake.common.cpp_param").attr("List")[py_T];
} else {
return GetPyParamScalarImpl(typeid(std::vector<T>));
}
}
} // namespace internal
/// Gets the canonical Python parameters for each C++ type.
/// @returns Python tuple of canonical parameters.
/// @throws std::exception on the first type it encounters that is neither
/// aliased nor registered in `pybind11`.
/// @tparam Ts The types to get C++ types for.
/// @pre Ts must be public symbols.
/// @pre Ts cannot be a `py::` symbol (e.g. `py::object`). On Mac, this may
/// cause failure depending on import order (e.g. trying to use
/// `Value<py::object>` between different modules). See #8704 and #13207 for
/// more details.
template <typename... Ts>
inline py::tuple GetPyParam(type_pack<Ts...> = {}) {
return py::make_tuple(internal::GetPyParamScalarImpl(type_pack<Ts>{})...);
}
} // namespace pydrake
} // namespace drake
namespace pybind11 {
namespace detail {
template <>
struct type_caster<drake::pydrake::Object>
: public drake::pydrake::internal::type_caster_wrapped<
drake::pydrake::internal::wrapper_pydrake_object> {};
} // namespace detail
} // namespace pybind11
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/containers.py | """Provides extensions for containers of Drake-related objects."""
import numpy as np
import re
class _EqualityProxyBase:
# Wraps an object with a non-compliant `__eq__` operator (returns a
# non-bool convertible expression) with a custom compliant `__eq__`
# operator.
def __init__(self, value):
self._value = value
def _get_value(self):
return self._value
def __hash__(self):
return hash(self._value)
def __eq__(self, other):
raise NotImplemented("Abstract method")
value = property(_get_value)
class _DictKeyWrap(dict):
# Wraps a dictionary's key access. For a key of a type `TOrig`, this
# dictionary will provide a key of type `TProxy`, that should proxy the
# original key.
def __init__(self, dict_in, key_wrap, key_unwrap):
# @param dict_in Dictionary with keys of types TOrig (not necessarily
# homogeneous).
# @param key_wrap Functor that maps from TOrig -> TProxy.
# @param key_unwrap Functor that maps from TProxy -> TOrig.
dict.__init__(self)
# N.B. Passing properties to these will cause an issue. This can be
# sidestepped by storing the properties in a `dict`.
self._key_wrap = key_wrap
self._key_unwrap = key_unwrap
for key, value in dict_in.items():
self[key] = value
def __setitem__(self, key, value):
return dict.__setitem__(self, self._key_wrap(key), value)
def __getitem__(self, key):
return dict.__getitem__(self, self._key_wrap(key))
def __delitem__(self, key):
return dict.__delitem__(self, self._key_wrap(key))
def __contains__(self, key):
return dict.__contains__(self, self._key_wrap(key))
def items(self):
return zip(self.keys(), self.values())
def keys(self):
return (self._key_unwrap(key) for key in dict.keys(self))
def raw(self):
"""Returns a dict with the original keys.
Note:
Copying to a `dict` will maintain the proxy keys.
"""
return dict(self.items())
class EqualToDict(_DictKeyWrap):
"""Implements a dictionary where keys are compared using type and
`lhs.EqualTo(rhs)`.
"""
def __init__(self, *args, **kwargs):
class Proxy(_EqualityProxyBase):
def __eq__(self, other):
T = type(self.value)
return (isinstance(other.value, T)
and self.value.EqualTo(other.value))
# https://stackoverflow.com/a/1608907/7829525
__hash__ = _EqualityProxyBase.__hash__
dict_in = dict(*args, **kwargs)
_DictKeyWrap.__init__(self, dict_in, Proxy, Proxy._get_value)
class NamedViewBase:
"""Base for classes generated by ``namedview``.
Inspired by: https://gitlab.com/ericvsmith/namedlist
"""
_fields = None # To be specified by inherited classes.
def __init__(self, value):
"""Creates a view on ``value``. Any mutations on this instance will be
reflected in ``value``, and any mutations on ``value`` will be
reflected in this instance."""
assert self._fields is not None, (
"Class must be generated by ``namedview``")
assert len(self._fields) == len(value)
object.__setattr__(self, '_value', value)
@classmethod
def get_fields(cls):
"""Returns all fields for this class or object."""
return cls._fields
def __getitem__(self, i):
return self._value[i]
def __setitem__(self, i, value_i):
self._value[i] = value_i
def __setattr__(self, name, value):
"""Prevent setting additional attributes."""
if not hasattr(self, name):
raise AttributeError(
"Cannot add attributes! The fields in this named view are"
f"{self.get_fields()}, but you tried to set '{name}'.")
object.__setattr__(self, name, value)
def __len__(self):
return len(self._value)
def __iter__(self):
return iter(self._value)
def __array__(self):
"""Proxy for use with NumPy."""
return np.asarray(self._value)
def __repr__(self):
"""Provides human-readable breakout of each field and value."""
value_strs = []
for i, field in enumerate(self._fields):
value_strs.append("{}={}".format(field, repr(self[i])))
return "{}({})".format(self.__class__.__name__, ", ".join(value_strs))
@staticmethod
def _item_property(i):
# Maps an item (at a given index) to a property.
return property(fget=lambda self: self[i],
fset=lambda self, value: self.__setitem__(i, value))
@classmethod
def Zero(cls):
"""Constructs a view onto values set to all zeros."""
return cls([0] * len(cls._fields))
def _sanitize_field_name(name: str):
result = name
# Ensure the first character is a valid opener (e.g., no numbers allowed).
if not result[0].isidentifier():
result = "_" + result
# Ensure that each additional character is valid in turn, avoiding the
# special case for opening characters by prepending "_" during the check.
for i in range(1, len(result)):
if not ("_" + result[i]).isidentifier():
result = result[:i] + "_" + result[i+1:]
result = re.sub("__+", "_", result)
assert result.isidentifier(), f"Sanitization failed on {name} => {result}"
return result
def namedview(name, fields, *, sanitize_field_names=True):
"""
Creates a class that is a named view with given ``fields``. When the class
is instantiated, it must be given the object that it will be a proxy for.
Similar to ``namedtuple``.
If ``sanitize_field_names`` is True (the default), then any characters in
``fields`` which are not valid in Python identifiers will be automatically
replaced with `_`. Leading numbers will have `_` inserted, and duplicate
`_` will be replaced by a single `_`.
Example:
::
MyView = namedview("MyView", ('a', 'b'))
value = np.array([1, 2])
view = MyView(value)
view.a = 10 # `value` is now [10, 2]
value[1] = 100 # `view` is now [10, 100]
view[:] = 3 # `value` is now [3, 3]
# Get an array from the view *aliasing* the original vector.
value_view = view[:]
# Another way to get an aliased array.
value_view_2 = np.asarray(view)
# Get an array from the view that is a *copy* of the original
# vector.
value_copy = np.array(view)
Warning:
As illustrated above, if you use ``np.array(view)``, then it will
provide a *copied* array from the view. If you want an *aliased* array
from the view, then use operations like ``view[:]``,
``np.asarray(view)``, or ``np.array(view, copy=False)``.
For more details, see ``NamedViewBase``.
"""
base_cls = (NamedViewBase, )
if sanitize_field_names:
fields = [_sanitize_field_name(f) for f in fields]
assert len(set(fields)) == len(fields), "Field names must be unique"
type_dict = dict(_fields=tuple(fields))
for i, field in enumerate(fields):
type_dict[field] = NamedViewBase._item_property(i)
cls = type(name, base_cls, type_dict)
return cls
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/identifier_pybind.h | #pragma once
#include <string>
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/identifier.h"
namespace drake {
namespace pydrake {
/// Binds an Identifier instantiation.
template <typename Class, typename ModuleOrClass>
void BindIdentifier(
ModuleOrClass m, const std::string& name, const char* id_doc) {
constexpr auto& cls_doc = pydrake_doc.drake.Identifier;
py::class_<Class>(m, name.c_str(), id_doc)
.def("get_value", &Class::get_value, cls_doc.get_value.doc)
.def("is_valid", &Class::is_valid, cls_doc.is_valid.doc)
.def(py::self == py::self)
.def(py::self != py::self)
.def(py::self < py::self)
.def(py::hash(py::self))
.def_static("get_new_id", &Class::get_new_id, cls_doc.get_new_id.doc)
.def("__repr__", [name](const Class& self) {
return py::str("<{} value={}>").format(name, self.get_value());
});
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/wrap_function.h | #pragma once
#include <functional>
#include <type_traits>
#include <utility>
namespace drake {
namespace pydrake {
namespace internal {
// Collects both a functor object and its signature for ease of inference.
template <typename Func, typename Return, typename... Args>
struct function_info {
// TODO(eric.cousineau): Ensure that this permits copy elision when combined
// with `std::forward<Func>(func)`, while still behaving well with primitive
// types.
std::decay_t<Func> func;
};
// Factory method for `function_info<>`, to be used by `infer_function_info`.
template <typename Return, typename... Args, typename Func>
auto make_function_info(Func&& func, Return (*infer)(Args...) = nullptr) {
(void)infer;
return function_info<Func, Return, Args...>{std::forward<Func>(func)};
}
// SFINAE for functors.
// N.B. This *only* distinguished between function / method pointers and
// lambda objects. It does *not* distinguish among other types.
template <typename Func, typename T = void>
using enable_if_lambda_t =
std::enable_if_t<!std::is_function_v<std::decay_t<Func>>, T>;
// Infers `function_info<>` from a function pointer.
template <typename Return, typename... Args>
auto infer_function_info(Return (*func)(Args...)) {
return make_function_info<Return, Args...>(func);
}
// Infers `function_info<>` from a mutable method pointer.
template <typename Return, typename Class, typename... Args>
auto infer_function_info(Return (Class::*method)(Args...)) {
auto func = [method](Class* self, Args... args) -> Return {
return (self->*method)(std::forward<Args>(args)...);
};
return make_function_info<Return, Class*, Args...>(func);
}
// Infers `function_info<>` from a const method pointer.
template <typename Return, typename Class, typename... Args>
auto infer_function_info(Return (Class::*method)(Args...) const) {
auto func = [method](const Class* self, Args... args) -> Return {
return (self->*method)(std::forward<Args>(args)...);
};
return make_function_info<Return, const Class*, Args...>(func);
}
// Helpers for general functor objects.
struct functor_helpers {
// Removes class from mutable method pointer for inferring signature
// of functor.
template <typename Class, typename Return, typename... Args>
static auto remove_class_from_ptr(Return (Class::*)(Args...)) {
using Ptr = Return (*)(Args...);
return Ptr{};
}
// Removes class from const method pointer for inferring signature of functor.
template <typename Class, typename Return, typename... Args>
static auto remove_class_from_ptr(Return (Class::*)(Args...) const) {
using Ptr = Return (*)(Args...);
return Ptr{};
}
// Infers function pointer from functor.
// @pre `Func` must have only *one* overload of `operator()`.
template <typename Func>
static auto infer_function_ptr() {
return remove_class_from_ptr(&Func::operator());
}
};
// Infers `function_info<>` from a generic functor.
template <typename Func, typename = internal::enable_if_lambda_t<Func>>
auto infer_function_info(Func&& func) {
return make_function_info(std::forward<Func>(func),
functor_helpers::infer_function_ptr<std::decay_t<Func>>());
}
// Implementation for wrapping a function by scanning and replacing arguments
// based on their types.
template <template <typename...> class wrap_arg_policy,
bool use_functions = true>
struct wrap_function_impl {
// By default `wrap_arg_functions` is the same as `wrap_arg_policy`. However,
// below we specialize it for the case when `T` is of the form
// `std::function<F>`.
// N.B. This must precede `wrap_type`.
template <typename T>
struct wrap_arg_functions : public wrap_arg_policy<T> {};
template <typename T>
using wrap_arg = std::conditional_t<use_functions, wrap_arg_functions<T>,
wrap_arg_policy<T>>;
// Provides wrapped argument type.
// Uses `Extra` to specialize within class scope to intercept `void`.
template <typename T, typename Extra>
struct wrap_type {
using type = decltype(wrap_arg<T>::wrap(std::declval<T>()));
};
// Intercept `void`, since `declval<void>()` is invalid.
template <typename Extra>
struct wrap_type<void, Extra> {
using type = void;
};
// Convenience helper type.
template <typename T>
using wrap_type_t = typename wrap_type<T, void>::type;
// Determines which overload should be used, since we cannot wrap a `void`
// type using `wrap_arg<void>::wrap()`.
template <typename Return>
static constexpr bool enable_wrap_output = !std::is_same_v<Return, void>;
// Specialization for callbacks of the form `std::function<>`.
// @note We could generalize this using SFINAE for functors of any form, but
// that complicates the details for a relatively low ROI.
template <typename Return, typename... Args>
struct wrap_arg_functions<const std::function<Return(Args...)>&> {
// Define types explicit, since `auto` is not easily usable as a return type
// (compilers struggle with inference).
using Func = std::function<Return(Args...)>;
using WrappedFunc =
std::function<wrap_type_t<Return>(wrap_type_t<Args>...)>;
static WrappedFunc wrap(const Func& func) {
if (!func) {
return {};
}
return wrap_function_impl::run(infer_function_info(func));
}
// Unwraps a `WrappedFunc`, also unwrapping the return value.
// @note We use `Defer` so that we can use SFINAE without a disptach method.
template <typename Defer = Return>
static Func unwrap( // BR
const WrappedFunc& func_wrapped,
std::enable_if_t<enable_wrap_output<Defer>, void*> = {}) {
if (!func_wrapped) {
return {};
}
return [func_wrapped](Args... args) -> Return {
return wrap_arg_functions<Return>::unwrap(func_wrapped(
wrap_arg_functions<Args>::wrap(std::forward<Args>(args))...));
};
}
// Specialization / overload of above, but not wrapping the return value.
template <typename Defer = Return>
static Func unwrap(const WrappedFunc& func_wrapped,
std::enable_if_t<!enable_wrap_output<Defer>, void*> = {}) {
if (!func_wrapped) {
return {};
}
return [func_wrapped](Args... args) {
func_wrapped(
wrap_arg_functions<Args>::wrap(std::forward<Args>(args))...);
};
}
};
// Ensure that we also wrap `std::function<>` returned by value.
template <typename Signature>
struct wrap_arg_functions<std::function<Signature>>
: public wrap_arg_functions<const std::function<Signature>&> {};
// Wraps function arguments and the return value.
// Generally used when `Return` is non-void.
template <typename Func, typename Return, typename... Args>
static auto run(function_info<Func, Return, Args...>&& info,
std::enable_if_t<enable_wrap_output<Return>, void*> = {}) {
// N.B. Since we do not use the `mutable` keyword with this lambda,
// any functors passed in *must* provide `operator()(...) const`.
auto func_wrapped =
[func_f = std::forward<Func>(info.func)](
wrap_type_t<Args>... args_wrapped) -> wrap_type_t<Return> {
return wrap_arg<Return>::wrap(func_f(wrap_arg<Args>::unwrap(
std::forward<wrap_type_t<Args>>(args_wrapped))...));
};
return func_wrapped;
}
// Wraps function arguments, but not the return value.
// Generally used when `Return` is void.
template <typename Func, typename Return, typename... Args>
static auto run(function_info<Func, Return, Args...>&& info,
std::enable_if_t<!enable_wrap_output<Return>, void*> = {}) {
auto func_wrapped = // BR
[func_f = std::forward<Func>(info.func)](
wrap_type_t<Args>... args_wrapped) -> Return {
return func_f(wrap_arg<Args>::unwrap(
std::forward<wrap_type_t<Args>>(args_wrapped))...);
};
return func_wrapped;
}
};
} // namespace internal
/// Wraps the types used in a function signature to produce a new function with
/// wrapped arguments and return value (if non-void). The wrapping is based on
/// `wrap_arg_policy`.
/// Any types that are of the form `std::function<F>` will be recursively
/// wrapped, such that callbacks will be of a wrapped form (arguments and
/// return types wrapped). The original form of the callbacks will still be
/// called in the wrapped callback.
/// @tparam wrap_arg_policy
/// User-supplied argument wrapper, that must supply the static functions
/// `wrap(Arg arg) -> Wrapped` and `unwrap(Wrapped wrapped) -> Arg`.
/// `Arg arg` is the original argument, and `Wrapped wrapped` is the wrapped
/// / transformed argument type.
/// N.B. This template template parameter uses a parameter pack to allow
/// for SFINAE. If passing a `using` template alias, ensure that the alias
/// template template parameter uses a parameter pack of the *exact* same
/// form.
/// @tparam use_functions
/// If true (default), will recursively wrap callbacks. If your policy
/// provides handling for functions, then you should set this to false.
/// @param func
/// Functor to be wrapped. Returns a function with wrapped arguments and
/// return type. If functor is a method pointer, it will return a function of
/// the form `Return ([const] Class* self, ...)`.
/// @return Wrapped function lambda.
/// N.B. Construct a `std::function<>` from this if you encounter inference
/// issues downstream of this method.
template <template <typename...> class wrap_arg_policy,
bool use_functions = true, typename Func = void>
auto WrapFunction(Func&& func) {
// TODO(eric.cousineau): Create an overload with `type_pack<Args...>` to
// handle overloads, to disambiguate when necessary.
return internal::wrap_function_impl<wrap_arg_policy, use_functions>::run(
internal::infer_function_info(std::forward<Func>(func)));
}
/// Default case for argument wrapping, with pure pass-through. Consider
/// inheriting from this for base cases.
/// N.B. `Wrapped` is not necessary, but is used for demonstration purposes.
template <typename T>
struct wrap_arg_default {
using Wrapped = T;
static Wrapped wrap(T arg) { return std::forward<T&&>(arg); }
static T unwrap(Wrapped arg_wrapped) {
return std::forward<Wrapped&&>(arg_wrapped);
}
// N.B. `T` rather than `T&&` is used as arguments here as it behaves well
// with primitive types, such as `int`.
};
/// Policy for explicitly wrapping functions for a given policy.
template <template <typename...> class wrap_arg_policy, typename Signature>
using wrap_arg_function = typename internal::wrap_function_impl<
wrap_arg_policy>::template wrap_arg<std::function<Signature>>;
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/jupyter.py | """
Provides support for using ipywidgets with the systems framework, and a number
of useful widget systems.
This is gui code; to test changes, please manually run
//bindings/pydrake/systems/jupyter_widgets_examples.ipynb.
"""
import asyncio
import sys
from warnings import warn
from IPython import get_ipython
# Note: The implementation below was inspired by
# https://github.com/Kirill888/jupyter-ui-poll , though I suspect it can be
# optimized.
#
# For reference,
# https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Asynchronous.html # noqa
# describes the problem but it only offers the solution of using separate
# threads for execution; a workflow that we do not wish to impose on users.
def process_ipywidget_events(num_events_to_process=1):
"""
Allows the kernel to process GUI events. This is required in order to
process ipywidget updates inside a simulation loop.
"""
shell = get_ipython()
# Ok to do nothing if running from console.
if shell is None or not hasattr(shell, 'kernel'):
return
kernel = shell.kernel
events = []
old_handler = kernel.shell_handlers['execute_request']
kernel.shell_handlers['execute_request'] = lambda *e: events.append(e)
current_parent = (kernel._parent_ident, kernel._parent_header)
for _ in range(num_events_to_process):
# Ensure stdout still happens in the same cell.
kernel.set_parent(*current_parent)
kernel.do_one_iteration()
kernel.set_parent(*current_parent)
kernel.shell_handlers['execute_request'] = old_handler
def _replay_events(shell, events):
kernel = shell.kernel
sys.stdout.flush()
sys.stderr.flush()
for stream, ident, parent in events:
kernel.set_parent(ident, parent)
kernel.execute_request(stream, ident, parent)
if len(events) > 0:
loop = asyncio.get_event_loop()
if loop.is_running():
loop.call_soon(lambda: _replay_events(shell, events))
else:
warn("One of your components is attempting to use pydrake's "
"process_ipywidget_events function. However, this IPython "
"kernel is not asyncio-based. This means the following:\n"
" (1) Once your block cell is done executing, future cells "
"will *not* execute, but it may appear like they are still "
"executing ([*]).\n"
" (2) Your Jupyter UI may break. If you find your UI to be "
"unresponsive, you may need to restart the UI itself.\n"
"To avoid this behavior, avoid requesting execution of "
"future cells before or during execution of this cell.")
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/wrap_pybind.h | /// @file
/// Defines convenience utilities to wrap pybind11 methods and classes.
#pragma once
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include "drake/bindings/pydrake/common/wrap_function.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/drake_copyable.h"
namespace drake {
namespace pydrake {
#ifndef DRAKE_DOXYGEN_CXX
namespace internal {
// Determines if a type will go through pybind11's generic caster. This
// implies that the type has been declared using `py::class_`, and can have
// a reference passed through. Otherwise, the type uses type-conversion:
// https://pybind11.readthedocs.io/en/stable/advanced/cast/index.html
template <typename T>
constexpr inline bool is_generic_pybind_v =
std::is_base_of_v<py::detail::type_caster_generic,
py::detail::make_caster<T>>;
template <typename T, typename = void>
struct wrap_ref_ptr : public wrap_arg_default<T> {};
template <typename T>
struct wrap_ref_ptr<T&, std::enable_if_t<is_generic_pybind_v<T>>> {
// NOLINTNEXTLINE[runtime/references]: Intentional.
static T* wrap(T& arg) { return &arg; }
static T& unwrap(T* arg_wrapped) { return *arg_wrapped; }
};
template <typename T, typename = void>
struct wrap_callback : public wrap_arg_default<T> {};
template <typename Signature>
struct wrap_callback<const std::function<Signature>&>
: public wrap_arg_function<wrap_ref_ptr, Signature> {};
template <typename Signature>
struct wrap_callback<std::function<Signature>>
: public wrap_callback<const std::function<Signature>&> {};
// Implements a `py::detail::type_caster<>` specialization used to convert
// types using a specific wrapping policy.
// @tparam Wrapper
// Struct which must provide `Type`, `WrappedType`, `unwrap`, `wrap`,
// `wrapped_name`, and `original_name`.
// Fails-fast at runtime if there is an attempt to pass by reference.
template <typename Wrapper>
struct type_caster_wrapped {
using Type = typename Wrapper::Type;
using WrappedType = typename Wrapper::WrappedType;
using WrappedTypeCaster = py::detail::type_caster<WrappedType>;
// Python to C++.
bool load(py::handle src, bool converter) {
WrappedTypeCaster caster;
if (!caster.load(src, converter)) {
return false;
}
value_ = Wrapper::unwrap(caster.operator WrappedType&());
loaded_ = true;
return true;
}
// See `pybind11/eigen.h`, `type_caster<>` implementations.
// N.B. Do not use `PYBIND11_TYPE_CASTER(...)` so we can avoid casting
// garbage values.
operator Type&() {
if (!loaded_) {
throw py::cast_error("Internal error: value not loaded?");
}
return value_;
}
template <typename T>
using cast_op_type = py::detail::movable_cast_op_type<T>;
static constexpr auto name = Wrapper::wrapped_name;
// C++ to Python.
template <typename TType>
static py::handle cast(
TType&& src, py::return_value_policy policy, py::handle parent) {
if (policy == py::return_value_policy::reference ||
policy == py::return_value_policy::reference_internal) {
// N.B. We must declare a local `static constexpr` here to prevent
// linking errors. This does not appear achievable with
// `constexpr char[]`, so we use `py::detail::descr`.
// See `pybind11/pybind11.h`, `cpp_function::initialize(...)` for an
// example.
static constexpr auto original_name = Wrapper::original_name;
throw py::cast_error(
std::string("Can only pass ") + original_name.text + " by value.");
}
return WrappedTypeCaster::cast(
Wrapper::wrap(std::forward<TType>(src)), policy, parent);
}
private:
bool loaded_{false};
Type value_;
};
} // namespace internal
#endif // DRAKE_DOXYGEN_CXX
/// Ensures that any `std::function<>` arguments are wrapped such that any `T&`
/// (which can infer for `T = const U`) is wrapped as `U*` (and conversely
/// unwrapped when returned).
/// Use this when you have a callback in C++ that has a lvalue reference (const
/// or mutable) to a C++ argument or return value.
/// Otherwise, `pybind11` may try and copy the object, will be bad if either
/// the type is a non-copyable or if you are trying to mutate the object; in
/// this case, the copy is mutated, but not the original you care about.
/// For more information, see: https://github.com/pybind/pybind11/issues/1241
template <typename Func>
auto WrapCallbacks(Func&& func) {
return WrapFunction<internal::wrap_callback, false>(std::forward<Func>(func));
}
/// Idempotent to pybind11's `def_readwrite()`, with the exception that the
/// setter is protected with keep_alive on a `member` variable that is a bare
/// pointer. Should not be used for unique_ptr members.
///
/// @tparam PyClass the python class.
/// @tparam Class the C++ class.
/// @tparam T type for the member we wish to apply keep alive semantics.
template <typename PyClass, typename Class, typename T>
void DefReadWriteKeepAlive(
PyClass* cls, const char* name, T Class::*member, const char* doc = "") {
auto getter = [member](const Class* obj) { return obj->*member; };
auto setter = [member](Class* obj, const T& value) { obj->*member = value; };
cls->def_property(name, // BR
py::cpp_function(getter),
py::cpp_function(setter,
// Keep alive, reference: `self` keeps `value` alive.
py::keep_alive<1, 2>()),
doc);
}
/// Idempotent to pybind11's `def_readonly()`, which works for unique_ptr
/// elements; the getter is protected with keep_alive on a `member` variable
/// that is a unique_ptr.
///
/// @tparam PyClass the python class.
/// @tparam Class the C++ class.
/// @tparam T type for the member we wish to apply keep alive semantics.
template <typename PyClass, typename Class, typename T>
void DefReadUniquePtr(PyClass* cls, const char* name,
const std::unique_ptr<T> Class::*member, const char* doc = "") {
auto getter = py::cpp_function(
[member](const Class* obj) { return (obj->*member).get(); },
py_rvp::reference_internal);
cls->def_property_readonly(name, getter, doc);
}
// Variant of DefReadUniquePtr() for copyable_unique_ptr.
template <typename PyClass, typename Class, typename T>
void DefReadUniquePtr(PyClass* cls, const char* name,
const copyable_unique_ptr<T> Class::*member, const char* doc = "") {
auto getter = py::cpp_function(
[member](const Class* obj) { return (obj->*member).get(); },
py_rvp::reference_internal);
cls->def_property_readonly(name, getter, doc);
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/eigen_pybind.h | #pragma once
#include <utility>
#include <Eigen/Dense>
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/eigen_types.h"
namespace drake {
namespace pydrake {
// TODO(eric.cousineau): Ensure that all C++ mutator call sites use `EigenPtr`.
/**
Provides a mutable Ref<> for a pointer.
Meant to be used for decorating methods passed to `pybind11` (e.g. virtual
function dispatch).
*/
template <typename Derived>
auto ToEigenRef(Eigen::VectorBlock<Derived>* derived) {
return Eigen::Ref<Derived>(*derived);
}
/** Converts a raw array to a numpy array. */
template <typename T>
py::object ToArray(T* ptr, int size, py::tuple shape,
py::return_value_policy policy = py_rvp::reference,
py::handle parent = py::handle()) {
// Create flat array to be reshaped in numpy.
using Vector = VectorX<T>;
Eigen::Map<Vector> data(ptr, size);
return py::cast(Eigen::Ref<Vector>(data), policy, parent)
.attr("reshape")(shape);
}
/** Converts a raw array to a numpy array (`const` variant). */
template <typename T>
py::object ToArray(const T* ptr, int size, py::tuple shape,
py::return_value_policy policy = py_rvp::reference,
py::handle parent = py::handle()) {
// Create flat array to be reshaped in numpy.
using Vector = const VectorX<T>;
Eigen::Map<Vector> data(ptr, size);
return py::cast(Eigen::Ref<Vector>(data), policy, parent)
.attr("reshape")(shape);
}
/**
Wraps a overload instance method to reshape the output to be the same as a
given input argument. The input should be the first and only argument to
trigger reshaping.
This preserves the original docstrings so that they still indicate the shapes
of the input and output arrays.
Example:
@code
cls // BR
.def("multiply", [](const Class& self, const Class& other) { ... })
.def("multiply", [](const Class& self, const Vector3<T>& p) { ... })
.def("multiply", [](const Class& self, const Matrix3X<T>& plist) { ... });
cls.attr("multiply") = WrapToMatchInputShape(cls.attr("multiply"));
@endcode
@sa @ref PydrakeReturnVectorsOrMatrices
*/
inline py::object WrapToMatchInputShape(py::handle func) {
py::handle wrap =
py::module::import("pydrake.common").attr("_wrap_to_match_input_shape");
return wrap(func);
}
} // namespace pydrake
} // namespace drake
namespace pybind11 {
namespace detail {
/**
Provides pybind11 `type_caster`s for drake::EigenPtr.
Uses `type_caster<Eigen::Ref>` internally to avoid code duplication.
See http://pybind11.readthedocs.io/en/stable/advanced/cast/custom.html for
more details on custom type casters.
TODO(eric.cousineau): Place all logic inside of `drake` namespace once our
pybind11 fork includes PYBIND11_TYPE_CASTER macro w/ fully qualified symbols.
*/
template <typename T>
struct type_caster<drake::EigenPtr<T>> {
using PtrType = drake::EigenPtr<T>;
using RefType = Eigen::Ref<T>;
using InnerCaster = type_caster<RefType>;
public:
PYBIND11_TYPE_CASTER(PtrType, _("Optional[") + InnerCaster::name + _("]"));
bool load(handle src, bool convert) {
value = PtrType(nullptr);
if (src.ptr() == Py_None) {
return true;
}
bool success = inner_caster.load(src, convert);
if (success) {
RefType& ref = inner_caster;
value = PtrType(&ref);
}
return success;
}
static handle cast(PtrType src, return_value_policy policy, handle parent) {
if (src == nullptr) {
return Py_None;
} else {
RefType ref = *src;
return InnerCaster::cast(ref, policy, parent);
}
}
private:
InnerCaster inner_caster;
};
} // namespace detail
} // namespace pybind11
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/eigen_geometry_py.cc | #include <cmath>
#include <stdexcept>
#include "drake/bindings/pydrake/common/cpp_template_pybind.h"
#include "drake/bindings/pydrake/common/default_scalars_pybind.h"
#include "drake/bindings/pydrake/common/eigen_pybind.h"
#include "drake/bindings/pydrake/common/type_pack.h"
#include "drake/bindings/pydrake/common/value_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/drake_assertion_error.h"
#include "drake/common/drake_throw.h"
#include "drake/common/eigen_types.h"
namespace drake {
namespace pydrake {
namespace internal {
namespace {
using std::abs;
// TODO(eric.cousineau): Remove checks (see #8960).
// N.B. This could potentially interfere with another library's bindings of
// Eigen types. If/when this happens, this should be addressed for both double
// and AutoDiff types, most likely using `py::module_local()`.
// N.B. Use a loose tolerance, so that we don't have to be super strict with
// C++.
const double kCheckTolerance = 1e-5;
constexpr char kCastDoc[] = "Cast to desired scalar type.";
using symbolic::Expression;
template <typename T>
void CheckRotMat(const Matrix3<T>& R) {
// See `ExpectRotMat`.
const T identity_error =
(R * R.transpose() - Matrix3<T>::Identity()).array().abs().maxCoeff();
if (identity_error >= kCheckTolerance) {
throw std::logic_error("Rotation matrix is not orthonormal");
}
const T det_error = abs(R.determinant() - 1);
if (det_error >= kCheckTolerance) {
throw std::logic_error("Rotation matrix violates right-hand rule");
}
}
template <typename T>
void CheckSe3(const Isometry3<T>& X) {
CheckRotMat<T>(X.linear());
Eigen::Matrix<T, 1, 4> bottom_expected;
bottom_expected << 0, 0, 0, 1;
const T bottom_error =
(X.matrix().bottomRows(1) - bottom_expected).array().abs().maxCoeff();
if (bottom_error >= kCheckTolerance) {
throw std::logic_error("Homogeneous matrix is improperly scaled.");
}
}
template <typename T>
void CheckQuaternion(const Eigen::Quaternion<T>& q) {
const T norm_error = abs(q.coeffs().norm() - 1);
if (norm_error >= kCheckTolerance) {
throw std::logic_error("Quaternion is not normalized");
}
}
template <typename T>
void CheckAngleAxis(const Eigen::AngleAxis<T>& value) {
const T norm_error = abs(value.axis().norm() - 1);
if (norm_error >= kCheckTolerance) {
throw std::logic_error("Axis is not normalized");
}
}
// N.B. The following overloads are meant to disable symbolic checks, which are
// not easily achievable for non-numeric values. These can be removed once the
// checks are removed in their entirety (#8960).
void CheckRotMat(const Matrix3<Expression>&) {}
void CheckSe3(const Isometry3<Expression>&) {}
void CheckQuaternion(const Eigen::Quaternion<Expression>&) {}
void CheckAngleAxis(const Eigen::AngleAxis<Expression>&) {}
template <typename T>
void DoScalarDependentDefinitions(py::module m, T) {
// Do not return references to matrices (e.g. `Eigen::Ref<>`) so that we have
// tighter control over validation.
py::tuple param = GetPyParam<T>();
// Isometry3d.
// @note `linear` implies rotation, and `affine` implies translation.
{
using Class = Isometry3<T>;
auto cls = DefineTemplateClassWithDefault<Class>(m, "Isometry3", param,
"Provides bindings of Eigen::Isometry3<> that only admit SE(3) "
"(no reflections).");
cls // BR
.def(py::init([]() { return Class::Identity(); }))
.def_static("Identity", []() { return Class::Identity(); })
.def(py::init([](const Matrix4<T>& matrix) {
Class out(matrix);
CheckSe3(out);
return out;
}),
py::arg("matrix"))
.def(py::init(
[](const Matrix3<T>& rotation, const Vector3<T>& translation) {
CheckRotMat(rotation);
Class out = Class::Identity();
out.linear() = rotation;
out.translation() = translation;
return out;
}),
py::arg("rotation"), py::arg("translation"))
.def(py::init([](const Eigen::Quaternion<T>& q,
const Vector3<T>& translation) {
CheckQuaternion(q);
Class out = Class::Identity();
out.linear() = q.toRotationMatrix();
out.translation() = translation;
return out;
}),
py::arg("quaternion"), py::arg("translation"))
.def(py::init([](const Class& other) {
CheckSe3(other);
return other;
}),
py::arg("other"))
.def("matrix",
[](const Class* self) -> Matrix4<T> { return self->matrix(); })
.def("set_matrix",
[](Class* self, const Matrix4<T>& matrix) {
Class update(matrix);
CheckSe3(update);
*self = update;
})
.def("translation",
[](const Class* self) -> Vector3<T> { return self->translation(); })
.def("set_translation",
[](Class* self, const Vector3<T>& translation) {
self->translation() = translation;
})
.def("rotation",
[](const Class* self) -> Matrix3<T> { return self->linear(); })
.def("set_rotation",
[](Class* self, const Matrix3<T>& rotation) {
CheckRotMat(rotation);
self->linear() = rotation;
})
.def("quaternion",
[](const Class* self) {
return Eigen::Quaternion<T>(self->linear());
})
.def("set_quaternion",
[](Class* self, const Eigen::Quaternion<T>& q) {
CheckQuaternion(q);
self->linear() = q.toRotationMatrix();
})
.def("__str__",
[](py::object self) { return py::str(self.attr("matrix")()); })
.def(
"multiply",
[](const Class& self, const Class& other) { return self * other; },
py::arg("other"), "RigidTransform multiplication")
.def(
"multiply",
[](const Class& self, const Vector3<T>& position) {
return self * position;
},
py::arg("position"), "Position vector multiplication")
.def(
"multiply",
[](const Class& self, const Matrix3X<T>& position) {
return self * position;
},
py::arg("position"), "Position vector list multiplication")
.def("inverse", [](const Class* self) { return self->inverse(); })
.def(py::pickle([](const Class& self) { return self.matrix(); },
[](const Matrix4<T>& matrix) { return Class(matrix); }));
cls.attr("multiply") = WrapToMatchInputShape(cls.attr("multiply"));
cls.attr("__matmul__") = cls.attr("multiply");
py::implicitly_convertible<Matrix4<T>, Class>();
DefCopyAndDeepCopy(&cls);
DefCast<T>(&cls, kCastDoc);
AddValueInstantiation<Isometry3<T>>(m);
}
// Quaternion.
// Since the Eigen API for Quaternion is insufficiently explicit, we will
// deviate some from the API to maintain clarity.
// TODO(eric.cousineau): Should this not be restricted to a unit quaternion?
{
using Class = Eigen::Quaternion<T>;
auto cls = DefineTemplateClassWithDefault<Class>(m, "Quaternion", param,
"Provides a unit quaternion binding of Eigen::Quaternion<>.");
py::object py_class_obj = cls;
cls // BR
.def(py::init([]() { return Class::Identity(); }))
.def_static("Identity", []() { return Class::Identity(); })
.def(py::init([](const Vector4<T>& wxyz) {
Class out(wxyz(0), wxyz(1), wxyz(2), wxyz(3));
CheckQuaternion(out);
return out;
}),
py::arg("wxyz"))
.def(py::init([](T w, T x, T y, T z) {
Class out(w, x, y, z);
CheckQuaternion(out);
return out;
}),
py::arg("w"), py::arg("x"), py::arg("y"), py::arg("z"))
.def(py::init([](const Matrix3<T>& rotation) {
Class out(rotation);
CheckQuaternion(out);
return out;
}),
py::arg("rotation"))
.def(py::init([](const Class& other) {
CheckQuaternion(other);
return other;
}),
py::arg("other"))
.def("w", [](const Class* self) { return self->w(); })
.def("x", [](const Class* self) { return self->x(); })
.def("y", [](const Class* self) { return self->y(); })
.def("z", [](const Class* self) { return self->z(); })
.def("xyz", [](const Class* self) { return Vector3<T>(self->vec()); })
.def("wxyz",
[](Class* self) {
Vector4<T> wxyz;
wxyz << self->w(), self->vec();
return wxyz;
})
.def(
"set_wxyz",
[](Class* self, const Vector4<T>& wxyz) {
Class update;
update.w() = wxyz(0);
update.vec() = wxyz.tail(3);
CheckQuaternion(update);
*self = update;
},
py::arg("wxyz"))
.def(
"set_wxyz",
[](Class* self, T w, T x, T y, T z) {
Class update(w, x, y, z);
CheckQuaternion(update);
*self = update;
},
py::arg("w"), py::arg("x"), py::arg("y"), py::arg("z"))
.def("rotation",
[](const Class* self) { return self->toRotationMatrix(); })
.def("set_rotation",
[](Class* self, const Matrix3<T>& rotation) {
Class update(rotation);
CheckQuaternion(update);
*self = update;
})
.def("__str__",
[py_class_obj](const Class* self) {
return py::str("{}(w={}, x={}, y={}, z={})")
.format(internal::PrettyClassName(py_class_obj), self->w(),
self->x(), self->y(), self->z());
})
.def(
"multiply",
[](const Class& self, const Class& other) { return self * other; },
"Quaternion multiplication")
.def(
"slerp",
[](const Class& self, double t, const Class& other) {
return self.slerp(t, other);
},
py::arg("t"), py::arg("other"),
"The spherical linear interpolation between the two quaternions "
"(self and other) at the parameter t in [0;1].");
auto multiply_vector = [](const Class& self, const Vector3<T>& vector) {
return self * vector;
};
auto multiply_vector_list = [](const Class& self,
const Matrix3X<T>& vector) {
Matrix3X<T> out(vector.rows(), vector.cols());
for (int i = 0; i < vector.cols(); ++i) {
out.col(i) = self * vector.col(i);
}
return out;
};
cls // BR
.def("multiply", multiply_vector, py::arg("vector"),
"Multiplication by a vector expressed in a frame")
.def("multiply", multiply_vector_list, py::arg("vector"),
"Multiplication by a list of vectors expressed in the same frame")
.def("inverse", [](const Class* self) { return self->inverse(); })
.def("conjugate", [](const Class* self) { return self->conjugate(); })
.def(py::pickle(
// Leverage Python API so we can easily use `wxyz` form.
[](py::object self) { return self.attr("wxyz")(); },
[py_class_obj](py::object wxyz) -> Class {
return py_class_obj(wxyz).cast<Class>();
}));
cls.attr("multiply") = WrapToMatchInputShape(cls.attr("multiply"));
cls.attr("__matmul__") = cls.attr("multiply");
DefCopyAndDeepCopy(&cls);
DefCast<T>(&cls, kCastDoc);
}
// Angle-axis.
{
using Class = Eigen::AngleAxis<T>;
auto cls = DefineTemplateClassWithDefault<Class>(
m, "AngleAxis", param, "Bindings for Eigen::AngleAxis<>.");
py::object py_class_obj = cls;
cls // BR
.def(py::init([]() { return Class::Identity(); }))
.def_static("Identity", []() { return Class::Identity(); })
.def(py::init([](const T& angle, const Vector3<T>& axis) {
Class out(angle, axis);
CheckAngleAxis(out);
return out;
}),
py::arg("angle"), py::arg("axis"))
.def(py::init([](const Eigen::Quaternion<T>& q) {
Class out(q);
CheckAngleAxis(out);
return out;
}),
py::arg("quaternion"))
.def(py::init([](const Matrix3<T>& rotation) {
Class out(rotation);
CheckAngleAxis(out);
return out;
}),
py::arg("rotation"))
.def(py::init([](const Class& other) {
CheckAngleAxis(other);
return other;
}),
py::arg("other"))
.def("angle", [](const Class* self) { return self->angle(); })
.def("axis", [](const Class* self) { return self->axis(); })
.def(
"set_angle",
[](Class* self, const T& angle) {
// N.B. Since `axis` should already be valid, do not need to
// check.
self->angle() = angle;
},
py::arg("angle"))
.def(
"set_axis",
[](Class* self, const Vector3<T>& axis) {
Class update(self->angle(), axis);
CheckAngleAxis(update);
*self = update;
},
py::arg("axis"))
.def("rotation",
[](const Class* self) { return self->toRotationMatrix(); })
.def(
"set_rotation",
[](Class* self, const Matrix3<T>& rotation) {
Class update(rotation);
CheckAngleAxis(update);
*self = update;
},
py::arg("rotation"))
.def("quaternion",
[](const Class* self) { return Eigen::Quaternion<T>(*self); })
.def(
"set_quaternion",
[](Class* self, const Eigen::Quaternion<T>& q) {
CheckQuaternion(q);
Class update(q);
CheckAngleAxis(update);
*self = update;
},
py::arg("q"))
.def("__str__",
[py_class_obj](const Class* self) {
return py::str("{}(angle={}, axis={})")
.format(internal::PrettyClassName(py_class_obj),
self->angle(), self->axis());
})
.def(
"multiply",
[](const Class& self, const Class& other) { return self * other; },
py::arg("other"))
.def("inverse", [](const Class* self) { return self->inverse(); })
.def(py::pickle(
[](const Class& self) {
return py::make_tuple(self.angle(), self.axis());
},
[](py::tuple t) {
DRAKE_THROW_UNLESS(t.size() == 2);
return Class(t[0].cast<T>(), t[1].cast<Vector3<T>>());
}));
// N.B. This class does not support multiplication with vectors, so we do
// not use `WrapToMatchInputShape` here.
cls.attr("__matmul__") = cls.attr("multiply");
DefCopyAndDeepCopy(&cls);
DefCast<T>(&cls, kCastDoc);
}
}
} // namespace
void DefineModuleEigenGeometry(py::module m) {
m.doc() = "Bindings for Eigen geometric types.";
type_visit([m](auto dummy) { DoScalarDependentDefinitions(m, dummy); },
CommonScalarPack{});
ExecuteExtraPythonCode(m);
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/text_logging_pybind.cc | #ifdef HAVE_SPDLOG
#include "drake/bindings/pydrake/common/text_logging_pybind.h"
#include <atomic>
#include <cstdlib>
#include <memory>
// clang-format off to disable clang-format-includes
// N.B. text-logging.h must be included before spdlog headers
// to avoid "SPDLOG_ACTIVE_LEVEL" redefined warning (#13771).
#include "drake/common/text_logging.h"
// clang-format on
#include <spdlog/sinks/base_sink.h>
#include <spdlog/sinks/dist_sink.h>
#include <spdlog/sinks/stdout_sinks.h>
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/drake_assert.h"
#endif
namespace drake {
namespace pydrake {
namespace internal {
#ifdef HAVE_SPDLOG
namespace {
class pylogging_sink final
// We use null_mutex below because we'll use the GIL as our *only* mutex.
// This is critically important to avoid deadlocks by lock order inversion.
: public spdlog::sinks::base_sink<spdlog::details::null_mutex> {
public:
pylogging_sink() {
// Add a Python logging.Logger to be used by Drake.
py::object logging = py::module::import("logging");
py::object logger = logging.attr("getLogger")(name_);
// Annotate that the logger is alive (fed by spdlog).
py::setattr(logger, "_tied_to_spdlog", py::cast(true));
// Match the C++ default level.
logger.attr("setLevel")(to_py_level(drake::log()->level()));
// Memoize the member functions we need to call.
is_enabled_for_ = logger.attr("isEnabledFor");
make_record_ = logger.attr("makeRecord");
handle_ = logger.attr("handle");
}
protected:
void sink_it_(const spdlog::details::log_msg& msg) final {
py::gil_scoped_acquire acquire;
// Bail out quickly in case this log level is disabled.
const int level = to_py_level(msg.level);
if (!is_enabled_for_(level).cast<bool>()) {
return;
}
// Ensure that basicConfig happens at least once prior to posting and log
// message. It's safe to call basicConfig more than once.
if (!is_configured_.load()) {
py::module::import("logging").attr("basicConfig")();
is_configured_.store(true);
}
// NOLINTNEXTLINE(build/namespaces) This is how pybind11 wants it.
using namespace pybind11::literals;
// Construct the LogRecord.
// https://docs.python.org/3/library/logging.html#logrecord-objects
py::object record = make_record_( // BR
"name"_a = name_, // BR
"level"_a = level, // BR
"fn"_a = msg.source.filename, // BR
"lno"_a = msg.source.line, // BR
"func"_a = msg.source.funcname, // BR
"msg"_a = std::string(msg.payload.begin(), msg.payload.end()), // BR
"args"_a = py::list(), // BR
"exc_info"_a = py::none());
py::setattr(record, "thread", py::cast(msg.thread_id));
// We don't pass msg.time along into the record time because we'd need to
// fix up record.created, record.msecs, and record.relativeCreated, and we'd
// still be brittle with respect to future changes to the record class's
// internal bookkeeping. Instead, we'll allow the record's own time from its
// constructor to survive.
// Publish the log record.
handle_(record);
}
void flush_() final {}
private:
// https://docs.python.org/3/library/logging.html#logging-levels
static int to_py_level(spdlog::level::level_enum level) {
using Enum = spdlog::level::level_enum;
switch (level) {
case Enum::trace:
return 5;
case Enum::debug:
return 10;
case Enum::info:
return 20;
case Enum::warn:
return 30;
case Enum::err:
return 40;
case Enum::critical:
return 50;
case Enum::off:
break;
#if SPDLOG_VERSION >= 10600
case Enum::n_levels:
break;
#endif
}
DRAKE_UNREACHABLE();
}
std::atomic<bool> is_configured_{false};
py::object name_{py::cast("drake")};
py::object is_enabled_for_;
py::object make_record_;
py::object handle_;
};
constexpr char kDisableEnv[] = "DRAKE_PYTHON_LOGGING";
constexpr char kDisableValue[] = "0";
bool ShouldDisableRedirect() {
const char* const value = std::getenv(kDisableEnv);
if (value != nullptr && std::string(value) == kDisableValue) {
return true;
}
return false;
}
} // namespace
void MaybeRedirectPythonLogging() {
if (ShouldDisableRedirect()) {
drake::log()->debug("Will not redirect C++ logging to Python ({}={})",
kDisableEnv, kDisableValue);
return;
}
// Inspect the spdlog configuration to check that it exactly matches how
// drake/common/text_logging.cc configures itself by default. If the spdlog
// configuration we observe here differs in any way, then we'll assume that
// a user has configured it to their taste already and we won't change it.
std::vector<std::shared_ptr<spdlog::sinks::sink> >& root_sinks =
drake::log()->sinks();
if (root_sinks.size() != 1) {
drake::log()->debug(
"Will not redirect C++ logging to Python (num root sinks != 1)");
return;
}
spdlog::sinks::sink* const root_sink = root_sinks.front().get();
auto* dist_sink = dynamic_cast<spdlog::sinks::dist_sink_mt*>(root_sink);
if (dist_sink == nullptr) {
drake::log()->debug(
"Will not redirect C++ logging to Python (wrong root sink)");
return;
}
std::vector<std::shared_ptr<spdlog::sinks::sink> >& dist_sinks =
dist_sink->sinks();
if (dist_sinks.size() != 1) {
drake::log()->debug(
"Will not redirect C++ logging to Python (num sinks != 1)");
return;
}
spdlog::sinks::sink* const only_sink = dist_sinks.front().get();
if (dynamic_cast<spdlog::sinks::stderr_sink_mt*>(only_sink) == nullptr) {
drake::log()->debug(
"Will not redirect C++ logging to Python (not a stderr sink)");
return;
}
// If we reach this point, then we've matched text_logging.cc exactly.
// Add the python sink. Note that we must add it to the root logger (not the
// dist_sink) because the dist_sink takes a mutex on every log, which suffers
// from lock priority order inversion once the GIL gets involved.
drake::log()->sinks().push_back(std::make_shared<pylogging_sink>());
// Remove the stderr sink.
dist_sink->set_sinks({});
drake::log()->trace("Successfully redirected C++ logs to Python");
}
void UseNativeCppLogging() {
// If the configurtion exactly matches what MaybeRedirectPythonLogging did,
// then we should undo that and return. If the sink configuration already
// exactly matches how drake/common/text_logging.cc configures itself by
// default, then we should return successfully as a no-op. Otherwise, we
// should throw an error.
constexpr char error_message[] =
"Switching to use_native_cpp_logging is not possible due to an "
"unexpected native logging configuration already in place";
// After MaybeRedirectPythonLogging has happened, we expect two sinks. In case
// it was opted-out of using the environment variable, we expect one sink.
std::vector<std::shared_ptr<spdlog::sinks::sink> >& root_sinks =
drake::log()->sinks();
if (!(root_sinks.size() == 2 || root_sinks.size() == 1)) {
throw std::runtime_error(error_message);
}
// We expect first sink should still be the text_logging.cc default dist sink,
// no matter whether MaybeRedirectPythonLogging has been called.
spdlog::sinks::sink* const root_sink = root_sinks.front().get();
auto* dist_sink = dynamic_cast<spdlog::sinks::dist_sink_mt*>(root_sink);
if (dist_sink == nullptr) {
throw std::runtime_error(error_message);
}
std::vector<std::shared_ptr<spdlog::sinks::sink> >& dist_sinks =
dist_sink->sinks();
// If MaybeRedirectPythonLogging has been opted-out, then we expect the dist
// sink should still have (only) the stderr sink.
if (root_sinks.size() == 1) {
if (!(dist_sinks.size() == 1 &&
dynamic_cast<spdlog::sinks::stderr_sink_mt*>(
dist_sinks.front().get()))) {
throw std::runtime_error(error_message);
}
// If we reach this point, then we've matched text_logging.cc exactly.
// There's nothing more we need to do.
return;
}
// MaybeRedirectPythonLogging is in effect, so we expect the second sink to be
// the pylogging_sink and the dist sink to be empty.
if (!(dist_sinks.empty() &&
dynamic_cast<const pylogging_sink*>(root_sinks.back().get()))) {
throw std::runtime_error(error_message);
}
// Roll back the MaybeRedirectPythonLogging changes.
dist_sink->add_sink(std::make_shared<spdlog::sinks::stderr_sink_mt>());
root_sinks.resize(1);
drake::log()->trace("Successfully routed C++ logs back to stderr directly");
}
#else
void MaybeRedirectPythonLogging() {}
void UseNativeCppLogging() {}
#endif
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/text_logging_pybind.h | #pragma once
namespace drake {
namespace pydrake {
namespace internal {
/* If possible, redirects Drake's C++ logs to Python's `logging` module. This
function is not thread-safe; no other threads should be running when it is
called. */
void MaybeRedirectPythonLogging();
/* Implements pydrake.common.use_native_cpp_logging(). This function is not
thread-safe; no other threads should be running when it is called. */
void UseNativeCppLogging();
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/cpp_param_pybind.cc | #include "drake/bindings/pydrake/common/cpp_param_pybind.h"
#include "pybind11/eval.h"
namespace drake {
namespace pydrake {
// N.B. py::handle::inc_ref() and ::dec_ref() use the Py_X* variants, implying
// that they are safe to use on nullptr, thus we do not need any
// `ptr != nullptr` checks.
Object::Object(::PyObject* ptr) : ptr_(ptr) {
inc_ref();
}
Object::~Object() {
dec_ref();
}
Object::Object(const Object& other) : Object(other.ptr()) {}
Object::Object(Object&& other) {
ptr_ = other.ptr_;
other.ptr_ = nullptr;
}
Object& Object::operator=(const Object& other) {
dec_ref();
ptr_ = other.ptr();
inc_ref();
return *this;
}
Object& Object::operator=(Object&& other) {
dec_ref();
ptr_ = other.ptr_;
other.ptr_ = nullptr;
return *this;
}
Object Object::Clone() const {
py::object py_copy = py::module::import("copy").attr("deepcopy");
py::object copied = py_copy(to_pyobject<py::object>());
return from_pyobject(copied);
}
void Object::inc_ref() {
py::handle(ptr_).inc_ref();
}
void Object::dec_ref() {
py::handle(ptr_).dec_ref();
}
namespace internal {
namespace {
// Creates a Python object that should uniquely hash for a primitive C++
// type.
py::object GetPyHash(const std::type_info& tinfo) {
return py::make_tuple("cpp_type", tinfo.hash_code());
}
// Registers C++ type.
template <typename T>
void RegisterType(
py::module m, py::object param_aliases, const std::string& canonical_str) {
// Create an object that is a unique hash.
py::object canonical = py::eval(canonical_str, m.attr("__dict__"));
py::list aliases(1);
aliases[0] = GetPyHash(typeid(T));
param_aliases.attr("register")(canonical, aliases);
}
// Registers common C++ types.
void RegisterCommon(py::module m, py::object param_aliases) {
// Make mappings for C++ RTTI to Python types.
// Unfortunately, this is hard to obtain from `pybind11`.
RegisterType<bool>(m, param_aliases, "bool");
RegisterType<std::string>(m, param_aliases, "str");
RegisterType<double>(m, param_aliases, "float");
RegisterType<float>(m, param_aliases, "np.float32");
RegisterType<int>(m, param_aliases, "int");
RegisterType<int16_t>(m, param_aliases, "np.int16");
RegisterType<int64_t>(m, param_aliases, "np.int64");
RegisterType<uint8_t>(m, param_aliases, "np.uint8");
RegisterType<uint16_t>(m, param_aliases, "np.uint16");
RegisterType<uint32_t>(m, param_aliases, "np.uint32");
RegisterType<uint64_t>(m, param_aliases, "np.uint64");
// For supporting generic Python types.
RegisterType<Object>(m, param_aliases, "object");
}
} // namespace
py::object GetParamAliases() {
py::module m = py::module::import("pydrake.common.cpp_param");
py::object param_aliases = m.attr("_param_aliases");
const char registered_check[] = "_register_common_cpp";
if (!py::hasattr(m, registered_check)) {
RegisterCommon(m, param_aliases);
m.attr(registered_check) = true;
}
return param_aliases;
}
py::object GetPyParamScalarImpl(const std::type_info& tinfo) {
py::object param_aliases = GetParamAliases();
py::object py_hash = GetPyHash(tinfo);
if (param_aliases.attr("is_aliased")(py_hash).cast<bool>()) {
// If it's an alias, return the canonical type.
return param_aliases.attr("get_canonical")(py_hash);
} else {
// This type is not aliased. Get the pybind-registered type,
// erroring out if it's not registered.
// WARNING: Internal API :(
auto* info = py::detail::get_type_info(tinfo);
if (!info) {
// TODO(eric.cousineau): Use NiceTypeName::Canonicalize(...Demangle(...))
// once simpler dependencies are used (or something else is used to
// justify linking in `libdrake.so`).
const std::string name = tinfo.name();
throw std::runtime_error("C++ type is not registered in pybind: " + name);
}
py::handle h(reinterpret_cast<PyObject*>(info->type));
return py::reinterpret_borrow<py::object>(h);
}
}
} // namespace internal
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/serialize_pybind.h | #pragma once
#include <climits>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#include <fmt/format.h>
#include "drake/bindings/pydrake/common/cpp_template_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/common/eigen_types.h"
namespace drake {
namespace pydrake {
namespace internal {
// Helper for DefAttributesUsingSerialize.
template <typename PyClass, typename Docs>
class DefAttributesArchive {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DefAttributesArchive)
using CxxClass = typename PyClass::type;
// @param ppy_class A pointer to the `py::class_` to add the properties to.
// @param prototype A pointer to the instance that will be visited.
// @param docs A pointer to the mkdoc struct for this ppy_class; can be null
// iff `Docs` is `void`, in which case docstrings will not be added.
DefAttributesArchive(
PyClass* ppy_class, CxxClass* prototype, const Docs* cls_docs)
: ppy_class_(ppy_class), prototype_(prototype), cls_docs_(cls_docs) {
DRAKE_DEMAND(ppy_class != nullptr);
DRAKE_DEMAND(prototype != nullptr);
DRAKE_DEMAND((std::is_same_v<Docs, void>) == (cls_docs == nullptr));
}
// Creates a class property for one instance field, akin to def_readwrite
// but using `nvp` created by the CxxClass's Serialize function to specify
// the field to be bound.
template <typename NameValuePair>
void Visit(const NameValuePair& nvp) {
// In the prototype CxxClass instance, we're visiting the field named `name`
// which stored at address `prototype_value` which sits at `offset` bytes
// inside of the CxxClass.
const char* const name = nvp.name();
using T = typename NameValuePair::value_type;
const T* const prototype_value = nvp.value();
const int offset = CalcClassOffset(prototype_value);
// Define property functions to get and set this particular field.
py::cpp_function getter(
[offset](const CxxClass& self) -> const T& {
const T* const field_in_self = reinterpret_cast<const T*>(
reinterpret_cast<const char*>(&self) + offset);
return *field_in_self;
},
py::is_method(*ppy_class_));
py::cpp_function setter(
[offset](CxxClass& self, const T& value) {
T* const field_in_self =
reinterpret_cast<T*>(reinterpret_cast<char*>(&self) + offset);
*field_in_self = value;
},
py::is_method(*ppy_class_));
// Fetch the docstring (or the empty string, if we aren't using docstrings).
const char* doc = "";
if constexpr (!std::is_same_v<Docs, void>) {
bool matched = false;
for (const auto& member : cls_docs_->Serialize__fields()) {
if (member.first == name) {
matched = true;
doc = member.second;
break;
}
}
if (!matched) {
throw std::runtime_error(fmt::format("Missing docstring for {}", name));
}
}
// Add the binding.
ppy_class_->def_property(
name, getter, setter, doc, py::return_value_policy::reference_internal);
// Remember the field's name and type for later use by Finished().
auto field = py::module::import("types").attr("SimpleNamespace")();
py::setattr(field, "name", py::str(name));
py::setattr(field, "type", CalcSchemaType(prototype_value));
fields_.append(field);
}
// To be called after Serialize() is complete; binds any members that are
// scoped to the entire struct (rather than one field at a time).
void Finished() {
ppy_class_->def_property_readonly_static("__fields__",
[fields_tuple = py::tuple(fields_)](py::object /* self */) { // BR
return fields_tuple;
});
}
private:
// Returns the offset (in bytes) of `address` within our `prototype_` object.
// Fails if the address does not fall within the `prototype_` object.
int CalcClassOffset(const void* address) {
static_assert(sizeof(CxxClass) < INT_MAX);
const char* begin = reinterpret_cast<const char*>(prototype_);
const char* end = begin + sizeof(CxxClass);
DRAKE_DEMAND(address >= begin);
DRAKE_DEMAND(address < end);
return reinterpret_cast<const char*>(address) - begin;
}
// Returns the python type annotation corresponding to the given T.
//
// Our goal here is to align with what pybind11::type_caster produces when we
// bind this struct's C++ member fields as Python attributes, e.g., for a C++
// type `int16_t` we'll return the Python type `int` not `np.int16`. For any
// compound types (list, dict, Union, etc.) we'll use Python's conventional
// generic types (either the builtins or via `typing`) but via the cpp_param
// logic to ensure that alias types are always canonicalized.
//
// This logic is similar to GetPyParam<T> (in cpp_param_pybind.h) but with
// the important difference that in our case the primitive types follow the
// type_caster<> rules (C++ int16_t => Python int) whereas GetPyParam uses
// the numpy sizes (C++ int16_t => Python np.int16). For the purposes of
// DefAttributesUsingSerialize we want the return type of property getters
// (which use the type_caster<>) to match the schema type.
//
// Note that the argument pointer is ignored (can be nullptr).
// Note that this template function is specialized below for container types.
//
// @tparam T the C++ type for which we'll return the Python type.
template <typename T>
static py::object CalcSchemaType(const T*) {
// Pybind11 doesn't support type::of<> for primitive types, so we must
// match them manually. See https://github.com/pybind/pybind11/issues/2486.
if constexpr (std::is_same_v<T, bool>) {
return py::type::of(py::bool_());
} else if constexpr (std::is_integral_v<T>) {
return py::type::of(py::int_());
} else if constexpr (std::is_floating_point_v<T>) {
return py::type::of(py::float_());
} else if constexpr (std::is_same_v<T, std::string>) {
return py::type::of(py::str());
} else if constexpr (is_eigen_type<T>::value) {
// TODO(jwnimmer-tri) Perhaps we can use numpy.typing here some day?
return py::module::import("numpy").attr("ndarray");
} else {
// Anything that remains should be a registered C++ type.
constexpr bool is_registered_type =
std::is_base_of_v<py::detail::type_caster_generic,
py::detail::make_caster<T>>;
if constexpr (is_registered_type) {
return py::type::of<T>();
} else {
return CannotIdentifySchemaType<T>();
}
}
}
// Partial specialization for List.
template <typename U, typename A>
static py::object CalcSchemaType(const std::vector<U, A>*) {
auto u_type = CalcSchemaType(static_cast<U*>(nullptr));
return GetTemplateClass("List")[u_type];
}
// Partial specialization for Dict.
template <typename U, typename V, typename C, typename A>
static py::object CalcSchemaType(const std::map<U, V, C, A>*) {
auto u_type = CalcSchemaType(static_cast<U*>(nullptr));
auto v_type = CalcSchemaType(static_cast<V*>(nullptr));
auto inner_types = py::make_tuple(u_type, v_type);
return GetTemplateClass("Dict")[inner_types];
}
// Partial specialization for Optional.
template <typename U>
static py::object CalcSchemaType(const std::optional<U>*) {
auto u_type = CalcSchemaType(static_cast<U*>(nullptr));
return GetTemplateClass("Optional")[u_type];
}
// Partial specialization for Union.
template <typename... Types>
static py::object CalcSchemaType(const std::variant<Types...>*) {
auto inner_types = py::make_tuple( // BR
CalcSchemaType(static_cast<Types*>(nullptr))...);
return GetTemplateClass("Union")[inner_types];
}
// Returns the cpp_param template class for the given name (e.g., "List",
// "Dict", etc.).
static py::object GetTemplateClass(const char* name) {
return py::module::import("pydrake.common.cpp_param").attr(name);
}
// When there is no match found for the schema type, this function will
// produce a compile-time error that's at least somewhat readable.
template <typename T>
static py::object CannotIdentifySchemaType(T*) {
// N.B. This static_assert will always fail, but with a nice message.
static_assert(std::is_same_v<T, void>,
"DefAttributesUsingSerialize() could not understand a field type");
return py::none();
}
PyClass* const ppy_class_;
CxxClass* const prototype_;
const Docs* const cls_docs_;
// As we visit each field, we'll accumulate a list of [{name=, type=}, ...]
// to bind later as the `__fields__` static property.
py::list fields_;
};
} // namespace internal
/// Binds the attributes visited by a C++ class Serialize function as readwrite
/// on properties its ppy_class. This function only works for classes with a
/// trivial Serialize function that uses DRAKE_NVP on each of its member fields;
/// Serialize functions that use DRAKE_NVP on temporary stack variables are not
/// supported. The class also must be default-constructible.
///
/// @internal TODO(eric.cousineau): Investigate exposing struct classes as a
/// `dataclass`.
template <typename PyClass, typename Docs>
void DefAttributesUsingSerialize(PyClass* ppy_class, const Docs& cls_docs) {
using CxxClass = typename PyClass::type;
CxxClass prototype{};
internal::DefAttributesArchive archive(ppy_class, &prototype, &cls_docs);
prototype.Serialize(&archive);
archive.Finished();
}
/// (Advanced) An overload that doesn't bind docstrings. We expect that pydrake
/// bindings should always pass a Docs class (i.e., use the other overload),
/// in some cases (especially downstream projects) that might not be possible.
template <typename PyClass>
void DefAttributesUsingSerialize(PyClass* ppy_class) {
using CxxClass = typename PyClass::type;
CxxClass prototype{};
internal::DefAttributesArchive<PyClass, void> archive(
ppy_class, &prototype, nullptr);
prototype.Serialize(&archive);
archive.Finished();
}
namespace internal {
// Helper for DefReprUsingSerialize.
class DefReprArchive {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DefReprArchive)
DefReprArchive() = default;
// Appends the visited item's name to the list of names.
template <typename NameValuePair>
void Visit(const NameValuePair& nvp) {
const char* const name = nvp.name();
property_names_.push_back(name);
}
std::vector<std::string>& property_names() { return property_names_; }
private:
std::vector<std::string> property_names_;
};
} // namespace internal
/// Binds __repr__ using a C++ class Serialize function.
/// The class must be default-constructible.
template <typename PyClass>
void DefReprUsingSerialize(PyClass* ppy_class) {
using CxxClass = typename PyClass::type;
internal::DefReprArchive archive;
CxxClass prototype{};
prototype.Serialize(&archive);
ppy_class->def("__repr__",
[names = std::move(archive.property_names())](py::object self) {
std::ostringstream result;
result << py::str(internal::PrettyClassName(self.attr("__class__")));
result << "(";
bool first = true;
for (const std::string& name : names) {
if (!first) {
result << ", ";
}
result << name << "=" << py::repr(self.attr(name.c_str()));
first = false;
}
result << ")";
return result.str();
});
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/_value_extra.py | # See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and
# rationale.
from pydrake.common.cpp_param import List
def _AbstractValue_Make(value):
"""Returns an AbstractValue containing the given ``value``.
The factory method ``AbstractValue.Make(value)`` and the constructor
``Value(value)`` are equivalent."""
if isinstance(value, list) and len(value) > 0:
inner_cls = type(value[0])
cls = List[inner_cls]
else:
cls = type(value)
value_cls, _ = Value.get_instantiation(cls, throw_error=False)
if value_cls is None:
value_cls = Value[object]
return value_cls(value)
AbstractValue.Make = _AbstractValue_Make
# Adjust how type inference works for Value(some_value). We want to use the
# precise semantics of AbstractValue.Make, not the anything-goes TemplateBase.
setattr(Value, "_call_internal", _AbstractValue_Make)
| 0 |
/home/johnshepherd/drake/bindings/pydrake | /home/johnshepherd/drake/bindings/pydrake/common/cpp_param.py | """
Defines a mapping between Python and alias types, and provides canonical
Python types as they relate to C++.
"""
import ctypes
import sys
import typing
import numpy as np
from pydrake.common import _MangledName, pretty_class_name
class _StrictMap:
# Provides a map which may only add a key once.
def __init__(self):
self._values = dict()
def add(self, key, value):
assert key not in self._values, "Already added: {}".format(key)
self._values[key] = value
def get(self, key, default):
return self._values.get(key, default)
class _ParamAliases:
# Registers aliases for a set of objects. This will be used for template
# parameters.
def __init__(self):
self._to_canonical = _StrictMap()
self._register_common()
def _register_common(self):
# Register common Python aliases relevant for C++.
self.register(float, [np.double, ctypes.c_double])
self.register(np.float32, [ctypes.c_float])
self.register(int, [np.int32, ctypes.c_int32])
self.register(np.int16, [ctypes.c_int16])
self.register(np.int64, [ctypes.c_int64])
self.register(np.uint8, [ctypes.c_uint8])
self.register(np.uint16, [ctypes.c_uint16])
self.register(np.uint32, [ctypes.c_uint32])
self.register(np.uint64, [ctypes.c_uint64])
def register(self, canonical, aliases):
# Registers a set of aliases to a canonical value.
for alias in aliases:
self._to_canonical.add(alias, canonical)
def is_aliased(self, alias):
# Determines if a parameter is aliased / registered.
return self._to_canonical.get(alias, None) is not None
def get_canonical(self, alias):
# Gets registered canonical parameter if it is aliased; otherwise
# return the same parameter.
return self._to_canonical.get(alias, alias)
@staticmethod
def _resugar_typing_shortcuts(origin_name, arg_names):
# Re-sugars typing.Union[T, NoneType] into typing.Optional[T] in case
# that's what the origin and arg names refer to. Otherwise, returns the
# data unchanged.
if (origin_name == "typing.Union"
and len(arg_names) == 2
and arg_names[-1] == "NoneType"):
origin_name = "typing.Optional"
arg_names = arg_names[:1]
return origin_name, arg_names
def get_name(self, alias, *, mangle):
# Gets string for an alias.
canonical = self.get_canonical(alias)
if typing.get_origin(alias) is not None:
origin = typing.get_origin(alias)
args = typing.get_args(alias)
origin_name = self.get_name(origin, mangle=mangle)
arg_names = [self.get_name(x, mangle=mangle) for x in args]
origin_name, arg_names = self._resugar_typing_shortcuts(
origin_name, arg_names)
result = f"{origin_name}[{','.join(arg_names)}]"
if mangle:
result = _MangledName.mangle(result)
return result
elif isinstance(canonical, type):
if mangle:
return canonical.__name__
else:
return pretty_class_name(canonical)
else:
# For literals.
result = str(canonical)
if mangle:
result = _MangledName.mangle(result)
return result
# Create singleton instance.
_param_aliases = _ParamAliases()
def get_param_canonical(param):
"""Gets the canonical types for a set of Python types (canonical as in
how they relate to C++ types).
"""
return tuple(map(_param_aliases.get_canonical, param))
def get_param_names(param, *, mangle=False):
"""Gets the canonical type names for a set of Python types (canonical as
in how they relate to C++ types).
The ``mangle`` controls whether we use the nice name or the mangled name;
see cpp_template.TemplateBase._instantiation_name for details.
"""
return tuple(_param_aliases.get_name(x, mangle=mangle) for x in param)
class _Generic:
"""Provides a C++-compatible way to denote generic types. This uses the
same type classes as Python's built-in generics (e.g., `typing.Union`) but
is careful to canonicalize any type aliases in params during instantiation.
"""
def __init__(self, name, instantiator, num_params):
self._name = name
self._instantiator = instantiator
self._num_params = num_params
def __getitem__(self, params):
if not isinstance(params, tuple):
params = (params,)
if self._num_params is not None and len(params) != self._num_params:
raise RuntimeError(
f"{self._name}[] requires exactly "
f"{self._num_params} type parameter(s)")
params_canonical = get_param_canonical(params)
return self._instantiator(params_canonical)
def __repr__(self):
return f"<Generic {self._name}>"
def _dict_instantiator(params):
return dict[params]
def _list_instantiator(params):
return list[params]
def _optional_instantiator(params):
# Unpack the tuple into the (single) argument required by typing.Optional.
(param,) = params
return typing.Optional[param]
# A generic type `dict[KT, VT]` for the C++ class std::map<KT, VT>.
Dict = _Generic("Dict", _dict_instantiator, 2)
# A generic type `list[T]` for the C++ class std::vector<T>.
List = _Generic("List", _list_instantiator, 1)
# A generic type `typing.Optional[T]` for the C++ class std::optional<T>.
# Note that `typing` de-sugars this to be `typing.Union[T, NoneType]`.
Optional = _Generic("Optional", _optional_instantiator, 1)
# A generic type `typing.Union[X, ...]` for the C++ class std::variant<X, ...>.
Union = _Generic("Union", typing.Union.__getitem__, None)
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/algebra_test_util.py | """
Provides utilities to test different algebra.
"""
import operator
import numpy as np
import pydrake.math as drake_math
class BaseAlgebra:
# Base class for defining scalar or vectorized (array) algebra and math.
# Checks on custom types that have numeric relations to `float`.
# Note that linear algebra itself is not "pluggable" for these operations,
# so care should be taken when defining it.
def __init__(self):
# Derived classes should define extra math functions.
pass
def to_algebra(self, scalar):
# Morphs a scalar to the given algebra (e.g. a scalar or array).
raise NotImplemented
class ScalarAlgebra(BaseAlgebra):
# Scalar algebra.
def __init__(self):
BaseAlgebra.__init__(self)
# Math functions:
self.log = drake_math.log
self.abs = drake_math.abs
self.exp = drake_math.exp
self.sqrt = drake_math.sqrt
self.pow = drake_math.pow
self.sin = drake_math.sin
self.cos = drake_math.cos
self.tan = drake_math.tan
self.arcsin = drake_math.asin
self.arccos = drake_math.acos
self.arctan2 = drake_math.atan2
self.sinh = drake_math.sinh
self.cosh = drake_math.cosh
self.tanh = drake_math.tanh
self.min = drake_math.min
self.max = drake_math.max
self.ceil = drake_math.ceil
self.floor = drake_math.floor
# Comparison. Defined in same order as in `_math_extra.py`.
self.lt = operator.lt
self.le = operator.le
self.eq = operator.eq
self.ne = operator.ne
self.ge = operator.ge
self.gt = operator.gt
def to_algebra(self, scalar):
return scalar
class VectorizedAlgebra(BaseAlgebra):
# Vectorized (array) algebra.
def __init__(self):
BaseAlgebra.__init__(self)
# Math functions:
self.log = np.log
self.abs = np.abs
self.exp = np.exp
self.sqrt = np.sqrt
self.pow = np.power
self.sin = np.sin
self.cos = np.cos
self.tan = np.tan
self.arcsin = np.arcsin
self.arccos = np.arccos
self.arctan2 = np.arctan2
self.sinh = np.sinh
self.cosh = np.cosh
self.tanh = np.tanh
self.min = np.fmin # N.B. Do not use `np.min`
self.max = np.fmax
self.ceil = np.ceil
self.floor = np.floor
# Comparison. Defined in same order as in `_math_extra.py`.
self.lt = drake_math.lt
self.le = drake_math.le
self.eq = drake_math.eq
self.ne = drake_math.ne
self.ge = drake_math.ge
self.gt = drake_math.gt
def to_algebra(self, scalar):
return np.array([scalar, scalar])
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/BUILD.bazel | load("//bindings/pydrake:pydrake.bzl", "add_lint_tests_pydrake")
load(
"//tools/skylark:drake_py.bzl",
"drake_py_library",
"drake_py_unittest",
)
load(
"//tools/skylark:pybind.bzl",
"drake_pybind_library",
"get_pybind_package_info",
)
package(default_visibility = [
"//bindings/pydrake:__subpackages__",
])
# This determines how `PYTHONPATH` is configured.
PACKAGE_INFO = get_pybind_package_info("//bindings")
drake_py_library(
name = "module_py",
testonly = 1,
srcs = ["__init__.py"],
imports = PACKAGE_INFO.py_imports,
deps = [
"//bindings/pydrake/common",
],
)
drake_py_library(
name = "algebra_test_util_py",
testonly = True,
srcs = ["algebra_test_util.py"],
visibility = [
"//bindings/pydrake/autodiffutils:__pkg__",
"//bindings/pydrake/symbolic:__pkg__",
],
deps = [
":module_py",
],
)
drake_pybind_library(
name = "autodiffutils_test_util_py",
testonly = True,
add_install = False,
cc_deps = [
"//bindings/pydrake:autodiff_types_pybind",
"//bindings/pydrake:documentation_pybind",
],
cc_so_name = "autodiffutils_test_util",
cc_srcs = ["autodiffutils_test_util_py.cc"],
package_info = PACKAGE_INFO,
)
drake_py_library(
name = "deprecation_py",
testonly = 1,
srcs = ["deprecation.py"],
deps = [":module_py"],
)
drake_py_library(
name = "meta_py",
testonly = 1,
srcs = ["meta.py"],
deps = [":module_py"],
)
drake_py_unittest(
name = "meta_test",
deps = [
":meta_py",
],
)
drake_py_library(
name = "numpy_compare_py",
testonly = 1,
srcs = ["numpy_compare.py"],
deps = [
":module_py",
"//bindings/pydrake:polynomial_py",
],
)
drake_py_library(
name = "pickle_compare_py",
testonly = 1,
srcs = ["pickle_compare.py"],
deps = [
":module_py",
":numpy_compare_py",
],
)
# A library that force-disables scipy, even if it's installed system-wide.
drake_py_library(
name = "scipy_none_py",
testonly = 1,
srcs = [
"scipy_none/scipy/__init__.py",
],
# N.B. We do not depend on ":module_py".
imports = ["scipy_none"],
)
# A minimal of implementation scipy.sparse that's barely functional enough
# to support unit testing the Drake APIs that return Eigen::Sparse matrices.
# The pybind11 type caster for Eigen::Sparse maps it to scipy.sparse.
drake_py_library(
name = "scipy_stub_py",
testonly = 1,
srcs = [
"scipy_stub/scipy/__init__.py",
"scipy_stub/scipy/sparse/__init__.py",
],
# N.B. We do not depend on ":module_py".
imports = ["scipy_stub"],
)
drake_py_unittest(
name = "scipy_stub_test",
deps = [":scipy_stub_py"],
)
# Package roll-up (for Bazel dependencies).
drake_py_library(
name = "test_utilities",
testonly = 1,
deps = [
":deprecation_py",
":module_py",
":numpy_compare_py",
":pickle_compare_py",
# N.B. Do not add algebra_test_util_py here; it should be scoped to
# only very specific tests that need it.
# N.B. Do not add scipy_stub_py here; it inserts scipy as a top-level
# module. Developers should only do that with intent, not as a bonus
# dependency from a conveience roll-up module.
],
)
add_lint_tests_pydrake()
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/numpy_compare.py | """
Provides consistent utilities for comparing NumPy matrices and scalars.
Prefer comparisons in the following order:
- Methods from this module.
- Methods from `np.testing.*`, if the dtypes are guaranteed to be NumPy
builtins and the API definitely won't support other scalar types.
"""
# TODO(eric.cousineau): Make custom assert-vectorize which will output
# coordinates and stuff.
from contextlib import contextmanager
from collections import namedtuple
import functools
import inspect
from itertools import product
import numpy as np
from pydrake.autodiffutils import AutoDiffXd
from pydrake.symbolic import (
Expression, Formula, Monomial, Polynomial, Variable, RationalFunction)
from pydrake.polynomial import Polynomial_ as RawPolynomial_
class _UnwantedEquality(AssertionError):
pass
class _Registry:
# Scalar comparator.
# `assert_eq` will be vectorized; it should raise an assertion error upon
# first inequality.
# `assert_ne` will stay as scalar; this should raise `_UnwantedEquality` to
# make intent explicit.
# TODO(eric.cousineau): Add `assert_near` when it's necessary.
AssertComparator = namedtuple(
'AssertComparator', ['assert_eq', 'assert_ne', 'assert_allclose'])
def __init__(self):
self._comparators = {}
self._to_float = {}
def register_comparator(
self,
cls_a,
cls_b,
assert_eq,
assert_ne=None,
assert_allclose=None):
key = (cls_a, cls_b)
assert key not in self._comparators, key
assert_eq = np.vectorize(assert_eq)
self._comparators[key] = self.AssertComparator(
assert_eq, assert_ne, assert_allclose)
def get_comparator_from_arrays(self, a, b):
# Ensure all types are homogeneous.
key = (resolve_type(a), resolve_type(b))
return self._comparators[key]
def register_to_float(self, cls, func):
assert cls not in self._to_float, cls
self._to_float[cls] = func
def get_to_float(self, cls):
return self._to_float[cls]
@np.vectorize
def to_float(x):
"""Converts scalar or array to floats."""
x = np.asarray(x)
if x.dtype == object:
x = x.item()
cls = type(x)
return _registry.get_to_float(cls)(x)
else:
return np.float64(x)
def assert_equal(a, b):
"""
Compare scalars or arrays directly, requiring equality.
For non-object dtypes, this has the same behavior as
``np.testing.assert_equal``, namely that two NaNs being in the same
positions in an array implies equality, rather than NaN being compared as
numbers.
"""
a, b = map(np.asarray, (a, b))
if a.size == 0 and b.size == 0:
return
if a.dtype != object and b.dtype != object:
np.testing.assert_equal(a, b)
else:
assert_eq = _registry.get_comparator_from_arrays(a, b).assert_eq
assert assert_eq is not None
assert_eq(a, b)
def assert_allclose(a, b, atol=1e-15, rtol=0):
"""
Same as `assert_equal`, but also checks for tolerances when possible.
"""
a, b = map(np.asarray, (a, b))
if a.size == 0 and b.size == 0:
return
if a.dtype != object and b.dtype != object:
np.testing.assert_allclose(a, b, atol=atol, rtol=rtol)
else:
assert_allclose = (
_registry.get_comparator_from_arrays(a, b).assert_allclose
)
assert assert_allclose is not None
assert_allclose(a, b, atol=atol, rtol=rtol)
def _raw_eq(a, b):
assert a == b, (a, b)
def _raw_ne(a, b):
if a == b:
raise _UnwantedEquality(str((a, b)))
def assert_not_equal(a, b):
"""Compare scalars or arrays directly, requiring inequality."""
a, b = map(np.asarray, (a, b))
assert not (a.size == 0 and b.size == 0)
if a.dtype != object and b.dtype != object:
assert_ne = _raw_ne
else:
assert_ne = _registry.get_comparator_from_arrays(a, b).assert_ne
assert assert_ne is not None
# For this to fail, all items must have failed.
br = np.broadcast(a, b)
errs = []
for ai, bi in br:
e = None
try:
assert_ne(ai, bi)
except _UnwantedEquality as e:
errs.append(str(e))
all_equal = len(errs) == br.size
if all_equal:
raise AssertionError("Unwanted equality: {}".format(errs))
def assert_float_equal(a, bf):
"""Checks equality of `a` (non-float) and `bf` (float) by converting `a` to
floats.
See also: ``assert_equal``
"""
assert np.asarray(bf).dtype == float, np.asarray(bf).dtype
af = to_float(a)
assert_equal(af, bf)
def assert_float_not_equal(a, bf):
"""Checks inequality of `a` (non-float) and `bf` (float) by converting `a`
to floats."""
assert np.asarray(bf).dtype == float, np.asarray(bf).dtype
af = to_float(a)
assert_not_equal(af, bf)
def assert_float_allclose(a, bf, atol=1e-15, rtol=0):
"""Checks nearness of `a` (non-float) to `bf` (float) by converting `a` to
floats.
Note:
This uses default tolerances that are different from
`np.testing.assert_allclose`.
"""
assert np.asarray(bf).dtype == float
af = to_float(a)
np.testing.assert_allclose(af, bf, atol=atol, rtol=rtol)
def resolve_type(a):
"""Resolves the type of an array `a`; useful for dtype=object. This will
ensure the entire array has homogeneous type, and will return the class of
the first item. `a` cannot be empty.
"""
a = np.asarray(a)
assert a.size != 0, "Cannot be empty."
cls_set = {type(np.asarray(x).item()) for x in a.flat}
assert len(cls_set) == 1, (
"Types must be homogeneous; got: {}".format(cls_set))
cls, = cls_set
return cls
def _str_eq(a, b):
# b is a string, a is to be converted.
a = str(a)
assert a == b, (a, b)
def _str_ne(a, b):
# b is a string, a is to be converted.
a = str(a)
if a == b:
raise _UnwantedEquality(str((a, b)))
def _register_autodiff():
def autodiff_eq(a, b):
assert a.value() == b.value(), (a.value(), b.value())
np.testing.assert_equal(a.derivatives(), b.derivatives())
def autodiff_ne(a, b):
if (a.value() == b.value()
and (a.derivatives() == b.derivatives()).all()):
raise _UnwantedEquality(str(a.value(), b.derivatives()))
def autodiff_allclose(a, b, atol, rtol):
# TODO(eric.cousineau): Figure out why `.item()` is necessary here, but
# not above.
a = a.item()
b = b.item()
np.testing.assert_allclose(a.value(), b.value(), atol=atol, rtol=rtol)
np.testing.assert_allclose(
a.derivatives(), b.derivatives(), atol=atol, rtol=rtol
)
_registry.register_to_float(AutoDiffXd, AutoDiffXd.value)
_registry.register_comparator(
AutoDiffXd, AutoDiffXd, autodiff_eq, autodiff_ne, autodiff_allclose)
def _register_symbolic():
def sym_struct_eq(a, b):
assert a.EqualTo(b), (a, b)
def sym_struct_ne(a, b):
assert not a.EqualTo(b), (a, b)
def from_bool(x):
assert isinstance(x, (bool, np.bool_)), type(x)
if x:
return Formula.True_()
else:
return Formula.False_()
def formula_bool_eq(a, b):
return sym_struct_eq(a, from_bool(b))
def formula_bool_ne(a, b):
return sym_struct_ne(a, from_bool(b))
_registry.register_to_float(Expression, Expression.Evaluate)
_registry.register_comparator(Formula, str, _str_eq, _str_ne)
_registry.register_comparator(
Formula, Formula, Formula.__eq__, Formula.__ne__)
# Ensure that we can do simple boolean comparison, e.g. in lieu of
# `unittest.TestCase.assertTrue`, use
# `numpy_compare.assert_equal(f, True)`.
_registry.register_comparator(
Formula, bool, formula_bool_eq, formula_bool_ne)
lhs_types = [Variable, Expression, Polynomial, Monomial]
rhs_types = lhs_types + [float]
for lhs_type in lhs_types:
_registry.register_comparator(lhs_type, str, _str_eq, _str_ne)
for lhs_type, rhs_type in product(lhs_types, rhs_types):
_registry.register_comparator(
lhs_type, rhs_type, sym_struct_eq, sym_struct_ne)
def _register_polynomial():
_registry.register_comparator(
RawPolynomial_[float], RawPolynomial_[float], _raw_eq, _raw_ne)
_registry.register_comparator(
RawPolynomial_[AutoDiffXd], RawPolynomial_[AutoDiffXd], _raw_eq,
_raw_ne)
_registry.register_comparator(
RawPolynomial_[Expression], RawPolynomial_[Expression], _raw_eq,
_raw_ne)
def _register_rational_function():
_registry.register_comparator(
RationalFunction, RationalFunction,
RationalFunction.__eq__, RationalFunction.__ne__)
# Globals.
_registry = _Registry()
_register_autodiff()
_register_symbolic()
_register_polynomial()
_register_rational_function()
def check_all_types(check_func):
"""Decorator to call a function multiple times with `T={type}`, where
`type` covers all (common) scalar types for Drake."""
@functools.wraps(check_func)
def wrapper(*args, **kwargs):
check_func(*args, T=float, **kwargs)
check_func(*args, T=AutoDiffXd, **kwargs)
check_func(*args, T=Expression, **kwargs)
return wrapper
def check_nonsymbolic_types(check_func):
"""Decorator to call a function multiple types with `T={type}`, where
`type` covers all (common) non-symbolic scalar types for Drake."""
assert inspect.isfunction(check_func), check_func
@functools.wraps(check_func)
def wrapper(*args, **kwargs):
check_func(*args, T=float, **kwargs)
check_func(*args, T=AutoDiffXd, **kwargs)
return wrapper
@contextmanager
def soft_sub_test(hint_for_error):
"""
Prints out a message when an exception is raised.
Useful for providing debug information for combinatorics tests.
With unittest's ``--failfast`` option (at least on Python 3.6), an error in
``unittest.TestCase.subTest`` does not stop execution, making it difficult
to digest errors. We use this workaround instead.
"""
try:
yield
except Exception:
print(f"soft_sub_test failure:\n {hint_for_error}")
raise
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/deprecation.py | """
Utilities for unit testing deprecation.
"""
import contextlib
import warnings
from pydrake.common.deprecation import DrakeDeprecationWarning
def _check_expected(caught, expected_count):
if expected_count is None:
return
if len(caught) == expected_count:
return
raise ValueError(
"Expected {} deprecation warnings but got {} instead:\n".format(
expected_count, len(caught)) + "\n".join([str(x) for x in caught]))
@contextlib.contextmanager
def catch_drake_warnings(action="always", expected_count=None):
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter(action, DrakeDeprecationWarning)
yield caught
# N.B. If an error occurs in the contained context, this will not get
# executed. This is intended behavior; see #10924 for more information.
_check_expected(caught, expected_count)
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/meta.py | import collections
import functools
import re
# TODO(jwnimmer-tri) It's probable that ValueParameterizedTest could be
# re-implemented using a class decorator, instead of a metaclass. That
# would likely be easier for developers to understand and maintain. We
# should explore that next time we revisit any new features here.
# A helper for ValueParameterizedTest that uses a subTest to display the
# exact kwargs upon a failure.
def _run_subtest(self, *, old_method, **kwargs):
with self.subTest(**kwargs):
old_method(self, **kwargs)
class ValueParameterizedTest(type):
"""A metaclass to repeat a test case over different argument values.
This can also be accomplished with a unittest.subTest, but that runs all
values via a single test case, which is awkward when we have large numbers
of sub-tests. In contrast, this metaclass will replicate a prototype
method into many standalone tests, so that unittest will automatically run
them one by one, allowing the developer to run them individually.
A value-paramaterized test case looks like this:
from module_under_test import dut
class MyTest(unittest.TestCase, metaclass=ValueParameterizedTest):
def _foo_values():
return [22, 33]
@run_with_multiple_values([dict(foo=foo) for foo in _foo_values()])
def test_dut(self, *, foo):
self.assertGreater(dut(foo), 0)
The effect of the metaclass is as-if the developer wrote this instead:
from module_under_test import dut
class MyTest(unittest.TestCase):
def test_dut_22(self):
foo = 22
self.assertGreater(dut(foo), 0)
def test_dut_33(self):
foo = 33
self.assertGreater(dut(foo), 0)
"""
def __new__(metacls, name, bases, namespace):
# Find all of the unittest methods.
test_methods = [
x for x in namespace.keys()
if x.startswith("test")
]
assert len(test_methods) > 0
# Find the unittest methods that used our decorator.
parameterized_methods = [
x for x in test_methods
if hasattr(namespace[x], "_value_parameterized_test_pairs")
]
if not parameterized_methods:
raise RuntimeError("ValueParameterizedTest was used without any"
" @run_with_multiple_values decorators")
# Multiply the decorated methods into real test cases.
for method_name in parameterized_methods:
# Use pop on the decorated method so it isn't run unparameterized.
old_method = namespace.pop(method_name)
for suffix, kwargs in old_method._value_parameterized_test_pairs:
# Conjure the new method name, and sanity check it.
new_name = method_name + "_" + suffix
assert new_name.startswith("test_"), new_name
assert new_name not in namespace, new_name
# Create a new method with bound kwargs.
new_method = functools.partialmethod(
_run_subtest,
old_method=old_method,
**kwargs)
# Keep the same docstring.
new_method.__doc__ = old_method.__doc__
# Inject the new method under the new name.
namespace[new_name] = new_method
# Continue class construction as usual.
return type.__new__(metacls, name, bases, namespace)
def _choose_test_suffix(kwargs):
"""Summarizes kwargs as a string, ensuring that the string is a valid
method name suffix.
"""
result = "_".join([str(x) for x in kwargs.values()])
result = re.sub("[^0-9a-zA-Z]+", "_", result)
result = result.strip("_").lower()
return result
def _make_test_pairs(values):
"""Returns a list of (test_suffix, kwargs) pairs for the given list of
kwargs values, by calculating a unique test_suffix summary of the kwargs.
"""
pairs = [
[_choose_test_suffix(kwargs), kwargs]
for kwargs in values
]
# Uniquify any duplicate (or missing) suffix names.
counter = collections.Counter([x for x, _ in pairs])
bad_names = set([x for x, count in counter.items() if count > 1 or not x])
return [
(x if x not in bad_names else f"{x}_iter{i}", kwargs)
for i, (x, kwargs) in enumerate(pairs)
]
def run_with_multiple_values(values):
"""Decorator for use with the ValueParameterizedTest metaclass to specify
the set of parameterized values.
"""
# Convert any iterables into a concrete list and choose method suffixes.
pairs = _make_test_pairs(values)
# Attach the list of values to the test function.
def wrap(check_func):
check_func._value_parameterized_test_pairs = pairs
return check_func
return wrap
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/autodiffutils_test_util_py.cc | #include "drake/bindings/pydrake/autodiff_types_pybind.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/math/roll_pitch_yaw.h"
#include "drake/math/rotation_matrix.h"
namespace drake {
namespace pydrake {
PYBIND11_MODULE(autodiffutils_test_util, m) {
m.doc() = "Utilities for testing Eigen AutoDiff Scalars";
py::module::import("pydrake.autodiffutils");
// For testing implicit argument conversion.
m.def("autodiff_scalar_pass_through",
[](const AutoDiffXd& value) { return value; });
m.def("autodiff_vector_pass_through",
[](const VectorX<AutoDiffXd>& value) { return value; });
m.def("autodiff_vector3_pass_through",
[](const Vector3<AutoDiffXd>& value) { return value; });
}
} // namespace pydrake
} // namespace drake
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/__init__.py | """
Utilities for unit testing.
"""
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/pickle_compare.py | """
Provides utilities to check if an object supports pickling (serlialization).
"""
from io import BytesIO
import pickle
import numpy as np
import pydrake.common.test_utilities.numpy_compare as numpy_compare
from pydrake.symbolic import Expression
_PYBIND11_METACLASS = type(Expression)
def _assert_equal(test, a, b):
if isinstance(a, np.ndarray):
numpy_compare.assert_equal(a, b)
else:
test.assertEqual(a, b)
def assert_pickle(test, obj, value_to_compare=lambda x: x.__dict__, T=None):
"""
Asserts that an object can be dumped and loaded and still maintain its
value.
Args:
test: Instance of `unittest.TestCase` (for assertions).
obj: Obj to dump and then load.
value_to_compare: (optional) Value to extract from the object to
compare. By default, compares dictionaries.
T: (optional) When pickling template instantiations on scalar types,
pass the scalar type T. This is used because `Expression` is
currently not a serializable type.
"""
metaclass = type(type(obj))
if T == Expression:
# Pickling not enabled for Expression.
return
else:
f = BytesIO()
pickle.dump(obj, f)
f.seek(0)
obj_again = pickle.load(f)
_assert_equal(test, value_to_compare(obj), value_to_compare(obj_again))
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common/test_utilities/scipy_stub | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/scipy_stub/scipy/__init__.py | """A minimal implementation of scipy.sparse that's barely functional enough
to support unit testing the Drake APIs that return Eigen::Sparse matrices.
The pybind11 type caster for Eigen::Sparse maps it to scipy.sparse.
"""
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common/test_utilities/scipy_stub/scipy | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/scipy_stub/scipy/sparse/__init__.py | """A minimal implementation of scipy.sparse that's barely functional enough
to support unit testing the Drake APIs that return Eigen::Sparse matrices.
The pybind11 type caster for Eigen::Sparse maps it to scipy.sparse.
"""
import numpy as np
class csc_matrix:
"""A minimal implementation of the scipy.sparse matrix type.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html
"""
def __init__(self, arg1, shape=None):
"""The scipy.csc_matrix constructor supports five possible overloads.
For this stub, we only support these two:
csc_array((data, indices, indptr), shape=(M, N))
csc_array(dense)
"""
if shape is not None:
(self.data, self.indices, self.indptr) = arg1
self.shape = shape
else:
dense = arg1
rows, cols = dense.shape
self.shape = (rows, cols)
self.data = []
self.indices = []
self.indptr = [0]
for c in range(cols):
for r in range(rows):
value = dense[r, c]
if not value:
continue
self.indices.append(r)
self.data.append(value)
self.indptr.append(len(self.indices))
self.data = np.asarray(self.data)
self.indices = np.asarray(self.indices)
self.indptr = np.asarray(self.indptr)
# To sanity-check our arguments, convert the data to triplets.
self._triplets = []
for col in range(len(self.indptr) - 1):
start = self.indptr[col]
end = self.indptr[col+1]
rows = self.indices[start:end]
values = self.data[start:end]
for row, value in zip(rows, values):
self._triplets.append((row, col, value))
self.nnz = 0
for _, _, value in self._triplets:
if value:
self.nnz += 1
def todense(self):
result = np.zeros(shape=self.shape)
for row, col, value in self._triplets:
result[row, col] = value
return result
| 0 |
/home/johnshepherd/drake/bindings/pydrake/common/test_utilities | /home/johnshepherd/drake/bindings/pydrake/common/test_utilities/test/meta_test.py | import pydrake.common.test_utilities.meta as mut
import unittest
class TestMeta(unittest.TestCase):
def _test_chosen_suffixes(self, expected_pairs):
"""Given an expected list of (suffix, kwargs) pairs to be returned by
_make_test_pairs, checks that when the kwargs are actually passed into
_make_test_pairs that it returns those desired pairs.
"""
dut = mut._make_test_pairs
with self.subTest(pairs=expected_pairs):
values = [x for _, x in expected_pairs]
actual_pairs = dut(values)
self.assertSequenceEqual(actual_pairs, expected_pairs)
def test_naming_basic(self):
"""Checks the basic case from the meta.py docstring."""
self._test_chosen_suffixes((
("22", dict(foo=22)),
("33", dict(foo=33)),
))
def test_naming_two_args(self):
"""Checks where each kwargs has multiple entries."""
self._test_chosen_suffixes((
("22_hello", dict(foo=22, bar="hello")),
("33_hello", dict(foo=33, bar="hello")),
))
def test_conflicting_names(self):
"""Checks where the suffix would not be unique without a nonce, and
that multiple unprintable characters in a row are combined into just
one underscore.
"""
self._test_chosen_suffixes((
("foo_bar_iter0", dict(quux="foo//bar")),
("foo_bar_iter1", dict(quux="foo::bar")),
))
def test_short_names(self):
"""Checks where the value is totally non-printable."""
# The leading "_" here is unfortunate, but we can live with it.
self._test_chosen_suffixes((
("_iter0", dict(quux="...")),
))
| 0 |
Subsets and Splits