repo_id
stringclasses
205 values
file_path
stringlengths
33
141
content
stringlengths
1
307k
__index_level_0__
int64
0
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/manipulation/manipulation_py_kuka_iiwa.cc
#include "drake/bindings/pydrake/common/serialize_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/manipulation/kuka_iiwa/build_iiwa_control.h" #include "drake/manipulation/kuka_iiwa/iiwa_command_receiver.h" #include "drake/manipulation/kuka_iiwa/iiwa_command_sender.h" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/manipulation/kuka_iiwa/iiwa_driver.h" #include "drake/manipulation/kuka_iiwa/iiwa_driver_functions.h" #include "drake/manipulation/kuka_iiwa/iiwa_status_receiver.h" #include "drake/manipulation/kuka_iiwa/iiwa_status_sender.h" #include "drake/manipulation/kuka_iiwa/sim_iiwa_driver.h" namespace drake { namespace pydrake { namespace internal { using systems::Diagram; using systems::LeafSystem; void DefineManipulationKukaIiwa(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::manipulation::kuka_iiwa; constexpr auto& doc = pydrake_doc.drake.manipulation.kuka_iiwa; // Constants. m.attr("kIiwaArmNumJoints") = kIiwaArmNumJoints; m.def("get_iiwa_max_joint_velocities", &get_iiwa_max_joint_velocities, doc.get_iiwa_max_joint_velocities.doc); m.attr("kIiwaLcmStatusPeriod") = kIiwaLcmStatusPeriod; { using Class = IiwaControlMode; constexpr auto& cls_doc = doc.IiwaControlMode; py::enum_<Class>(m, "IiwaControlMode", cls_doc.doc) .value("kPositionOnly", Class::kPositionOnly, cls_doc.kPositionOnly.doc) .value("kTorqueOnly", Class::kTorqueOnly, cls_doc.kTorqueOnly.doc) .value("kPositionAndTorque", Class::kPositionAndTorque, cls_doc.kPositionAndTorque.doc); } m.def("position_enabled", &position_enabled, py::arg("control_mode"), doc.position_enabled.doc); m.def("torque_enabled", &torque_enabled, py::arg("control_mode"), doc.torque_enabled.doc); m.def("ParseIiwaControlMode", &ParseIiwaControlMode, py::arg("control_mode"), doc.ParseIiwaControlMode.doc); { using Class = IiwaCommandReceiver; constexpr auto& cls_doc = doc.IiwaCommandReceiver; py::class_<Class, LeafSystem<double>>(m, "IiwaCommandReceiver", cls_doc.doc) .def(py::init<int, IiwaControlMode>(), py::arg("num_joints") = kIiwaArmNumJoints, py::arg("control_mode") = IiwaControlMode::kPositionAndTorque, cls_doc.ctor.doc) .def("get_message_input_port", &Class::get_message_input_port, py_rvp::reference_internal, cls_doc.get_message_input_port.doc) .def("get_position_measured_input_port", &Class::get_position_measured_input_port, py_rvp::reference_internal, cls_doc.get_position_measured_input_port.doc) .def("get_commanded_position_output_port", &Class::get_commanded_position_output_port, py_rvp::reference_internal, cls_doc.get_commanded_position_output_port.doc) .def("get_commanded_torque_output_port", &Class::get_commanded_torque_output_port, py_rvp::reference_internal, cls_doc.get_commanded_torque_output_port.doc) .def("get_time_output_port", &Class::get_time_output_port, py_rvp::reference_internal, cls_doc.get_time_output_port.doc); } { using Class = IiwaCommandSender; constexpr auto& cls_doc = doc.IiwaCommandSender; py::class_<Class, LeafSystem<double>>(m, "IiwaCommandSender", cls_doc.doc) .def(py::init<int, IiwaControlMode>(), py::arg("num_joints") = kIiwaArmNumJoints, py::arg("control_mode") = IiwaControlMode::kPositionAndTorque, cls_doc.ctor.doc) .def("get_time_input_port", &Class::get_time_input_port, py_rvp::reference_internal, cls_doc.get_time_input_port.doc) .def("get_position_input_port", &Class::get_position_input_port, py_rvp::reference_internal, cls_doc.get_position_input_port.doc) .def("get_torque_input_port", &Class::get_torque_input_port, py_rvp::reference_internal, cls_doc.get_torque_input_port.doc); } { using Class = IiwaStatusReceiver; constexpr auto& cls_doc = doc.IiwaStatusReceiver; py::class_<Class, LeafSystem<double>>(m, "IiwaStatusReceiver", cls_doc.doc) .def(py::init<int>(), py::arg("num_joints") = kIiwaArmNumJoints, cls_doc.ctor.doc) .def("get_time_measured_output_port", &Class::get_time_measured_output_port, py_rvp::reference_internal, cls_doc.get_time_measured_output_port.doc) .def("get_position_commanded_output_port", &Class::get_position_commanded_output_port, py_rvp::reference_internal, cls_doc.get_position_commanded_output_port.doc) .def("get_position_measured_output_port", &Class::get_position_measured_output_port, py_rvp::reference_internal, cls_doc.get_position_measured_output_port.doc) .def("get_velocity_estimated_output_port", &Class::get_velocity_estimated_output_port, py_rvp::reference_internal, cls_doc.get_velocity_estimated_output_port.doc) .def("get_torque_commanded_output_port", &Class::get_torque_commanded_output_port, py_rvp::reference_internal, cls_doc.get_torque_commanded_output_port.doc) .def("get_torque_measured_output_port", &Class::get_torque_measured_output_port, py_rvp::reference_internal, cls_doc.get_torque_measured_output_port.doc) .def("get_torque_external_output_port", &Class::get_torque_external_output_port, py_rvp::reference_internal, cls_doc.get_torque_external_output_port.doc); } { using Class = IiwaStatusSender; constexpr auto& cls_doc = doc.IiwaStatusSender; py::class_<Class, LeafSystem<double>>(m, "IiwaStatusSender", cls_doc.doc) .def(py::init<int>(), py::arg("num_joints") = kIiwaArmNumJoints, cls_doc.ctor.doc) .def("get_time_measured_input_port", &Class::get_time_measured_input_port, py_rvp::reference_internal, cls_doc.get_time_measured_input_port.doc) .def("get_position_commanded_input_port", &Class::get_position_commanded_input_port, py_rvp::reference_internal, cls_doc.get_position_commanded_input_port.doc) .def("get_position_measured_input_port", &Class::get_position_measured_input_port, py_rvp::reference_internal, cls_doc.get_position_measured_input_port.doc) .def("get_velocity_estimated_input_port", &Class::get_velocity_estimated_input_port, py_rvp::reference_internal, cls_doc.get_velocity_estimated_input_port.doc) .def("get_torque_commanded_input_port", &Class::get_torque_commanded_input_port, py_rvp::reference_internal, cls_doc.get_torque_commanded_input_port.doc) .def("get_torque_measured_input_port", &Class::get_torque_measured_input_port, py_rvp::reference_internal, cls_doc.get_torque_measured_input_port.doc) .def("get_torque_external_input_port", &Class::get_torque_external_input_port, py_rvp::reference_internal, cls_doc.get_torque_external_input_port.doc); } { using Class = IiwaDriver; constexpr auto& cls_doc = doc.IiwaDriver; py::class_<Class> cls(m, "IiwaDriver", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } { using Class = SimIiwaDriver<double>; constexpr auto& cls_doc = doc.SimIiwaDriver; py::class_<Class, Diagram<double>>(m, "SimIiwaDriver", cls_doc.doc) .def(py::init<IiwaControlMode, const multibody::MultibodyPlant<double>*, double, const std::optional<Eigen::VectorXd>&>(), py::arg("control_mode"), py::arg("controller_plant"), py::arg("ext_joint_filter_tau"), py::arg("kp_gains"), // Keep alive, ownership: `self` keeps `controller_plant` alive. py::keep_alive<1, 3>(), cls_doc.ctor.doc) .def_static("AddToBuilder", &Class::AddToBuilder, py::arg("builder"), py::arg("plant"), py::arg("iiwa_instance"), py::arg("controller_plant"), py::arg("ext_joint_filter_tau"), py::arg("desired_iiwa_kp_gains"), py::arg("control_mode"), // Keep alive, ownership: `return` keeps `builder` alive. py::keep_alive<0, 1>(), // Keep alive, reference: `builder` keeps `controller_plant` alive. py::keep_alive<1, 4>(), py_rvp::reference, cls_doc.AddToBuilder.doc); } { m.def("ApplyDriverConfig", &ApplyDriverConfig, py::arg("driver_config"), py::arg("model_instance_name"), py::arg("sim_plant"), py::arg("models_from_directives"), py::arg("lcms"), py::arg("builder"), doc.ApplyDriverConfig.doc); m.def("BuildIiwaControl", &BuildIiwaControl, py::arg("plant"), py::arg("iiwa_instance"), py::arg("controller_plant"), py::arg("lcm"), py::arg("builder"), py::arg("ext_joint_filter_tau") = 0.01, py::arg("desired_iiwa_kp_gains") = std::nullopt, py::arg("control_mode") = IiwaControlMode::kPositionAndTorque, // Keep alive, reference: `builder` keeps `controller_plant` alive. py::keep_alive<5, 3>(), doc.BuildIiwaControl.doc); } } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/manipulation/_manipulation_extra.py
import inspect as _inspect def ApplyDriverConfigs(*, driver_configs, sim_plant, models_from_directives, lcm_buses, builder): """Applies many driver configurations to a model. A "driver configuration" helps stack Drake systems between an LCM interface subscriber system and the actuation input ports of a MultibodyPlant (to enact the driver command), as well as the output ports of a MultibodyPlant back to an LCM interface publisher system (to provide the driver status). These conceptually simulate "drivers" -- they take the role that driver software and control cabinets would take in real life -- but may also model some physical properties of the robot that are not easily reflected in MultibodyPlant (e.g., the WSG belt drive). This function assumes that the ApplyDriverConfig functions associated with the values in the driver_configs map are defined in the same module as the value itself. Args: driver_configs: The configurations to apply, mapping a ``str`` model instance name to some kind of a DriverConfig object (e.g., a ``pydrake.manipulation.util.ZeroForceDriver``). sim_plant: The plant containing the model. models_from_directives: The list of ``ModelInstanceInfo`` from previously-loaded directives (e.g., from ``ProcessModelDirectives``). lcm_buses: The available LCM buses to drive and/or sense from this driver. builder: The ``DiagramBuilder`` into which to install this driver. """ # This implements the drake/manipulation/util/apply_driver_configs.h # function of the same name. Due to the peculiarities of std::variant # and argument-dependent lookup, it's easier to re-implement it rather # than bind it via pybind11. models_from_directives_map = dict([ (info.model_name, info) for info in models_from_directives ]) for model_instance_name, driver_config in driver_configs.items(): module = _inspect.getmodule(driver_config) apply_function = getattr(module, "ApplyDriverConfig") apply_function( driver_config, model_instance_name, sim_plant, models_from_directives_map, lcm_buses, builder)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/manipulation/manipulation_py.cc
#include "drake/bindings/pydrake/manipulation/manipulation_py.h" namespace drake { namespace pydrake { PYBIND11_MODULE(manipulation, m) { PYDRAKE_PREVENT_PYTHON3_MODULE_REIMPORT(m); py::module::import("pydrake.systems.framework"); // The order of these calls matters. Some modules rely on prior definitions. internal::DefineManipulationKukaIiwa(m); internal::DefineManipulationSchunkWsg(m); internal::DefineManipulationUtil(m); ExecuteExtraPythonCode(m, true); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake/manipulation
/home/johnshepherd/drake/bindings/pydrake/manipulation/test/util_test.py
# -*- coding: utf-8 -*- import pydrake.manipulation as mut import unittest from pydrake.common import FindResourceOrThrow from pydrake.multibody.parsing import ( LoadModelDirectives, Parser, ProcessModelDirectives, ) from pydrake.manipulation import ApplyDriverConfigs from pydrake.multibody.plant import MultibodyPlant from pydrake.systems.framework import DiagramBuilder from pydrake.systems.lcm import LcmBuses class TestUtil(unittest.TestCase): def test_driver(self): dut = mut.ZeroForceDriver() self.assertIn("ZeroForceDriver", repr(dut)) builder = DiagramBuilder() plant = builder.AddSystem(MultibodyPlant(1.)) parser = Parser(plant) directives = LoadModelDirectives(FindResourceOrThrow( "drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")) models_from_directives = ProcessModelDirectives(directives, parser) plant.Finalize() model_dict = dict() for model in models_from_directives: model_dict[model.model_name] = model self.assertEqual(len(builder.GetSystems()), 1) mut.ApplyDriverConfig( driver_config=dut, model_instance_name="iiwa7", sim_plant=plant, models_from_directives=model_dict, lcms=LcmBuses(), builder=builder) self.assertEqual(len(builder.GetSystems()), 2) def test_apply_driver_configs(self): """Checks the ApplyDriverConfigs from our parent module. """ builder = DiagramBuilder() plant = builder.AddSystem(MultibodyPlant(1.)) parser = Parser(plant) directives = LoadModelDirectives(FindResourceOrThrow( "drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")) models_from_directives = ProcessModelDirectives(directives, parser) plant.Finalize() driver_configs = { "iiwa7": mut.ZeroForceDriver(), "schunk_wsg": mut.ZeroForceDriver(), } lcm_buses = LcmBuses() self.assertEqual(len(builder.GetSystems()), 1) ApplyDriverConfigs( driver_configs=driver_configs, sim_plant=plant, models_from_directives=models_from_directives, lcm_buses=lcm_buses, builder=builder) self.assertEqual(len(builder.GetSystems()), 3)
0
/home/johnshepherd/drake/bindings/pydrake/manipulation
/home/johnshepherd/drake/bindings/pydrake/manipulation/test/schunk_wsg_test.py
# -*- coding: utf-8 -*- import pydrake.manipulation as mut import unittest import numpy as np from pydrake.common import FindResourceOrThrow from pydrake.lcm import DrakeLcm from pydrake.multibody.parsing import ( LoadModelDirectives, Parser, ProcessModelDirectives, ) from pydrake.multibody.plant import MultibodyPlant from pydrake.systems.framework import ( DiagramBuilder, InputPort, OutputPort, VectorSystem, ) from pydrake.systems.lcm import LcmBuses from pydrake.systems.primitives import MatrixGain class TestSchunkWsg(unittest.TestCase): def test_schunk_wsg_controller(self): controller = mut.SchunkWsgPositionController(time_step=0.01, kp_command=100., kd_command=1., kp_constraint=1000., kd_constraint=1., default_force_limit=37.0) self.assertIsInstance( controller.get_desired_position_input_port(), InputPort) self.assertIsInstance( controller.get_force_limit_input_port(), InputPort) self.assertIsInstance( controller.get_state_input_port(), InputPort) self.assertIsInstance( controller.get_generalized_force_output_port(), OutputPort) self.assertIsInstance( controller.get_grip_force_output_port(), OutputPort) controller = mut.SchunkWsgController(kp=100., ki=2., kd=1.) self.assertIsInstance( controller.GetInputPort("command_message"), InputPort) self.assertIsInstance(controller.GetInputPort("state"), InputPort) self.assertIsInstance(controller.GetOutputPort("force"), OutputPort) def test_schunk_wsg_lcm(self): command_rec = mut.SchunkWsgCommandReceiver(initial_position=0.01, initial_force=5.) self.assertIsInstance( command_rec.get_position_output_port(), OutputPort) self.assertIsInstance( command_rec.get_force_limit_output_port(), OutputPort) command_send = mut.SchunkWsgCommandSender(default_force_limit=37.0) self.assertIsInstance( command_send.get_position_input_port(), InputPort) self.assertIsInstance( command_send.get_force_limit_input_port(), InputPort) self.assertIsInstance( command_send.get_command_output_port(), OutputPort) status_rec = mut.SchunkWsgStatusReceiver() self.assertIsInstance(status_rec.get_status_input_port(), InputPort) self.assertIsInstance(status_rec.get_state_output_port(), OutputPort) self.assertIsInstance(status_rec.get_force_output_port(), OutputPort) status_send = mut.SchunkWsgStatusSender() self.assertIsInstance(status_send.get_state_input_port(), InputPort) self.assertIsInstance(status_send.get_force_input_port(), InputPort) def test_schunk_wsg_api(self): self.assertEqual(mut.GetSchunkWsgOpenPosition().shape, (2,)) self.assertIsInstance( mut.MakeMultibodyStateToWsgStateSystem(), MatrixGain) self.assertIsInstance( mut.MakeMultibodyForceToWsgForceSystem(), VectorSystem) def test_schunk_wsg_build_control(self): builder = DiagramBuilder() plant = builder.AddSystem(MultibodyPlant(1.)) parser = Parser(plant) directives = LoadModelDirectives(FindResourceOrThrow( "drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")) models_from_directives = ProcessModelDirectives(directives, parser) plant.Finalize() self.assertEqual(len(builder.GetSystems()), 1) mut.BuildSchunkWsgControl( plant=plant, wsg_instance=plant.GetModelInstanceByName("schunk_wsg"), lcm=DrakeLcm(), builder=builder, pid_gains=[2., 3., 4.]) self.assertEqual(len(builder.GetSystems()), 7) def test_schunk_wsg_driver(self): dut = mut.SchunkWsgDriver() dut.pid_gains = np.array([1., 2., 3.]) dut.lcm_bus = "test" self.assertIn("lcm_bus", repr(dut)) builder = DiagramBuilder() plant = builder.AddSystem(MultibodyPlant(1.)) parser = Parser(plant) directives = LoadModelDirectives(FindResourceOrThrow( "drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")) models_from_directives = ProcessModelDirectives(directives, parser) plant.Finalize() model_dict = dict() for model in models_from_directives: model_dict[model.model_name] = model lcm_bus = LcmBuses() lcm_bus.Add("test", DrakeLcm()) self.assertEqual(len(builder.GetSystems()), 1) mut.ApplyDriverConfig( driver_config=dut, model_instance_name="schunk_wsg", sim_plant=plant, models_from_directives=model_dict, lcms=lcm_bus, builder=builder) self.assertEqual(len(builder.GetSystems()), 7)
0
/home/johnshepherd/drake/bindings/pydrake/manipulation
/home/johnshepherd/drake/bindings/pydrake/manipulation/test/kuka_iiwa_test.py
# -*- coding: utf-8 -*- import pydrake.manipulation as mut import unittest import numpy as np from pydrake.common import FindResourceOrThrow from pydrake.lcm import DrakeLcm from pydrake.math import RigidTransform from pydrake.multibody.parsing import ( LoadModelDirectives, Parser, ProcessModelDirectives, ) from pydrake.multibody.plant import MultibodyPlant from pydrake.systems.framework import ( DiagramBuilder, InputPort, OutputPort, ) from pydrake.systems.lcm import LcmBuses class TestKukaIiwa(unittest.TestCase): def make_builder_plant_controller_plant(self): builder = DiagramBuilder() plant = builder.AddSystem(MultibodyPlant(1.0)) parser = Parser(plant) directives = LoadModelDirectives(FindResourceOrThrow( "drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")) models_from_directives = ProcessModelDirectives(directives, parser) plant.Finalize() controller_plant = MultibodyPlant(1.) parser = Parser(controller_plant) parser.AddModels(url=( "package://drake_models/iiwa_description/sdf/" + "iiwa7_no_collision.sdf")) controller_plant.WeldFrames( controller_plant.world_frame(), controller_plant.GetFrameByName("iiwa_link_0"), RigidTransform()) controller_plant.Finalize() return builder, plant, controller_plant def test_constants(self): self.assertEqual(mut.kIiwaArmNumJoints, 7) self.assertIsInstance(mut.get_iiwa_max_joint_velocities(), np.ndarray) self.assertEqual(mut.kIiwaLcmStatusPeriod, 0.005) self.assertIsInstance( mut.IiwaControlMode.kPositionOnly, mut.IiwaControlMode) self.assertIsInstance( mut.IiwaControlMode.kTorqueOnly, mut.IiwaControlMode) self.assertIsInstance( mut.IiwaControlMode.kPositionAndTorque, mut.IiwaControlMode) control_mode = mut.IiwaControlMode.kPositionAndTorque self.assertTrue(mut.position_enabled(control_mode=control_mode)) self.assertTrue(mut.torque_enabled(control_mode=control_mode)) self.assertEqual( mut.ParseIiwaControlMode(control_mode="position_and_torque"), control_mode) def test_kuka_iiwa_lcm(self): command_rec = mut.IiwaCommandReceiver( num_joints=mut.kIiwaArmNumJoints, control_mode=mut.IiwaControlMode.kPositionAndTorque) self.assertIsInstance( command_rec.get_message_input_port(), InputPort) self.assertIsInstance( command_rec.get_position_measured_input_port(), InputPort) self.assertIsInstance( command_rec.get_commanded_position_output_port(), OutputPort) self.assertIsInstance( command_rec.get_commanded_torque_output_port(), OutputPort) self.assertIsInstance( command_rec.get_time_output_port(), OutputPort) command_send = mut.IiwaCommandSender() self.assertIsInstance( command_send.get_time_input_port(), InputPort) self.assertIsInstance( command_send.get_position_input_port(), InputPort) self.assertIsInstance( command_send.get_torque_input_port(), InputPort) # Constructor variants. mut.IiwaCommandSender( num_joints=mut.kIiwaArmNumJoints, control_mode=mut.IiwaControlMode.kPositionAndTorque) status_rec = mut.IiwaStatusReceiver() self.assertIsInstance( status_rec.get_time_measured_output_port(), OutputPort) self.assertIsInstance( status_rec.get_position_commanded_output_port(), OutputPort) self.assertIsInstance( status_rec.get_position_measured_output_port(), OutputPort) self.assertIsInstance( status_rec.get_velocity_estimated_output_port(), OutputPort) self.assertIsInstance( status_rec.get_torque_commanded_output_port(), OutputPort) self.assertIsInstance( status_rec.get_torque_measured_output_port(), OutputPort) self.assertIsInstance( status_rec.get_torque_external_output_port(), OutputPort) status_send = mut.IiwaStatusSender() self.assertIsInstance( status_send.get_time_measured_input_port(), InputPort) self.assertIsInstance( status_send.get_position_commanded_input_port(), InputPort) self.assertIsInstance( status_send.get_position_measured_input_port(), InputPort) self.assertIsInstance( status_send.get_velocity_estimated_input_port(), InputPort) self.assertIsInstance( status_send.get_torque_commanded_input_port(), InputPort) self.assertIsInstance( status_send.get_torque_measured_input_port(), InputPort) self.assertIsInstance( status_send.get_torque_external_input_port(), InputPort) def test_kuka_iiwa_api(self): self.assertEqual(mut.get_iiwa_max_joint_velocities().shape, (7,)) def test_kuka_iiwa_build_control(self): builder, plant, controller_plant = ( self.make_builder_plant_controller_plant() ) tare = len(builder.GetSystems()) mut.BuildIiwaControl( plant=plant, iiwa_instance=plant.GetModelInstanceByName("iiwa7"), controller_plant=controller_plant, lcm=DrakeLcm(), builder=builder, ext_joint_filter_tau=0.12, desired_iiwa_kp_gains=np.arange(7), control_mode=mut.IiwaControlMode.kPositionAndTorque) self.assertGreater(len(builder.GetSystems()), tare) def test_kuka_iiwa_driver(self): dut = mut.IiwaDriver() dut.hand_model_name = "schunk_wsg" dut.ext_joint_filter_tau = 0.12 dut.lcm_bus = "test" self.assertIn("lcm_bus", repr(dut)) builder = DiagramBuilder() plant = builder.AddSystem(MultibodyPlant(1.0)) parser = Parser(plant) directives = LoadModelDirectives(FindResourceOrThrow( "drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")) models_from_directives = ProcessModelDirectives(directives, parser) plant.Finalize() model_dict = dict() for model in models_from_directives: model_dict[model.model_name] = model lcm_bus = LcmBuses() lcm_bus.Add("test", DrakeLcm()) tare = len(builder.GetSystems()) mut.ApplyDriverConfig( driver_config=dut, model_instance_name="iiwa7", sim_plant=plant, models_from_directives=model_dict, lcms=lcm_bus, builder=builder) self.assertGreater(len(builder.GetSystems()), tare) def test_kuka_iiwa_sim_driver(self): builder, plant, controller_plant = ( self.make_builder_plant_controller_plant() ) dut = mut.SimIiwaDriver( control_mode=mut.IiwaControlMode.kPositionAndTorque, controller_plant=controller_plant, ext_joint_filter_tau=0.1, kp_gains=np.full(7, 100.0), ) self.assertGreater(dut.num_input_ports(), 0) self.assertGreater(dut.num_output_ports(), 0) tare = len(builder.GetSystems()) dut1 = mut.SimIiwaDriver.AddToBuilder( builder=builder, plant=plant, iiwa_instance=plant.GetModelInstanceByName("iiwa7"), controller_plant=controller_plant, ext_joint_filter_tau=0.1, desired_iiwa_kp_gains=np.full(7, 100.0), control_mode=mut.IiwaControlMode.kPositionAndTorque, ) self.assertGreater(dut1.num_input_ports(), 0) self.assertGreater(dut1.num_output_ports(), 0) self.assertGreater(len(builder.GetSystems()), tare)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py_iris_from_clique_cover.cc
#include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/planning/graph_algorithms/max_clique_solver_base.h" #include "drake/planning/iris/iris_from_clique_cover.h" namespace drake { namespace pydrake { namespace internal { void DefinePlanningIrisFromCliqueCover(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::planning; constexpr auto& doc = pydrake_doc.drake.planning; auto cls_doc = doc.IrisFromCliqueCoverOptions; py::class_<IrisFromCliqueCoverOptions>( m, "IrisFromCliqueCoverOptions", cls_doc.doc) .def(py::init<>()) .def_readwrite("iris_options", &IrisFromCliqueCoverOptions::iris_options, cls_doc.iris_options.doc) .def_readwrite("coverage_termination_threshold", &IrisFromCliqueCoverOptions::coverage_termination_threshold, cls_doc.coverage_termination_threshold.doc) .def_readwrite("iteration_limit", &IrisFromCliqueCoverOptions::iteration_limit, cls_doc.iteration_limit.doc) .def_readwrite("num_points_per_coverage_check", &IrisFromCliqueCoverOptions::num_points_per_coverage_check, cls_doc.num_points_per_coverage_check.doc) .def_readwrite("parallelism", &IrisFromCliqueCoverOptions::parallelism, cls_doc.parallelism.doc) .def_readwrite("minimum_clique_size", &IrisFromCliqueCoverOptions::minimum_clique_size, cls_doc.minimum_clique_size.doc) .def_readwrite("num_points_per_visibility_round", &IrisFromCliqueCoverOptions::num_points_per_visibility_round, cls_doc.num_points_per_visibility_round.doc) .def_readwrite("rank_tol_for_minimum_volume_circumscribed_ellipsoid", &IrisFromCliqueCoverOptions:: rank_tol_for_minimum_volume_circumscribed_ellipsoid, cls_doc.rank_tol_for_minimum_volume_circumscribed_ellipsoid.doc) .def_readwrite("point_in_set_tol", &IrisFromCliqueCoverOptions::point_in_set_tol, cls_doc.point_in_set_tol.doc); m.def( "IrisInConfigurationSpaceFromCliqueCover", [](const CollisionChecker& checker, const IrisFromCliqueCoverOptions& options, RandomGenerator generator, std::vector<geometry::optimization::HPolyhedron> sets, const planning::graph_algorithms::MaxCliqueSolverBase* max_clique_solver) { IrisInConfigurationSpaceFromCliqueCover( checker, options, &generator, &sets, max_clique_solver); return sets; }, py::arg("checker"), py::arg("options"), py::arg("generator"), py::arg("sets"), py::arg("max_clique_solver") = nullptr, py::call_guard<py::gil_scoped_release>(), doc.IrisInConfigurationSpaceFromCliqueCover.doc); } // DefinePlanningIrisFromCliqueCover } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/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_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. # TODO(eric.cousineau): address # https://github.com/RobotLocomotion/drake/issues/12055 PACKAGE_INFO = get_pybind_package_info("//bindings") drake_pybind_library( name = "planning", cc_deps = [ "//bindings/pydrake:documentation_pybind", "//bindings/pydrake/common:cpp_template_pybind", "//bindings/pydrake/common:default_scalars_pybind", "//bindings/pydrake/common:wrap_pybind", "//bindings/pydrake/geometry:optimization_pybind", ], cc_so_name = "__init__", cc_srcs = [ "planning_py.h", "planning_py.cc", "planning_py_collision_checker.cc", "planning_py_collision_checker_interface_types.cc", "planning_py_graph_algorithms.cc", "planning_py_robot_diagram.cc", "planning_py_trajectory_optimization.cc", "planning_py_visibility_graph.cc", "planning_py_iris_from_clique_cover.cc", "planning_py_zmp_planner.cc", ], package_info = PACKAGE_INFO, py_deps = [ "//bindings/pydrake/geometry", "//bindings/pydrake/multibody:parsing_py", "//bindings/pydrake/multibody:plant_py", "//bindings/pydrake/systems:framework_py", "//bindings/pydrake/systems:primitives_py", "//bindings/pydrake/solvers", "//bindings/pydrake:trajectories_py", ], ) install( name = "install", targets = [":planning"], py_dest = PACKAGE_INFO.py_dest, deps = get_drake_py_installs([":planning"]), ) drake_py_unittest( name = "collision_checker_test", data = [ "//multibody:models", "//planning/test_utilities:collision_ground_plane.sdf", ], num_threads = 2, deps = [ ":planning", "//bindings/pydrake/common/test_utilities:numpy_compare_py", "//bindings/pydrake/common/test_utilities:scipy_stub_py", ], ) drake_py_unittest( name = "collision_checker_trace_test", data = [ "//multibody:models", "//planning/test_utilities:collision_ground_plane.sdf", ], num_threads = 2, deps = [ ":planning", ], ) drake_py_unittest( name = "robot_diagram_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":planning", "//bindings/pydrake/common/test_utilities:numpy_compare_py", ], ) drake_py_unittest( name = "trajectory_optimization_test", deps = [ ":planning", "//bindings/pydrake/examples", ], ) drake_py_unittest( name = "graph_algorithms_test", deps = [ ":planning", "//bindings/pydrake/common/test_utilities:numpy_compare_py", "//bindings/pydrake/common/test_utilities:scipy_stub_py", ], ) drake_py_unittest( name = "iris_from_clique_cover_test", data = [ "//multibody:models", "//planning/test_utilities:collision_ground_plane.sdf", ], num_threads = 2, deps = [ ":planning", "//bindings/pydrake/common/test_utilities:numpy_compare_py", "//bindings/pydrake/common/test_utilities:scipy_stub_py", ], ) drake_py_unittest( name = "zmp_planner_test", deps = [ ":planning", "//bindings/pydrake/common/test_utilities:numpy_compare_py", ], ) add_lint_tests_pydrake()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py.cc
#include "drake/bindings/pydrake/planning/planning_py.h" namespace drake { namespace pydrake { PYBIND11_MODULE(planning, m) { PYDRAKE_PREVENT_PYTHON3_MODULE_REIMPORT(m); m.doc() = R"""( A collection of motion planning algorithms for finding configurations and/or trajectories of dynamical systems. )"""; py::module::import("pydrake.geometry"); py::module::import("pydrake.multibody.parsing"); py::module::import("pydrake.multibody.plant"); py::module::import("pydrake.solvers"); py::module::import("pydrake.symbolic"); py::module::import("pydrake.systems.framework"); py::module::import("pydrake.systems.primitives"); py::module::import("pydrake.trajectories"); // The order of these calls matters. Some modules rely on prior definitions. internal::DefinePlanningRobotDiagram(m); internal::DefinePlanningCollisionCheckerInterfaceTypes(m); internal::DefinePlanningCollisionChecker(m); internal::DefinePlanningGraphAlgorithms(m); internal::DefinePlanningTrajectoryOptimization(m); internal::DefinePlanningVisibilityGraph(m); internal::DefinePlanningIrisFromCliqueCover(m); internal::DefinePlanningZmpPlanner(m); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py_zmp_planner.cc
#include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/planning/locomotion/zmp_planner.h" namespace drake { namespace pydrake { namespace internal { void DefinePlanningZmpPlanner(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::planning; constexpr auto& doc = pydrake_doc.drake.planning; { using Class = ZmpPlanner; constexpr auto& cls_doc = doc.ZmpPlanner; auto cls = py::class_<Class>(m, "ZmpPlanner", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc); cls.def("Plan", &Class::Plan, py::arg("zmp_d"), py::arg("x0"), py::arg("height"), py::arg("gravity") = 9.81, py::arg("Qy") = Eigen::Matrix2d::Identity(), py::arg("R") = 0.1 * Eigen::Matrix2d::Identity(), cls_doc.ctor.doc) .def("has_planned", &Class::has_planned, cls_doc.has_planned.doc) .def("ComputeOptimalCoMdd", &Class::ComputeOptimalCoMdd, py::arg("time"), py::arg("x"), cls_doc.ComputeOptimalCoMdd.doc) .def("comdd_to_cop", &Class::comdd_to_cop, py::arg("x"), py::arg("u"), cls_doc.comdd_to_cop.doc) .def("get_A", &Class::get_A, cls_doc.get_A.doc) .def("get_B", &Class::get_B, cls_doc.get_B.doc) .def("get_C", &Class::get_C, cls_doc.get_C.doc) .def("get_D", &Class::get_D, cls_doc.get_D.doc) .def("get_Qy", &Class::get_Qy, cls_doc.get_Qy.doc) .def("get_R", &Class::get_R, cls_doc.get_R.doc) .def("get_desired_zmp", overload_cast_explicit<Eigen::Vector2d, double>( &Class::get_desired_zmp), py::arg("time"), cls_doc.get_desired_zmp.doc_at_time) .def("get_nominal_com", overload_cast_explicit<Eigen::Vector2d, double>( &Class::get_nominal_com), py::arg("time"), cls_doc.get_nominal_com.doc_at_time) .def("get_nominal_comd", overload_cast_explicit<Eigen::Vector2d, double>( &Class::get_nominal_comd), py::arg("time"), cls_doc.get_nominal_comd.doc_at_time) .def("get_nominal_comdd", overload_cast_explicit<Eigen::Vector2d, double>( &Class::get_nominal_comdd), py::arg("time"), cls_doc.get_nominal_comdd.doc_at_time) .def("get_final_desired_zmp", &Class::get_final_desired_zmp, cls_doc.get_final_desired_zmp.doc) .def("get_desired_zmp", overload_cast_explicit< const trajectories::PiecewisePolynomial<double>&>( &Class::get_desired_zmp), py_rvp::copy, cls_doc.get_desired_zmp.doc) .def("get_nominal_com", overload_cast_explicit<const trajectories:: ExponentialPlusPiecewisePolynomial<double>&>( &Class::get_nominal_com), py_rvp::copy, cls_doc.get_nominal_com.doc) .def("get_nominal_comd", overload_cast_explicit<const trajectories:: ExponentialPlusPiecewisePolynomial<double>&>( &Class::get_nominal_comd), py_rvp::copy, cls_doc.get_nominal_comd.doc) .def("get_nominal_comdd", overload_cast_explicit<const trajectories:: ExponentialPlusPiecewisePolynomial<double>&>( &Class::get_nominal_comdd), py_rvp::copy, cls_doc.get_nominal_comdd.doc) .def("get_Vxx", &Class::get_Vxx, cls_doc.get_Vxx.doc) .def("get_Vx", overload_cast_explicit<const Eigen::Vector4d, double>( &Class::get_Vx), py::arg("time"), cls_doc.get_Vx.doc_at_time) .def("get_Vx", overload_cast_explicit<const trajectories:: ExponentialPlusPiecewisePolynomial<double>&>( &Class::get_Vx), py_rvp::copy, cls_doc.get_Vx.doc); DefCopyAndDeepCopy(&cls); } } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py_collision_checker_interface_types.cc
#include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/planning/planning_py.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/planning/body_shape_description.h" #include "drake/planning/collision_checker_context.h" #include "drake/planning/collision_checker_params.h" #include "drake/planning/distance_and_interpolation_provider.h" #include "drake/planning/edge_measure.h" #include "drake/planning/linear_distance_and_interpolation_provider.h" #include "drake/planning/robot_clearance.h" #include "drake/planning/robot_collision_type.h" namespace drake { namespace pydrake { namespace internal { void DefinePlanningCollisionCheckerInterfaceTypes(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::planning; constexpr auto& doc = pydrake_doc.drake.planning; { using Class = BodyShapeDescription; constexpr auto& cls_doc = doc.BodyShapeDescription; py::class_<Class> cls(m, "BodyShapeDescription", cls_doc.doc); cls // BR .def(py::init<const geometry::Shape&, const math::RigidTransformd&, std::string, std::string>(), py::arg("shape"), py::arg("X_BS"), py::arg("model_instance_name"), py::arg("body_name"), cls_doc.ctor.doc) .def(py::init<const Class&>(), py::arg("other")) .def("shape", &Class::shape, py_rvp::reference_internal, cls_doc.shape.doc) .def("pose_in_body", &Class::pose_in_body, cls_doc.pose_in_body.doc) .def("model_instance_name", &Class::model_instance_name, cls_doc.model_instance_name.doc) .def("body_name", &Class::body_name, cls_doc.body_name.doc); DefCopyAndDeepCopy(&cls); } m.def("MakeBodyShapeDescription", &MakeBodyShapeDescription, py::arg("plant"), py::arg("plant_context"), py::arg("geometry_id"), doc.MakeBodyShapeDescription.doc); { using Class = CollisionCheckerContext; constexpr auto& cls_doc = doc.CollisionCheckerContext; py::class_<Class, std::shared_ptr<Class>> cls( m, "CollisionCheckerContext", cls_doc.doc); cls // BR .def(py::init<const RobotDiagram<double>*>(), py::arg("model"), // Keep alive, reference: `self` keeps `model` alive. py::keep_alive<1, 2>(), cls_doc.ctor.doc) .def("model_context", &Class::model_context, py_rvp::reference_internal, cls_doc.model_context.doc) .def("plant_context", &Class::plant_context, py_rvp::reference_internal, cls_doc.plant_context.doc) .def("scene_graph_context", &Class::scene_graph_context, py_rvp::reference_internal, cls_doc.scene_graph_context.doc) .def("GetQueryObject", &Class::GetQueryObject, py_rvp::reference_internal, cls_doc.GetQueryObject.doc); DefClone(&cls); } { using Class = DistanceAndInterpolationProvider; constexpr auto& cls_doc = doc.DistanceAndInterpolationProvider; py::class_<Class, std::shared_ptr<Class>> cls( m, "DistanceAndInterpolationProvider", cls_doc.doc); cls // BR .def("ComputeConfigurationDistance", &Class::ComputeConfigurationDistance, cls_doc.ComputeConfigurationDistance.doc) .def("InterpolateBetweenConfigurations", &Class::InterpolateBetweenConfigurations, cls_doc.InterpolateBetweenConfigurations.doc); } { using Class = LinearDistanceAndInterpolationProvider; constexpr auto& cls_doc = doc.LinearDistanceAndInterpolationProvider; py::class_<Class, DistanceAndInterpolationProvider, std::shared_ptr<LinearDistanceAndInterpolationProvider>> cls(m, "LinearDistanceAndInterpolationProvider", cls_doc.doc); cls // BR .def(py::init<const drake::multibody::MultibodyPlant<double>&>(), py::arg("plant"), cls_doc.ctor.doc_1args_plant) .def(py::init<const drake::multibody::MultibodyPlant<double>&, const Eigen::VectorXd&>(), py::arg("plant"), py::arg("distance_weights"), cls_doc.ctor.doc_2args_plant_distance_weights) .def(py::init<const drake::multibody::MultibodyPlant<double>&, const std::map<drake::multibody::JointIndex, Eigen::VectorXd>&>(), py::arg("plant"), py::arg("joint_distance_weights"), cls_doc.ctor.doc_2args_plant_joint_distance_weights) .def("distance_weights", &Class::distance_weights, py_rvp::reference_internal, cls_doc.distance_weights.doc) .def("quaternion_dof_start_indices", &Class::quaternion_dof_start_indices, cls_doc.quaternion_dof_start_indices.doc); } { using Class = CollisionCheckerParams; constexpr auto& cls_doc = doc.CollisionCheckerParams; py::class_<Class> cls(m, "CollisionCheckerParams", cls_doc.doc); cls // BR .def(py::init<>()) .def(ParamInit<Class>()) .def_property( "model", [](const Class& self) -> const RobotDiagram<double>* { return self.model.get(); }, [](Class& self, std::unique_ptr<RobotDiagram<double>> model) { self.model = std::move(model); }, cls_doc.model.doc) .def_readwrite("distance_and_interpolation_provider", &Class::distance_and_interpolation_provider, cls_doc.distance_and_interpolation_provider.doc) .def_readwrite("robot_model_instances", &Class::robot_model_instances, cls_doc.robot_model_instances.doc) .def_readwrite("configuration_distance_function", &Class::configuration_distance_function, cls_doc.configuration_distance_function.doc) .def_readwrite("edge_step_size", &Class::edge_step_size, cls_doc.edge_step_size.doc) .def_readwrite("env_collision_padding", &Class::env_collision_padding, cls_doc.env_collision_padding.doc) .def_readwrite("self_collision_padding", &Class::self_collision_padding, cls_doc.self_collision_padding.doc) .def_readwrite("implicit_context_parallelism", &Class::implicit_context_parallelism, cls_doc.implicit_context_parallelism.doc); // N.B. Any time we bind new CollisionCheckerParams fields that have pointer // semantics (e.g., std::unique_ptr), we should revisit the CollisionChecker // constructor bindings (e.g., SceneGraphCollisionChecker) and fix up their // keep_alive<> annotations. } { using Class = EdgeMeasure; constexpr auto& cls_doc = doc.EdgeMeasure; py::class_<Class> cls(m, "EdgeMeasure", cls_doc.doc); cls // BR .def(py::init<double, double>(), py::arg("distance"), py::arg("alpha"), cls_doc.ctor.doc) .def(py::init<const Class&>(), py::arg("other")) .def("completely_free", &Class::completely_free, cls_doc.completely_free.doc) .def("partially_free", &Class::partially_free, cls_doc.partially_free.doc) .def("distance", &Class::distance, cls_doc.distance.doc) .def("alpha", &Class::alpha, cls_doc.alpha.doc) .def("alpha_or", &Class::alpha_or, py::arg("default_value"), cls_doc.alpha_or.doc); DefCopyAndDeepCopy(&cls); } { using Class = RobotClearance; constexpr auto& cls_doc = doc.RobotClearance; py::class_<Class> cls(m, "RobotClearance", cls_doc.doc); cls // BR .def(py::init<int>(), py::arg("num_positions"), cls_doc.ctor.doc) .def(py::init<const Class&>(), py::arg("other")) .def("size", &Class::size, cls_doc.size.doc) .def("num_positions", &Class::num_positions, cls_doc.num_positions.doc) .def("robot_indices", &Class::robot_indices, cls_doc.robot_indices.doc) .def("other_indices", &Class::other_indices, cls_doc.other_indices.doc) .def("collision_types", &Class::collision_types, cls_doc.collision_types.doc) .def("distances", &Class::distances, py_rvp::reference_internal, cls_doc.distances.doc) .def("jacobians", &Class::jacobians, py_rvp::reference_internal, cls_doc.jacobians.doc) .def("mutable_jacobians", &Class::mutable_jacobians, py_rvp::reference_internal, cls_doc.mutable_jacobians.doc) .def("Reserve", &Class::Reserve, py::arg("size"), cls_doc.Reserve.doc) .def("Append", &Class::Append, py::arg("robot_index"), py::arg("other_index"), py::arg("collision_type"), py::arg("distance"), py::arg("jacobian"), cls_doc.Append.doc); DefCopyAndDeepCopy(&cls); } { using Class = RobotCollisionType; constexpr auto& cls_doc = doc.RobotCollisionType; py::enum_<Class> cls(m, "RobotCollisionType", cls_doc.doc); cls // BR .value("kNoCollision", Class::kNoCollision, cls_doc.kNoCollision.doc) .value("kEnvironmentCollision", Class::kEnvironmentCollision, cls_doc.kEnvironmentCollision.doc) .value( "kSelfCollision", Class::kSelfCollision, cls_doc.kSelfCollision.doc) .value("kEnvironmentAndSelfCollision", Class::kEnvironmentAndSelfCollision, cls_doc.kEnvironmentAndSelfCollision.doc) // We don't bind the un-Pythonic SetInEnvironmentCollision and // SetInSelfCollision. Instead, we'll define some Python-only sugar. .def( "MakeUpdated", [](const Class& self, std::optional<bool> in_environment_collision, std::optional<bool> in_self_collision) -> Class { Class result = self; if (in_environment_collision.has_value()) { result = SetInEnvironmentCollision( result, *in_environment_collision); } if (in_self_collision.has_value()) { result = SetInSelfCollision(result, *in_self_collision); } return result; }, py::kw_only(), py::arg("in_environment_collision") = py::none(), py::arg("in_self_collision") = py::none(), "Returns the RobotCollisionType value that reflects an " "incrementally different collision status versus the current" " value; the ``self`` object is unchanged. " "If ``in_environment_collision`` and/or ``in_self_collision`` is " "given, the return value will reflect those given value(s). " "This function subsumes the C++ free functions " "``SetInEnvironmentCollision()`` and ``SetInSelfCollision()``."); } } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py_collision_checker.cc
#include "drake/bindings/pydrake/common/wrap_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/planning/planning_py.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/planning/collision_checker.h" #include "drake/planning/distance_and_interpolation_provider.h" #include "drake/planning/scene_graph_collision_checker.h" #include "drake/planning/unimplemented_collision_checker.h" namespace drake { namespace pydrake { namespace internal { using multibody::BodyIndex; using multibody::Frame; using multibody::RigidBody; void DefinePlanningCollisionChecker(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::planning; constexpr auto& doc = pydrake_doc.drake.planning; { using Class = CollisionChecker; constexpr auto& cls_doc = doc.CollisionChecker; py::class_<Class> cls(m, "CollisionChecker", cls_doc.doc); cls // BR .def("model", &Class::model, py_rvp::reference_internal, cls_doc.model.doc) .def("plant", &Class::plant, py_rvp::reference_internal, cls_doc.plant.doc) .def("get_body", &Class::get_body, py::arg("body_index"), py_rvp::reference_internal, cls_doc.get_body.doc) .def("robot_model_instances", &Class::robot_model_instances, cls_doc.robot_model_instances.doc) .def("IsPartOfRobot", overload_cast_explicit<bool, const RigidBody<double>&>( &Class::IsPartOfRobot), py::arg("body"), cls_doc.IsPartOfRobot.doc) .def("IsPartOfRobot", overload_cast_explicit<bool, BodyIndex>(&Class::IsPartOfRobot), py::arg("body_index"), cls_doc.IsPartOfRobot.doc) .def("GetZeroConfiguration", &Class::GetZeroConfiguration, cls_doc.GetZeroConfiguration.doc) .def("num_allocated_contexts", &Class::num_allocated_contexts, cls_doc.num_allocated_contexts.doc) .def("model_context", &Class::model_context, py::arg("context_number") = std::nullopt, py_rvp::reference_internal, cls_doc.model_context.doc) .def("plant_context", &Class::plant_context, py::arg("context_number") = std::nullopt, py_rvp::reference_internal, cls_doc.plant_context.doc) .def("UpdatePositions", &Class::UpdatePositions, py_rvp::reference_internal, py::arg("q"), py::arg("context_number") = std::nullopt, cls_doc.UpdatePositions.doc) .def("UpdateContextPositions", &Class::UpdateContextPositions, py::arg("model_context"), py::arg("q"), // Keep alive, ownership: `return` keeps `model_context` alive. py::keep_alive<0, 2>(), py_rvp::reference, cls_doc.UpdateContextPositions.doc) .def("MakeStandaloneModelContext", &Class::MakeStandaloneModelContext, cls_doc.MakeStandaloneModelContext.doc) .def("PerformOperationAgainstAllModelContexts", WrapCallbacks(&Class::PerformOperationAgainstAllModelContexts), py::arg("operation"), cls_doc.PerformOperationAgainstAllModelContexts.doc) .def("AddCollisionShape", &Class::AddCollisionShape, py::arg("group_name"), py::arg("description"), cls_doc.AddCollisionShape.doc) .def("AddCollisionShapes", py::overload_cast<const std::string&, const std::vector<BodyShapeDescription>&>( &Class::AddCollisionShapes), py::arg("group_name"), py::arg("descriptions"), cls_doc.AddCollisionShapes.doc_2args) .def("AddCollisionShapes", py::overload_cast<const std::map<std::string, std::vector<BodyShapeDescription>>&>( &Class::AddCollisionShapes), py::arg("geometry_groups"), cls_doc.AddCollisionShapes.doc_1args) .def("AddCollisionShapeToFrame", &Class::AddCollisionShapeToFrame, py::arg("group_name"), py::arg("frameA"), py::arg("shape"), py::arg("X_AG"), cls_doc.AddCollisionShapeToFrame.doc) .def("AddCollisionShapeToBody", &Class::AddCollisionShapeToBody, py::arg("group_name"), py::arg("bodyA"), py::arg("shape"), py::arg("X_AG"), cls_doc.AddCollisionShapeToBody.doc) .def("GetAllAddedCollisionShapes", &Class::GetAllAddedCollisionShapes, cls_doc.GetAllAddedCollisionShapes.doc) .def("RemoveAllAddedCollisionShapes", py::overload_cast<const std::string&>( &Class::RemoveAllAddedCollisionShapes), py::arg("group_name"), cls_doc.RemoveAllAddedCollisionShapes.doc_1args) .def("RemoveAllAddedCollisionShapes", py::overload_cast<>(&Class::RemoveAllAddedCollisionShapes), cls_doc.RemoveAllAddedCollisionShapes.doc_0args) .def("MaybeGetUniformRobotEnvironmentPadding", &Class::MaybeGetUniformRobotEnvironmentPadding, cls_doc.MaybeGetUniformRobotEnvironmentPadding.doc) .def("MaybeGetUniformRobotRobotPadding", &Class::MaybeGetUniformRobotRobotPadding, cls_doc.MaybeGetUniformRobotRobotPadding.doc) .def("GetPaddingBetween", overload_cast_explicit<double, BodyIndex, BodyIndex>( &Class::GetPaddingBetween), py::arg("bodyA_index"), py::arg("bodyB_index"), cls_doc.GetPaddingBetween.doc_2args_bodyA_index_bodyB_index) .def("GetPaddingBetween", overload_cast_explicit<double, const RigidBody<double>&, const RigidBody<double>&>(&Class::GetPaddingBetween), py::arg("bodyA"), py::arg("bodyB"), cls_doc.GetPaddingBetween.doc_2args_bodyA_bodyB) .def("SetPaddingBetween", py::overload_cast<BodyIndex, BodyIndex, double>( &Class::SetPaddingBetween), py::arg("bodyA_index"), py::arg("bodyB_index"), py::arg("padding"), cls_doc.SetPaddingBetween.doc_3args_bodyA_index_bodyB_index_padding) .def("SetPaddingBetween", py::overload_cast<const RigidBody<double>&, const RigidBody<double>&, double>(&Class::SetPaddingBetween), py::arg("bodyA"), py::arg("bodyB"), py::arg("padding"), cls_doc.SetPaddingBetween.doc_3args_bodyA_bodyB_padding) .def("GetPaddingMatrix", &Class::GetPaddingMatrix, py_rvp::reference_internal, cls_doc.GetPaddingMatrix.doc) .def("SetPaddingMatrix", &Class::SetPaddingMatrix, py::arg("collision_padding"), cls_doc.SetPaddingMatrix.doc) .def("GetLargestPadding", &Class::GetLargestPadding, cls_doc.GetLargestPadding.doc) .def("SetPaddingOneRobotBodyAllEnvironmentPairs", &Class::SetPaddingOneRobotBodyAllEnvironmentPairs, py::arg("body_index"), py::arg("padding"), cls_doc.SetPaddingOneRobotBodyAllEnvironmentPairs.doc) .def("SetPaddingAllRobotEnvironmentPairs", &Class::SetPaddingAllRobotEnvironmentPairs, py::arg("padding"), cls_doc.SetPaddingAllRobotEnvironmentPairs.doc) .def("SetPaddingAllRobotRobotPairs", &Class::SetPaddingAllRobotRobotPairs, py::arg("padding"), cls_doc.SetPaddingAllRobotRobotPairs.doc) .def("GetNominalFilteredCollisionMatrix", &Class::GetNominalFilteredCollisionMatrix, py_rvp::reference_internal, cls_doc.GetNominalFilteredCollisionMatrix.doc) .def("GetFilteredCollisionMatrix", &Class::GetFilteredCollisionMatrix, py_rvp::reference_internal, cls_doc.GetFilteredCollisionMatrix.doc) .def("SetCollisionFilterMatrix", &Class::SetCollisionFilterMatrix, py::arg("filter_matrix"), cls_doc.SetCollisionFilterMatrix.doc) .def("IsCollisionFilteredBetween", overload_cast_explicit<bool, BodyIndex, BodyIndex>( &Class::IsCollisionFilteredBetween), py::arg("bodyA_index"), py::arg("bodyB_index"), cls_doc.IsCollisionFilteredBetween .doc_2args_bodyA_index_bodyB_index) .def("IsCollisionFilteredBetween", overload_cast_explicit<bool, const RigidBody<double>&, const RigidBody<double>&>(&Class::IsCollisionFilteredBetween), py::arg("bodyA"), py::arg("bodyB"), cls_doc.IsCollisionFilteredBetween.doc_2args_bodyA_bodyB) .def("SetCollisionFilteredBetween", py::overload_cast<BodyIndex, BodyIndex, bool>( &Class::SetCollisionFilteredBetween), py::arg("bodyA_index"), py::arg("bodyB_index"), py::arg("filter_collision"), cls_doc.SetCollisionFilteredBetween .doc_3args_bodyA_index_bodyB_index_filter_collision) .def("SetCollisionFilteredBetween", py::overload_cast<const RigidBody<double>&, const RigidBody<double>&, bool>( &Class::SetCollisionFilteredBetween), py::arg("bodyA"), py::arg("bodyB"), py::arg("filter_collision"), cls_doc.SetCollisionFilteredBetween .doc_3args_bodyA_bodyB_filter_collision) .def("SetCollisionFilteredWithAllBodies", py::overload_cast<BodyIndex>( &Class::SetCollisionFilteredWithAllBodies), py::arg("body_index"), cls_doc.SetCollisionFilteredWithAllBodies.doc_1args_body_index) .def("SetCollisionFilteredWithAllBodies", py::overload_cast<const RigidBody<double>&>( &Class::SetCollisionFilteredWithAllBodies), py::arg("body"), cls_doc.SetCollisionFilteredWithAllBodies.doc_1args_body) .def("CheckConfigCollisionFree", &Class::CheckConfigCollisionFree, py::arg("q"), py::arg("context_number") = std::nullopt, cls_doc.CheckConfigCollisionFree.doc) .def("CheckContextConfigCollisionFree", &Class::CheckContextConfigCollisionFree, py::arg("model_context"), py::arg("q"), cls_doc.CheckContextConfigCollisionFree.doc) .def("CheckConfigsCollisionFree", &Class::CheckConfigsCollisionFree, py::arg("configs"), py::arg("parallelize") = true, py::call_guard<py::gil_scoped_release>(), cls_doc.CheckConfigsCollisionFree.doc) .def("SetDistanceAndInterpolationProvider", &Class::SetDistanceAndInterpolationProvider, py::arg("provider"), cls_doc.SetDistanceAndInterpolationProvider.doc) .def("distance_and_interpolation_provider", &Class::distance_and_interpolation_provider, py_rvp::reference_internal, cls_doc.distance_and_interpolation_provider.doc) .def("SetConfigurationDistanceFunction", WrapCallbacks(&Class::SetConfigurationDistanceFunction), py::arg("distance_function"), cls_doc.SetConfigurationDistanceFunction.doc) .def("ComputeConfigurationDistance", &Class::ComputeConfigurationDistance, py::arg("q1"), py::arg("q2"), cls_doc.ComputeConfigurationDistance.doc) .def("MakeStandaloneConfigurationDistanceFunction", &Class::MakeStandaloneConfigurationDistanceFunction, cls_doc.MakeStandaloneConfigurationDistanceFunction.doc) .def("SetConfigurationInterpolationFunction", WrapCallbacks(&Class::SetConfigurationInterpolationFunction), py::arg("interpolation_function"), cls_doc.SetConfigurationInterpolationFunction.doc) .def("InterpolateBetweenConfigurations", &Class::InterpolateBetweenConfigurations, py::arg("q1"), py::arg("q2"), py::arg("ratio"), cls_doc.InterpolateBetweenConfigurations.doc) .def("MakeStandaloneConfigurationInterpolationFunction", &Class::MakeStandaloneConfigurationInterpolationFunction, cls_doc.MakeStandaloneConfigurationInterpolationFunction.doc) .def("edge_step_size", &Class::edge_step_size, cls_doc.edge_step_size.doc) .def("set_edge_step_size", &Class::set_edge_step_size, py::arg("edge_step_size"), cls_doc.set_edge_step_size.doc) .def("CheckEdgeCollisionFree", &Class::CheckEdgeCollisionFree, py::arg("q1"), py::arg("q2"), py::arg("context_number") = std::nullopt, cls_doc.CheckEdgeCollisionFree.doc) .def("CheckContextEdgeCollisionFree", &Class::CheckContextEdgeCollisionFree, py::arg("model_context"), py::arg("q1"), py::arg("q2")) .def("CheckEdgeCollisionFreeParallel", &Class::CheckEdgeCollisionFreeParallel, py::arg("q1"), py::arg("q2"), py::arg("parallelize") = true, py::call_guard<py::gil_scoped_release>(), cls_doc.CheckEdgeCollisionFreeParallel.doc) .def("CheckEdgesCollisionFree", &Class::CheckEdgesCollisionFree, py::arg("edges"), py::arg("parallelize") = true, py::call_guard<py::gil_scoped_release>(), cls_doc.CheckEdgesCollisionFree.doc) .def("MeasureEdgeCollisionFree", &Class::MeasureEdgeCollisionFree, py::arg("q1"), py::arg("q2"), py::arg("context_number") = std::nullopt, cls_doc.MeasureEdgeCollisionFree.doc) .def("MeasureContextEdgeCollisionFree", &Class::MeasureContextEdgeCollisionFree, py::arg("model_context"), py::arg("q1"), py::arg("q2"), cls_doc.MeasureContextEdgeCollisionFree.doc) .def("MeasureEdgeCollisionFreeParallel", &Class::MeasureEdgeCollisionFreeParallel, py::arg("q1"), py::arg("q2"), py::arg("parallelize") = true, py::call_guard<py::gil_scoped_release>(), cls_doc.MeasureEdgeCollisionFreeParallel.doc) .def("MeasureEdgesCollisionFree", &Class::MeasureEdgesCollisionFree, py::arg("edges"), py::arg("parallelize") = true, py::call_guard<py::gil_scoped_release>(), cls_doc.MeasureEdgesCollisionFree.doc) .def("CalcRobotClearance", &Class::CalcRobotClearance, py::arg("q"), py::arg("influence_distance"), py::arg("context_number") = std::nullopt, cls_doc.CalcRobotClearance.doc) .def("CalcContextRobotClearance", &Class::CalcContextRobotClearance, py::arg("model_context"), py::arg("q"), py::arg("influence_distance"), cls_doc.CalcContextRobotClearance.doc) .def("MaxNumDistances", &Class::MaxNumDistances, py::arg("context_number") = std::nullopt, cls_doc.MaxNumDistances.doc) .def("MaxContextNumDistances", &Class::MaxContextNumDistances, py::arg("model_context"), cls_doc.MaxContextNumDistances.doc) .def("ClassifyBodyCollisions", &Class::ClassifyBodyCollisions, py::arg("q"), py::arg("context_number") = std::nullopt, cls_doc.ClassifyBodyCollisions.doc) .def("ClassifyContextBodyCollisions", &Class::ClassifyContextBodyCollisions, py::arg("model_context"), py::arg("q"), cls_doc.ClassifyContextBodyCollisions.doc) .def("SupportsParallelChecking", &Class::SupportsParallelChecking, cls_doc.SupportsParallelChecking.doc); DefClone(&cls); } { using Class = SceneGraphCollisionChecker; constexpr auto& cls_doc = doc.SceneGraphCollisionChecker; py::class_<Class, CollisionChecker> cls( m, "SceneGraphCollisionChecker", cls_doc.doc); // TODO(jwnimmer-tri) Bind the __init__(params=...) constructor here once // we've solved the unique_ptr vs shared_ptr binding lifetime issue. py::object params_ctor = m.attr("CollisionCheckerParams"); cls // BR .def(py::init([params_ctor](std::unique_ptr<RobotDiagram<double>> model, const py::kwargs& kwargs) { // For lifetime management, we need to treat pointer-like arguments // separately. Start by creating a Params object in Python with all // of the other non-pointer kwargs. py::object params_py = params_ctor(**kwargs); auto* params = params_py.cast<CollisionCheckerParams*>(); DRAKE_DEMAND(params != nullptr); // Now, transfer ownership of the pointer. params->model = std::move(model); return std::make_unique<SceneGraphCollisionChecker>( std::move(*params)); }), py::kw_only(), py::arg("model"), // Keep alive, ownership: `model` keeps `self` alive. py::keep_alive<2, 1>(), (std::string(cls_doc.ctor.doc) + "\n\n" "See :class:`pydrake.planning.CollisionCheckerParams` for the " "list of properties available here as kwargs.") .c_str()); } { using Class = UnimplementedCollisionChecker; constexpr auto& cls_doc = doc.UnimplementedCollisionChecker; py::class_<Class, CollisionChecker> cls( m, "UnimplementedCollisionChecker", cls_doc.doc); // TODO(jwnimmer-tri) Bind the __init__(params=...) constructor here once // we've solved the unique_ptr vs shared_ptr binding lifetime issue. py::object params_ctor = m.attr("CollisionCheckerParams"); cls // BR .def(py::init([params_ctor](std::unique_ptr<RobotDiagram<double>> model, bool supports_parallel_checking, const py::kwargs& kwargs) { // For lifetime management, we need to treat pointer-like arguments // separately. Start by creating a Params object in Python with all // of the other non-pointer kwargs. py::object params_py = params_ctor(**kwargs); auto* params = params_py.cast<CollisionCheckerParams*>(); DRAKE_DEMAND(params != nullptr); // Now, transfer ownership of the pointer. params->model = std::move(model); return std::make_unique<UnimplementedCollisionChecker>( std::move(*params), supports_parallel_checking); }), py::kw_only(), py::arg("model"), py::arg("supports_parallel_checking"), // Keep alive, ownership: `model` keeps `self` alive. py::keep_alive<2, 1>(), (std::string(cls_doc.ctor.doc) + "\n\n" "See :class:`pydrake.planning.CollisionCheckerParams` for the " "list of properties available here as kwargs.") .c_str()); } } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py_visibility_graph.cc
#include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/planning/visibility_graph.h" namespace drake { namespace pydrake { namespace internal { void DefinePlanningVisibilityGraph(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::planning; constexpr auto& doc = pydrake_doc.drake.planning; m.def("VisibilityGraph", &planning::VisibilityGraph, py::arg("checker"), py::arg("points"), py::arg("parallelize") = true, py::call_guard<py::gil_scoped_release>(), doc.VisibilityGraph.doc); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py_trajectory_optimization.cc
#include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/geometry/optimization_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/bindings/pydrake/symbolic_types_pybind.h" #include "drake/geometry/optimization/convex_set.h" #include "drake/planning/trajectory_optimization/direct_collocation.h" #include "drake/planning/trajectory_optimization/direct_transcription.h" #include "drake/planning/trajectory_optimization/gcs_trajectory_optimization.h" #include "drake/planning/trajectory_optimization/kinematic_trajectory_optimization.h" namespace drake { namespace pydrake { namespace internal { template <typename C> void RegisterAddConstraintToAllKnotPoints( py::class_<planning::trajectory_optimization::MultipleShooting>* cls) { using drake::planning::trajectory_optimization::MultipleShooting; constexpr auto& doc = pydrake_doc.drake.planning.trajectory_optimization; cls->def( "AddConstraintToAllKnotPoints", [](MultipleShooting* self, std::shared_ptr<C> constraint, const Eigen::Ref<const VectorX<symbolic::Variable>>& vars) -> std::vector<solvers::Binding<C>> { return self->AddConstraintToAllKnotPoints<C>(constraint, vars); }, py::arg("constraint"), py::arg("vars"), doc.MultipleShooting.AddConstraintToAllKnotPoints.doc_shared_ptr); } void DefinePlanningTrajectoryOptimization(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::planning::trajectory_optimization; constexpr auto& doc = pydrake_doc.drake.planning.trajectory_optimization; using solvers::MathematicalProgram; using solvers::MatrixXDecisionVariable; using solvers::VectorXDecisionVariable; { using Class = MultipleShooting; constexpr auto& cls_doc = doc.MultipleShooting; py::class_<Class> cls(m, "MultipleShooting", cls_doc.doc); cls // BR .def("time", &Class::time, cls_doc.time.doc) .def("prog", overload_cast_explicit<MathematicalProgram&>(&Class::prog), py_rvp::reference_internal, cls_doc.prog.doc) .def("time_step", &Class::time_step, py::arg("index"), cls_doc.time_step.doc) .def("fixed_time_step", &Class::fixed_time_step, cls_doc.fixed_time_step.doc) // TODO(eric.cousineau): The original bindings returned references // instead of copies using VectorXBlock. Restore this once dtype=custom // is resolved. .def( "state", [](const Class& self) -> VectorXDecisionVariable { return self.state(); }, cls_doc.state.doc_0args) .def( "state", [](const Class& self, int index) -> VectorXDecisionVariable { return self.state(index); }, py::arg("index"), cls_doc.state.doc_1args) .def( "initial_state", [](const Class& self) -> VectorXDecisionVariable { return self.initial_state(); }, cls_doc.initial_state.doc) .def( "final_state", [](const Class& self) -> VectorXDecisionVariable { return self.final_state(); }, cls_doc.final_state.doc) .def( "input", [](const Class& self) -> VectorXDecisionVariable { return self.input(); }, cls_doc.input.doc_0args) .def( "input", [](const Class& self, int index) -> VectorXDecisionVariable { return self.input(index); }, py::arg("index"), cls_doc.input.doc_1args) .def( "NewSequentialVariable", [](Class& self, int rows, const std::string& name) -> VectorXDecisionVariable { return self.NewSequentialVariable(rows, name); }, py::arg("rows"), py::arg("name"), cls_doc.NewSequentialVariable.doc) .def( "GetSequentialVariableAtIndex", [](const Class& self, const std::string& name, int index) -> VectorXDecisionVariable { return self.GetSequentialVariableAtIndex(name, index); }, py::arg("name"), py::arg("index"), cls_doc.GetSequentialVariableAtIndex.doc) .def( "AddRunningCost", [](Class& prog, const symbolic::Expression& g) { prog.AddRunningCost(g); }, py::arg("g"), cls_doc.AddRunningCost.doc_1args_g) .def( "AddRunningCost", [](Class& prog, const Eigen::Ref<const MatrixX<symbolic::Expression>>& g) { prog.AddRunningCost(g); }, py::arg("g"), cls_doc.AddRunningCost.doc_1args_constEigenMatrixBase) .def( "AddConstraintToAllKnotPoints", [](Class* self, const symbolic::Formula& f) { return self->AddConstraintToAllKnotPoints(f); }, py::arg("f"), cls_doc.AddConstraintToAllKnotPoints.doc) .def( "AddConstraintToAllKnotPoints", [](Class* self, const Eigen::Ref<const VectorX<symbolic::Formula>>& f) { return self->AddConstraintToAllKnotPoints(f); }, py::arg("f"), cls_doc.AddConstraintToAllKnotPoints.doc_formulas) .def("AddTimeIntervalBounds", &Class::AddTimeIntervalBounds, py::arg("lower_bound"), py::arg("upper_bound"), cls_doc.AddTimeIntervalBounds.doc) .def("AddEqualTimeIntervalsConstraints", &Class::AddEqualTimeIntervalsConstraints, cls_doc.AddEqualTimeIntervalsConstraints.doc) .def("AddDurationBounds", &Class::AddDurationBounds, py::arg("lower_bound"), py::arg("upper_bound"), cls_doc.AddDurationBounds.doc) .def("AddFinalCost", py::overload_cast<const symbolic::Expression&>( &Class::AddFinalCost), py::arg("e"), cls_doc.AddFinalCost.doc_1args_e) .def("AddFinalCost", py::overload_cast< const Eigen::Ref<const MatrixX<symbolic::Expression>>&>( &Class::AddFinalCost), py::arg("matrix"), cls_doc.AddFinalCost.doc_1args_matrix) .def("AddInputTrajectoryCallback", &Class::AddInputTrajectoryCallback, py::arg("callback"), cls_doc.AddInputTrajectoryCallback.doc) .def("AddStateTrajectoryCallback", &Class::AddStateTrajectoryCallback, py::arg("callback"), cls_doc.AddStateTrajectoryCallback.doc) .def("AddCompleteTrajectoryCallback", &Class::AddCompleteTrajectoryCallback, py::arg("callback"), py::arg("names"), cls_doc.AddCompleteTrajectoryCallback.doc) .def("SetInitialTrajectory", &Class::SetInitialTrajectory, py::arg("traj_init_u"), py::arg("traj_init_x"), cls_doc.SetInitialTrajectory.doc) .def("GetSampleTimes", overload_cast_explicit<Eigen::VectorXd, const solvers::MathematicalProgramResult&>( &Class::GetSampleTimes), py::arg("result"), cls_doc.GetSampleTimes.doc_1args_h_var_values) .def("GetInputSamples", overload_cast_explicit<Eigen::MatrixXd, const solvers::MathematicalProgramResult&>( &Class::GetInputSamples), py::arg("result"), cls_doc.GetInputSamples.doc) .def("GetStateSamples", overload_cast_explicit<Eigen::MatrixXd, const solvers::MathematicalProgramResult&>( &Class::GetStateSamples), py::arg("result"), cls_doc.GetStateSamples.doc) .def("GetSequentialVariableSamples", overload_cast_explicit<Eigen::MatrixXd, const solvers::MathematicalProgramResult&, const std::string&>( &Class::GetSequentialVariableSamples), py::arg("result"), py::arg("name"), cls_doc.GetSequentialVariableSamples.doc) .def("ReconstructInputTrajectory", overload_cast_explicit<trajectories::PiecewisePolynomial<double>, const solvers::MathematicalProgramResult&>( &Class::ReconstructInputTrajectory), py::arg("result"), cls_doc.ReconstructInputTrajectory.doc) .def("ReconstructStateTrajectory", overload_cast_explicit<trajectories::PiecewisePolynomial<double>, const solvers::MathematicalProgramResult&>( &Class::ReconstructStateTrajectory), py::arg("result"), cls_doc.ReconstructStateTrajectory.doc); RegisterAddConstraintToAllKnotPoints<solvers::BoundingBoxConstraint>(&cls); RegisterAddConstraintToAllKnotPoints<solvers::LinearEqualityConstraint>( &cls); RegisterAddConstraintToAllKnotPoints<solvers::LinearConstraint>(&cls); RegisterAddConstraintToAllKnotPoints<solvers::Constraint>(&cls); } { using Class = DirectCollocation; constexpr auto& cls_doc = doc.DirectCollocation; py::class_<Class, MultipleShooting>(m, "DirectCollocation", cls_doc.doc) .def(py::init<const systems::System<double>*, const systems::Context<double>&, int, double, double, std::variant<systems::InputPortSelection, systems::InputPortIndex>, bool, solvers::MathematicalProgram*>(), py::arg("system"), py::arg("context"), py::arg("num_time_samples"), py::arg("minimum_time_step"), py::arg("maximum_time_step"), py::arg("input_port_index") = systems::InputPortSelection::kUseFirstInputIfItExists, py::arg("assume_non_continuous_states_are_fixed") = false, py::arg("prog") = nullptr, cls_doc.ctor.doc); } { using Class = DirectCollocationConstraint; constexpr auto& cls_doc = doc.DirectCollocationConstraint; py::class_<Class, solvers::Constraint, std::shared_ptr<Class>>( m, "DirectCollocationConstraint", cls_doc.doc) .def(py::init<const systems::System<double>&, const systems::Context<double>&, std::variant<systems::InputPortSelection, systems::InputPortIndex>, bool>(), py::arg("system"), py::arg("context"), py::arg("input_port_index") = systems::InputPortSelection::kUseFirstInputIfItExists, py::arg("assume_non_continuous_states_are_fixed") = false, cls_doc.ctor.doc_double); } m.def("AddDirectCollocationConstraint", &AddDirectCollocationConstraint, py::arg("constraint"), py::arg("time_step"), py::arg("state"), py::arg("next_state"), py::arg("input"), py::arg("next_input"), py::arg("prog"), doc.AddDirectCollocationConstraint.doc); { using Class = DirectTranscription; constexpr auto& cls_doc = doc.DirectTranscription; py::class_<Class, MultipleShooting> cls( m, "DirectTranscription", doc.DirectTranscription.doc); // Inject the nested TimeStep so it's already bound when we bind the // constructor that depends on it. In C++ it's *not* nested. Nesting makes // things a bit more pythonic -- better would be kwonly named arg. py::class_<TimeStep>(cls, "TimeStep", doc.TimeStep.doc) .def(py::init<double>(), py::arg("value")) .def_readwrite("value", &TimeStep::value, doc.TimeStep.value.doc); cls // BR .def(py::init<const systems::System<double>*, const systems::Context<double>&, int, std::variant<systems::InputPortSelection, systems::InputPortIndex>>(), py::arg("system"), py::arg("context"), py::arg("num_time_samples"), py::arg("input_port_index") = systems::InputPortSelection::kUseFirstInputIfItExists, cls_doc.ctor.doc_4args) .def(py::init<const systems::System<double>*, const systems::Context<double>&, int, TimeStep, std::variant<systems::InputPortSelection, systems::InputPortIndex>>(), py::arg("system"), py::arg("context"), py::arg("num_time_samples"), py::arg("fixed_time_step"), py::arg("input_port_index") = systems::InputPortSelection::kUseFirstInputIfItExists, cls_doc.ctor.doc_5args); } { using Class = KinematicTrajectoryOptimization; constexpr auto& cls_doc = doc.KinematicTrajectoryOptimization; py::class_<Class>(m, "KinematicTrajectoryOptimization", cls_doc.doc) .def(py::init<int, int, int, double>(), py::arg("num_positions"), py::arg("num_control_points"), py::arg("spline_order") = 4, py::arg("duration") = 1.0, cls_doc.ctor.doc_4args) .def(py::init<const trajectories::BsplineTrajectory<double>&>(), py::arg("trajectory"), cls_doc.ctor.doc_1args) .def("num_positions", &Class::num_positions, cls_doc.num_positions.doc) .def("num_control_points", &Class::num_control_points, cls_doc.num_control_points.doc) .def("basis", &Class::basis, py_rvp::reference_internal, cls_doc.basis.doc) .def( "control_points", [](const Class& self) -> MatrixXDecisionVariable { return self.control_points(); }, cls_doc.control_points.doc) .def( "duration", [](const Class& self) -> symbolic::Variable { return self.duration(); }, cls_doc.duration.doc) .def("prog", &Class::prog, py_rvp::reference_internal, cls_doc.prog.doc) .def("get_mutable_prog", &Class::get_mutable_prog, py_rvp::reference_internal, cls_doc.get_mutable_prog.doc) .def("SetInitialGuess", &Class::SetInitialGuess, py::arg("trajectory"), cls_doc.SetInitialGuess.doc) .def("ReconstructTrajectory", &Class::ReconstructTrajectory, py::arg("result"), cls_doc.ReconstructTrajectory.doc) .def("AddPathPositionConstraint", py::overload_cast<const Eigen::Ref<const Eigen::VectorXd>&, const Eigen::Ref<const Eigen::VectorXd>&, double>( &Class::AddPathPositionConstraint), py::arg("lb"), py::arg("ub"), py::arg("s"), cls_doc.AddPathPositionConstraint.doc_3args) .def("AddPathPositionConstraint", py::overload_cast<const std::shared_ptr<solvers::Constraint>&, double>(&Class::AddPathPositionConstraint), py::arg("constraint"), py::arg("s"), cls_doc.AddPathPositionConstraint.doc_2args) .def("AddPathVelocityConstraint", &Class::AddPathVelocityConstraint, py::arg("lb"), py::arg("ub"), py::arg("s"), cls_doc.AddPathVelocityConstraint.doc) .def("AddVelocityConstraintAtNormalizedTime", &Class::AddVelocityConstraintAtNormalizedTime, py::arg("constraint"), py::arg("s"), cls_doc.AddVelocityConstraintAtNormalizedTime.doc) .def("AddPathAccelerationConstraint", &Class::AddPathAccelerationConstraint, py::arg("lb"), py::arg("ub"), py::arg("s"), cls_doc.AddPathAccelerationConstraint.doc) .def("AddDurationConstraint", &Class::AddDurationConstraint, py::arg("lb"), py::arg("ub"), cls_doc.AddDurationConstraint.doc) .def("AddPositionBounds", &Class::AddPositionBounds, py::arg("lb"), py::arg("ub"), cls_doc.AddPositionBounds.doc) .def("AddVelocityBounds", &Class::AddVelocityBounds, py::arg("lb"), py::arg("ub"), cls_doc.AddVelocityBounds.doc) .def("AddAccelerationBounds", &Class::AddAccelerationBounds, py::arg("lb"), py::arg("ub"), cls_doc.AddAccelerationBounds.doc) .def("AddJerkBounds", &Class::AddJerkBounds, py::arg("lb"), py::arg("ub"), cls_doc.AddJerkBounds.doc) .def("AddDurationCost", &Class::AddDurationCost, py::arg("weight") = 1.0, cls_doc.AddDurationCost.doc) .def("AddPathLengthCost", &Class::AddPathLengthCost, py::arg("weight") = 1.0, py::arg("use_conic_constraint") = false, cls_doc.AddPathLengthCost.doc); } { using Class = GcsTrajectoryOptimization; constexpr auto& cls_doc = doc.GcsTrajectoryOptimization; py::class_<Class> gcs_traj_opt(m, "GcsTrajectoryOptimization", cls_doc.doc); // Subgraph const auto& subgraph_doc = doc.GcsTrajectoryOptimization.Subgraph; py::class_<Class::Subgraph>(gcs_traj_opt, "Subgraph", subgraph_doc.doc) .def("name", &Class::Subgraph::name, subgraph_doc.name.doc) .def("order", &Class::Subgraph::order, subgraph_doc.order.doc) .def("size", &Class::Subgraph::size, subgraph_doc.size.doc) .def("Vertices", overload_cast_explicit<const std::vector< geometry::optimization::GraphOfConvexSets::Vertex*>&>( &Class::Subgraph::Vertices), py_rvp::reference_internal, subgraph_doc.Vertices.doc) .def( "regions", [](Class::Subgraph* self) { std::vector<const geometry::optimization::ConvexSet*> regions; for (auto& region : self->regions()) { regions.push_back(region.get()); } py::object self_py = py::cast(self, py_rvp::reference); // Keep alive, ownership: each item in `regions` keeps `self` // alive. return py::cast(regions, py_rvp::reference_internal, self_py); }, subgraph_doc.regions.doc) .def("AddTimeCost", &Class::Subgraph::AddTimeCost, py::arg("weight") = 1.0, subgraph_doc.AddTimeCost.doc) .def("AddPathLengthCost", py::overload_cast<const Eigen::MatrixXd&>( &Class::Subgraph::AddPathLengthCost), py::arg("weight_matrix"), subgraph_doc.AddPathLengthCost.doc_1args_weight_matrix) .def("AddPathLengthCost", py::overload_cast<double>(&Class::Subgraph::AddPathLengthCost), py::arg("weight") = 1.0, subgraph_doc.AddPathLengthCost.doc_1args_weight) .def("AddVelocityBounds", &Class::Subgraph::AddVelocityBounds, py::arg("lb"), py::arg("ub"), subgraph_doc.AddVelocityBounds.doc) .def("AddNonlinearDerivativeBounds", &Class::Subgraph::AddNonlinearDerivativeBounds, py::arg("lb"), py::arg("ub"), py::arg("derivative_order"), subgraph_doc.AddNonlinearDerivativeBounds.doc) .def("AddPathContinuityConstraints", &Class::Subgraph::AddPathContinuityConstraints, py::arg("continuity_order"), subgraph_doc.AddPathContinuityConstraints.doc) .def("AddContinuityConstraints", &Class::Subgraph::AddContinuityConstraints, py::arg("continuity_order"), subgraph_doc.AddContinuityConstraints.doc); // EdgesBetweenSubgraphs const auto& subgraph_edges_doc = doc.GcsTrajectoryOptimization.EdgesBetweenSubgraphs; py::class_<Class::EdgesBetweenSubgraphs>( gcs_traj_opt, "EdgesBetweenSubgraphs", subgraph_edges_doc.doc) .def("AddVelocityBounds", &Class::EdgesBetweenSubgraphs::AddVelocityBounds, py::arg("lb"), py::arg("ub"), subgraph_edges_doc.AddVelocityBounds.doc) .def("AddNonlinearDerivativeBounds", &Class::EdgesBetweenSubgraphs::AddNonlinearDerivativeBounds, py::arg("lb"), py::arg("ub"), py::arg("derivative_order"), subgraph_edges_doc.AddNonlinearDerivativeBounds.doc) .def("AddZeroDerivativeConstraints", &Class::EdgesBetweenSubgraphs::AddZeroDerivativeConstraints, py::arg("derivative_order"), subgraph_edges_doc.AddZeroDerivativeConstraints.doc) .def("AddPathContinuityConstraints", &Class::EdgesBetweenSubgraphs::AddPathContinuityConstraints, py::arg("continuity_order"), subgraph_edges_doc.AddPathContinuityConstraints.doc) .def("AddContinuityConstraints", &Class::EdgesBetweenSubgraphs::AddContinuityConstraints, py::arg("continuity_order"), subgraph_edges_doc.AddContinuityConstraints.doc); gcs_traj_opt // BR .def(py::init<int, const std::vector<int>&>(), py::arg("num_positions"), py::arg("continuous_revolute_joints") = std::vector<int>(), cls_doc.ctor.doc) .def("num_positions", &Class::num_positions, cls_doc.num_positions.doc) .def("continuous_revolute_joints", &Class::continuous_revolute_joints, cls_doc.continuous_revolute_joints.doc) .def("GetGraphvizString", &Class::GetGraphvizString, py::arg("result") = std::nullopt, py::arg("show_slack") = true, py::arg("precision") = 3, py::arg("scientific") = false, cls_doc.GetGraphvizString.doc) .def( "AddRegions", [](Class& self, const std::vector<geometry::optimization::ConvexSet*>& regions, const std::vector<std::pair<int, int>>& edges_between_regions, int order, double h_min, double h_max, std::string name, std::optional<std::vector<Eigen::VectorXd>> edge_offsets) -> Class::Subgraph& { return self.AddRegions(CloneConvexSets(regions), edges_between_regions, order, h_min, h_max, std::move(name), edge_offsets); }, py_rvp::reference_internal, py::arg("regions"), py::arg("edges_between_regions"), py::arg("order"), py::arg("h_min") = 1e-6, py::arg("h_max") = 20, py::arg("name") = "", py::arg("edge_offsets") = std::nullopt, cls_doc.AddRegions.doc_7args) .def( "AddRegions", [](Class& self, const std::vector<geometry::optimization::ConvexSet*>& regions, int order, double h_min, double h_max, std::string name) -> Class::Subgraph& { return self.AddRegions(CloneConvexSets(regions), order, h_min, h_max, std::move(name)); }, py_rvp::reference_internal, py::arg("regions"), py::arg("order"), py::arg("h_min") = 1e-6, py::arg("h_max") = 20, py::arg("name") = "", cls_doc.AddRegions.doc_5args) .def("RemoveSubgraph", &Class::RemoveSubgraph, py::arg("subgraph"), cls_doc.RemoveSubgraph.doc) .def("AddEdges", &Class::AddEdges, py_rvp::reference_internal, py::arg("from_subgraph"), py::arg("to_subgraph"), py::arg("subspace") = py::none(), cls_doc.AddEdges.doc) .def("AddTimeCost", &Class::AddTimeCost, py::arg("weight") = 1.0, cls_doc.AddTimeCost.doc) .def("AddPathLengthCost", py::overload_cast<const Eigen::MatrixXd&>( &Class::AddPathLengthCost), py::arg("weight_matrix"), cls_doc.AddPathLengthCost.doc_1args_weight_matrix) .def("AddPathLengthCost", py::overload_cast<double>(&Class::AddPathLengthCost), py::arg("weight") = 1.0, cls_doc.AddPathLengthCost.doc_1args_weight) .def("AddVelocityBounds", &Class::AddVelocityBounds, py::arg("lb"), py::arg("ub"), cls_doc.AddVelocityBounds.doc) .def("AddNonlinearDerivativeBounds", &Class::AddNonlinearDerivativeBounds, py::arg("lb"), py::arg("ub"), py::arg("derivative_order"), cls_doc.AddNonlinearDerivativeBounds.doc) .def("AddPathContinuityConstraints", &Class::AddPathContinuityConstraints, py::arg("continuity_order"), cls_doc.AddPathContinuityConstraints.doc) .def("AddContinuityConstraints", &Class::AddContinuityConstraints, py::arg("continuity_order"), cls_doc.AddContinuityConstraints.doc) .def("SolvePath", &Class::SolvePath, py::arg("source"), py::arg("target"), py::arg("options") = geometry::optimization::GraphOfConvexSetsOptions(), cls_doc.SolvePath.doc) .def("SolveConvexRestriction", &Class::SolveConvexRestriction, py::arg("active_vertices"), py::arg("options") = geometry::optimization::GraphOfConvexSetsOptions(), cls_doc.SolveConvexRestriction.doc) .def("GetSubgraphs", &Class::GetSubgraphs, py_rvp::reference_internal, cls_doc.GetSubgraphs.doc) .def("GetEdgesBetweenSubgraphs", &Class::GetEdgesBetweenSubgraphs, py_rvp::reference_internal, cls_doc.GetEdgesBetweenSubgraphs.doc) .def("graph_of_convex_sets", &Class::graph_of_convex_sets, py_rvp::reference_internal, cls_doc.graph_of_convex_sets.doc) .def_static("NormalizeSegmentTimes", &Class::NormalizeSegmentTimes, py::arg("trajectory"), cls_doc.NormalizeSegmentTimes.doc); } m.def("GetContinuousRevoluteJointIndices", &GetContinuousRevoluteJointIndices, py::arg("plant"), doc.GetContinuousRevoluteJointIndices.doc); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py_robot_diagram.cc
#include "drake/bindings/pydrake/common/cpp_template_pybind.h" #include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/planning/planning_py.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/planning/robot_diagram.h" #include "drake/planning/robot_diagram_builder.h" namespace drake { namespace pydrake { namespace internal { void DefinePlanningRobotDiagram(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::planning; constexpr auto& doc = pydrake_doc.drake.planning; auto bind_common_scalar_types = [&m, &doc](auto dummy) { using T = decltype(dummy); { using Class = RobotDiagram<T>; constexpr auto& cls_doc = doc.RobotDiagram; auto cls = DefineTemplateClassWithDefault<Class, systems::Diagram<T>>( m, "RobotDiagram", GetPyParam<T>(), cls_doc.doc); cls // BR .def("plant", &Class::plant, py_rvp::reference_internal, cls_doc.plant.doc) .def("mutable_scene_graph", &Class::mutable_scene_graph, py_rvp::reference_internal, cls_doc.mutable_scene_graph.doc) .def("scene_graph", &Class::scene_graph, py_rvp::reference_internal, cls_doc.scene_graph.doc) .def("mutable_plant_context", &Class::mutable_plant_context, py::arg("root_context"), py_rvp::reference, // Keep alive, ownership: `return` keeps `root_context` alive. py::keep_alive<0, 2>(), cls_doc.mutable_plant_context.doc) .def("plant_context", &Class::plant_context, py::arg("root_context"), py_rvp::reference, // Keep alive, ownership: `return` keeps `root_context` alive. py::keep_alive<0, 2>(), cls_doc.plant_context.doc) .def("mutable_scene_graph_context", &Class::mutable_scene_graph_context, py::arg("root_context"), py_rvp::reference, // Keep alive, ownership: `return` keeps `root_context` alive. py::keep_alive<0, 2>(), cls_doc.mutable_scene_graph_context.doc) .def("scene_graph_context", &Class::scene_graph_context, py::arg("root_context"), py_rvp::reference, // Keep alive, ownership: `return` keeps `root_context` alive. py::keep_alive<0, 2>(), cls_doc.scene_graph_context.doc); } { using Class = RobotDiagramBuilder<T>; constexpr auto& cls_doc = doc.RobotDiagramBuilder; auto cls = DefineTemplateClassWithDefault<Class>( m, "RobotDiagramBuilder", GetPyParam<T>(), cls_doc.doc); cls // BR .def(py::init<double>(), py::arg("time_step") = 0.001, cls_doc.ctor.doc) .def("builder", overload_cast_explicit<systems::DiagramBuilder<T>&>( &Class::builder), py_rvp::reference_internal, cls_doc.builder.doc_0args_nonconst); if constexpr (std::is_same_v<T, double>) { cls // BR .def( "parser", [](Class& self) { return &self.parser(); }, py_rvp::reference_internal, cls_doc.parser.doc_0args_nonconst); } cls // BR .def("plant", overload_cast_explicit<multibody::MultibodyPlant<T>&>( &Class::plant), py_rvp::reference_internal, cls_doc.plant.doc_0args_nonconst) .def("scene_graph", overload_cast_explicit<geometry::SceneGraph<T>&>( &Class::scene_graph), py_rvp::reference_internal, cls_doc.scene_graph.doc_0args_nonconst) .def("IsDiagramBuilt", &Class::IsDiagramBuilt, cls_doc.IsDiagramBuilt.doc) .def("Build", &Class::Build, // Keep alive, ownership (tr.): `self` keeps `return` alive. // Any prior reference access to our owned systems (e.g., plant()) // must remain valid, so the RobotDiagram cannot be destroyed // until the builder (and all of its internal references) are // finished. py::keep_alive<1, 0>(), cls_doc.Build.doc); } }; type_visit(bind_common_scalar_types, CommonScalarPack{}); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py_graph_algorithms.cc
#include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/planning/graph_algorithms/max_clique_solver_base.h" #include "drake/planning/graph_algorithms/max_clique_solver_via_greedy.h" #include "drake/planning/graph_algorithms/max_clique_solver_via_mip.h" namespace drake { namespace pydrake { namespace internal { void DefinePlanningGraphAlgorithms(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::planning::graph_algorithms; constexpr auto& doc = pydrake_doc.drake.planning.graph_algorithms; { class PyMaxCliqueSolverBase : public py::wrapper<MaxCliqueSolverBase> { public: // Trampoline virtual methods. // The private virtual method of DoSolveMaxClique is made public to enable // Python implementations to override it. VectorX<bool> DoSolveMaxClique( const Eigen::SparseMatrix<bool>& adjacency_matrix) const override { PYBIND11_OVERRIDE_PURE(VectorX<bool>, MaxCliqueSolverBase, DoSolveMaxClique, adjacency_matrix); } }; const auto& cls_doc = doc.MaxCliqueSolverBase; py::class_<MaxCliqueSolverBase, PyMaxCliqueSolverBase>( m, "MaxCliqueSolverBase", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc) .def("SolveMaxClique", &MaxCliqueSolverBase::SolveMaxClique, py::arg("adjacency_matrix"), cls_doc.SolveMaxClique.doc); } { const auto& cls_doc = doc.MaxCliqueSolverViaMip; py::class_<MaxCliqueSolverViaMip, MaxCliqueSolverBase>( m, "MaxCliqueSolverViaMip", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc) .def(py::init<const std::optional<Eigen::VectorXd>&, const solvers::SolverOptions&>(), py::arg("initial_guess"), py::arg("solver_options"), cls_doc.ctor.doc) .def("SetSolverOptions", &MaxCliqueSolverViaMip::SetSolverOptions, py::arg("solver_options"), cls_doc.SetSolverOptions.doc) .def("GetSolverOptions", &MaxCliqueSolverViaMip::GetSolverOptions, cls_doc.GetSolverOptions.doc) .def("SetInitialGuess", &MaxCliqueSolverViaMip::SetInitialGuess, py::arg("initial_guess"), cls_doc.SetInitialGuess.doc) .def("GetInitialGuess", &MaxCliqueSolverViaMip::GetInitialGuess, cls_doc.GetInitialGuess.doc); } { const auto& cls_doc = doc.MaxCliqueSolverViaGreedy; py::class_<MaxCliqueSolverViaGreedy, MaxCliqueSolverBase>( m, "MaxCliqueSolverViaGreedy", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc); } } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/planning/planning_py.h
#pragma once /* This file declares the functions that bind the drake::planning namespace. These functions form a complete partition of the drake::planning 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 { // For simplicity, these declarations are listed in alphabetical order. /* Defines bindings per planning_py_collision_checker.cc. */ void DefinePlanningCollisionChecker(py::module m); /* Defines bindings per planning_py_collision_checker_interface_types.cc. */ void DefinePlanningCollisionCheckerInterfaceTypes(py::module m); /* Defines bindings per planning_py_graph_algorithms.cc. */ void DefinePlanningGraphAlgorithms(py::module m); /* Defines bindings per planning_py_iris_from_clique_cover.cc. */ void DefinePlanningIrisFromCliqueCover(py::module m); /* Defines bindings per planning_py_robot_diagram.cc. */ void DefinePlanningRobotDiagram(py::module m); /* Defines bindings per planning_py_trajectory_optimization.cc. */ void DefinePlanningTrajectoryOptimization(py::module m); /* Defines bindings per planning_py_visibility_graph.cc. */ void DefinePlanningVisibilityGraph(py::module m); /* Defines bindings per planning_py_zmp_planner.cc. */ void DefinePlanningZmpPlanner(py::module m); } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake/planning
/home/johnshepherd/drake/bindings/pydrake/planning/test/trajectory_optimization_test.py
import math import unittest import warnings import numpy as np from pydrake.examples import PendulumPlant from pydrake.math import eq, BsplineBasis from pydrake.planning import ( AddDirectCollocationConstraint, DirectCollocation, DirectCollocationConstraint, DirectTranscription, GcsTrajectoryOptimization, KinematicTrajectoryOptimization, GetContinuousRevoluteJointIndices ) from pydrake.geometry.optimization import ( ConvexSet, GraphOfConvexSetsOptions, GraphOfConvexSets, HPolyhedron, Point, VPolytope, ) from pydrake.multibody.plant import MultibodyPlant import pydrake.solvers as mp from pydrake.symbolic import Variable from pydrake.systems.framework import InputPortSelection from pydrake.systems.primitives import LinearSystem from pydrake.trajectories import ( BsplineTrajectory, CompositeTrajectory, PiecewisePolynomial, ) from pydrake.symbolic import Variable from pydrake.systems.framework import InputPortSelection from pydrake.systems.primitives import LinearSystem class TestTrajectoryOptimization(unittest.TestCase): def test_direct_collocation(self): plant = PendulumPlant() context = plant.CreateDefaultContext() num_time_samples = 21 dircol = DirectCollocation( plant, context, num_time_samples=num_time_samples, minimum_time_step=0.2, maximum_time_step=0.5, input_port_index=InputPortSelection.kUseFirstInputIfItExists, assume_non_continuous_states_are_fixed=False) prog = dircol.prog() num_initial_vars = prog.num_vars() # Spell out most of the methods, regardless of whether they make sense # as a consistent optimization. The goal is to check the bindings, # not the implementation. t = dircol.time() dt = dircol.time_step(index=0) x = dircol.state() x2 = dircol.state(index=2) x0 = dircol.initial_state() xf = dircol.final_state() u = dircol.input() u2 = dircol.input(index=2) v = dircol.NewSequentialVariable(rows=1, name="test") v2 = dircol.GetSequentialVariableAtIndex(name="test", index=2) dircol.AddRunningCost(x.dot(x)) input_con = dircol.AddConstraintToAllKnotPoints(u[0] == 0) self.assertEqual(len(input_con), 21) interval_bound = dircol.AddTimeIntervalBounds( lower_bound=0.3, upper_bound=0.4) self.assertIsInstance(interval_bound.evaluator(), mp.BoundingBoxConstraint) equal_time_con = dircol.AddEqualTimeIntervalsConstraints() self.assertEqual(len(equal_time_con), 19) duration_bound = dircol.AddDurationBounds( lower_bound=0.3*21, upper_bound=0.4*21) self.assertIsInstance(duration_bound.evaluator(), mp.LinearConstraint) final_cost = dircol.AddFinalCost(2*x.dot(x)) self.assertIsInstance(final_cost.evaluator(), mp.Cost) initial_u = PiecewisePolynomial.ZeroOrderHold([0, 0.3*21], np.zeros((1, 2))) initial_x = PiecewisePolynomial() dircol.SetInitialTrajectory(traj_init_u=initial_u, traj_init_x=initial_x) was_called = dict( input=False, state=False, complete=False ) def input_callback(t, u): was_called["input"] = True def state_callback(t, x): was_called["state"] = True def complete_callback(t, x, u, v): was_called["complete"] = True dircol.AddInputTrajectoryCallback(callback=input_callback) dircol.AddStateTrajectoryCallback(callback=state_callback) dircol.AddCompleteTrajectoryCallback(callback=complete_callback, names=["test"]) result = mp.Solve(dircol.prog()) self.assertTrue(was_called["input"]) self.assertTrue(was_called["state"]) self.assertTrue(was_called["complete"]) dircol.GetSampleTimes(result=result) dircol.GetInputSamples(result=result) dircol.GetStateSamples(result=result) dircol.GetSequentialVariableSamples(result=result, name="test") u_traj = dircol.ReconstructInputTrajectory(result=result) x_traj = dircol.ReconstructStateTrajectory(result=result) constraint = DirectCollocationConstraint(plant, context) AddDirectCollocationConstraint(constraint, dircol.time_step(0), dircol.state(0), dircol.state(1), dircol.input(0), dircol.input(1), prog) # Test AddConstraintToAllKnotPoints variants. nc = len(prog.bounding_box_constraints()) c = dircol.AddConstraintToAllKnotPoints( constraint=mp.BoundingBoxConstraint([0], [1]), vars=u) self.assertIsInstance(c[0], mp.Binding[mp.BoundingBoxConstraint]) self.assertEqual(len(prog.bounding_box_constraints()), nc + num_time_samples) nc = len(prog.linear_equality_constraints()) c = dircol.AddConstraintToAllKnotPoints( constraint=mp.LinearEqualityConstraint([1], [0]), vars=u) self.assertIsInstance(c[0], mp.Binding[mp.LinearEqualityConstraint]) self.assertEqual(len(prog.linear_equality_constraints()), nc + num_time_samples) nc = len(prog.linear_constraints()) c = dircol.AddConstraintToAllKnotPoints( constraint=mp.LinearConstraint([1], [0], [1]), vars=u) self.assertIsInstance(c[0], mp.Binding[mp.LinearConstraint]) self.assertEqual(len(prog.linear_constraints()), nc + num_time_samples) nc = len(prog.linear_equality_constraints()) # eq(x, 2) produces a 2-dimensional vector of Formula. c = dircol.AddConstraintToAllKnotPoints(eq(x, 2)) self.assertIsInstance(c[0].evaluator(), mp.LinearEqualityConstraint) self.assertEqual(len(prog.linear_equality_constraints()), nc + 2*num_time_samples) # Add a second direct collocation problem to the same prog. num_vars = prog.num_vars() dircol2 = DirectCollocation( plant, context, num_time_samples=num_time_samples, minimum_time_step=0.2, maximum_time_step=0.5, input_port_index=InputPortSelection.kUseFirstInputIfItExists, assume_non_continuous_states_are_fixed=False, prog=prog) self.assertEqual(dircol.prog(), dircol2.prog()) self.assertEqual(prog.num_vars(), num_vars + num_initial_vars) def test_direct_transcription(self): # Integrator. plant = LinearSystem( A=[0.0], B=[1.0], C=[1.0], D=[0.0], time_period=0.1) context = plant.CreateDefaultContext() # Constructor for discrete systems. dirtran = DirectTranscription(plant, context, num_time_samples=21) # Spell out most of the methods, regardless of whether they make sense # as a consistent optimization. The goal is to check the bindings, # not the implementation. t = dirtran.time() dt = dirtran.fixed_time_step() x = dirtran.state() x2 = dirtran.state(2) x0 = dirtran.initial_state() xf = dirtran.final_state() u = dirtran.input() u2 = dirtran.input(2) dirtran.AddRunningCost(x.dot(x)) dirtran.AddConstraintToAllKnotPoints(u[0] == 0) dirtran.AddFinalCost(2*x.dot(x)) initial_u = PiecewisePolynomial.ZeroOrderHold([0, 0.3*21], np.zeros((1, 2))) initial_x = PiecewisePolynomial() dirtran.SetInitialTrajectory(initial_u, initial_x) result = mp.Solve(dirtran.prog()) times = dirtran.GetSampleTimes(result) inputs = dirtran.GetInputSamples(result) states = dirtran.GetStateSamples(result) input_traj = dirtran.ReconstructInputTrajectory(result) state_traj = dirtran.ReconstructStateTrajectory(result) # Confirm that the constructor for continuous systems works (and # confirm binding of nested TimeStep). plant = LinearSystem( A=[0.0], B=[1.0], C=[1.0], D=[0.0], time_period=0.0) context = plant.CreateDefaultContext() dirtran = DirectTranscription( plant, context, num_time_samples=21, fixed_time_step=DirectTranscription.TimeStep(0.1)) def test_kinematic_trajectory_optimization(self): trajopt = KinematicTrajectoryOptimization(num_positions=2, num_control_points=10, spline_order=3, duration=2.0) self.assertIsInstance(trajopt.prog(), mp.MathematicalProgram) self.assertIsInstance(trajopt.get_mutable_prog(), mp.MathematicalProgram) self.assertEqual(trajopt.num_positions(), 2) self.assertEqual(trajopt.num_control_points(), 10) self.assertIsInstance(trajopt.basis(), BsplineBasis) self.assertEqual(trajopt.basis().order(), 3) self.assertEqual(trajopt.control_points().shape, (2, 10)) self.assertIsInstance(trajopt.duration(), Variable) self.assertEqual(trajopt.prog().GetInitialGuess(trajopt.duration()), 2.0) b = np.zeros((2, 1)) trajopt.AddPathPositionConstraint(lb=b, ub=b, s=0) con = mp.LinearConstraint(np.eye(2), lb=b, ub=b) trajopt.AddPathPositionConstraint(con, 0) trajopt.AddPathVelocityConstraint(lb=b, ub=b, s=0) velocity_constraint = mp.LinearConstraint(np.eye(4), lb=np.zeros((4, 1)), ub=np.zeros((4, 1))) trajopt.AddVelocityConstraintAtNormalizedTime(velocity_constraint, s=0) trajopt.AddPathAccelerationConstraint(lb=b, ub=b, s=0) trajopt.AddDurationConstraint(1, 1) trajopt.AddPositionBounds(lb=b, ub=b) trajopt.AddVelocityBounds(lb=b, ub=b) trajopt.AddAccelerationBounds(lb=b, ub=b) trajopt.AddJerkBounds(lb=b, ub=b) trajopt.AddDurationCost(weight=1) trajopt.AddPathLengthCost(weight=1) result = mp.Solve(trajopt.prog()) q = trajopt.ReconstructTrajectory(result=result) self.assertIsInstance(q, BsplineTrajectory) trajopt.SetInitialGuess(trajectory=q) def test_gcs_trajectory_optimization_basic(self): """This based on the C++ GcsTrajectoryOptimizationTest.Basic test. It's a simple test of the bindings. It uses a single region (the unit box), and plans a line segment inside that box. """ gcs = GcsTrajectoryOptimization(num_positions=2) start = [-0.5, -0.5] end = [0.5, 0.5] source = gcs.AddRegions(regions=[Point(start)], order=0) self.assertIn(source, gcs.GetSubgraphs()) target = gcs.AddRegions(regions=[Point(end)], order=0) self.assertIn(target, gcs.GetSubgraphs()) regions = gcs.AddRegions(regions=[HPolyhedron.MakeUnitBox(2)], order=1, h_min=1.0) self.assertIn(regions, gcs.GetSubgraphs()) self.assertIn(gcs.AddEdges(source, regions), gcs.GetEdgesBetweenSubgraphs()) self.assertIn(gcs.AddEdges(regions, target), gcs.GetEdgesBetweenSubgraphs()) traj, result = gcs.SolvePath(source, target) self.assertTrue(result.is_success()) self.assertEqual(traj.rows(), 2) self.assertEqual(traj.cols(), 1) traj_start = traj.value(traj.start_time()).squeeze() traj_end = traj.value(traj.end_time()).squeeze() np.testing.assert_allclose(traj_start, start, atol=1e-6) np.testing.assert_allclose(traj_end, end, atol=1e-6) # Since each segment of the normalized trajectory is one second long, # we expect the duration of the normalized trajectory to match the # number of segments. normalized_traj = GcsTrajectoryOptimization.NormalizeSegmentTimes( trajectory=traj) self.assertEqual(traj.start_time(), normalized_traj.start_time()) self.assertEqual(traj.get_number_of_segments(), normalized_traj.get_number_of_segments()) self.assertEqual(normalized_traj.get_number_of_segments(), normalized_traj.end_time() - normalized_traj.start_time()) # The start and goal should be not altered. normalized_traj_start = normalized_traj.value( normalized_traj.start_time()).squeeze() normalized_traj_end = normalized_traj.value( normalized_traj.end_time()).squeeze() np.testing.assert_allclose(normalized_traj_start, start, atol=1e-6) np.testing.assert_allclose(normalized_traj_end, end, atol=1e-6) # We can also solve the convex restriction, by manually defining # through which regions the path should go. active_vertices = (source.Vertices() + regions.Vertices() + target.Vertices()) restricted_traj, restricted_result = ( gcs.SolveConvexRestriction(active_vertices) ) self.assertTrue(restricted_result.is_success()) self.assertEqual(restricted_traj.rows(), 2) self.assertEqual(restricted_traj.cols(), 1) restricted_traj_start = restricted_traj.value( restricted_traj.start_time()).squeeze() restricted_traj_end = restricted_traj.value( restricted_traj.end_time()).squeeze() np.testing.assert_allclose(restricted_traj_start, start, atol=1e-6) np.testing.assert_allclose(restricted_traj_end, end, atol=1e-6) # Test that removing all subgraphs, removes all vertices and edges. self.assertEqual(len(gcs.graph_of_convex_sets().Vertices()), len(source.Vertices()) + len(regions.Vertices()) + len(target.Vertices())) self.assertEqual(len(gcs.GetSubgraphs()), 3) self.assertEqual(len(gcs.GetEdgesBetweenSubgraphs()), 2) gcs.RemoveSubgraph(source) gcs.RemoveSubgraph(regions) gcs.RemoveSubgraph(target) # We expect the underlying gcs problem to be empty. self.assertFalse(len(gcs.graph_of_convex_sets().Vertices())) self.assertFalse(len(gcs.graph_of_convex_sets().Edges())) self.assertFalse(len(gcs.GetSubgraphs())) self.assertFalse(len(gcs.GetEdgesBetweenSubgraphs()), 0) def test_gcs_trajectory_optimization_2d(self): """The following 2D environment has been presented in the GCS paper. We have two possible starts, S1 and S2, and two possible goals, G1 and G2. The goal is to find a the shortest path from either of the starts to either of the goals while avoiding the obstacles. Further we constraint the path to go through either the intermediate point I or the subspace. ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░ G1 ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ S2░░░░░░░░ ░░░░░░░░░░ I ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░ ░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░ ░░ ░░░░░░░░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░░░░░░░░░░░░░░░░░░ G2 ░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░xxxxxx░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░xxxxxxxx░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░xxxxxxxxxx░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░░░░░xxxxxxxxxxxx░░ ░░ ░░░░░░░░ ░░░░░░░░░░░░░xxx Subspace x░░ ░░ ░░░░░░░░ xxxxxxxxxxxxxxxx░░ ░░ S1 ░░░░░░░░ xxxxxxxxxxxxxxxx░░ ░░ ░░░░░░░░ xxxxxxxxxxxxxxxx░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ """ dimension = 2 gcs = GcsTrajectoryOptimization(num_positions=dimension) self.assertEqual(gcs.num_positions(), dimension) # Define the collision free space. vertices = [ np.array([[0.4, 0.4, 0.0, 0.0], [0.0, 5.0, 5.0, 0.0]]), np.array([[0.4, 1.0, 1.0, 0.4], [2.4, 2.4, 2.6, 2.6]]), np.array([[1.4, 1.4, 1.0, 1.0], [2.2, 4.6, 4.6, 2.2]]), np.array([[1.4, 2.4, 2.4, 1.4], [2.2, 2.6, 2.8, 2.8]]), np.array([[2.2, 2.4, 2.4, 2.2], [2.8, 2.8, 4.6, 4.6]]), np.array([[1.4, 1.0, 1.0, 3.8, 3.8], [2.2, 2.2, 0.0, 0.0, 0.2]]), np.array([[3.8, 3.8, 1.0, 1.0], [4.6, 5.0, 5.0, 4.6]]), np.array([[5.0, 5.0, 4.8, 3.8, 3.8], [0.0, 1.2, 1.2, 0.2, 0.0]]), np.array([[3.4, 4.8, 5.0, 5.0], [2.6, 1.2, 1.2, 2.6]]), np.array([[3.4, 3.8, 3.8, 3.4], [2.6, 2.6, 4.6, 4.6]]), np.array([[3.8, 4.4, 4.4, 3.8], [2.8, 2.8, 3.0, 3.0]]), np.array([[5.0, 5.0, 4.4, 4.4], [2.8, 5.0, 5.0, 2.8]]) ] max_vel = np.ones((2, 1)) # We add a path length cost to the entire graph. # This can be called ahead of time or after adding the regions. gcs.AddPathLengthCost(weight=1.0) # This cost is equivalent to the above. # It will be added twice, which is unnecessary, # but we do it to test the binding. gcs.AddPathLengthCost(weight_matrix=np.eye(dimension)) # Add a mimimum time cost to the entire graph. gcs.AddTimeCost(weight=1.0) # Add the cost again, which is unnecessary for the optimization # but useful to check the binding with the default values. gcs.AddTimeCost() # Add velocity bounds to the entire graph. gcs.AddVelocityBounds(lb=-max_vel, ub=max_vel) # Add a velocity and acceleration continuity to the entire graph. gcs.AddPathContinuityConstraints(1) gcs.AddPathContinuityConstraints(2) # Add two subgraphs with different orders. main1 = gcs.AddRegions( regions=[HPolyhedron(VPolytope(v)) for v in vertices], order=4, name="main1") self.assertIsInstance(main1, GcsTrajectoryOptimization.Subgraph) self.assertEqual(main1.order(), 4) self.assertEqual(main1.name(), "main1") self.assertEqual(main1.size(), len(vertices)) self.assertIsInstance(main1.regions(), list) self.assertIsInstance(main1.regions()[0], HPolyhedron) self.assertIn(main1, gcs.GetSubgraphs()) # This adds the edges manually. # Doing this is much faster since it avoids computing # pairwise set intersection checks. main2 = gcs.AddRegions( regions=[HPolyhedron(VPolytope(v)) for v in vertices], edges_between_regions=[(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2), (2, 5), (5, 2), (2, 6), (6, 2), (3, 4), (4, 3), (3, 5), (5, 3), (4, 6), (6, 4), (5, 7), (7, 5), (6, 9), (9, 6), (7, 8), (8, 7), (8, 9), (9, 8), (9, 10), (10, 9), (10, 11), (11, 10)], order=6, name="main2") self.assertIsInstance(main2, GcsTrajectoryOptimization.Subgraph) self.assertEqual(main2.order(), 6) self.assertEqual(main2.name(), "main2") self.assertEqual(main2.size(), len(vertices)) self.assertIsInstance(main2.regions(), list) self.assertIsInstance(main2.regions()[0], HPolyhedron) self.assertIsInstance(main2.Vertices(), list) self.assertIsInstance(main2.Vertices()[0], GraphOfConvexSets.Vertex) self.assertIn(main2, gcs.GetSubgraphs()) # Add two start and goal regions. start1 = np.array([0.2, 0.2]) start2 = np.array([0.3, 3.2]) goal1 = np.array([4.8, 4.8]) goal2 = np.array([4.9, 2.4]) source = gcs.AddRegions([Point(start1), Point(start2)], order=0, name="starts") self.assertIsInstance(source, GcsTrajectoryOptimization.Subgraph) self.assertEqual(source.order(), 0) self.assertEqual(source.name(), "starts") self.assertEqual(source.size(), 2) self.assertIsInstance(source.regions(), list) self.assertIsInstance(source.regions()[0], Point) self.assertIsInstance(source.Vertices(), list) self.assertIsInstance(source.Vertices()[0], GraphOfConvexSets.Vertex) self.assertIn(source, gcs.GetSubgraphs()) # Here we force a delay of 10 seconds at the goal. target = gcs.AddRegions(regions=[Point(goal1), Point(goal2)], order=0, h_min=10, h_max=10, name='goals') self.assertIsInstance(target, GcsTrajectoryOptimization.Subgraph) self.assertEqual(target.order(), 0) self.assertEqual(target.name(), "goals") self.assertEqual(target.size(), 2) self.assertIsInstance(target.regions(), list) self.assertIsInstance(target.regions()[0], Point) self.assertIsInstance(target.Vertices(), list) self.assertIsInstance(target.Vertices()[0], GraphOfConvexSets.Vertex) self.assertIn(target, gcs.GetSubgraphs()) # We connect the subgraphs main1 and main2 by constraining it to # go through either of the subspaces. subspace_region = HPolyhedron(VPolytope(vertices[7])) subspace_point = Point([2.3, 3.5]) main1_to_main2_pt = gcs.AddEdges(main1, main2, subspace=subspace_point) self.assertIsInstance(main1_to_main2_pt, GcsTrajectoryOptimization.EdgesBetweenSubgraphs) self.assertIn(main1_to_main2_pt, gcs.GetEdgesBetweenSubgraphs()) main1_to_main2_region = gcs.AddEdges(main1, main2, subspace=subspace_region) self.assertIsInstance(main1_to_main2_region, GcsTrajectoryOptimization.EdgesBetweenSubgraphs) self.assertIn(main1_to_main2_region, gcs.GetEdgesBetweenSubgraphs()) # Add half of the maximum velocity constraint at the subspace point # and region. main1_to_main2_pt.AddVelocityBounds(lb=-max_vel / 2, ub=max_vel / 2) main1_to_main2_region.AddVelocityBounds(lb=-max_vel / 2, ub=max_vel / 2) # We connect the start and goal regions to the rest of the graph. self.assertIsInstance(gcs.AddEdges(source, main1), GcsTrajectoryOptimization.EdgesBetweenSubgraphs) main2_to_target = gcs.AddEdges(main2, target) self.assertIsInstance(main2_to_target, GcsTrajectoryOptimization.EdgesBetweenSubgraphs) self.assertIn(main2_to_target, gcs.GetEdgesBetweenSubgraphs()) # Add final zero velocity and acceleration. main2_to_target.AddZeroDerivativeConstraints(derivative_order=1) main2_to_target.AddZeroDerivativeConstraints(derivative_order=2) # This weight matrix penalizes movement in the y direction three # times more than in the x direction only for the main2 subgraph. main2.AddPathLengthCost(weight_matrix=np.diag([1.0, 3.0])) # Adding this cost checks the python binding. It won't contribute to # the solution since we already added the minimum time cost to the # whole graph. main2.AddTimeCost(weight=1.0) # Add the cost again, which is unnecessary for the optimization # but useful to check the binding with the default values. main2.AddTimeCost() # Adding this constraint checks the python binding. It won't # contribute to the solution since we already added the continuity # constraints to the whole graph. main2.AddPathContinuityConstraints(1) main1_to_main2_region.AddPathContinuityConstraints(1) # Add tighter velocity bounds to the main2 subgraph. main2.AddVelocityBounds(lb=-0.5*max_vel, ub=0.5*max_vel) self.assertIsInstance(gcs.graph_of_convex_sets(), GraphOfConvexSets) options = GraphOfConvexSetsOptions() options.convex_relaxation = True options.max_rounded_paths = 5 traj, result = gcs.SolvePath(source=source, target=target, options=options) self.assertIsInstance(result, mp.MathematicalProgramResult) self.assertIsInstance(traj, CompositeTrajectory) self.assertTrue(result.is_success()) self.assertEqual(traj.rows(), dimension) np.testing.assert_array_almost_equal(traj.value(traj.start_time()), start2[:, None], 6) np.testing.assert_array_almost_equal(traj.value(traj.end_time()), goal2[:, None], 6) # Check that the delay at the goal is respected. np.testing.assert_array_almost_equal(traj.value(traj.end_time() - 10), goal2[:, None], 6) self.assertTrue(traj.end_time() - traj.start_time() >= 10) self.assertIsInstance( gcs.GetGraphvizString(result=result, show_slack=True, precision=3, scientific=False), str) # In the follwoing, we test adding the bindings for nonlinear # constraints. max_acceleration = np.ones((2, 1)) max_jerk = 7.5 * np.ones((2, 1)) # Add global acceleration bounds. gcs.AddNonlinearDerivativeBounds( lb=-max_acceleration, ub=max_acceleration, derivative_order=2) # Add the jerk bounds to each subgraph. main1.AddNonlinearDerivativeBounds( lb=-max_jerk, ub=max_jerk, derivative_order=3) main2.AddNonlinearDerivativeBounds( lb=-max_jerk, ub=max_jerk, derivative_order=3) # Add half of the maximum acceleration and jerk bounds at the subspace # point and region. main1_to_main2_pt.AddVelocityBounds( lb=-max_acceleration / 2, ub=max_acceleration / 2) main1_to_main2_region.AddVelocityBounds( lb=-max_acceleration / 2, ub=max_acceleration / 2) main1_to_main2_pt.AddVelocityBounds(lb=-max_jerk / 2, ub=max_jerk / 2) main1_to_main2_region.AddVelocityBounds( lb=-max_jerk / 2, ub=max_jerk / 2) # Add global velocity continuity. gcs.AddContinuityConstraints(continuity_order=1) # Add acceleration continuity to each subgraph. main1.AddContinuityConstraints(continuity_order=2) main2.AddContinuityConstraints(continuity_order=2) # Add acceleration continuity at the subspace point and region. main1_to_main2_pt.AddContinuityConstraints(continuity_order=2) main1_to_main2_region.AddContinuityConstraints(continuity_order=2) def test_gcs_trajectory_optimization_wraparound(self): gcs_wraparound = GcsTrajectoryOptimization( num_positions=1, continuous_revolute_joints=[0]) self.assertEqual(len(gcs_wraparound.continuous_revolute_joints()), 1) gcs_wraparound.AddRegions(regions=[Point([0]), Point([2*np.pi])], order=1, edges_between_regions=[[0, 1]], edge_offsets=[[2*np.pi]]) def test_get_continuous_revolute_joint_indices(self): plant = MultibodyPlant(0.0) plant.Finalize() indices = GetContinuousRevoluteJointIndices(plant=plant) self.assertEqual(len(indices), 0)
0
/home/johnshepherd/drake/bindings/pydrake/planning
/home/johnshepherd/drake/bindings/pydrake/planning/test/robot_diagram_test.py
import pydrake.planning as mut import unittest from pydrake.common import FindResourceOrThrow from pydrake.common.test_utilities import numpy_compare from pydrake.geometry import SceneGraph_ from pydrake.multibody.parsing import Parser from pydrake.multibody.plant import MultibodyPlant_, MultibodyPlantConfig from pydrake.systems.framework import Context_, DiagramBuilder_ class TestRobotDiagram(unittest.TestCase): @numpy_compare.check_all_types def test_robot_diagram_builder_default_time_step(self, T): Class = mut.RobotDiagramBuilder_[T] dut = Class() self.assertEqual(dut.plant().time_step(), MultibodyPlantConfig().time_step) @numpy_compare.check_all_types def test_robot_diagram_builder(self, T): """Tests the full RobotDiagramBuilder API. """ Class = mut.RobotDiagramBuilder_[T] dut = Class(time_step=0.0) if T == float: dut.parser().AddModels(url=( "package://drake_models/iiwa_description/urdf/" + "iiwa14_spheres_dense_collision.urdf")) else: # TODO(jwnimmer-tri) Use dut.plant() to manually add some # models, bodies, and geometries here. pass # Sanity check all of the accessors. self.assertIsInstance(dut.builder(), DiagramBuilder_[T]) self.assertIsInstance(dut.plant(), MultibodyPlant_[T]) self.assertIsInstance(dut.scene_graph(), SceneGraph_[T]) # Build. self.assertFalse(dut.IsDiagramBuilt()) diagram = dut.Build() self.assertTrue(dut.IsDiagramBuilt()) self.assertIsInstance(diagram, mut.RobotDiagram_[T]) @numpy_compare.check_all_types def test_robot_diagram(self, T): """Tests the full RobotDiagram API. """ builder = mut.RobotDiagramBuilder_[T]() dut = builder.Build() self.assertIsInstance(dut.plant(), MultibodyPlant_[T]) self.assertIsInstance(dut.mutable_scene_graph(), SceneGraph_[T]) self.assertIsInstance(dut.scene_graph(), SceneGraph_[T]) root_context = dut.CreateDefaultContext() self.assertIsInstance( dut.mutable_plant_context(root_context=root_context), Context_[T]) self.assertIsInstance( dut.plant_context(root_context=root_context), Context_[T]) self.assertIsInstance( dut.mutable_scene_graph_context(root_context=root_context), Context_[T]) self.assertIsInstance( dut.scene_graph_context(root_context=root_context), Context_[T])
0
/home/johnshepherd/drake/bindings/pydrake/planning
/home/johnshepherd/drake/bindings/pydrake/planning/test/collision_checker_trace_test.py
import pydrake.planning as mut import logging import textwrap import unittest import numpy as np class TestCollisionCheckerTrace(unittest.TestCase): """Confirms that trace-level logging from the CollisionChecker's C++ worker threads doesn't deadlock the Python interpreter. A deadlock can happen when: - the default pydrake logging configuration is still intact, where all text logging flows through Python (i.e., use_native_cpp_logging() was not called, DRAKE_PYTHON_LOGGING was not set, etc); - some Python code calls a bound C++ function; - that binding is NOT annotated with `gil_scoped_release`, so keeps hold of its lock on the Python GIL; - the C++ function spawns worker thread(s), and blocks awaiting their completion (while still holding the GIL); - one of the worker threads posts a log message using a log level that isn't filtered out; - the log sink blocks forever while trying to acquire the GIL, because the lock is still held by the original function. In short, here we are proving that the `gil_scoped_release` annotation is present on the relevant function (CheckEdgeCollisionFreeParallel) and that that annotation is sufficient to prevent a deadlock. """ def _make_robot_diagram(self): builder = mut.RobotDiagramBuilder() scene_yaml = textwrap.dedent(""" directives: - add_model: name: box file: package://drake/multibody/models/box.urdf - add_model: name: ground file: package://drake/planning/test_utilities/collision_ground_plane.sdf # noqa - add_weld: parent: world child: ground::ground_plane_box """) builder.parser().AddModelsFromString(scene_yaml, "dmd.yaml") model_instance_index = builder.plant().GetModelInstanceByName("box") robot_diagram = builder.Build() return (robot_diagram, model_instance_index) def test_tracing(self): # Prepare a checker with a box that can collide with the ground. robot, index = self._make_robot_diagram() dut = mut.SceneGraphCollisionChecker( model=robot, robot_model_instances=[index], edge_step_size=0.125) # Check an edge that has a box-ground collision. q1 = np.array([-0.5] * 7) q2 = np.array([0.5] * 7) with self.assertLogs("drake", level=1) as manager: free = dut.CheckEdgeCollisionFreeParallel(q1, q2, parallelize=True) self.assertEqual(free, False) self.assertRegex(manager.output[-1], "collision.*box.*ground")
0
/home/johnshepherd/drake/bindings/pydrake/planning
/home/johnshepherd/drake/bindings/pydrake/planning/test/zmp_planner_test.py
import unittest import numpy as np from pydrake.planning import ( ZmpPlanner, ) from pydrake.trajectories import PiecewisePolynomial class TestZmpPlanner(unittest.TestCase): def test_zmp_planner(self): height = 1 x0 = [0, 0, 0, 0] time = [0, 1, 2, 3] zmp_knots = np.array([[0, 0], [0.2, -0.1], [0.4, 0.1], [0.4, 0.1]]).T zmp_d = PiecewisePolynomial.FirstOrderHold(time, zmp_knots) planner = ZmpPlanner() planner.Plan( zmp_d=zmp_d, x0=x0, height=height, gravity=9.8, Qy=np.eye(2), R=0.2*np.eye(2)) self.assertTrue(planner.has_planned()) self.assertEqual(planner.get_A().shape, (4, 4)) self.assertEqual(planner.get_B().shape, (4, 2)) self.assertEqual(planner.get_C().shape, (2, 4)) self.assertEqual(planner.get_D().shape, (2, 2)) np.testing.assert_almost_equal(planner.get_Qy(), np.eye(2)) np.testing.assert_almost_equal(planner.get_R(), 0.2*np.eye(2)) sample_time = 0.1 np.testing.assert_almost_equal( planner.get_desired_zmp(time=sample_time).reshape((2, 1)), zmp_d.value(sample_time)) np.testing.assert_almost_equal( planner.get_desired_zmp(time=sample_time).reshape((2, 1)), planner.get_desired_zmp().value(sample_time)) np.testing.assert_almost_equal( planner.get_nominal_com(time=sample_time).reshape((2, 1)), planner.get_nominal_com().value(sample_time)) np.testing.assert_almost_equal( planner.get_nominal_comd(time=sample_time).reshape((2, 1)), planner.get_nominal_comd().value(sample_time)) np.testing.assert_almost_equal( planner.get_nominal_comdd(time=sample_time).reshape((2, 1)), planner.get_nominal_comdd().value(sample_time)) self.assertEqual(planner.get_Vxx().shape, (4, 4)) np.testing.assert_almost_equal( planner.get_Vx(time=sample_time).reshape((4, 1)), planner.get_Vx().value(sample_time))
0
/home/johnshepherd/drake/bindings/pydrake/planning
/home/johnshepherd/drake/bindings/pydrake/planning/test/iris_from_clique_cover_test.py
import unittest import pydrake.planning as mut from pydrake.common import RandomGenerator, Parallelism from pydrake.planning import ( RobotDiagramBuilder, SceneGraphCollisionChecker, CollisionCheckerParams, ) from pydrake.solvers import MosekSolver, GurobiSolver, SnoptSolver import textwrap import numpy as np import scipy.sparse as sp import scipy def _snopt_and_mip_solver_available(): mip_solver_available = ( MosekSolver().available() and MosekSolver().enabled() or ( GurobiSolver().available() and GurobiSolver().enabled() ) ) snopt_solver_available = ( SnoptSolver().available() and SnoptSolver().enabled() ) return mip_solver_available and snopt_solver_available class TestIrisFromCliqueCover(unittest.TestCase): def _make_robot_diagram(self): # Code taken from # bindings/pydrake/planning/test/collision_checker_test.py builder = mut.RobotDiagramBuilder() scene_yaml = textwrap.dedent( """ directives: - add_model: name: box file: package://drake/multibody/models/box.urdf - add_model: name: ground file: package://drake/planning/test_utilities/collision_ground_plane.sdf # noqa - add_weld: parent: world child: ground::ground_plane_box """ ) builder.parser().AddModelsFromString(scene_yaml, "dmd.yaml") model_instance_index = builder.plant().GetModelInstanceByName("box") robot_diagram = builder.Build() return (robot_diagram, model_instance_index) def _make_scene_graph_collision_checker(self, use_provider, use_function): # Code taken from # bindings/pydrake/planning/test/collision_checker_test.py self.assertFalse(use_provider and use_function) robot, index = self._make_robot_diagram() plant = robot.plant() checker_kwargs = dict( model=robot, robot_model_instances=[index], edge_step_size=0.125 ) if use_provider: checker_kwargs[ "distance_and_interpolation_provider" ] = mut.LinearDistanceAndInterpolationProvider(plant) if use_function: checker_kwargs[ "configuration_distance_function" ] = self._configuration_distance return mut.SceneGraphCollisionChecker(**checker_kwargs) def test_iris_in_configuration_space_from_clique_cover_options(self): options = mut.IrisFromCliqueCoverOptions() options.iris_options.iteration_limit = 2 self.assertEqual(options.iris_options.iteration_limit, 2) options.coverage_termination_threshold = 1e-3 self.assertEqual(options.coverage_termination_threshold, 1e-3) options.iteration_limit = 10 self.assertEqual(options.iteration_limit, 10) options.num_points_per_coverage_check = 100 self.assertEqual(options.num_points_per_coverage_check, 100) options.parallelism = Parallelism(3) self.assertEqual(options.parallelism.num_threads(), 3) options.minimum_clique_size = 2 self.assertEqual(options.minimum_clique_size, 2) options.num_points_per_visibility_round = 150 self.assertEqual(options.num_points_per_visibility_round, 150) options.rank_tol_for_minimum_volume_circumscribed_ellipsoid = 1e-3 self.assertEqual( options.rank_tol_for_minimum_volume_circumscribed_ellipsoid, 1e-3 ) options.point_in_set_tol = 1e-5 self.assertEqual(options.point_in_set_tol, 1e-5) # IPOPT performs poorly on this test. We also need a MIP solver to # be available. Hence only run this test if both SNOPT and a MIP solver # are available. @unittest.skipUnless( _snopt_and_mip_solver_available(), "Requires Snopt and a MIP solver" ) def test_iris_in_configuration_space_from_clique_cover(self): cross_cspace_urdf = """ <robot name="boxes"> <link name="fixed"> <collision name="top_left"> <origin rpy="0 0 0" xyz="-1 1 0"/> <geometry><box size="1 1 1"/></geometry> </collision> <collision name="top_right"> <origin rpy="0 0 0" xyz="1 1 0"/> <geometry><box size="1 1 1"/></geometry> </collision> <collision name="bottom_left"> <origin rpy="0 0 0" xyz="-1 -1 0"/> <geometry><box size="1 1 1"/></geometry> </collision> <collision name="bottom_right"> <origin rpy="0 0 0" xyz="1 -1 0"/> <geometry><box size="1 1 1"/></geometry> </collision> </link> <joint name="fixed_link_weld" type="fixed"> <parent link="world"/> <child link="fixed"/> </joint> <link name="movable"> <collision name="sphere"> <geometry><sphere radius="0.1"/></geometry> </collision> </link> <link name="for_joint"/> <joint name="x" type="prismatic"> <axis xyz="1 0 0"/> <limit lower="-2" upper="2"/> <parent link="world"/> <child link="for_joint"/> </joint> <joint name="y" type="prismatic"> <axis xyz="0 1 0"/> <limit lower="-2" upper="2"/> <parent link="for_joint"/> <child link="movable"/> </joint> </robot> """ params = dict(edge_step_size=0.125) builder = RobotDiagramBuilder() params["robot_model_instances"] = builder.parser().AddModelsFromString( cross_cspace_urdf, "urdf" ) params["model"] = builder.Build() checker = SceneGraphCollisionChecker(**params) options = mut.IrisFromCliqueCoverOptions() options.num_points_per_coverage_check = 10 options.num_points_per_visibility_round = 25 # We can achieve almost 100% coverage with 2 regions. options.coverage_termination_threshold = 0.999 options.iteration_limit = 3 generator = RandomGenerator(0) sets = mut.IrisInConfigurationSpaceFromCliqueCover( checker=checker, options=options, generator=generator, sets=[] ) self.assertGreaterEqual(len(sets), 2) class DummyMaxCliqueSolver(mut.MaxCliqueSolverBase): def __init__(self, name): mut.MaxCliqueSolverBase.__init__(self) self.name = name def DoSolveMaxClique(self, adjacency_matrix): return np.ones(adjacency_matrix.shape[1]) # Check that a Python solver can be used with 1 thread. options.parallelism = Parallelism(1) sets = mut.IrisInConfigurationSpaceFromCliqueCover( checker=checker, options=options, generator=generator, sets=[], max_clique_solver=DummyMaxCliqueSolver("dummy"), ) self.assertGreaterEqual(len(sets), 1)
0
/home/johnshepherd/drake/bindings/pydrake/planning
/home/johnshepherd/drake/bindings/pydrake/planning/test/graph_algorithms_test.py
import unittest import numpy as np import scipy.sparse as sp import pydrake.planning as mut from pydrake.solvers import (SolverOptions, CommonSolverOption, MosekSolver, GurobiSolver) from pydrake.common.test_utilities import numpy_compare def GurobiOrMosekSolverAvailable(): return (MosekSolver().available() and MosekSolver().enabled()) or ( GurobiSolver().available() and GurobiSolver().enabled()) class TestGraphAlgorithms(unittest.TestCase): """Tests the classes and methods defined in pydrake.planning.graph_algorithms. """ def _butteryfly_graph(self): adjacency = np.array([ [0, 1, 1, 0, 0], [1, 0, 1, 0, 0], [1, 1, 0, 1, 1], [0, 0, 1, 0, 1], [0, 0, 1, 1, 0], ]).astype(bool) data = np.ones(12).astype(bool) indices = [1, 2, 0, 2, 0, 1, 3, 4, 2, 4, 2, 3] indptr = [0, 2, 4, 8, 10, 12] sparse = sp.csc_matrix([data, indices, indptr], shape=(5, 5)) assert np.all(sparse.todense() == adjacency) assert np.all(adjacency == adjacency.T) return sparse def test_max_clique_solver_base_subclassable(self): class DummyMaxCliqueSolver(mut.MaxCliqueSolverBase): def __init__(self, name): mut.MaxCliqueSolverBase.__init__(self) self.name = name def DoSolveMaxClique(self, adjacency_matrix): return np.ones(adjacency_matrix.shape[0]) name = "dummy" solver = DummyMaxCliqueSolver(name=name) graph = self._butteryfly_graph() self.assertEqual(name, solver.name) numpy_compare.assert_equal( solver.SolveMaxClique(adjacency_matrix=graph), np.ones(graph.shape[0]) ) def test_max_clique_solver_via_mip_methods(self): graph = self._butteryfly_graph() # Test the default constructor. solver_default = mut.MaxCliqueSolverViaMip() self.assertIsNone(solver_default.GetInitialGuess()) self.assertFalse( solver_default.GetSolverOptions().get_print_to_console()) # Test the argument constructor. solver_options = SolverOptions() solver_options.SetOption(CommonSolverOption.kPrintToConsole, True) initial_guess = np.ones(graph.shape[0]) solver = mut.MaxCliqueSolverViaMip(solver_options=solver_options, initial_guess=initial_guess) # Test the getters. numpy_compare.assert_equal( solver.GetInitialGuess(), initial_guess ) self.assertTrue(solver.GetSolverOptions().get_print_to_console()) # Test the setters. new_guess = np.zeros(graph.shape[0]) solver.SetInitialGuess(initial_guess=new_guess) numpy_compare.assert_equal( solver.GetInitialGuess(), new_guess ) new_options = SolverOptions() solver.SetSolverOptions(solver_options=new_options) self.assertFalse(solver.GetSolverOptions().get_print_to_console()) # Test solve max clique. if GurobiOrMosekSolverAvailable(): max_clique = solver.SolveMaxClique(graph) # Butteryfly graph has a max clique of 3. self.assertEqual(max_clique.sum(), 3) def test_max_clique_solver_via_greedy_methods(self): graph = self._butteryfly_graph() # Test the default constructor. solver = mut.MaxCliqueSolverViaGreedy() # Test solve max clique. max_clique = solver.SolveMaxClique(graph) # Butteryfly graph has a max clique of 3. self.assertEqual(max_clique.sum(), 3)
0
/home/johnshepherd/drake/bindings/pydrake/planning
/home/johnshepherd/drake/bindings/pydrake/planning/test/collision_checker_test.py
import pydrake.planning as mut import copy import textwrap import unittest import numpy as np import scipy.sparse from pydrake.common.test_utilities import numpy_compare from pydrake.geometry import Sphere from pydrake.math import RigidTransform from pydrake.multibody.plant import MultibodyPlant from pydrake.multibody.tree import ( BodyIndex, ModelInstanceIndex, ) from pydrake.systems.framework import Context class TestCollisionChecker(unittest.TestCase): """Tests the CollisionChecker API including all of its concrete subclasses as well as all of its related lower-level "accoutrements" classes. """ def _make_robot_diagram(self): builder = mut.RobotDiagramBuilder() scene_yaml = textwrap.dedent(""" directives: - add_model: name: box file: package://drake/multibody/models/box.urdf - add_model: name: ground file: package://drake/planning/test_utilities/collision_ground_plane.sdf # noqa - add_weld: parent: world child: ground::ground_plane_box """) builder.parser().AddModelsFromString(scene_yaml, "dmd.yaml") model_instance_index = builder.plant().GetModelInstanceByName("box") robot_diagram = builder.Build() return (robot_diagram, model_instance_index) def test_body_shape_description(self): # Constructor. dut = mut.BodyShapeDescription( shape=Sphere(0.25), X_BS=RigidTransform.Identity(), model_instance_name="foo", body_name="bar") # Getters. self.assertEqual(dut.shape().radius(), 0.25) self.assertIsInstance(dut.pose_in_body(), RigidTransform) self.assertEqual(dut.model_instance_name(), "foo") self.assertEqual(dut.body_name(), "bar") # Copyable. copy.copy(dut) mut.BodyShapeDescription(other=dut) def test_make_body_shape_description(self): robot, _ = self._make_robot_diagram() plant = robot.plant() (geometry_id,) = plant.GetCollisionGeometriesForBody( plant.GetBodyByName("box")) context = robot.CreateDefaultContext() dut = mut.MakeBodyShapeDescription( plant=plant, plant_context=robot.plant_context(context), geometry_id=geometry_id) self.assertIsInstance(dut, mut.BodyShapeDescription) self.assertEqual(dut.body_name(), "box") def test_linear_distance_interpolation_provider(self): robot, _ = self._make_robot_diagram() plant = robot.plant() mut.LinearDistanceAndInterpolationProvider(plant=plant) box_joint_index = plant.GetJointByName("box").index() box_joint_weights = np.array([1.0, 0.0, 0.0, 0.0, 2.0, 3.0, 4.0]) joint_distance_weights = {box_joint_index: box_joint_weights} mut.LinearDistanceAndInterpolationProvider( plant=plant, joint_distance_weights=joint_distance_weights) distance_weights = np.array([1.0, 0.0, 0.0, 0.0, 2.0, 3.0, 4.0]) weights_vector_provider = mut.LinearDistanceAndInterpolationProvider( plant=plant, distance_weights=distance_weights) numpy_compare.assert_equal( weights_vector_provider.distance_weights(), distance_weights) self.assertEqual( weights_vector_provider.quaternion_dof_start_indices(), [0]) @staticmethod def _configuration_distance(q1, q2): """A boring implementation of ConfigurationDistanceFunction.""" return np.linalg.norm(q1 - q2) def test_collision_checker_params(self): robot, index = self._make_robot_diagram() # Default constructor; write to properties. dut = mut.CollisionCheckerParams() dut.model = robot dut.robot_model_instances = [index] dut.configuration_distance_function = self._configuration_distance dut.edge_step_size = 0.125 dut.env_collision_padding = 0.0625 dut.self_collision_padding = 0.03125 # Read from properties. self.assertIsInstance(dut.model.plant(), MultibodyPlant) self.assertListEqual(dut.robot_model_instances, [index]) self.assertEqual(dut.configuration_distance_function( np.array([0.25]), np.array([0.75])), 0.5) self.assertEqual(dut.edge_step_size, 0.125) self.assertEqual(dut.env_collision_padding, 0.0625) self.assertEqual(dut.self_collision_padding, 0.03125) # ParamInit. dut = mut.CollisionCheckerParams( robot_model_instances=[index, index]) self.assertEqual(len(dut.robot_model_instances), 2) def test_collision_checker_context(self): robot, _ = self._make_robot_diagram() # Constructor. dut = mut.CollisionCheckerContext(model=robot) # Getters. dut.model_context() dut.plant_context() dut.scene_graph_context() dut.GetQueryObject() # Clone. dut.Clone() copy.copy(dut) def test_edge_measure(self): # Constructor. dut = mut.EdgeMeasure(distance=0.25, alpha=1.0) # Getters. self.assertEqual(dut.completely_free(), True) self.assertEqual(dut.partially_free(), True) self.assertEqual(dut.distance(), 0.25) self.assertEqual(dut.alpha(), 1.0) self.assertEqual(dut.alpha_or(default_value=0.2), 1.0) # Copyable. copy.copy(dut) mut.EdgeMeasure(other=dut) def test_robot_clearance(self): # Constructor. dut = mut.RobotClearance(num_positions=3) # Getters (empty). self.assertEqual(dut.num_positions(), 3) self.assertEqual(dut.size(), 0) self.assertListEqual(dut.robot_indices(), []) self.assertListEqual(dut.other_indices(), []) self.assertListEqual(dut.collision_types(), []) numpy_compare.assert_equal(dut.distances(), []) numpy_compare.assert_equal(dut.jacobians(), [[]]) numpy_compare.assert_equal(dut.mutable_jacobians(), [[]]) # Setters. type_self = mut.RobotCollisionType.kSelfCollision type_env = mut.RobotCollisionType.kEnvironmentCollision dut.Reserve(size=2) dut.Append( robot_index=BodyIndex(10), other_index=BodyIndex(11), collision_type=type_self, distance=0.1, jacobian=np.array([0.0, 0.0, 0.01])) dut.Append( robot_index=BodyIndex(10), other_index=BodyIndex(22), collision_type=type_env, distance=0.2, jacobian=np.array([0.25, 0.00, 0.0])) # Getters (non-empty). self.assertEqual(dut.num_positions(), 3) self.assertEqual(dut.size(), 2) self.assertEqual(dut.robot_indices(), [BodyIndex(10), BodyIndex(10)]) self.assertEqual(dut.other_indices(), [BodyIndex(11), BodyIndex(22)]) self.assertEqual(dut.collision_types(), [type_self, type_env]) numpy_compare.assert_equal(dut.distances(), [0.1, 0.2]) expected_jacobians = np.array([ [0.0, 0.0, 0.01], [0.25, 0.0, 0.0], ]) numpy_compare.assert_equal(dut.jacobians(), expected_jacobians) numpy_compare.assert_equal(dut.mutable_jacobians(), expected_jacobians) # Mutation. dut.mutable_jacobians()[1, 2] = 0.5 self.assertEqual(dut.jacobians()[1, 2], 0.5) # Copyable. copy.copy(dut) mut.RobotClearance(other=dut) def test_robot_collision_type(self): # Check that all values are bound. dut = mut.RobotCollisionType values = [ dut.kNoCollision, dut.kEnvironmentCollision, dut.kSelfCollision, dut.kEnvironmentAndSelfCollision, ] # Calling MakeUpdated() with no arguments is a no-op. for x in values: updated = x.MakeUpdated() self.assertEqual(x, updated) # Helper function to create the enum via two bools. # (It would be nice if the Enum itself offered this directly.) def _make(env_col, self_col): if env_col and self_col: return dut.kEnvironmentAndSelfCollision if env_col: return dut.kEnvironmentCollision if self_col: return dut.kSelfCollision return dut.kNoCollision # Brute-force test all permutations of the Update method. for start_env in (False, True): for start_self in (False, True): start = _make(start_env, start_self) for update_env in (None, False, True): for update_self in (None, False, True): actual = start.MakeUpdated( in_environment_collision=update_env, in_self_collision=update_self) expected = _make( start_env if update_env is None else update_env, start_self if update_self is None else update_self) self.assertEqual(actual, expected) def _test_collision_checker_base_class(self, dut, has_provider): """Checks the API of CollisionChecker, given a concrete instance. """ self.assertIsInstance(dut.model(), mut.RobotDiagram) self.assertIsInstance(dut.plant(), MultibodyPlant) body = dut.plant().GetBodyByName("box") frame = body.body_frame() env_body = dut.plant().GetBodyByName("ground_plane_box") num_bodies = 3 self.assertIs(dut.get_body(body_index=body.index()), body) self.assertEqual(len(dut.robot_model_instances()), 1) self.assertTrue(dut.IsPartOfRobot(body=body)) self.assertTrue(dut.IsPartOfRobot(body_index=body.index())) self.assertGreater(len(dut.GetZeroConfiguration()), 0) self.assertGreater(dut.num_allocated_contexts(), 0) self.assertIsInstance(dut.model_context(), mut.CollisionCheckerContext) self.assertIsInstance(dut.plant_context(), Context) self.assertIsInstance( dut.model_context(context_number=1), mut.CollisionCheckerContext) self.assertIsInstance(dut.plant_context(context_number=1), Context) q = np.array([0.25] * 7) self.assertIs(dut.UpdatePositions(q=q), dut.plant_context()) self.assertIs( dut.UpdatePositions(q=q, context_number=1), dut.plant_context(context_number=1)) ccc = dut.MakeStandaloneModelContext() # ... a CollisionCheckerContext self.assertIsInstance(dut.UpdateContextPositions( model_context=ccc, q=q), Context) def operation(robot_diagram, context): self.assertIsInstance(robot_diagram, mut.RobotDiagram) self.assertIsInstance(context, mut.CollisionCheckerContext) dut.PerformOperationAgainstAllModelContexts(operation) X = RigidTransform.Identity() shape = Sphere(0.1) body_shape_description = mut.BodyShapeDescription( shape=shape, X_BS=X, model_instance_name="ground", body_name="ground_plane_box") dut.AddCollisionShape( group_name="foo", description=body_shape_description) dut.AddCollisionShapes( group_name="bar", descriptions=[body_shape_description]) dut.AddCollisionShapes( geometry_groups={"baz": [body_shape_description]}) dut.AddCollisionShapeToFrame( group_name="quux", frameA=frame, shape=shape, X_AG=X) dut.AddCollisionShapeToBody( group_name="quux", bodyA=body, shape=shape, X_AG=X) dut.GetAllAddedCollisionShapes() dut.RemoveAllAddedCollisionShapes(group_name="foo") dut.RemoveAllAddedCollisionShapes() dut.MaybeGetUniformRobotEnvironmentPadding() dut.MaybeGetUniformRobotRobotPadding() dut.GetPaddingBetween(bodyA_index=env_body.index(), bodyB_index=body.index()) dut.GetPaddingBetween(bodyA=env_body, bodyB=body) dut.SetPaddingBetween(bodyA_index=env_body.index(), bodyB_index=body.index(), padding=0.1) dut.SetPaddingBetween(bodyA=env_body, bodyB=body, padding=0.2) self.assertEqual(dut.GetPaddingMatrix().shape, (num_bodies, num_bodies)) dut.SetPaddingMatrix(collision_padding=np.zeros( (num_bodies, num_bodies))) dut.GetLargestPadding() dut.SetPaddingOneRobotBodyAllEnvironmentPairs( body_index=body.index(), padding=0.1) dut.SetPaddingAllRobotEnvironmentPairs(padding=0.1) dut.SetPaddingAllRobotRobotPairs(padding=0.1) self.assertEqual(dut.GetNominalFilteredCollisionMatrix().shape, (num_bodies, num_bodies)) self.assertEqual(dut.GetFilteredCollisionMatrix().shape, (num_bodies, num_bodies)) dut.SetCollisionFilterMatrix( filter_matrix=dut.GetNominalFilteredCollisionMatrix()) dut.IsCollisionFilteredBetween(bodyA_index=env_body.index(), bodyB_index=body.index()) dut.IsCollisionFilteredBetween(bodyA=env_body, bodyB=body) dut.SetCollisionFilteredBetween( bodyA_index=env_body.index(), bodyB_index=body.index(), filter_collision=True) dut.SetCollisionFilteredBetween( bodyA=env_body, bodyB=body, filter_collision=True) dut.SetCollisionFilteredWithAllBodies(body_index=body.index()) dut.SetCollisionFilteredWithAllBodies(body=body) dut.CheckConfigCollisionFree(q=q) dut.CheckConfigCollisionFree(q=q, context_number=1) dut.CheckContextConfigCollisionFree(model_context=ccc, q=q) self.assertEqual( len(dut.CheckConfigsCollisionFree( configs=[q]*4, parallelize=True)), 4) dut.CheckConfigsCollisionFree([q]) # Omit the defaulted arg. if not has_provider: def distance_function(q1, q2): return np.linalg.norm(q1 - q2) dut.SetConfigurationDistanceFunction( distance_function=distance_function) dut.ComputeConfigurationDistance(q1=q, q2=q) self.assertEqual( dut.MakeStandaloneConfigurationDistanceFunction()(q, q), 0.0) def interpolation_function(q1, q2, r): return q1 + (q2 - q1) * r dut.SetConfigurationInterpolationFunction( interpolation_function=interpolation_function) dut.InterpolateBetweenConfigurations(q1=q, q2=q, ratio=0.5) numpy_compare.assert_equal( dut.MakeStandaloneConfigurationInterpolationFunction()( q, q, 0.5), q) dut.edge_step_size() dut.set_edge_step_size(edge_step_size=0.2) dut.CheckEdgeCollisionFree(q1=q, q2=q) dut.CheckEdgeCollisionFree(q1=q, q2=q, context_number=1) dut.CheckContextEdgeCollisionFree(model_context=ccc, q1=q, q2=q) dut.CheckEdgeCollisionFreeParallel(q1=q, q2=q, parallelize=True) self.assertEqual( len(dut.CheckEdgesCollisionFree( edges=[(q, q)]*4, parallelize=True)), 4) dut.CheckEdgesCollisionFree([(q, q)]) # Omit the defaulted arg. dut.MeasureEdgeCollisionFree(q1=q, q2=q) dut.MeasureEdgeCollisionFree(q1=q, q2=q, context_number=1) dut.MeasureContextEdgeCollisionFree(model_context=ccc, q1=q, q2=q) dut.MeasureEdgeCollisionFreeParallel(q1=q, q2=q, parallelize=True) measures = dut.MeasureEdgesCollisionFree( edges=[(q, q)]*4, parallelize=True) self.assertEqual(len(measures), 4) self.assertIsInstance(measures[0], mut.EdgeMeasure) dut.MeasureEdgesCollisionFree([(q, q)]) # Omit the defaulted arg. clearance = dut.CalcRobotClearance(q=q, influence_distance=10) self.assertIsInstance(clearance, mut.RobotClearance) clearance = dut.CalcRobotClearance( q=q, influence_distance=10, context_number=1) self.assertIsInstance(clearance, mut.RobotClearance) clearance = dut.CalcContextRobotClearance( model_context=ccc, q=q, influence_distance=10) self.assertIsInstance(clearance, mut.RobotClearance) dut.MaxNumDistances() dut.MaxNumDistances(context_number=1) dut.MaxContextNumDistances(model_context=ccc) dut.ClassifyBodyCollisions(q=q) dut.ClassifyBodyCollisions(q=q, context_number=1) dut.ClassifyContextBodyCollisions(model_context=ccc, q=q) self.assertIsInstance(dut.SupportsParallelChecking(), bool) provider = dut.distance_and_interpolation_provider() self.assertIsInstance(provider, mut.DistanceAndInterpolationProvider) new_provider = mut.LinearDistanceAndInterpolationProvider( dut.model().plant()) dut.SetDistanceAndInterpolationProvider(provider=new_provider) def _make_scene_graph_collision_checker(self, use_provider, use_function): self.assertFalse(use_provider and use_function) robot, index = self._make_robot_diagram() plant = robot.plant() checker_kwargs = dict( model=robot, robot_model_instances=[index], edge_step_size=0.125) if use_provider: checker_kwargs["distance_and_interpolation_provider"] = \ mut.LinearDistanceAndInterpolationProvider(plant) if use_function: checker_kwargs["configuration_distance_function"] = \ self._configuration_distance return mut.SceneGraphCollisionChecker(**checker_kwargs) def test_scene_graph_collision_checker(self): """Tests the full CollisionChecker API. """ # With no provider or function specified, the default SGCC has a # LinearDistanceAndInterpolationProvider. default_checker = self._make_scene_graph_collision_checker( False, False) self._test_collision_checker_base_class(default_checker, True) provider_checker = self._make_scene_graph_collision_checker( True, False) self._test_collision_checker_base_class(provider_checker, True) function_checker = self._make_scene_graph_collision_checker( False, True) self._test_collision_checker_base_class(function_checker, False) def test_visibility_graph(self): checker = self._make_scene_graph_collision_checker(True, False) plant = checker.model().plant() num_points = 2 points = np.empty((plant.num_positions(), num_points)) points[:, 0] = plant.GetPositions(checker.plant_context()) points[:, 1] = points[:, 0] points[-1, 1] += 0.1 A = mut.VisibilityGraph(checker=checker, points=points, parallelize=True) self.assertEqual(A.shape, (num_points, num_points)) self.assertIsInstance(A, scipy.sparse.csc_matrix)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/_model_visualizer.py
import copy from enum import Enum import logging import os from pathlib import Path import time from webbrowser import open as _webbrowser_open import numpy as np from pydrake.geometry import ( Box, Cylinder, GeometryInstance, MakePhongIllustrationProperties, MeshcatCone, Role, Rgba, StartMeshcat, ) from pydrake.math import RigidTransform, RotationMatrix from pydrake.multibody.meshcat import JointSliders from pydrake.multibody.tree import ( FixedOffsetFrame, FrameIndex, default_model_instance, ) from pydrake.planning import RobotDiagramBuilder from pydrake.systems.analysis import Simulator from pydrake.systems.planar_scenegraph_visualizer import ( ConnectPlanarSceneGraphVisualizer, ) from pydrake.systems.sensors import ( ApplyCameraConfig, CameraConfig, ) from pydrake.visualization import ( VisualizationConfig, ApplyVisualizationConfig, ) from pydrake.visualization._triad import ( AddFrameTriadIllustration, ) class ModelVisualizer: """ Visualizes models from a file or string buffer in MeshCat or Meldis. To use this class to visualize model(s), create an instance with any desired options, add any models, and then call Run():: visualizer = ModelVisualizer(browser_new=True) visualizer.AddModels(filename) visualizer.Run() The class also provides a `parser()` method to allow more complex Parser handling, e.g. adding a model from a string:: visualizer.parser().AddModelsFromString(buffer_containing_model, 'sdf') This class may also be run as a standalone command-line tool using the ``pydrake.visualization.model_visualizer`` script, or via ``bazel run //tools:model_visualizer``. """ # Note: this class uses C++ method names to ease future porting. def __init__(self, *, visualize_frames=False, triad_length=0.3, triad_radius=0.005, triad_opacity=0.9, publish_contacts=True, show_rgbd_sensor=False, browser_new=False, pyplot=False, meshcat=None, environment_map: Path = Path()): """ Initializes a ModelVisualizer. Args: visualize_frames: a flag that visualizes frames as triads for all links. triad_length: the length of visualization triads. triad_radius: the radius of visualization triads. triad_opacity: the opacity of visualization triads. publish_contacts: a flag for VisualizationConfig. show_rgbd_sensor: when True, adds an RgbdSensor to the scene and pops up a local preview window of the rgb image. At the moment, the image display uses a native window so will not work in a remote or cloud runtime environment. browser_new: a flag that will open the MeshCat display in a new browser window during Run(). pyplot: a flag that will open a pyplot figure for rendering using PlanarSceneGraphVisualizer. meshcat: an existing Meshcat instance to re-use instead of creating a new instance. Useful in, e.g., Python notebooks. """ self._visualize_frames = visualize_frames self._triad_length = triad_length self._triad_radius = triad_radius self._triad_opacity = triad_opacity self._publish_contacts = publish_contacts self._show_rgbd_sensor = show_rgbd_sensor self._browser_new = browser_new self._pyplot = pyplot self._meshcat = meshcat self._environment_map = environment_map # This is the list of loaded models, to enable the Reload button. # If set to None, it means that we won't support reloading because # the user might have added models outside of our purview. Each item # in the list contains whatever kwargs we passed to AddModels(). self._added_models = list() # This is set to a non-None value iff our Meshcat has a reload button. self._reload_button_name = None # The builder is set to None during Finalize(), though during a Reload # it will be temporarily resurrected. self._builder = RobotDiagramBuilder() self._builder.parser().SetAutoRenaming(True) # The following fields are set non-None during Finalize(). self._original_package_map = None self._diagram = None # This will be a planning.RobotDiagram. self._sliders = None self._context = None # State necessary for self._render_if_necessary(). self._last_camera_time = time.time() def _check_rep(self, *, finalized): """ Checks that our self members are consistent with the provided expected state of finalization. """ if not finalized: # The builder is alive. assert self._builder is not None # The meshcat might or might not exist yet. # Everything else is dead. assert self._original_package_map is None assert self._diagram is None assert self._sliders is None assert self._context is None else: # The builder is dead. assert self._builder is None # Everything else is alive. assert self._meshcat is not None assert self._original_package_map is not None assert self._diagram is not None assert self._sliders is not None assert self._context is not None @staticmethod def _get_constructor_defaults(): """ Returns a dict of the default values used in our constructor's named keyword arguments (for any non-None values); this helps our companion main() function share those same defaults. """ result = dict() prototype = ModelVisualizer() for name in [ "visualize_frames", "triad_length", "triad_radius", "triad_opacity", "publish_contacts", "show_rgbd_sensor", "browser_new", "pyplot", "environment_map"]: value = getattr(prototype, f"_{name}") assert value is not None result[name] = value return result def package_map(self): """ Returns the PackageMap being used during parsing. Users should add entries here to be able to load models from non-Drake packages. This method cannot be used after Finalize is called. """ if self._builder is None: raise ValueError("Finalize has already been called.") self._check_rep(finalized=False) # It's safe to let the user change the package map. We'll make a copy # of it during Finalize(). return self._builder.parser().package_map() def parser(self): """ (Advanced) Returns a Parser that will load models into this visualizer. Prefer to use package_map() and AddModels() to load models, instead of this method. Calling this method will disable the "Reload" button in the visualizer, because we can no longer determine the scope of what to reload. This method cannot be used after Finalize is called. """ if self._builder is None: raise ValueError("Finalize has already been called.") self._check_rep(finalized=False) # We can't easily know what the user is going to do with the parser, # so we need to disable model reloading once they access it. self._added_models = None return self._builder.parser() def meshcat(self): """ Returns the Meshcat object this visualizer is plugged into. If none was provided in the constructor, this creates one on demand. """ if self._meshcat is None: self._meshcat = StartMeshcat() return self._meshcat def AddModels(self, filename: Path = None, *, url: str = None): """ Adds all models found in an input file (or url). This can be called multiple times, until the object is finalized. Args: filename: the name of a file containing one or more models. url: the package:// URL containing one or more models. Exactly one of filename or url must be non-None. """ if self._builder is None: raise ValueError("Finalize has already been called.") if sum([filename is not None, url is not None]) != 1: raise ValueError("Must provide either filename= or url=") self._check_rep(finalized=False) if filename is not None: kwargs = dict(file_name=filename) else: assert url is not None kwargs = dict(url=url) self._builder.parser().AddModels(**kwargs) if self._added_models is not None: self._added_models.append(kwargs) def Finalize(self, position=None): """ Finalizes the object and sets up the visualization using the provided options once models have been added. Args: position: a list of slider positions for the model(s); must match the number of positions in all model(s), including the 7 positions corresponding to any model bases that aren't welded to the world. """ self._check_rep(finalized=False) if self._builder is None: raise RuntimeError("Finalize has already been called.") if self._visualize_frames: # Find all the frames (except the world frame) and draw them. # The frames are drawn using the configured length. for i in range(1, self._builder.plant().num_frames()): AddFrameTriadIllustration( plant=self._builder.plant(), scene_graph=self._builder.scene_graph(), frame_index=FrameIndex(i), length=self._triad_length, radius=self._triad_radius, opacity=self._triad_opacity, ) # Add a model to provide a pose-able anchor for the camera. if self._show_rgbd_sensor: sensor_offset_frame = self._builder.plant().AddFrame( FixedOffsetFrame( name="$rgbd_sensor_offset", P=self._builder.plant().world_frame(), X_PF=RigidTransform.Identity(), model_instance=default_model_instance())) sensor_body = self._builder.plant().AddRigidBody( name="$rgbd_sensor_body", model_instance=default_model_instance()) self._builder.plant().WeldFrames( frame_on_parent_F=sensor_offset_frame, frame_on_child_M=sensor_body.body_frame()) self._builder.plant().Finalize() # (Re-)initialize the meshcat instance, creating one if needed. self.meshcat() self._meshcat.Delete() self._meshcat.DeleteAddedControls() if self._environment_map.is_file(): self._meshcat.SetEnvironmentMap(self._environment_map) # We want to place the Reload Model Files button far away from the # Stop Running button, hence the work to do this here. if self._added_models: self._reload_button_name = "Reload Model Files" self._meshcat.AddButton(self._reload_button_name) # Connect to meldis and meshcat. # Meldis and meshcat provide simultaneous visualization of # illustration and proximity geometry. ApplyVisualizationConfig( config=VisualizationConfig( publish_contacts=self._publish_contacts, enable_alpha_sliders=True), plant=self._builder.plant(), scene_graph=self._builder.scene_graph(), builder=self._builder.builder(), meshcat=self._meshcat) # Add a render camera so we can show role=perception images. The # sensor is affixed to the world frame and we'll modify that pose # below. if self._show_rgbd_sensor: camera_config = CameraConfig(width=1440, height=1080) camera_config.name = "preview" camera_config.X_PB.base_frame = "$rgbd_sensor_body" camera_config.z_far = 3 # Show 3m of frustum. camera_config.fps = 1.0 # Ignored -- we're not simulating. is_unit_test = "TEST_SRCDIR" in os.environ camera_config.show_rgb = not is_unit_test # Pop up a local window. ApplyCameraConfig( config=camera_config, builder=self._builder.builder()) camera_sensor = self._builder.builder().GetSubsystemByName( "rgbd_sensor_preview") camera_publisher = self._builder.builder().GetSubsystemByName( "LcmPublisherSystem(DRAKE_RGBD_CAMERA_IMAGES_preview)") # Export the preview camera image output port for later use. self._builder.builder().ExportOutput( camera_sensor.GetOutputPort("color_image"), "preview_image") # Disable LCM image transmission. It has a non-trivial cost, and # at the moment Meldis can't display LCM images anyway. self._builder.builder().RemoveSystem(camera_publisher) # Add joint sliders to meshcat. # TODO(trowell-tri) Restoring slider values depends on the slider # names remaining consistent across the reload; currently the # JointSlider code names sliders by joint name and position suffix # and adds a model name suffix when those names aren't unique, e.g. # when the same model appears multiple times. Thus if the set of # models changes to cause or eliminate such a name collision then # slider values won't be fully restored. It would probably be better to # be able to configure the JointSliders to always use fully-qualified # names on demand, especially once the size of the control panel is # adjustable so that the slider names are better visible. self._sliders = self._builder.builder().AddNamedSystem( "joint_sliders", JointSliders(meshcat=self._meshcat, plant=self._builder.plant())) # Connect to PyPlot. if self._pyplot: ConnectPlanarSceneGraphVisualizer( self._builder.builder(), self._builder.scene_graph()) self._original_package_map = copy.copy( self._builder.parser().package_map()) self._diagram = self._builder.Build() self._builder = None self._context = self._diagram.CreateDefaultContext() # We don't just test 'position' because NumPy does weird things with # the truth values of arrays. if position is not None and len(position) > 0: self._raise_if_invalid_positions(position) self._diagram.plant().SetPositions( self._diagram.plant().GetMyContextFromRoot(self._context), position) self._sliders.SetPositions(position) # Use Simulator to dispatch initialization events. # TODO(eric.cousineau): Simplify as part of #13776 (was #10015). Simulator(self._diagram).Initialize() # Publish draw messages with current state. self._diagram.ForcedPublish(self._context) self._check_rep(finalized=True) @staticmethod def _camera_config_to_frustum(camera: CameraConfig): """ Returns a mesh as (vertices, faces) to visualize the given camera's frustum. """ distance = camera.z_far width = 0.5 * camera.width * distance / camera.focal_x() height = 0.5 * camera.height * distance / camera.focal_y() vertices = np.array([ [0.0, 0.0, 0.0], [+width, +height, distance], [+width, -height, distance], [-width, -height, distance], [-width, +height, distance], ]).T faces = np.array([ [0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], ]).T return (vertices, faces) def _reload(self): """ Re-creates the Diagram using the same sequence of calls to AddModels as the user performed. In effect, this will refresh the visualizer to show any changes the user made on disk to their models. """ self._check_rep(finalized=True) assert self._added_models is not None # Clear out the old diagram. self._diagram = None self._sliders = None self._context = None self._remove_traffic_cone() # Populate the diagram builder again with the same packages and models. self._builder = RobotDiagramBuilder() self._builder.parser().SetAutoRenaming(True) self._builder.parser().package_map().AddMap(self._original_package_map) try: for kwargs in self._added_models: self._builder.parser().AddModels(**kwargs) logging.getLogger("drake").info(f"Reload was successful") except BaseException as e: # If there's a parsing error, show it; don't crash. logging.getLogger("drake").error(e) logging.getLogger("drake").warning( f"Click '{self._reload_button_name}' to try again") # Clear the display to help indicate the failure to the user. self._builder = RobotDiagramBuilder() self._builder.parser().package_map().AddMap( self._original_package_map) self._add_traffic_cone() self._original_package_map = None # Finalize the rest of the systems and widgets. self.Finalize() def _render_if_necessary(self, *, loop_once): """This evaluates the state of the camera and plant and possibly triggers a rendering (up to a maximum hard-coded rate). """ if not self._show_rgbd_sensor: return # When we only have a loop once, we should get one rendering. if not loop_once and time.time() < (self._last_camera_time + 0.0625): return self._last_camera_time = time.time() X_WC = self._meshcat.GetTrackedCameraPose() if X_WC is None: return frame = self._diagram.plant().GetFrameByName("$rgbd_sensor_offset") frame.SetPoseInParentFrame( context=self._diagram.plant().GetMyContextFromRoot(self._context), X_PF=X_WC) self._diagram.GetOutputPort("preview_image").Eval(self._context) def Run(self, position=None, loop_once=False): """ Runs the model. If Finalize() hasn't already been explicitly called then the object will be finalized first. Will iterate once and exit if `loop_once` is True, otherwise will loop until the user quits. Args: position: an ndarray-like list of slider positions for the model(s); must match the number of positions in all model(s), including the 7 positions corresponding to any model bases that aren't welded to the world. loop_once: a flag that exits the evaluation loop after one pass. """ if self._builder is not None: self.Finalize(position=position) else: self._check_rep(finalized=True) if position is not None and len(position) > 0: self._raise_if_invalid_positions(position) self._diagram.plant().SetPositions( self._diagram.plant().GetMyContextFromRoot(self._context), position) self._sliders.SetPositions(position) self._diagram.ForcedPublish(self._context) # Everything is finally fully configured. We can open the window now. # TODO(jwnimmer-tri) The browser_new config knob would probably make # more sense as an argument to Run() vs an argument to our constructor. if self._browser_new: self._browser_new = False url_params = "" if self._show_rgbd_sensor: url_params = "?tracked_camera=on" url = self._meshcat.web_url() + url_params _webbrowser_open(url=url, new=True) elif self._show_rgbd_sensor: logging.getLogger("drake").info( "You've requested to show the RGBD Sensor. To control the " "sensor position, make sure you open one browser to the " "following url:\n\n" f"\t{self._meshcat.web_url()}?tracked_camera=on\n") # Wait for the user to cancel us. stop_button_name = "Stop Running" if not loop_once: logging.getLogger("drake").info( f"Click '{stop_button_name}' or press Esc to quit") try: self._meshcat.AddButton(stop_button_name, "Escape") def has_clicks(button_name): if not button_name: return False return self._meshcat.GetButtonClicks(button_name) > 0 while True: self._render_if_necessary(loop_once=loop_once) time.sleep(1 / 32.0) if has_clicks(self._reload_button_name): self._meshcat.DeleteButton(stop_button_name) slider_values = self._get_slider_values() self._reload() self._set_slider_values(slider_values) self._meshcat.AddButton(stop_button_name, "Escape") q = self._sliders.get_output_port().Eval( self._sliders.GetMyContextFromRoot(self._context)) self._diagram.plant().SetPositions( self._diagram.plant().GetMyContextFromRoot(self._context), q) self._diagram.ForcedPublish(self._context) if loop_once or has_clicks(stop_button_name): break except KeyboardInterrupt: pass self._meshcat.DeleteButton(stop_button_name) if self._reload_button_name is not None: self._meshcat.DeleteButton(self._reload_button_name) self._reload_button_name = None def _raise_if_invalid_positions(self, position): """ Validate the position argument. Raises: ValueError: if the length of the position list does not match the number of positions in the plant. """ assert self._diagram is not None actual = len(position) expected = self._diagram.plant().num_positions() if actual != expected: raise ValueError( f"Number of passed positions ({actual}) does not match the " f"number in the model ({expected}).") def _get_slider_values(self): """Returns a map of slider names to current values.""" return {name: self._meshcat.GetSliderValue(name) for name in self._meshcat.GetSliderNames()} def _set_slider_values(self, slider_values): """ Sets current sliders to the values found in the slider_values dict. Current sliders not in the passed map -- or values in the map but which not longer exist in the GUI -- are ignored. """ current_names = self._meshcat.GetSliderNames() for old_name, old_value in slider_values.items(): if old_name in current_names: self._meshcat.SetSliderValue(old_name, old_value) def _add_traffic_cone(self): """Adds a traffic cone to the scene, indicating a parsing error.""" base_width = 0.4 base_thickness = 0.01 base = Box(base_width, base_width, base_thickness) cone_height = 0.6 cone_radius = 0.75 * (base_width / 2) cone = MeshcatCone(cone_height, cone_radius, cone_radius) path = "/PARSE_ERROR" orange = Rgba(1.0, 0.33, 0) self._meshcat.SetObject(path=f"{path}/base", shape=base, rgba=orange) self._meshcat.SetObject(path=f"{path}/cone", shape=cone, rgba=orange) self._meshcat.SetTransform(f"{path}/base", RigidTransform( [0, 0, base_thickness * 0.5])) self._meshcat.SetTransform(f"{path}/cone", RigidTransform( RotationMatrix.MakeYRotation(np.pi), [0, 0, base_thickness + cone_height])) def _remove_traffic_cone(self): """Removes the traffic cone from the scene.""" self._meshcat.Delete("/PARSE_ERROR")
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/visualization_py_sliders.cc
#include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/visualization/visualization_py.h" #include "drake/visualization/meshcat_pose_sliders.h" namespace drake { namespace pydrake { namespace internal { namespace { template <typename T> void DoScalarDependentDefinitions(py::module m, T) { py::tuple param = GetPyParam<T>(); // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::visualization; constexpr auto& doc = pydrake_doc.drake.visualization; // MeshcatPoseSliders { using Class = MeshcatPoseSliders<T>; constexpr auto& cls_doc = doc.MeshcatPoseSliders; DefineTemplateClassWithDefault<MeshcatPoseSliders<T>, systems::LeafSystem<T>>( m, "MeshcatPoseSliders", param, doc.MeshcatPoseSliders.doc) .def( py::init<std::shared_ptr<geometry::Meshcat>, const math::RigidTransformd&, const Eigen::Ref<const Vector6d>&, const Eigen::Ref<const Vector6d>&, const Eigen::Ref<const Vector6d>&, std::vector<std::string>, std::vector<std::string>, std::string, const Eigen::Ref<const Vector6<bool>>&>(), py::arg("meshcat"), py::arg("initial_pose") = math::RigidTransformd(), py::arg("lower_limit") = (Vector6d() << -M_PI, -M_PI, -M_PI, -1, -1, -1).finished(), py::arg("upper_limit") = (Vector6d() << M_PI, M_PI, M_PI, 1, 1, 1).finished(), py::arg("step") = Vector6d::Constant(0.01), py::arg("decrement_keycodes") = std::vector<std::string>( {"KeyQ", "KeyS", "KeyA", "KeyJ", "KeyK", "KeyU"}), py::arg("increment_keycodes") = std::vector<std::string>( {"KeyE", "KeyW", "KeyD", "KeyL", "KeyI", "KeyO"}), py::arg("prefix") = "", py::arg("visible") = Vector6<bool>::Constant(true), cls_doc.ctor.doc) .def("Delete", &Class::Delete, cls_doc.Delete.doc) .def("Run", &Class::Run, py::arg("system"), py::arg("context"), py::arg("timeout") = py::none(), py::arg("stop_button_keycode") = "Escape", // This is a long-running function that sleeps; for both reasons, we // must release the GIL. py::call_guard<py::gil_scoped_release>(), cls_doc.Run.doc) .def("SetPose", &Class::SetPose, py::arg("pose"), cls_doc.SetPose.doc); } } } // namespace void DefineVisualizationSliders(py::module m) { type_visit([m](auto dummy) { DoScalarDependentDefinitions(m, dummy); }, NonSymbolicScalarPack{}); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/model_visualizer.py
r"""The ``model_visualizer`` program displays a model file (e.g., ``*.sdf``) in Drake's built-in visualizers (MeshCat and/or Meldis). When viewing in MeshCat, joint sliders to posture the model are available by clicking on "Open Controls" in the top right corner. If the loaded model file is changed, it can be reloaded by pressing the "Reload Model Files" button, which will attempt to maintain slider values once reloading is finished. To exit, press the "Stop Running" button or press the Escape key. This command-line module is provided for convenience, but the feature is also available via the library class ``pydrake.visualization.ModelVisualizer``. From a Drake source build, run this module as:: bazel run //tools:model_visualizer -- --help From a Drake binary release (including pip releases), run this module as:: python3 -m pydrake.visualization.model_visualizer --help For binary releases (except for pip) there is also a shortcut available as:: /opt/drake/bin/model_visualizer Refer to the instructions printed by ``--help`` for additional details. An example of viewing an iiwa model file:: python3 -m pydrake.visualization.model_visualizer --open-window \ package://drake_models/iiwa_description/sdf/iiwa7_with_box_collision.sdf This program respects the ``ROS_PACKAGE_PATH``; if your model uses external resources then you will need to set that environment variable. """ import argparse import logging import os from pathlib import Path from pydrake.visualization._model_visualizer import \ ModelVisualizer as _ModelVisualizer def _main(): # Use a few color highlights for the user's terminal output. logging.addLevelName(logging.INFO, "\033[36mINFO\033[0m") logging.addLevelName(logging.WARNING, "\033[33mWARNING\033[0m") logging.addLevelName(logging.ERROR, "\033[31mERROR\033[0m") format = "%(levelname)s: %(message)s" logging.basicConfig(level=logging.INFO, format=format) # Prepare to parse arguments. args_parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) # Many of our command line arguments map directly onto named arguments to # the ModelVisualizer constructor. We'll obey those constructor defaults # as we define the argparse defaults. defaults = _ModelVisualizer._get_constructor_defaults() args_parser.add_argument( "filename", nargs="+", type=str, help="Filesystem path to an SDFormat, URDF, OBJ, or DMD file; " "or a package:// URL to use a ROS package path.") assert defaults["browser_new"] is False args_parser.add_argument( "-w", "--open-window", dest="browser_new", action="store_true", help="Open the MeshCat display in a new browser window.") assert defaults["pyplot"] is False args_parser.add_argument( "--pyplot", action="store_true", help="Open a pyplot figure for rendering using " "PlanarSceneGraphVisualizer.") # TODO(russt): Consider supporting the PlanarSceneGraphVisualizer # options as additional arguments. assert defaults["visualize_frames"] is False args_parser.add_argument( "--visualize_frames", action="store_true", help="Visualize the frames as triads for all links.", ) assert defaults["show_rgbd_sensor"] is False args_parser.add_argument( "--show_rgbd_sensor", action="store_true", help="Add and show an RgbdSensor. At the moment, the image display " "uses a native window so will not work in a remote or cloud " "runtime environment.", ) assert defaults["environment_map"] == Path() args_parser.add_argument( "--environment_map", default=Path(), type=Path, help="Filesystem path to an image to be used as an environment map. " "It must be an image type normally used by your browser (e.g., " ".jpg, .png, etc.). HDR images are not supported yet." ) args_parser.add_argument( "--triad_length", type=float, dest="triad_length", default=defaults["triad_length"], help="Triad length for frame visualization.", ) args_parser.add_argument( "--triad_radius", type=float, dest="triad_radius", default=defaults["triad_radius"], help="Triad radius for frame visualization.", ) args_parser.add_argument( "--triad_opacity", type=float, dest="triad_opacity", default=defaults["triad_opacity"], help="Triad opacity for frame visualization.", ) args_parser.add_argument( "-q", "--position", dest="position", type=float, nargs="+", default=[], help="A list of positions which must be the same length as the number " "of positions in the sdf models. Note that most models have a " "floating-base joint by default (unless the sdf explicitly welds " "the base to the world, and so have 7 positions corresponding to " "the quaternion representation of that floating-base position).") args_parser.add_argument( "--loop_once", action='store_true', help="Run the evaluation loop once and then quit.") args = args_parser.parse_args() if 'BUILD_WORKSPACE_DIRECTORY' in os.environ: os.chdir(os.environ['BUILD_WORKING_DIRECTORY']) visualizer = _ModelVisualizer(visualize_frames=args.visualize_frames, show_rgbd_sensor=args.show_rgbd_sensor, triad_length=args.triad_length, triad_radius=args.triad_radius, triad_opacity=args.triad_opacity, browser_new=args.browser_new, pyplot=args.pyplot, environment_map=args.environment_map) package_map = visualizer.package_map() package_map.PopulateFromRosPackagePath() for item in args.filename: if item.startswith("package://"): visualizer.AddModels(url=item) else: visualizer.AddModels(item) visualizer.Run(position=args.position, loop_once=args.loop_once) if __name__ == '__main__': _main()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/visualization_py_image_systems.cc
#include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/bindings/pydrake/visualization/visualization_py.h" #include "drake/visualization/colorize_depth_image.h" #include "drake/visualization/colorize_label_image.h" #include "drake/visualization/concatenate_images.h" namespace drake { namespace pydrake { namespace internal { void DefineVisualizationImageSystems(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::visualization; constexpr auto& doc = pydrake_doc.drake.visualization; { using Class = ColorizeDepthImage<double>; constexpr auto& cls_doc = doc.ColorizeDepthImage; py::class_<Class, systems::LeafSystem<double>>( m, "ColorizeDepthImage", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc) .def_property("invalid_color", &Class::get_invalid_color, &Class::set_invalid_color, "The color used for pixels with too-near or too-far depth.") .def("Calc", overload_cast_explicit<void, const systems::sensors::ImageDepth32F&, systems::sensors::ImageRgba8U*>(&Class::Calc), cls_doc.Calc.doc) .def("Calc", overload_cast_explicit<void, const systems::sensors::ImageDepth16U&, systems::sensors::ImageRgba8U*>(&Class::Calc), cls_doc.Calc.doc); } { using Class = ColorizeLabelImage<double>; constexpr auto& cls_doc = doc.ColorizeLabelImage; py::class_<Class, systems::LeafSystem<double>>( m, "ColorizeLabelImage", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc) .def_property("background_color", &Class::get_background_color, &Class::set_background_color, "The color used for pixels with no label.") .def("Calc", &Class::Calc, cls_doc.Calc.doc); } { using Class = ConcatenateImages<double>; constexpr auto& cls_doc = doc.ConcatenateImages; py::class_<Class, systems::LeafSystem<double>>( m, "ConcatenateImages", cls_doc.doc) .def(py::init<int, int>(), py::kw_only(), py::arg("rows") = 1, py::arg("cols") = 1, cls_doc.ctor.doc) .def("get_input_port", &Class::get_input_port, py::kw_only(), py::arg("row"), py::arg("col"), py_rvp::reference_internal, cls_doc.get_input_port.doc); } } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/BUILD.bazel
load("@python//:version.bzl", "PYTHON_SITE_PACKAGES_RELPATH") load("//bindings/pydrake:pydrake.bzl", "add_lint_tests_pydrake") load("//tools/install:install.bzl", "install", "install_files") load( "//tools/skylark:drake_py.bzl", "drake_py_binary", "drake_py_library", "drake_py_unittest", ) load( "//tools/skylark:pybind.bzl", "drake_pybind_library", "get_drake_py_installs", "get_pybind_package_info", ) load( "//tools/workspace:cmake_configure_file.bzl", "cmake_configure_file", ) 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 = "visualization", cc_deps = [ "//bindings/pydrake:documentation_pybind", "//bindings/pydrake/common:default_scalars_pybind", "//bindings/pydrake/common:serialize_pybind", ], cc_so_name = "__init__", cc_srcs = [ "visualization_py.cc", "visualization_py_config.cc", "visualization_py_image_systems.cc", "visualization_py_sliders.cc", "visualization_py.h", ], package_info = PACKAGE_INFO, py_deps = [ "//bindings/pydrake/multibody", "//bindings/pydrake/planning", "//bindings/pydrake/solvers", "//bindings/pydrake/systems", "//bindings/pydrake/geometry", "//bindings/pydrake:lcm_py", "//lcmtypes:lcmtypes_drake_py", ], py_srcs = [ "meldis.py", "model_visualizer.py", "_meldis.py", "_model_visualizer.py", "_plotting.py", "_triad.py", "_video.py", "_visualization_extra.py", ], ) drake_py_binary( name = "meldis", srcs = ["meldis.py"], visibility = ["//tools:__pkg__"], deps = [":visualization"], ) drake_py_binary( name = "model_visualizer", srcs = ["model_visualizer.py"], data = ["//:all_models"], visibility = ["//tools:__pkg__"], deps = [":visualization"], ) drake_py_binary( name = "lcm_image_array_viewer", srcs = ["_lcm_image_array_viewer.py"], deps = [":visualization"], ) # TODO(jwnimmer-tri) For now, this is a private library for testing only. Once # Meldis needs this it should move up into the main "visualization" library. drake_py_library( name = "_lcm_image_array_viewer_py", srcs = ["_lcm_image_array_viewer.py"], deps = [":visualization"], ) cmake_configure_file( name = "generate_run_installed_meldis", src = "run_installed_meldis.py.in", out = "run_installed_meldis.py", defines = [ "PYTHON_SITE_PACKAGES_RELPATH=" + PYTHON_SITE_PACKAGES_RELPATH, ], ) cmake_configure_file( name = "generate_run_installed_model_visualizer", src = "run_installed_model_visualizer.py.in", out = "run_installed_model_visualizer.py", defines = [ "PYTHON_SITE_PACKAGES_RELPATH=" + PYTHON_SITE_PACKAGES_RELPATH, ], ) install_files( name = "install_wrapper_scripts", dest = "bin", files = [ "run_installed_meldis.py", "run_installed_model_visualizer.py", ], rename = { "bin/run_installed_meldis.py": "meldis", "bin/run_installed_model_visualizer.py": "model_visualizer", }, ) PY_LIBRARIES = [ ":visualization", ] install( name = "install", install_tests = [ ":test/visualization_install_tests.py", ], targets = [":visualization"], py_dest = PACKAGE_INFO.py_dest, deps = get_drake_py_installs(PY_LIBRARIES) + [ ":install_wrapper_scripts", ], ) drake_py_unittest( name = "config_test", deps = [ ":visualization", ], ) drake_py_unittest( name = "image_systems_test", deps = [ ":visualization", "//bindings/pydrake/common/test_utilities:numpy_compare_py", ], ) drake_py_unittest( name = "meldis_test", data = [ "//examples/hydroelastic/spatula_slip_control:models", "//multibody/benchmarks/acrobot:models", "//multibody/meshcat:models", ], deps = [ ":visualization", ], ) drake_py_unittest( name = "model_visualizer_test", timeout = "moderate", data = [ ":model_visualizer", "//manipulation/util:test_models", "//multibody/benchmarks/acrobot:models", "//multibody/parsing:test_models", ], deps = [ ":model_visualizer", ], ) drake_py_unittest( name = "model_visualizer_reload_test", data = [ ":model_visualizer", "//geometry:meshcat_websocket_client", "//multibody/benchmarks/acrobot:models", ], flaky = True, deps = [ ":model_visualizer", ], ) drake_py_unittest( name = "model_visualizer_camera_test", flaky = True, deps = [ ":model_visualizer", "//bindings/pydrake/common/test_utilities", ], ) drake_py_unittest( name = "plotting_test", deps = [ ":visualization", ], ) drake_py_unittest( name = "sliders_test", deps = [ ":visualization", ], ) drake_py_unittest( name = "triad_test", data = [ "//multibody/benchmarks/acrobot:models", ], deps = [ ":visualization", ], ) drake_py_unittest( name = "video_test", size = "medium", deps = [ ":visualization", "//bindings/pydrake/common/test_utilities:numpy_compare_py", ], ) drake_py_unittest( name = "lcm_image_array_viewer_test", deps = [ ":_lcm_image_array_viewer_py", ], ) drake_py_unittest( name = "multicam_scenario_test", # Note: It's safe to use lcm in the test because it uses a non-default URL # and only transmits status messages. allow_network = ["lcm:meshcat"], data = [ "test/multicam_scenario.yaml", "//examples/hardware_sim:hardware_sim_py", ], ) add_lint_tests_pydrake( python_lint_extra_srcs = [ "run_installed_meldis.py.in", "run_installed_model_visualizer.py.in", "test/visualization_install_tests.py", ], )
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/_video.py
import copy import numpy as np from pydrake.common.value import Value from pydrake.geometry import ( ClippingRange, DepthRange, DepthRenderCamera, MakeRenderEngineVtk, RenderCameraCore, RenderEngineVtkParams, SceneGraph, ) from pydrake.math import RigidTransform from pydrake.systems.framework import LeafSystem from pydrake.systems.sensors import ( CameraInfo, ImageRgba8U, RgbdSensor, ) from pydrake.visualization import ( ColorizeDepthImage, ColorizeLabelImage, ConcatenateImages, ) class VideoWriter(LeafSystem): """Publishes RgbdSensor output to a video file. .. pydrake_system:: name: VideoWriter input_ports: - color_image The video will contain recorded images from the color_image input port. The methods AddToBuilder() or ConnectToRgbdSensor() make it easy to record color and/or depth and/or labels all at once. For companion systems, see also ColorizeDepthImage, ColorizeLabelImage, and ConcatenateImages. This class delegates actual video output to one of two video backends, either "PIL" (aka Pillow) or "cv2". PIL generally only supports image formats (e.g., gif, apng, webp) while cv2 also supports movies (e.g., mp4). Warning: Once all images have been published, you must call ``video_writer.Save()`` to finish writing to the video file. Warning: This class will fail at construction time if the specified ``backend`` module cannot be imported. You must ensure that whichever backend you choose is available in your environment. Drake neither bundles nor depends on either one. """ def __init__(self, *, filename, fps=16.0, backend="PIL", fourcc=None): """Constructs a VideoWriter system. In many cases, the AddToBuilder() or ConnectRgbdSensor() methods might be easier to use than this constructor. Args: filename: filename to write, e.g., ``"output.gif"`` or ``"output.mp4"`` fps: the output video's frame rate (in frames per second) backend: which backend to use: "PIL" or "cv2" fourcc: when using the cv2 backend, which encoder to use; good choices are "mp4v" or "avc1"; defaults to "mp4v"; refer to the OpenCV documentation for details. """ LeafSystem.__init__(self) self._filename = filename self._fps = fps self._input = self.DeclareAbstractInputPort( name="color_image", model_value=Value(ImageRgba8U())) # TODO(jwnimmer-tri) Support forced triggers as well (so users can # manually record videos of prescribed motion). self.DeclarePeriodicPublishEvent(1.0 / fps, 0.0, self._publish) self._cv2_writer = None self._pil_images = None if backend == "PIL": from PIL import Image self._backend = Image self._write = self._write_pil elif backend == "cv2": import cv2 self._backend = cv2 self._write = self._write_cv2 self._fourcc = fourcc or "mp4v" if len(self._fourcc) != 4: raise ValueError(f"The fourcc={fourcc!r} must be 4 characters") else: raise RuntimeError(f"Invalid backend={backend!r}") @staticmethod def AddToBuilder(*, filename, builder, sensor_pose, fps=16.0, width=320, height=240, fov_y=np.pi/6, near=0.01, far=10.0, kinds=None, backend="PIL", fourcc=None): """Adds a RgbdSensor and VideoWriter system to the given builder, using a world-fixed pose. Returns the VideoWriter system. See also ConnectRgbdSensor() in case you want to attach a VideoWriter to an already existing RgbdSensor (e.g., on attached to a robot). Args: filename: filename to write, e.g., ``"output.gif"`` or ``"output.mp4"`` builder: the DiagramBuilder sensor_pose: the world-fixed position for the video camera fps: the output video's frame rate (in frames per second) width: video camera width (in pixels) height: video camera width (in pixels) fov_y: video camera fov (in radians) near: clipping plane distance (in meters) far: clipping plane distance (in meters) kinds: which image kind(s) to include in the video; valid options are ``"color"``, ``"label"``, and/or ``"depth"`` backend: which backend to use: "PIL" or "cv2". fourcc: when using the cv2 backend, which encoder to use; good choices are "mp4v" or "avc1"; defaults to "mp4v" refer to the OpenCV documentation for details. Warning: Once all images have been published, you must call ``video_writer.Save()`` to finish writing to the video file. """ sensor = VideoWriter._AddRgbdSensor( builder=builder, pose=sensor_pose, width=width, height=height, fov_y=fov_y, near=near, far=far) writer = VideoWriter(filename=filename, fps=fps, backend=backend, fourcc=fourcc) builder.AddSystem(writer) writer.ConnectRgbdSensor(builder=builder, sensor=sensor, kinds=kinds) return writer @staticmethod def _AddRgbdSensor(*, builder, pose, width, height, fov_y, near, far): """Helper function that adds a fixed-pose RgbdSensor to a scene. Returns the sensor system, already added to the builder and connected to the scene graph and configured to use the VTK render engine. """ scene_graph = [x for x in builder.GetSystems() if x.get_name() == "scene_graph"][0] if not scene_graph.HasRenderer("vtk"): scene_graph.AddRenderer("vtk", MakeRenderEngineVtk( RenderEngineVtkParams())) intrinsics = CameraInfo(width, height, fov_y) clip = ClippingRange(near, far) camera = DepthRenderCamera( RenderCameraCore("vtk", intrinsics, clip, RigidTransform()), DepthRange(near, far)) sensor = RgbdSensor(SceneGraph.world_frame_id(), pose, camera) builder.AddSystem(sensor) builder.Connect(scene_graph.GetOutputPort("query"), sensor.GetInputPort("geometry_query")) return sensor def ConnectRgbdSensor(self, *, builder, sensor, kinds=None): """Adds a VideoWriter system to the given builder and connects it to the given RgbdSensor. Returns the VideoWriter system. See also AddToBuilder() in case you want to record video from a world- fixed pose by creating a new sensor. Args: builder: the DiagramBuilder kinds: which image kind(s) to include in the video; valid options are ``"color"``, ``"label"``, and/or ``"depth"``; when set to ``None``, defaults to ``"color"`` only. Warning: Once all images have been published, you must call ``video_writer.Save()`` to finish writing to the video file. """ # Make a list of ImageRgba8U output ports to feed as video input. image_sources = [] for kind in (kinds or ("color",)): if kind == "color": image_sources.append(sensor.GetOutputPort("color_image")) elif kind == "depth": converter = builder.AddSystem(ColorizeDepthImage()) builder.Connect( sensor.GetOutputPort("depth_image_32f"), converter.GetInputPort("depth_image_32f")) image_sources.append(converter.get_output_port()) elif kind == "label": converter = builder.AddSystem(ColorizeLabelImage()) builder.Connect( sensor.GetOutputPort(f"label_image"), converter.get_input_port()) image_sources.append(converter.get_output_port()) else: raise RuntimeError(f"Unknown image kind={kind!r}") num_sources = len(image_sources) if num_sources == 1: image_source = image_sources[0] else: stacker = builder.AddSystem(ConcatenateImages(cols=num_sources)) for i, source in enumerate(image_sources): builder.Connect(source, stacker.get_input_port(row=0, col=i)) image_source = stacker.get_output_port() builder.Connect(image_source, self.get_input_port()) def Save(self): """Flushes all images to the video file and closes the file. Warning: Continuing a simulation after calling Save() will begin to overwrite the prior video with a new one. """ # For PIL. if self._pil_images is not None: images = self._pil_images frame_millis = int(1000.0 / self._fps) images[0].save( self._filename, save_all=True, append_images=images[1:], optimize=True, duration=frame_millis) self._pil_images = None # For cv2. if self._cv2_writer is not None: self._cv2_writer.release() self._cv2_writer = None def _publish(self, context): """The framework event handler that saves one input image.""" color = self._input.Eval(context) # Call the backend-specific function that was set by our constructor. self._write(rgba=color.data) def _write_pil(self, *, rgba): """Saves one input image (when we're configured to use PIL).""" # Grab the `from PIL import Image` that we stored at construction-time. Image = self._backend image = Image.fromarray(copy.copy(rgba), mode="RGBA") if self._pil_images is None: self._pil_images = [image] else: self._pil_images.append(image) def _write_cv2(self, *, rgba): """Saves one input image (when we're configured to use cv2).""" # Grab `import cv2` that we stored at construction-time. cv2 = self._backend # Open the output file upon the first publish event. if self._cv2_writer is None: fourcc = cv2.VideoWriter.fourcc(*self._fourcc) (height, width, _) = rgba.shape self._cv2_writer = cv2.VideoWriter( self._filename, fourcc, self._fps, (width, height)) bgra = cv2.cvtColor(rgba, cv2.COLOR_RGB2BGR) self._cv2_writer.write(bgra)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/_plotting.py
""" Provides some general visualization tools using matplotlib. This is not related to `rendering`. """ import numpy as np import matplotlib as mpl from pydrake.symbolic import Evaluate, Jacobian, Polynomial from pydrake.solvers import MathematicalProgram, Solve def plot_sublevelset_quadratic(ax, A, b=[0, 0], c=0, vertices=51, **kwargs): """ Plots the 2D ellipse representing x'Ax + b'x + c <= 1, e.g. the one sub-level set of a quadratic form. Args: ax: the matplotlib axis to receive the plot A: an 2x2 PSD numpy array. b: broadcastable to a 2x1 array c: scalar vertices: number of sample points along the boundary kwargs: are passed to the matplotlib fill method Returns: the return values from matplotlib's fill command. """ # TODO(russt): Add project_quadratic_form and slice_quadratic_form # methods to drake::math and recommend users call them first to plot # higher-dimensional ellipsoids. assert isinstance(ax, mpl.axes.Axes) A = np.asarray(A) assert A.shape == (2, 2), "A must be 2x2" # Note: this is closely related to # drake::math::DecomposePositiveQuadraticForm, but does not require the # function to be positive for all x. # f = x'Ax + b'x + c # dfdx = x'(A+A') + b' # H = .5*(A+A') # aka, the symmetric part of A (note: x'Hx = x'Ax) # dfdx = 0 => xmin = -inv(A+A')*b = -.5 inv(H)*b H = .5*(A+A.T) xmin = np.linalg.solve(-2*H, np.reshape(b, (2, 1))) fmin = -xmin.T.dot(H).dot(xmin) + c # since b = -2*H*xmin assert fmin <= 1, "The minimum value is > 1; there is no sub-level set " \ "to plot" # To plot the contour at f = (x-xmin)'H(x-xmin) + fmin = 1, # we make a circle of values y, such that: y'y = 1-fmin, th = np.linspace(0, 2*np.pi, vertices) Y = np.sqrt(1-fmin)*np.vstack([np.sin(th), np.cos(th)]) # then choose L'*(x - xmin) = y, where H = LL'. L = np.linalg.cholesky(H) X = np.tile(xmin, vertices) + np.linalg.inv(np.transpose(L)).dot(Y) return ax.fill(X[0, :], X[1, :], **kwargs) def plot_sublevelset_expression(ax, e, vertices=51, **kwargs): """ Plots the 2D sub-level set e(x) <= 1, which must contain the origin. Args: ax: the matplotlib axis to receive the plot e: a symbolic expression in two variables vertices: number of sample points along the boundary kwargs: are passed to the matplotlib fill method Returns: the return values from matplotlib's fill command. """ x = list(e.GetVariables()) assert len(x) == 2, "e must be an expression in two variables" # Handle the special case where e is a degree 2 polynomial. if e.is_polynomial(): p = Polynomial(e) if p.TotalDegree() == 2: env = {a: 0 for a in x} c = e.Evaluate(env) e1 = e.Jacobian(x) b = Evaluate(e1, env) e2 = Jacobian(e1, x) A = 0.5*Evaluate(e2, env) return plot_sublevelset_quadratic(ax, A, b, c, vertices, **kwargs) # Find the level-set in polar coordinates, by sampling theta and # root-finding (on the scalar expression) to find a rplus and rminus. Xplus = np.empty((2, vertices)) Xminus = np.empty((2, vertices)) i = 0 for theta in np.linspace(0, np.pi, vertices): prog = MathematicalProgram() r = prog.NewContinuousVariables(1, "r")[0] env = {x[0]: r*np.cos(theta), x[1]: r*np.sin(theta)} scalar = e.Substitute(env) b = prog.AddBoundingBoxConstraint(0, np.inf, r) prog.AddConstraint(scalar == 1) prog.AddQuadraticCost([1], [0], [r]) prog.SetInitialGuess(r, 0.1) # or anything non-zero. result = Solve(prog) assert result.is_success(), "Failed to find the level set" rplus = result.GetSolution(r) Xplus[0, i] = rplus*np.cos(theta) Xplus[1, i] = rplus*np.sin(theta) b.evaluator().UpdateLowerBound([-np.inf]) b.evaluator().UpdateUpperBound([0]) prog.SetInitialGuess(r, -0.1) # or anything non-zero. result = Solve(prog) assert result.is_success(), "Failed to find the level set" rminus = result.GetSolution(r) Xminus[0, i] = rminus*np.cos(theta) Xminus[1, i] = rminus*np.sin(theta) i = i + 1 return ax.fill(np.hstack((Xplus[0, :], Xminus[0, :])), np.hstack((Xplus[1, :], Xminus[1, :])), **kwargs)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/run_installed_model_visualizer.py.in
#!/usr/bin/env python3 """ Runs Model Visualizer from an install tree. """ from os.path import isdir, join, dirname, realpath import sys def main(): # Ensure that we can import pydrake, accommodating symlinks. prefix_dir = dirname(dirname(realpath(__file__))) assert isdir(join(prefix_dir, "bin")), f"Bad location: {prefix_dir}" site_dir = join(prefix_dir, "@PYTHON_SITE_PACKAGES_RELPATH@") sys.path.insert(0, site_dir) # Execute the imported main. from pydrake.visualization.model_visualizer import _main _main() assert __name__ == "__main__" main()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/_lcm_image_array_viewer.py
import argparse from io import BytesIO import zlib from flask import Flask, Response import numpy as np from PIL import Image from drake import lcmt_image, lcmt_image_array from pydrake.lcm import DrakeLcm from pydrake.systems.sensors import ( ImageDepth16U, ImageDepth32F, ImageLabel16I, ImageRgba8U, ) from pydrake.visualization import ColorizeDepthImage, ColorizeLabelImage class _ImageServer(Flask): """Streams images via the HTTP protocol given an image source. The image source, i.e., `image_generator`, should be a generator function that yields a (mime_type, image_data) pair. The `mime-type` is a str, and the `image_data` is bytes representing the image. """ def __init__(self, *, image_generator): super().__init__("meldis_lcm_image_viewer") self.add_url_rule("/", view_func=self._serve_image) self._image_generator = image_generator def _serve_image(self): return Response( self._response_generator(), mimetype="multipart/x-mixed-replace; boundary=frame", ) def _response_generator(self): for mime_type, image_data in self._image_generator(): yield ( b"--frame\r\nContent-Type: " + mime_type.encode("utf-8") + b"\r\n\r\n" + image_data + b"\r\n" ) class LcmImageArrayViewer: """Displays LCM images to an URL. The program waits for `lcmt_image_array` messages from a particular channel and processes them to image files. It contains a flask server, _ImageServer, that grabs images whenever available and broadcasts them to an URL for visualization. """ _IMAGE_DATA_TYPE = { lcmt_image.CHANNEL_TYPE_UINT8: np.uint8, lcmt_image.CHANNEL_TYPE_INT16: np.int16, lcmt_image.CHANNEL_TYPE_UINT16: np.uint16, lcmt_image.CHANNEL_TYPE_FLOAT32: np.float32, } """The mapping from `lcmt_image` channel_type enum to numpy data type.""" _IMAGE_CHANNEL_NUM = { lcmt_image.PIXEL_FORMAT_RGBA: 4, lcmt_image.PIXEL_FORMAT_DEPTH: 1, lcmt_image.PIXEL_FORMAT_LABEL: 1, } """The mapping from `lcmt_image` pixel_format enum to the number of channels. """ def __init__(self, *, host, port, channel, unit_test=False): # Only the latest message from LCM is kept. self._latest_message = None # Subscribe to the channel. self._lcm = DrakeLcm() self._lcm.Subscribe(channel=channel, handler=self._update_message) # Helpers to convert images to aid visualization. self._colorize_label = ColorizeLabelImage() self._colorize_depth = ColorizeDepthImage() # Instantiate an `_ImageServer` and run it. If `unit_test` is True, the # server will not be launched. if not unit_test: self._image_server = _ImageServer( image_generator=self.image_generator ) self._image_server.run( host=host, port=port, debug=False, threaded=False ) def image_generator(self): mime_type = "image/png" while True: self._lcm.HandleSubscriptions(timeout_millis=1000) if self._latest_message is not None: new_image = self._process_message() self._latest_message = None yield (mime_type, new_image) def _update_message(self, message): self._latest_message = message def _process_message(self): """Processes the latest lcmt_image_array message into a single PNG image. Depth and label images will be colorized to color images for visualization. If the LCM message contains multiple images, they will be concatenated together horizontally. """ image_array = lcmt_image_array.decode(self._latest_message) assert len(image_array.images) > 0 rgba_images = [] for image in image_array.images: w = image.width h = image.height data_type = self._IMAGE_DATA_TYPE[image.channel_type] num_channels = self._IMAGE_CHANNEL_NUM[image.pixel_format] bytes_per_pixel = np.dtype(data_type).itemsize * num_channels assert image.row_stride == w * bytes_per_pixel, image.row_stride if ( image.compression_method == lcmt_image.COMPRESSION_METHOD_NOT_COMPRESSED ): data_bytes = image.data elif ( image.compression_method == lcmt_image.COMPRESSION_METHOD_ZLIB ): # TODO(eric): Consider using `data`s buffer, if possible. # Can decompress() somehow use an existing buffer in Python? data_bytes = zlib.decompress(image.data) else: raise RuntimeError( f"Unsupported compression type:{image.compression_method}" ) np_image_data = np.frombuffer(data_bytes, dtype=data_type) rgba = ImageRgba8U(w, h) if image.pixel_format == lcmt_image.PIXEL_FORMAT_RGBA: rgba.mutable_data[:] = np_image_data.reshape(h, w, 4) elif image.pixel_format == lcmt_image.PIXEL_FORMAT_LABEL: label = ImageLabel16I(w, h) label.mutable_data[:] = np_image_data.reshape(h, w, 1) self._colorize_label.Calc(label, rgba) elif image.pixel_format == lcmt_image.PIXEL_FORMAT_DEPTH: if image.channel_type == lcmt_image.CHANNEL_TYPE_UINT16: depth = ImageDepth16U(w, h) elif image.channel_type == lcmt_image.CHANNEL_TYPE_FLOAT32: depth = ImageDepth32F(w, h) else: raise RuntimeError( f"Unsupported depth pixel format: {image.pixel_format}" ) depth.mutable_data[:] = np_image_data.reshape(h, w, 1) self._colorize_depth.Calc(depth, rgba) rgba_images.append(rgba) # Stack the images horizontally. np_concatenated_image = self._concatenate_images( rgba_images, rows=1, cols=len(rgba_images) ) # Save the image in-memory. pil_image = Image.fromarray(np_concatenated_image) buffer = BytesIO() pil_image.save(buffer, format="png", compress_level=0) return buffer.getbuffer() @staticmethod def _concatenate_images(images, rows, cols): """Helper function to concatenate multiple images. It is assumed that `images` to be a list of systems::sensors::Image with the same size. """ assert len(images) == rows * cols col_images = [] for r in range(rows): row_images = [] for c in range(cols): image = images[r * cols + c] row_images.append(image.data) row_image = np.hstack(row_images) col_images.append(row_image) return np.vstack(col_images) def main(): parser = argparse.ArgumentParser( description=__doc__, ) parser.add_argument( "--host", type=str, required=False, default="127.0.0.1", help="URL to host on, default: 127.0.0.1.", ) parser.add_argument( "--port", type=int, required=False, default=8000, help="Port to host on, default: 8000.", ) parser.add_argument( "--channel", type=str, required=True, help="The LCM channel to subscribe to.", ) args = parser.parse_args() image_array_viewer = LcmImageArrayViewer( host=args.host, port=args.port, channel=args.channel ) if __name__ == "__main__": main()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/visualization_py.cc
#include "drake/bindings/pydrake/visualization/visualization_py.h" namespace drake { namespace pydrake { PYBIND11_MODULE(visualization, m) { PYDRAKE_PREVENT_PYTHON3_MODULE_REIMPORT(m); m.doc() = R"""( Bindings for Visualization. )"""; py::module::import("pydrake.geometry"); py::module::import("pydrake.multibody"); py::module::import("pydrake.systems"); // The order of these calls matters. Some modules rely on prior definitions. internal::DefineVisualizationConfig(m); internal::DefineVisualizationImageSystems(m); internal::DefineVisualizationSliders(m); py::module::import("pydrake.visualization._meldis"); py::module::import("pydrake.visualization._model_visualizer"); ExecuteExtraPythonCode(m, true); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/run_installed_meldis.py.in
#!/usr/bin/env python3 """ Runs Meldis from an install tree. """ from os.path import isdir, join, dirname, realpath import sys def main(): # Ensure that we can import pydrake, accommodating symlinks. prefix_dir = dirname(dirname(realpath(__file__))) assert isdir(join(prefix_dir, "bin")), f"Bad location: {prefix_dir}" site_dir = join(prefix_dir, "@PYTHON_SITE_PACKAGES_RELPATH@") sys.path.insert(0, site_dir) # Execute the imported main. from pydrake.visualization.meldis import _main _main() assert __name__ == "__main__" main()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/_meldis.py
# Remove once we have Python >= 3.10. from __future__ import annotations import copy import hashlib import json import logging import numpy as np from pathlib import Path import re import sys import time from drake import ( lcmt_contact_results_for_viz, lcmt_point_cloud, lcmt_point_cloud_field, lcmt_viewer_draw, lcmt_viewer_geometry_data, lcmt_viewer_link_data, lcmt_viewer_load_robot, ) from pydrake.common import ( configure_logging, ) from pydrake.common.eigen_geometry import ( Quaternion, ) from pydrake.geometry import ( Box, Capsule, Cylinder, Ellipsoid, Mesh, Meshcat, MeshcatParams, Rgba, Sphere, SurfaceTriangle, TriangleSurfaceMesh, ) from pydrake.lcm import ( DrakeLcm, ) from pydrake.math import ( RigidTransform, RotationMatrix, ) from pydrake.multibody.meshcat import ( _HydroelasticContactVisualizer, _HydroelasticContactVisualizerItem, _PointContactVisualizer, _PointContactVisualizerItem, ContactVisualizerParams, ) from pydrake.perception import ( BaseField, Fields, PointCloud, ) _logger = logging.getLogger("drake") _DEFAULT_MESHCAT_PARAMS = MeshcatParams( host="localhost", show_stats_plot=False, ) def _to_pose(position, quaternion): """Given pose parts, parses it into a RigidTransform. """ return RigidTransform(Quaternion(wxyz=quaternion), p=position) class _Slider: """A slider with range [small-positive-value to 1.0].""" def __init__(self, meshcat, name): self._meshcat = meshcat self._name = name self._value = 1.0 self._exists = False def realize(self): """Ensures the slider is created and visible.""" # Avoid a redundant slider crash if the user runs a sending program # twice with the same meldis still running. if not self._exists: self._exists = True self._meshcat.AddSlider(self._name, 0.02, 1.0, 0.02, self._value) def read(self): """Returns a pair of the current value, and a flag that is True if the value has changed since the last read(). Clients *must* call realize() before calling read(). """ assert self._exists, "Call realize() before calling read()" value = self._meshcat.GetSliderValue(self._name) value_changed = (value != self._value) self._value = value return value, value_changed class _GeometryFileHasher: """Calculates a checksum of external file(s) referenced by geometry messages such as lcmt_viewer_load_robot or similar. Each "on_..." method incorporates all of the external files cited by the given argument (of a specific type) into the current hash. Files that are named but cannot be opened are silently skipped. """ def __init__(self): self._paths = [] self._hasher = hashlib.sha256() def value(self): return self._hasher.hexdigest() def _read_file(self, path: Path): """Reads the given file and adds its content to the current hash. Returns the file content (as ``bytes``, not ``str``). Remembers the filename (for unit testing). If the file is missing, silently returns an empty ``bytes``. """ try: with open(path, "rb") as f: content = f.read() self._hasher.update(content) self._paths.append(path) return content except IOError: return b"" def on_viewer_load_robot(self, message: lcmt_viewer_load_robot): assert isinstance(message, lcmt_viewer_load_robot) for link in message.link: for geom in link.geom: self.on_viewer_geometry_data(geom) def on_viewer_geometry_data(self, message: lcmt_viewer_geometry_data): assert isinstance(message, lcmt_viewer_geometry_data) if (message.type == lcmt_viewer_geometry_data.MESH and message.string_data): self.on_mesh(Path(message.string_data)) def on_mesh(self, path: Path): assert isinstance(path, Path) # Hash the file contents, even if we don't know how to interpret it. content = self._read_file(path) if path.suffix.lower() == ".obj": self.on_obj(path, content) elif path.suffix.lower() == ".gltf": self.on_gltf(path, content) else: _logger.warn(f"Unsupported mesh file: '{path}'\n" "Update Meldis's hasher to trigger reloads on this " "kind of file.") def on_obj(self, path: Path, content: bytes): assert isinstance(path, Path) for mtl_names in re.findall(rb"^\s*mtllib\s+(.*?)\s*$", content, re.MULTILINE): for mtl_name in mtl_names.decode("utf-8").split(): self.on_mtl(path.parent / mtl_name) def on_mtl(self, path: Path): assert isinstance(path, Path) content = self._read_file(path) for tex_name in re.findall(rb"^\s*map_.*?\s+(\S+)\s*$", content, re.MULTILINE): self.on_texture(path.parent / tex_name.decode("utf-8")) def on_texture(self, path: Path): assert isinstance(path, Path) self._read_file(path) def on_gltf(self, path: Path, content: bytes): assert isinstance(path, Path) try: document = json.loads(content.decode(encoding="utf-8")) except json.JSONDecodeError: _logger.warn(f"glTF file is not valid JSON: {path}") return # Handle the images for image in document.get("images", []): if not image.get("uri", "").startswith("data:"): self.on_texture(path.parent / image["uri"]) # Handle the .bin files. for buffer in document.get("buffers", []): if not buffer.get("uri", "").startswith("data:"): self._read_file(path.parent / buffer["uri"]) class _ViewerApplet: """Displays lcmt_viewer_load_robot and lcmt_viewer_draw into MeshCat.""" def __init__(self, *, meshcat, path, alpha_slider_name, should_accept_link=None, start_visible=True, initial_alpha_value=1): """Constructs an applet. If should_accept_link is given, only links where `should_accept_link(link.name)` is true will be displayed. (N.B. This predicate only applies to rigid bodies; it does not apply to deformable geometries, which do not have a concept of a "link".) """ self._meshcat = meshcat self._path = path self._load_message = None self._load_message_mesh_checksum = None self._alpha_slider = _Slider(meshcat, f"{alpha_slider_name} α") self._alpha_slider._value = initial_alpha_value if should_accept_link is not None: self._should_accept_link = should_accept_link else: self._should_accept_link = lambda _: True self._applet_name = alpha_slider_name self._start_visible = start_visible self._geom_paths = [] # Initialize ourself with an empty load message. self.on_viewer_load(message=lcmt_viewer_load_robot()) def on_viewer_load(self, message): """Handler for lcmt_viewer_load.""" # Ignore duplicate load messages. This is important for visualization # performance when the user is repeatedly viewing the same simulation # over and over again, since reloading a scene into Meshcat has high # latency. hasher = _GeometryFileHasher() hasher.on_viewer_load_robot(message) mesh_checksum = hasher.value() if self._load_message is not None: if (message.num_links == self._load_message.num_links and message.encode() == self._load_message.encode() and mesh_checksum == self._load_message_mesh_checksum): _logger.info("Ignoring duplicate load message for " f"{self._applet_name}.") return # The semantics of a load message is to reset the entire scene. self._meshcat.Delete(path=self._path) self._waiting_for_first_draw_message = True self._load_message = message self._load_message_mesh_checksum = mesh_checksum self.set_alpha(self._alpha_slider._value, on_load=True) def _build_links(self): # Make all of our (ViewerApplet's) geometry invisible so that the # lcmt_viewer_load geometry does not clutter up the scene until we # are given its poses in a lcmt_viewer_draw message. self._set_visible(False) message = self._load_message # Add the links and their geometries. self._geom_paths = [] for link in message.link: if not self._should_accept_link(link.name): continue robot_num = link.robot_num link_name = link.name.replace("::", "/") link_path = f"{self._path}/{robot_num}/{link_name}" for j, geom in enumerate(link.geom): geom_path = f"{link_path}/{j}" shape, rgba, pose = self._convert_geom(geom) if shape is None: continue self._geom_paths.append(geom_path) set_object_kwargs = dict(path=geom_path, rgba=rgba) if isinstance(shape, TriangleSurfaceMesh): set_object_kwargs.update(mesh=shape) else: set_object_kwargs.update(shape=shape) self._meshcat.SetObject(**set_object_kwargs) self._meshcat.SetTransform(path=geom_path, X_ParentPath=pose) def on_viewer_draw(self, message): """Handler for lcmt_viewer_draw.""" for i in range(message.num_links): if not self._should_accept_link(message.link_name[i]): continue link_name = message.link_name[i].replace("::", "/") robot_num = message.robot_num[i] link_path = f"{self._path}/{robot_num}/{link_name}" pose = _to_pose(message.position[i], message.quaternion[i]) self._meshcat.SetTransform(path=link_path, X_ParentPath=pose) if self._waiting_for_first_draw_message: self._waiting_for_first_draw_message = False self._build_links() self._alpha_slider.realize() if self._start_visible: self._set_visible(True) self.on_poll(force=True) def set_alpha(self, value, on_load: bool): """Applies the given alpha `value` to the visualized geometries.""" if on_load: # When we're loading the geometries, we have to address each # geometry individually because they may not be loaded yet in the # browser. for path in self._geom_paths: self._meshcat.SetProperty(path, "modulated_opacity", value) else: # When things are truly loaded and we're reacting to changes in # the slider value, we can simply set the root and let meshcat.js # percolate the change through the tree. self._meshcat.SetProperty(self._path, "modulated_opacity", value) def on_poll(self, force=False): if self._waiting_for_first_draw_message: return value, value_changed = self._alpha_slider.read() if force or value_changed: self.set_alpha(value, on_load=False) def on_viewer_draw_deformable(self, message): """Handler for lcmt_viewer_link_data.""" link_name = message.name robot = message.robot_num link_path = f"{self._path}/{robot}/{link_name}" for i, geom in enumerate(message.geom): geom_name = geom.string_data geom_path = f"{link_path}/{geom_name}" vertices, faces, rgba, pose = self._convert_deformable_geom(geom) self._meshcat.SetTriangleMesh( path=geom_path, vertices=vertices, faces=faces, rgba=rgba) self._meshcat.SetTransform(path=link_path, X_ParentPath=pose) if self._waiting_for_first_draw_message: self._waiting_for_first_draw_message = False self._set_visible(True) def _set_visible(self, value): self._meshcat.SetProperty(self._path, property="visible", value=value) def _convert_deformable_geom(self, geom): """Given an lcmt_viewer_geometry_data, parses it into a tuple of (vertices, faces, Rgba, RigidTransform) if the geometry type is a MESH. """ assert geom.type == lcmt_viewer_geometry_data.MESH num_verts = int(geom.float_data[0]) num_faces = int(geom.float_data[1]) # The first two floats encode the number of vertices and number of # triangles. v_start_index = 2 f_start_index = v_start_index + 3 * num_verts vertices = np.array(geom.float_data[v_start_index:f_start_index]) faces = np.array(geom.float_data[f_start_index:]).astype(int) vertices = np.reshape(vertices, (3, num_verts), order='F') faces = np.reshape(faces, (3, num_faces), order='F') rgba = Rgba(*geom.color) pose = _to_pose(geom.position, geom.quaternion) return (vertices, faces, rgba, pose) def _convert_geom(self, geom): """Given an lcmt_viewer_geometry_data, parses it into a tuple of (Shape, Rgba, RigidTransform) or (TriangleSurfaceMesh, Rgbd, RigidTransform). """ shape = None if geom.type == lcmt_viewer_geometry_data.BOX: (width, depth, height) = geom.float_data shape = Box(width=width, depth=depth, height=height) elif geom.type == lcmt_viewer_geometry_data.CAPSULE: (radius, length) = geom.float_data shape = Capsule(radius=radius, length=length) elif geom.type == lcmt_viewer_geometry_data.CYLINDER: (radius, length) = geom.float_data shape = Cylinder(radius=radius, length=length) elif geom.type == lcmt_viewer_geometry_data.ELLIPSOID: (a, b, c) = geom.float_data shape = Ellipsoid(a=a, b=b, c=c) elif geom.type == lcmt_viewer_geometry_data.MESH and geom.string_data: # A mesh to be loaded from a file. (scale_x, scale_y, scale_z) = geom.float_data filename = geom.string_data assert scale_x == scale_y and scale_y == scale_z shape = Mesh(filename=filename, scale=scale_x) elif geom.type == lcmt_viewer_geometry_data.MESH: assert not geom.string_data shape = self._make_triangle_mesh(geom.float_data) elif geom.type == lcmt_viewer_geometry_data.SPHERE: (radius,) = geom.float_data shape = Sphere(radius=radius) else: _logger.warning(f"Unknown geom.type of {geom.type}") return (None, None, None) rgba = Rgba(*geom.color) pose = _to_pose(geom.position, geom.quaternion) return (shape, rgba, pose) @staticmethod def _make_triangle_mesh(data): """Returns a TriangleSurfaceMesh parsed from the given float data. The data is formatted like this: V | T | v0 | v1 | ... vN | t0 | t1 | ... | tM where V: The number of vertices. T: The number of triangles. N: 3V, the number of floating point values for the V vertices. M: 3T, the number of vertex indices for the T triangles. """ V = int(data[0] if len(data) > 0 else -1) T = int(data[1] if len(data) > 1 else -1) if len(data) != 2 + 3*V + 3*T: _logger.warning("Ignoring mesh with malformed data length.") return None start = 2 vertices = [] for i in range(start, start + 3*V, 3): vertex = np.array(data[i:i+3]) vertices.append(vertex) start = 2 + 3*V triangles = [] for i in range(start, start + 3*T, 3): indices = [int(j) for j in data[i:i+3]] triangle = SurfaceTriangle(*indices) triangles.append(triangle) return TriangleSurfaceMesh(triangles=triangles, vertices=vertices) class _ContactApplet: """Displays lcmt_contact_results_for_viz into Meshcat.""" def __init__(self, *, meshcat): # By default, don't show any contact illustrations. meshcat.SetProperty("/CONTACT_RESULTS", "visible", True) # Add point visualization. params = ContactVisualizerParams() params.prefix = "/CONTACT_RESULTS/point" self._point_helper = _PointContactVisualizer(meshcat, params) # Add hydroelastic visualization. params = ContactVisualizerParams() params.prefix = "/CONTACT_RESULTS/hydroelastic" self._hydro_helper = _HydroelasticContactVisualizer(meshcat, params) # Converts poly_data from a hydro lcm message to numpy array. def convert_faces(self, poly_data): poly_index = 0 faces = [] while poly_index < len(poly_data): poly_i_num_vertices = poly_data[poly_index] vertex_0_index = poly_index + 1 vertex_0_global_index = poly_data[vertex_0_index] for i in range(1, poly_i_num_vertices - 1): vertex_1_global_index = poly_data[vertex_0_index + i] vertex_2_global_index = poly_data[vertex_0_index + i + 1] faces.append([vertex_0_global_index, vertex_1_global_index, vertex_2_global_index]) poly_index += poly_i_num_vertices + 1 return np.array(faces).transpose() # Converts verts from hydro lcm message to numpy array def convert_verts(self, p_WV): verts = np.empty((3, len(p_WV))) for i in range(len(p_WV)): verts[0, i] = p_WV[i].x verts[1, i] = p_WV[i].y verts[2, i] = p_WV[i].z return verts def get_full_names(self, item): name1 = [] name2 = [] # Use model instance name if necessary. if not item.body1_unique: name1.append(item.model1_name) if not item.body2_unique: name2.append(item.model2_name) name1.append(item.body1_name) name2.append(item.body2_name) # Use geometry name if necessary. if item.collision_count1 > 1: name1.append(item.geometry1_name) if item.collision_count2 > 1: name2.append(item.geometry2_name) return (".".join(name1), ".".join(name2)) def on_contact_results(self, message): """Handler for lcmt_contact_results_for_viz. Note that only point hydroelastic contact force and moment vectors are shown; contact surface and pressure are not shown. """ # Handle point contact pairs viz_items = [] for lcm_item in message.point_pair_contact_info: viz_items.append(_PointContactVisualizerItem( body_A=lcm_item.body1_name, body_B=lcm_item.body2_name, contact_force=lcm_item.contact_force, contact_point=lcm_item.contact_point)) self._point_helper.Update(0, viz_items) # Handle hydroelastic contact pairs viz_items = [] for lcm_item in message.hydroelastic_contacts: (name1, name2) = self.get_full_names(lcm_item) viz_items.append(_HydroelasticContactVisualizerItem( body_A=name1, body_B=name2, centroid_W=lcm_item.centroid_W, force_C_W=lcm_item.force_C_W, moment_C_W=lcm_item.moment_C_W, p_WV=self.convert_verts(lcm_item.p_WV), faces=self.convert_faces(lcm_item.poly_data), pressure=lcm_item.pressure)) self._hydro_helper.Update(0, viz_items) class _PointCloudApplet: """Displays lcmt_point_cloud into MeshCat.""" _POINT_CLOUD_FIELDS = ( # (name, byte_offset, datatype, count) ("x", 0, lcmt_point_cloud_field.FLOAT32, 1), ("y", 4, lcmt_point_cloud_field.FLOAT32, 1), ("z", 8, lcmt_point_cloud_field.FLOAT32, 1), ("rgb", 12, lcmt_point_cloud_field.UINT32, 1), ("normal_x", 16, lcmt_point_cloud_field.FLOAT32, 1), ("normal_y", 20, lcmt_point_cloud_field.FLOAT32, 1), ("normal_z", 24, lcmt_point_cloud_field.FLOAT32, 1), ) """The supported fields and their data types of a point cloud. An XYZ, XYZRGB, and XYZRGBNormal cloud will have the first three, first four, and all the fields in this particular order. """ def __init__(self, *, meshcat): self._meshcat = meshcat self._already_warned_channel_names = set() def _validate_and_get_fields(self, message): """Checks the point cloud LCM message and returns the corresponding `Fields` for the PointCloud object. Either XYZ, XYZRGB, or XYZRGBNormal cloud with the exact data type is supported. """ if message.flags != lcmt_point_cloud.IS_STRICTLY_FINITE: return None if message.num_fields not in (3, 4, 7): return None for i in range(message.num_fields): (name, byte_offset, datatype, count) = self._POINT_CLOUD_FIELDS[i] if ( message.fields[i].name != name or message.fields[i].byte_offset != byte_offset or message.fields[i].datatype != datatype or message.fields[i].count != count ): return None if message.num_fields == 3: return Fields(BaseField.kXYZs) elif message.num_fields == 4: return Fields(BaseField.kXYZs | BaseField.kRGBs) else: return Fields( BaseField.kXYZs | BaseField.kRGBs | BaseField.kNormals ) def _channel_to_meshcat_path(self, channel): assert channel.startswith("DRAKE_POINT_CLOUD") if channel == "DRAKE_POINT_CLOUD": return "/POINT_CLOUD/default" else: # E.g., `DRAKE_POINT_CLOUD_FOO` => `/POINT_CLOUD/FOO`. suffix = channel[len("DRAKE_POINT_CLOUD_"):] return f"/POINT_CLOUD/{suffix}" def on_point_cloud(self, channel, message): """Handler for lcmt_point_cloud. Validates and converts the lcmt_point_cloud message to a PointCloud object for display. """ cloud_fields = self._validate_and_get_fields(message) if cloud_fields is None: # Throttle warning messages to one per channel. if channel not in self._already_warned_channel_names: self._already_warned_channel_names.add(channel) _logger.warn(f"Unsupported point cloud data from {channel}.") return # Transform the raw data into an N x num_fields array. raw_data = np.frombuffer(message.data, dtype=np.float32).reshape( -1, message.num_fields ) num_points = raw_data.shape[0] cloud = PointCloud(num_points, cloud_fields) xyzs = raw_data[:, 0:3] cloud.mutable_xyzs()[:] = xyzs.transpose() if message.num_fields > 3: rgbs_with_padding = ( raw_data[:, 3].astype(np.float32).view(np.uint8).reshape(-1, 4) ) rgbs = rgbs_with_padding[:, 0:3] cloud.mutable_rgbs()[:] = rgbs.transpose() if message.num_fields > 4: normals = raw_data[:, 4:] cloud.mutable_normals()[:] = normals.transpose() self._meshcat.SetObject( path=self._channel_to_meshcat_path(channel), cloud=cloud, point_size=0.01 ) class _DrawFrameApplet: """Applet to visualize triads in meshcat""" def __init__(self, *, meshcat): """Constructs an applet.""" self._meshcat = meshcat # previously published link names self._channel_link_map = {} def _channel_to_meshcat_path(self, channel): assert channel.startswith("DRAKE_DRAW_FRAMES") if channel == "DRAKE_DRAW_FRAMES": return "/DRAKE_DRAW_FRAMES/default" else: # E.g., `DRAKE_DRAW_FRAMES_FOO` => `/DRAKE_DRAW_FRAMES/FOO`. suffix = channel[len("DRAKE_DRAW_FRAMES_"):] return f"/DRAKE_DRAW_FRAMES/{suffix}" def _add_meshcat_triad(self, path, X_PT): length = 0.25 radius = 0.01 opacity = 1.0 self._meshcat.SetTransform(path, X_PT) # x-axis X_TG = RigidTransform( RotationMatrix.MakeYRotation(np.pi / 2), [length / 2.0, 0, 0] ) self._meshcat.SetTransform(path + "/x-axis", X_TG) self._meshcat.SetObject( path + "/x-axis", Cylinder(radius, length), Rgba(1, 0, 0, opacity) ) # y-axis X_TG = RigidTransform( RotationMatrix.MakeXRotation(np.pi / 2), [0, length / 2.0, 0] ) self._meshcat.SetTransform(path + "/y-axis", X_TG) self._meshcat.SetObject( path + "/y-axis", Cylinder(radius, length), Rgba(0, 1, 0, opacity) ) # z-axis X_TG = RigidTransform([0, 0, length / 2.0]) self._meshcat.SetTransform(path + "/z-axis", X_TG) self._meshcat.SetObject( path + "/z-axis", Cylinder(radius, length), Rgba(0, 0, 1, opacity) ) def on_frame_update(self, channel, message): """Handler to update triads in meshcat. It updates poses sent using the lcmt_viewer_draw message.""" channel_path = self._channel_to_meshcat_path(channel) # delete old frames if the link names have changed link_names = set(message.link_name) if self._channel_link_map.get(channel) != link_names: self._meshcat.Delete(path=channel_path) self._channel_link_map[channel] = link_names for i in range(message.num_links): link_name = message.link_name[i].replace("::", "/") link_path = f"{channel_path}/{link_name}" self._add_meshcat_triad(path=link_path, X_PT=_to_pose(message.position[i], message.quaternion[i])) class Meldis: """ MeshCat LCM Display Server (MeLDiS) Offers a MeshCat visualization server that listens for and draws Drake's legacy LCM visualization messages. If the meshcat_host parameter is not supplied, 'localhost' will be used by default. Refer to the pydrake.visualization.meldis module docs for details. """ def __init__(self, *, meshcat_host: str | None = None, meshcat_port: int | None = None, meshcat_params: MeshcatParams | None = None, environment_map: Path | None = None): """Constructs a new Meldis instance. The meshcat_host (when given) takes precedence over meshcat_params.host. The meshcat_post (when given) takes precedence over meshcat_params.port. """ # Bookkeeping for update throttling. self._last_update_time = time.time() # Bookkeeping for subscriptions, keyed by LCM channel name. self._message_types = {} self._message_handlers = {} self._message_pending_data = {} self._poll_handlers = [] self._lcm = DrakeLcm() lcm_url = self._lcm.get_lcm_url() _logger.info(f"Meldis is listening for LCM messages at {lcm_url}") # Create our meshcat object, merging all of the params goop into one. if meshcat_params is None: meshcat_params = _DEFAULT_MESHCAT_PARAMS params = copy.deepcopy(meshcat_params) if meshcat_host is not None: params.host = meshcat_host if meshcat_port is not None: params.port = meshcat_port self.meshcat = Meshcat(params=params) if environment_map is not None: self.meshcat.SetEnvironmentMap(environment_map) def is_inertia_link(link_name): return "::InertiaVisualizer::" in link_name def is_not_inertia_link(link_name): return not is_inertia_link(link_name) default_viewer = _ViewerApplet(meshcat=self.meshcat, path="/DRAKE_VIEWER", alpha_slider_name="Viewer", should_accept_link=is_not_inertia_link) self._subscribe(channel="DRAKE_VIEWER_LOAD_ROBOT", message_type=lcmt_viewer_load_robot, handler=default_viewer.on_viewer_load) self._subscribe(channel="DRAKE_VIEWER_DRAW", message_type=lcmt_viewer_draw, handler=default_viewer.on_viewer_draw) self._subscribe(channel="DRAKE_VIEWER_DEFORMABLE", message_type=lcmt_viewer_link_data, handler=default_viewer.on_viewer_draw_deformable) self._poll(handler=default_viewer.on_poll) inertia_viewer = _ViewerApplet(meshcat=self.meshcat, path="/Inertia Visualizer", alpha_slider_name="Inertia", should_accept_link=is_inertia_link, start_visible=False) inertia_viewer._alpha_slider._value = 0.5 self._subscribe(channel="DRAKE_VIEWER_LOAD_ROBOT", message_type=lcmt_viewer_load_robot, handler=inertia_viewer.on_viewer_load) self._subscribe(channel="DRAKE_VIEWER_DRAW", message_type=lcmt_viewer_draw, handler=inertia_viewer.on_viewer_draw) self._poll(handler=inertia_viewer.on_poll) illustration_viewer = _ViewerApplet(meshcat=self.meshcat, path="/Visual Geometry", alpha_slider_name="Visual") self._subscribe(channel="DRAKE_VIEWER_LOAD_ROBOT_ILLUSTRATION", message_type=lcmt_viewer_load_robot, handler=illustration_viewer.on_viewer_load) self._subscribe(channel="DRAKE_VIEWER_DRAW_ILLUSTRATION", message_type=lcmt_viewer_draw, handler=illustration_viewer.on_viewer_draw) self._subscribe(channel="DRAKE_VIEWER_DEFORMABLE_ILLUSTRATION", message_type=lcmt_viewer_link_data, handler=default_viewer.on_viewer_draw_deformable) self._poll(handler=illustration_viewer.on_poll) proximity_viewer = _ViewerApplet(meshcat=self.meshcat, path="/Collision Geometry", alpha_slider_name="Collision", start_visible=False, initial_alpha_value=0.5) self._subscribe(channel="DRAKE_VIEWER_LOAD_ROBOT_PROXIMITY", message_type=lcmt_viewer_load_robot, handler=proximity_viewer.on_viewer_load) self._subscribe(channel="DRAKE_VIEWER_DRAW_PROXIMITY", message_type=lcmt_viewer_draw, handler=proximity_viewer.on_viewer_draw) self._subscribe(channel="DRAKE_VIEWER_DEFORMABLE_PROXIMITY", message_type=lcmt_viewer_link_data, handler=default_viewer.on_viewer_draw_deformable) self._poll(handler=proximity_viewer.on_poll) contact = _ContactApplet(meshcat=self.meshcat) self._subscribe(channel="CONTACT_RESULTS", message_type=lcmt_contact_results_for_viz, handler=contact.on_contact_results) # Subscribe to all the point-cloud-related channels. point_cloud = _PointCloudApplet(meshcat=self.meshcat) self._subscribe_multichannel(regex="DRAKE_POINT_CLOUD.*", message_type=lcmt_point_cloud, handler=point_cloud.on_point_cloud) # Subscribe to all the frame display channels. draw_frame = _DrawFrameApplet(meshcat=self.meshcat) self._subscribe_multichannel(regex="DRAKE_DRAW_FRAMES.*", message_type=lcmt_viewer_draw, handler=draw_frame.on_frame_update) # Bookkeeping for automatic shutdown. self._last_poll = None self._last_active = None def _subscribe(self, channel, message_type, handler): """Subscribes the handler to the given channel, using message_type to pass in a decoded message object (not the raw bytes). The handler will only be called at some maximum frequency. Messages on the same channel that arrive too quickly will be discarded. """ # Record this channel's type and handler. assert self._message_types.get(channel, message_type) == message_type self._message_types[channel] = message_type # A wrapper to discard `channel` information as it's not used in the # actual handler. def _multi_handler(*, channel, message): handler(message) self._message_handlers.setdefault(channel, []).append(_multi_handler) # Subscribe using an internal function that implements "last one wins". # It's important to service the LCM queue as frequently as possible: # https://github.com/RobotLocomotion/drake/issues/15234 # https://github.com/lcm-proj/lcm/issues/345 # However, if the sender is transmitting visualization messages at # a high rate (e.g., if a sim is running much faster than realtime), # then we should only pass some of them along to MeshCat to avoid # flooding it. The handler merely records the message data; we'll # pass it along to MeshCat using our `self._should_update()` timer. def _on_message(data): self._message_pending_data[channel] = data self._lcm.Subscribe(channel=channel, handler=_on_message) def _subscribe_multichannel(self, regex, message_type, handler): """Subscribes the handler to a group of channels filtered by regex. How this function handles messages is the same as _subscribe() except that the channel name is only known when invoking the callback. """ def _on_message(channel, data): if channel not in self._message_types: self._message_types[channel] = message_type self._message_handlers.setdefault(channel, []).append(handler) self._message_pending_data[channel] = data self._lcm.SubscribeMultichannel(regex=regex, handler=_on_message) def _poll(self, handler): self._poll_handlers.append(handler) def _invoke_poll(self): for function in self._poll_handlers: function() def _invoke_subscriptions(self): """Posts any unhandled messages to their handlers and clears the collection of unhandled messages. """ for channel, data in self._message_pending_data.items(): message = self._message_types[channel].decode(data) for function in self._message_handlers[channel]: function(channel=channel, message=message) self._message_pending_data.clear() def serve_forever(self, *, idle_timeout=None): """Runs indefinitely, forwarding LCM => MeshCat messages. If provided, the optional idle_timeout must be strictly positive and this loop will sys.exit after that many seconds without any websocket connections. """ while True: self._lcm.HandleSubscriptions(timeout_millis=1000) if not self._should_update(): continue self._invoke_subscriptions() self._invoke_poll() self.meshcat.Flush() self._check_for_shutdown(idle_timeout=idle_timeout) def _should_update(self): """Posts LCM-driven updates to MeshCat no faster than 40 Hz.""" now = time.time() update_period = 0.025 # 40 Hz remaining = update_period - (now - self._last_update_time) if remaining > 0.0: return False else: self._last_update_time = now return True def _check_for_shutdown(self, *, idle_timeout): # Allow the user to opt-out of the timeout feature. if idle_timeout is None: return assert idle_timeout > 0.0 # One-time initialization. now = time.time() if self._last_active is None: self._last_active = now return # Only check once every 5 seconds. if (self._last_poll is not None) and (now < self._last_poll + 5.0): return self._last_poll = now # Check to see if any browser client(s) are connected. if self.meshcat.GetNumActiveConnections() > 0: self._last_active = now return # In case we are idle for too long, exit automatically. if now > self._last_active + idle_timeout: _logger.info("Meldis is exiting now; no browser was connected for" f" >{idle_timeout} seconds") sys.exit(1)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/visualization_py_config.cc
#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/visualization/visualization_py.h" #include "drake/visualization/visualization_config.h" #include "drake/visualization/visualization_config_functions.h" namespace drake { namespace pydrake { namespace internal { void DefineVisualizationConfig(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::visualization; constexpr auto& doc = pydrake_doc.drake.visualization; { using Class = VisualizationConfig; constexpr auto& cls_doc = doc.VisualizationConfig; py::class_<Class> cls(m, "VisualizationConfig", cls_doc.doc); cls.def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } m // BR .def("ApplyVisualizationConfig", &ApplyVisualizationConfig, py::arg("config"), py::arg("builder"), py::arg("lcm_buses") = nullptr, py::arg("plant") = nullptr, py::arg("scene_graph") = nullptr, py::arg("meshcat") = nullptr, py::arg("lcm") = nullptr, doc.ApplyVisualizationConfig.doc) .def("AddDefaultVisualization", &AddDefaultVisualization, py::arg("builder"), py::arg("meshcat") = nullptr, doc.AddDefaultVisualization.doc); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/_visualization_extra.py
from ._meldis import ( Meldis, ) from ._model_visualizer import ( AddFrameTriadIllustration, ModelVisualizer, ) from ._plotting import ( plot_sublevelset_expression, plot_sublevelset_quadratic, ) from ._video import ( VideoWriter, ) __all__ = [x for x in globals() if not x.startswith("_")]
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/_triad.py
import numpy as np from pydrake.common.eigen_geometry import AngleAxis from pydrake.geometry import ( Cylinder, FrameId, GeometryInstance, MakePhongIllustrationProperties, SceneGraph, ) from pydrake.math import RigidTransform from pydrake.multibody.plant import MultibodyPlant from pydrake.multibody.tree import ( Frame, FrameIndex, RigidBody, ) def AddFrameTriadIllustration( *, scene_graph: SceneGraph, body: RigidBody = None, frame: Frame = None, frame_index: FrameIndex = None, frame_id: FrameId = None, plant: MultibodyPlant = None, name: str = None, length: float = 0.3, radius: float = 0.005, opacity: float = 0.9, X_FT: RigidTransform = None, ): """ Adds illustration geometry representing the given frame using an RGB triad, with the x-axis drawn in red, the y-axis in green and the z-axis in blue. The given frame can be either a geometry FrameId, a multibody RigidBody, a multibody FrameIndex or a multibody Frame. Note: exactly one of body=, frame=, frame_index= or frame_id= must be provided. Note: body frames and frames fixed to bodies are colored differently (body frames are brighter). Args: scene_graph: the SceneGraph where geometry will be added. body: when provided, illustrates the frame of the given body. frame: when provided, illustrates the frame from a plant. frame_index: when provided, illustrates the indexed frame from a plant. `plant` must not be None. frame_id: when provided, illustrates the given geometry.FrameId registered with the given plant and scene_graph. plant: MultibodyPlant associated with the given frame_id; required if frame_index= or frame_id= is being used. If body= or frame= is supplied, they must belong to this plant. name: the added geometries will have names "_frames::{name}::x-axis", etc. If None, the name is inferred from the indicated frame. length: the length of each axis in meters. radius: the radius of each axis in meters. opacity: the opacity each axis, between 0.0 and 1.0. X_FT: optional rigid transform relating frame T (the triad geometry) and frame F (the given body=, frame=, or frame_id= frame); when None, X_FT is the identity transform and therefore the triad will depict F. Returns: The newly-added geometry ids for (x, y, z) respectively. """ if sum([body is not None, frame is not None, frame_index is not None, frame_id is not None]) != 1: raise ValueError("Must provide exactly one of body=, frame=, " "frame_index=, or frame_id=") if X_FT is None: X_FT = RigidTransform() resolved_plant_arg = "body=" if frame_index is not None: if plant is None: raise ValueError( "When using frame_index=, the plant cannot be None.") frame = plant.get_frame(frame_index) if frame is not None: body = frame.body() X_FT = frame.GetFixedPoseInBodyFrame() @ X_FT resolved_plant_arg = ("frame=" if frame_index is None else "frame_index=") if body is not None: if plant is not None: if plant is not body.GetParentPlant(): raise ValueError( f"Mismatched {resolved_plant_arg} and plant=; remove the " f"plant= arg") else: plant = body.GetParentPlant() frame_id = plant.GetBodyFrameIdOrThrow(body.index()) if frame is None: assert frame_id is not None frame = plant.GetBodyFromFrameId(frame_id).body_frame() if name is None: name = f"{frame.name()}({int(frame.model_instance())})" brightness = 1 if frame.is_body_frame() else 0.5 source_id = plant.get_source_id() eye = np.eye(3) result = [] for i, char in enumerate(("x", "y", "z")): geom_name = f"_frames::{name}::{char}-axis" # p_TG centers the cylinder halfway along the i'th axis. p_TG = 0.5 * length * eye[i] # R_TG rotates the canonical cylinder (aligned with +z) to align with # the i'th axis instead. When i == 2, it spins the cylinder around the # z axis, but this is effectively a no-op. R_TG = AngleAxis(angle=np.pi/2, axis=eye[1-i]) X_FG = X_FT @ RigidTransform(R_TG, p_TG) geom = GeometryInstance(X_FG, Cylinder(radius, length), geom_name) phong = MakePhongIllustrationProperties(np.append(eye[i] * brightness, [opacity])) geom.set_illustration_properties(phong) geometry_id = scene_graph.RegisterGeometry(source_id, frame_id, geom) result.append(geometry_id) return tuple(result)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/meldis.py
""" MeshCat LCM Display Server (MeLDiS) A standalone program that can display Drake visualizations in MeshCat by listening for LCM messages that are broadcast by the simulation. From a Drake source build, run this as:: bazel run //tools:meldis & From a Drake binary release (including pip releases), run this as:: python3 -m pydrake.visualization.meldis For binary releases (except for pip) there is also a shortcut available as:: /opt/drake/bin/meldis In many cases, passing ``-w`` (i.e., ``--open-window``) to the program will be convenient:: bazel run //tools:meldis -- -w & """ import argparse import os import sys import webbrowser from pydrake.common import configure_logging as _configure_logging from pydrake.common.yaml import yaml_load_typed as _yaml_load_typed from pydrake.visualization._meldis import Meldis as _Meldis from pydrake.visualization._meldis import _DEFAULT_MESHCAT_PARAMS def _available_browsers(): """Returns the list of known webbrowser controller names. There does not appear to be a public API for this, so we best-effort call a private one. """ try: webbrowser.register_standard_browsers() return sorted(webbrowser._browsers) except Exception: return [] def _main(args=None): # Make cwd be what the user expected, not the runfiles tree. if "BUILD_WORKING_DIRECTORY" in os.environ: os.chdir(os.environ["BUILD_WORKING_DIRECTORY"]) _configure_logging() parser = argparse.ArgumentParser() parser.add_argument( "--host", action="store", help="The http listen host for MeshCat. If none is given, 'localhost'" " will be used by default. In any case, the result will be printed to" " the console.") parser.add_argument( "-p", "--port", action="store", metavar="NUM", type=int, help="The http listen port for MeshCat. If none is given, a default" " will be chosen and printed to the console.") parser.add_argument( "-t", "--open-tab", dest="browser_new", action="store_const", const=2, default=None, help="Open the MeshCat display in a browser tab.") parser.add_argument( "-w", "--open-window", dest="browser_new", action="store_const", const=1, default=None, help="Open the MeshCat display in a new browser window.") parser.add_argument( "--browser", metavar="NAME", choices=_available_browsers(), help="Open the MeshCat display using the given browser. " "By default, opens as a new window (use --open-tab to override). " "When no --browser is provided, the --open-tab or --open-window flags " "use the $BROWSER environment variable by default. " f"(Available names: %(choices)s)") parser.add_argument( "--idle-timeout", metavar="TIME", type=float, default=15*60, help="When no web browser has been connected for this many seconds," " this program will automatically exit. Set to 0 to run indefinitely.") parser.add_argument( "--meshcat-params", metavar="PATH", help="Filesystem path to a YAML or JSON config for MeshcatParams. " "This can be used to configure Meshcat's initial properties. " "For options that are available as both command line arguments and " "YAML params (e.g., --port), the command line takes precedence.") parser.add_argument( "--environment_map", metavar="PATH", help="Filesystem path to an image to be used as an environment map. " "It must be an image type normally used by your browser (e.g., " ".jpg, .png, etc.). HDR images are not supported yet." ) args = parser.parse_args(args) meshcat_params = None if args.meshcat_params is not None: meshcat_params = _yaml_load_typed( filename=args.meshcat_params, defaults=_DEFAULT_MESHCAT_PARAMS) meldis = _Meldis(meshcat_host=args.host, meshcat_port=args.port, meshcat_params=meshcat_params, environment_map=args.environment_map) if args.browser is not None and args.browser_new is None: args.browser_new = 1 if args.browser_new is not None: url = meldis.meshcat.web_url() controller = webbrowser.get(args.browser) controller.open(url=url, new=args.browser_new) idle_timeout = args.idle_timeout if idle_timeout == 0.0: idle_timeout = None elif idle_timeout < 0.0: parser.error("The --idle_timeout cannot be negative.") try: meldis.serve_forever(idle_timeout=idle_timeout) except KeyboardInterrupt: pass if __name__ == "__main__": _main(args=sys.argv[1:])
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/visualization/visualization_py.h
#pragma once /* This file declares the functions that bind the drake::visualization namespace. These functions form a complete partition of visualization 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 visualization_py_config.cc. */ void DefineVisualizationConfig(py::module m); /* Defines bindings per visualization_py_image_systems.cc. */ void DefineVisualizationImageSystems(py::module m); /* Defines bindings per visualization_py_sliders.cc. */ void DefineVisualizationSliders(py::module m); } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/lcm_image_array_viewer_test.py
from io import BytesIO import unittest import numpy as np from PIL import Image from drake import lcmt_image, lcmt_image_array from pydrake.systems.sensors import ImageRgba8U from pydrake.visualization._lcm_image_array_viewer import LcmImageArrayViewer class TestLcmImageArrayViewer(unittest.TestCase): def _get_rgba_lcmt_image(self): image_message = lcmt_image() image_message.pixel_format = lcmt_image.PIXEL_FORMAT_RGBA image_message.channel_type = lcmt_image.CHANNEL_TYPE_UINT8 image_message.width = 3 image_message.height = 2 image_message.row_stride = 12 image_message.size = 24 image_data = np.ones((2, 3, 4), dtype=np.uint8) image_message.data = image_data.tobytes() return image_message def _get_depth_lcmt_image(self): image_message = lcmt_image() image_message.pixel_format = lcmt_image.PIXEL_FORMAT_DEPTH image_message.channel_type = lcmt_image.CHANNEL_TYPE_FLOAT32 image_message.width = 3 image_message.height = 2 image_message.row_stride = 12 image_message.size = 24 image_data = np.array( [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32 ) image_message.data = image_data.tobytes() return image_message def _get_label_lcmt_image(self): image_message = lcmt_image() image_message.pixel_format = lcmt_image.PIXEL_FORMAT_LABEL image_message.channel_type = lcmt_image.CHANNEL_TYPE_INT16 image_message.width = 3 image_message.height = 2 image_message.row_stride = 6 image_message.size = 12 image_data = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16) image_message.data = image_data.tobytes() return image_message def test_image_processing(self): """Publishes a sample image_array message, checks the dimension of the returned image and the pixel values. """ lcm_image_array_viewer = LcmImageArrayViewer( host="localhost", port=1234, channel="does_not_matter", unit_test=True, ) # Create an lcmt_image_array containing different types of images. array_message = lcmt_image_array() array_message.num_images = 4 array_message.images = [ self._get_rgba_lcmt_image(), self._get_depth_lcmt_image(), self._get_label_lcmt_image(), # Include two images of the same type. self._get_rgba_lcmt_image(), ] lcm = lcm_image_array_viewer._lcm lcm.Publish(channel="does_not_matter", buffer=array_message.encode()) lcm.HandleSubscriptions(timeout_millis=1) # Manually invoke the image processing function and read the buffer # back to an image for testing. image_buffer = lcm_image_array_viewer._process_message() pil_image = Image.open(BytesIO(image_buffer)) # PIL Image returns the size as (width, height). self.assertEqual(pil_image.size, (12, 2)) # Sanity check the pixel values of the images. For RGBA, they should # remain exactly the same. For depth and label, we only check they have # at least six unique values after the colorization (to rule out # failure cases such as all-black pixels). np_image_data = np.array(pil_image) image_width = 3 # RGBAs. np.testing.assert_equal(np_image_data[:, 0:image_width], 1) np.testing.assert_equal(np_image_data[:, -image_width:], 1) # Depth and label. np_depth_data = np_image_data[:, image_width: image_width * 2] np_label_data = np_image_data[:, image_width * 2: image_width * 3] depth_pixel_values = set(np_depth_data.flatten()) label_pixel_values = set(np_label_data.flatten()) self.assertGreaterEqual(len(depth_pixel_values), 6) self.assertGreaterEqual(len(label_pixel_values), 6) def test_concatenate_images(self): """Checks the pixel values and the dimension of the image after the concatenation. """ image_width = 3 image_height = 2 pixel_value_base = 10 # Initialize the images with a distinct value. test_images = [] for index in range(4): image = ImageRgba8U(image_width, image_height) image.mutable_data[:] = pixel_value_base + index test_images.append(image) test_rows_cols = [(1, 4), (4, 1), (2, 2)] for rows, cols in test_rows_cols: result = LcmImageArrayViewer._concatenate_images( test_images, rows, cols ) # The overall image dimension should match. self.assertEqual( result.shape, (image_height * rows, image_width * cols, 4) ) # Each sub-image should remain the same pixel value. for r in range(rows): for c in range(cols): expected_pixel_value = pixel_value_base + r * cols + c sub_image = result[ r * image_height: (r + 1) * image_height, c * image_width: (c + 1) * image_width, ] np.testing.assert_equal(sub_image, expected_pixel_value)
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/visualization_install_tests.py
from os.path import join import sys import unittest import install_test_helper class TestVisualizationInstalled(unittest.TestCase): # TODO(#21023) This test is a bit too tricky in CI. @unittest.skipIf(sys.platform == "darwin", "Skipped for tricky macOS CI") def test_meldis_help(self): """Ensures we can call `./bin/meldis --help` from install.""" # Get install directory. install_dir = install_test_helper.get_install_dir() # N.B. Do not update PYTHONPATH, as the script should handle that # itself. bin_path = join(install_dir, "bin", "meldis") text = install_test_helper.check_output([bin_path, "--help"]) self.assertIn("usage: meldis ", text) # TODO(#21023) This test is a bit too tricky in CI. @unittest.skipIf(sys.platform == "darwin", "Skipped for tricky macOS CI") def test_model_visualizer_help(self): """Ensures we can call `./bin/model_visualizer --help` from install.""" # Get install directory. install_dir = install_test_helper.get_install_dir() # N.B. Do not update PYTHONPATH, as the script should handle that # itself. bin_path = join(install_dir, "bin", "model_visualizer") text = install_test_helper.check_output([bin_path, "--help"]) self.assertIn("usage: model_visualizer ", text) # TODO(#21023) This test is a bit too tricky in CI. @unittest.skipIf(sys.platform == "darwin", "Skipped for tricky macOS CI") def test_drake_models_meshes(self): """Ensures that the package://drake_models/... can be found by testing a model that uses a meshfile from that location. """ install_dir = install_test_helper.get_install_dir() install_test_helper.check_call([ join(install_dir, "bin", "model_visualizer"), "--loop_once", "package://drake_models/" "ycb/meshes/004_sugar_box_textured.obj" ]) if __name__ == '__main__': unittest.main()
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/model_visualizer_test.py
import copy import inspect import os import subprocess import textwrap import time import unittest from pydrake.common import FindResourceOrThrow from pydrake.geometry import Meshcat from pydrake.multibody.parsing import PackageMap import pydrake.visualization as mut import pydrake.visualization._model_visualizer as mut_private class TestModelVisualizerSubprocess(unittest.TestCase): """ Tests the model_visualizer script as a subprocess. This also tests the supplied main() method. """ def setUp(self): self.dut = FindResourceOrThrow( "drake/bindings/pydrake/visualization/model_visualizer") def model_file(self, *, model_url): """Get a model file from a URL.""" return PackageMap().ResolveUrl(model_url) def test_model_visualizer(self): """Test that model_visualizer doesn't crash.""" model_urls = [ # Simple SDFormat file. "package://drake/multibody/benchmarks/acrobot/acrobot.sdf", # Simple URDF file. "package://drake/multibody/benchmarks/acrobot/acrobot.urdf", # Nested SDFormat file. "package://drake/manipulation/util/test/simple_nested_model.sdf", # SDFormat world file with multiple models. "package://drake/manipulation/util/test/" + "simple_world_with_two_models.sdf", ] for model_url in model_urls: print(model_url) filename = self.model_file(model_url=model_url) subprocess.check_call([self.dut, filename, "--loop_once"]) def test_package_url(self): """Test that a package URL works.""" subprocess.check_call([ self.dut, "package://drake/multibody/benchmarks/acrobot/acrobot.sdf", "--loop_once"]) def test_pyplot(self): """Test that pyplot doesn't crash.""" model_url = ("package://drake_models/iiwa_description/sdf/" + "iiwa14_no_collision.sdf") subprocess.check_call([self.dut, self.model_file(model_url=model_url), "--loop_once", "--pyplot"]) def test_set_position(self): """Test that the --position option doesn't crash.""" model_urls = [ # Simple SDFormat file. "package://drake/multibody/benchmarks/acrobot/acrobot.sdf", # Simple URDF file. "package://drake/multibody/benchmarks/acrobot/acrobot.urdf", ] for model_url in model_urls: print(model_url) filename = self.model_file(model_url=model_url) subprocess.check_call([self.dut, filename, "--loop_once", "--position", "0.1", "0.2"]) class TestModelVisualizer(unittest.TestCase): """ Tests the ModelVisualizer class. Note that camera tests are split into the model_visualizer_camera_test, and reload tests are split into the model_visualizer_reload_test. """ SAMPLE_OBJ = textwrap.dedent("""<?xml version="1.0"?> <sdf version="1.7"> <model name="cylinder"> <pose>0 0 0 0 0 0</pose> <link name="cylinder_link"> <visual name="visual"> <geometry> <cylinder> <radius>0.1</radius> <length>0.2</length> </cylinder> </geometry> </visual> </link> </model> </sdf> """) def setUp(self): mut_private._webbrowser_open = self._mock_webbrowser_open # When we want to allow webbrowser.open, this will be a list() that # captures the kwargs it was called with. self._webbrowser_opened = None def _mock_webbrowser_open(self, *args, **kwargs): self.assertEqual(args, tuple()) if self._webbrowser_opened is None: self.fail("Unexpected webbrowser.open") self._webbrowser_opened.append(copy.deepcopy(kwargs)) def test_model_from_string(self): """Visualizes a model from a string buffer.""" dut = mut.ModelVisualizer() dut.parser().AddModelsFromString(self.SAMPLE_OBJ, "sdf") self.assertIsNotNone(dut.meshcat()) dut.Run(position=[1, 0, 0, 0, 0, 0, 0], loop_once=True) def test_provided_meshcat(self): """Visualizes using a user-provided meshcat.""" meshcat = Meshcat() dut = mut.ModelVisualizer(meshcat=meshcat) self.assertEqual(dut.meshcat(), meshcat) dut.parser().AddModelsFromString(self.SAMPLE_OBJ, "sdf") dut.Run(loop_once=True) def test_pyplot(self): """Enables pyplot and ensures nothing crashes.""" # This acute test only makes sense when pyplot is disabled by default. defaults = mut.ModelVisualizer._get_constructor_defaults() assert defaults["pyplot"] is False dut = mut.ModelVisualizer(pyplot=True) dut.parser().AddModelsFromString(self.SAMPLE_OBJ, "sdf") dut.Run(loop_once=True) def test_model_from_file(self): """ Visualizes models from files, one at a time. Enables frame visualization for additional code coverage. """ model_urls = [ # Simple SDFormat file. "package://drake/multibody/benchmarks/acrobot/acrobot.sdf", # Simple URDF file. "package://drake/multibody/benchmarks/acrobot/acrobot.urdf", # Nested SDFormat file. "package://drake/manipulation/util/test/simple_nested_model.sdf", # SDFormat world file with multiple models. "package://drake/manipulation/util/test/" + "simple_world_with_two_models.sdf", ] for i, model_url in enumerate(model_urls): with self.subTest(model=model_url): filename = PackageMap().ResolveUrl(model_url) dut = mut.ModelVisualizer(visualize_frames=True) if i % 2 == 0: # Conditionally Ping the parser() here, so that we cover # both branching paths within AddModels(). dut.parser() dut.AddModels(filename=filename) dut.Run(loop_once=True) def test_model_from_url(self): url = "package://drake/multibody/benchmarks/acrobot/acrobot.sdf" dut = mut.ModelVisualizer() dut.AddModels(url=url) dut.Run(loop_once=True) def test_add_model_args_error(self): filename = "drake/multibody/benchmarks/acrobot/acrobot.sdf" url = f"package://{filename}" dut = mut.ModelVisualizer() with self.assertRaisesRegex(ValueError, "either filename.*url"): dut.AddModels(filename, url=url) def test_methods_and_multiple_models(self): """ Tests main class methods individually as well as adding models twice. Also tests passing `position` to both Finalize and Run. """ dut = mut.ModelVisualizer() # Check that models can be added multiple times without error. dut.parser().AddModelsFromString(self.SAMPLE_OBJ, "sdf") sample2 = self.SAMPLE_OBJ.replace('name="cylinder"', 'name="cylinder2"') dut.parser().AddModelsFromString(sample2, "sdf") positions = [1, 0, 0, 0, 0, 0, 0] * 2 # Model is just doubled. dut.Finalize(position=positions) dut.Run(position=positions, loop_once=True) def test_precondition_messages(self): dut = mut.ModelVisualizer() dut.Finalize() with self.assertRaisesRegex(ValueError, "already been"): dut.package_map() with self.assertRaisesRegex(ValueError, "already been"): dut.parser() with self.assertRaisesRegex(ValueError, "already been"): dut.AddModels("ignored.urdf") def test_traffic_cone(self): """ Checks that the traffic cone helpers don't crash. """ meshcat = Meshcat() dut = mut.ModelVisualizer(meshcat=meshcat) path = "/PARSE_ERROR" # The add & removes functions must work even when called too many, too # few, or an unmatched number of times. It's not practical to have the # calling code keep track of how often things are called, so the code # must be robust to any ordering. for _ in range(2): dut._add_traffic_cone() self.assertTrue(dut._meshcat.HasPath(path)) for _ in range(3): dut._remove_traffic_cone() self.assertFalse(dut._meshcat.HasPath(path)) def test_webbrowser(self): """ Checks that the webbrowser launch command is properly invoked. """ # If the browser is opened in this stanza, the test will fail. dut = mut.ModelVisualizer(browser_new=True) dut.parser().AddModelsFromString(self.SAMPLE_OBJ, "sdf") dut.Finalize() # Now we allow (mocked) webbrowser.open. self._webbrowser_opened = list() dut.Run(loop_once=True) # Check that was called exactly once, with correct kwargs. self.assertEqual(len(self._webbrowser_opened), 1) kwargs = self._webbrowser_opened[0] self.assertEqual(kwargs["new"], True) self.assertIn("localhost", kwargs["url"]) self.assertEqual(len(kwargs), 2) def test_triad_defaults(self): # Cross-check the default triad parameters. expected = inspect.signature(mut.AddFrameTriadIllustration).parameters actual = mut.ModelVisualizer._get_constructor_defaults() for name in ("length", "radius", "opacity"): self.assertEqual(actual[f"triad_{name}"], expected[name].default) def test_visualize_all_frames(self): """ Confirm that *all* frames get added. """ dut = mut.ModelVisualizer(visualize_frames=True) dut.parser().AddModels(file_type=".urdf", file_contents=""" <?xml version="1.0"?> <robot name="test_model"> <link name="box"> <inertial> <mass value="1"/> <inertia ixx="0.01" ixy="0" ixz="0" iyy="0.01" iyz="0" izz="0.01"/> </inertial> <visual> <geometry> <box size=".1 .2 .3"/> </geometry> </visual> </link> <frame name="offset_frame" link="box" xyz="0.25 0 0" rpy="0 0 0"/> </robot> """) dut.Run(loop_once=True) meshcat = dut.meshcat() self.assertTrue(meshcat.HasPath("/drake/illustration/test_model")) # Body frame. self.assertTrue(meshcat.HasPath("/drake/illustration/test_model/box" "/_frames/box(2)/x-axis")) self.assertTrue(meshcat.HasPath("/drake/illustration/test_model/box" "/_frames/box(2)/y-axis")) self.assertTrue(meshcat.HasPath("/drake/illustration/test_model/box" "/_frames/box(2)/z-axis")) # Offset frame. self.assertTrue(meshcat.HasPath("/drake/illustration/test_model/box" "/_frames/offset_frame(2)/x-axis")) self.assertTrue(meshcat.HasPath("/drake/illustration/test_model/box" "/_frames/offset_frame(2)/y-axis")) self.assertTrue(meshcat.HasPath("/drake/illustration/test_model/box" "/_frames/offset_frame(2)/z-axis")) def test_visualize_all_frames_nested_models(self): """When parsing SDFormat with nested models, we can get multiple __model__ frames associated with the same body. It should still process the frames and not complain about repeated geometry names. """ sdf_file = FindResourceOrThrow( "drake/multibody/parsing/test/sdf_parser_test/" "model_with_directly_nested_models.sdf") dut = mut.ModelVisualizer(visualize_frames=True) dut.AddModels(filename=sdf_file) dut.Run(loop_once=True) # Note: reaching here without throwing is enough.
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/model_visualizer_reload_test.py
import subprocess import time import unittest from pydrake.common import FindResourceOrThrow from pydrake.geometry import Meshcat import pydrake.visualization as mut class TestModelVisualizerReload(unittest.TestCase): """ Tests the reload feature of the ModelVisualizer class. The reload testing is carved into a separate file vs model_visualizer_test because networking can be flaky on our continuous integration builds. """ def test_reload(self): """ Checks that the _reload() function does not crash. """ # Prepare a model that should allow reloading. meshcat = Meshcat() dut = mut.ModelVisualizer(meshcat=meshcat) filename = "drake/multibody/benchmarks/acrobot/acrobot.sdf" dut.AddModels(FindResourceOrThrow(filename)) dut.Finalize() # Check that it allowed reloading. self.assertIsNotNone(dut._reload_button_name) button = dut._reload_button_name self.assertEqual(meshcat.GetButtonClicks(button), 0) # Remember the originally-created diagram. orig_diagram = dut._diagram # Click the reload button. cli = FindResourceOrThrow("drake/geometry/meshcat_websocket_client") message = f"""{{ "type": "button", "name": "{button}" }}""" subprocess.check_call([ cli, f"--ws_url={meshcat.ws_url()}", f"--send_message={message}"]) # Wait up to 5 seconds for the button click to be processed. for _ in range(500): if meshcat.GetButtonClicks(button) > 0: break time.sleep(1 / 100) self.assertEqual(meshcat.GetButtonClicks(button), 1) # Run once. If a reload() happened, the diagram will have changed out. # Use a non-default position so we can check that it is maintained. original_q = [1.0, 2.0] dut.Run(position=original_q, loop_once=True) self.assertNotEqual(id(orig_diagram), id(dut._diagram)) # Ensure the reloaded slider and joint values are the same. slider_q = dut._sliders.get_output_port().Eval( dut._sliders.GetMyContextFromRoot(dut._context)) self.assertListEqual(list(original_q), list(slider_q)) joint_q = dut._diagram.plant().GetPositions( dut._diagram.plant().GetMyContextFromRoot(dut._context)) self.assertListEqual(list(original_q), list(joint_q))
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/multicam_scenario_test.py
import os.path import subprocess import sys import unittest from python.runfiles import Create as CreateRunfiles class TestMulticamScenario(unittest.TestCase): def _find_resource(self, respath): runfiles = CreateRunfiles() result = runfiles.Rlocation(respath) self.assertTrue(result, respath) self.assertTrue(os.path.exists(result), respath) return result @unittest.skipIf(sys.platform == "darwin", "Missing RenderEngineGl") def test_smoke(self): """Runs `multicam_scenario.yaml` and checks it doesn't crash.""" simulator = self._find_resource( "drake/examples/hardware_sim/hardware_sim_py" ) test_scenarios = self._find_resource( "drake/bindings/pydrake/visualization/test/multicam_scenario.yaml" ) run_args = [ simulator, f"--scenario_file={test_scenarios}", "--scenario_name=Multicam", # For the smoke test, exit fairly quickly. "--scenario_text={simulation_duration: 0.0625}", ] subprocess.run(run_args, check=True)
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/triad_test.py
import unittest import numpy as np from pydrake.geometry import Meshcat, Rgba from pydrake.math import RigidTransform, RotationMatrix from pydrake.multibody.plant import MultibodyPlant from pydrake.multibody.tree import FixedOffsetFrame from pydrake.planning import RobotDiagramBuilder import pydrake.visualization as mut class TestTriad(unittest.TestCase): def setUp(self): # Create a simple robot. builder = RobotDiagramBuilder() builder.parser().AddModels( url="package://drake/multibody/benchmarks/acrobot/acrobot.sdf") self._X_PF = RigidTransform([1.0, 2.0, 3.0]) self._frame = builder.plant().AddFrame( FixedOffsetFrame( "frame", builder.plant().GetFrameByName("Link2"), self._X_PF)) self._frame_index = self._frame.index() robot = builder.Build() self._plant = robot.plant() self._scene_graph = robot.scene_graph() self._axis_offsets = { "x": RigidTransform( RotationMatrix.MakeYRotation(np.pi/2), [0.1, 0, 0]), "y": RigidTransform( RotationMatrix.MakeXRotation(np.pi/2), [0, 0.1, 0]), "z": RigidTransform( RotationMatrix.MakeZRotation(np.pi/2), [0, 0, 0.1]), } def _assert_equal_transform(self, X1, X2): np.testing.assert_equal(X1.GetAsMatrix34(), X2.GetAsMatrix34()) def test_via_body(self): # Illustrate the Link2 body frame. x, y, z = mut.AddFrameTriadIllustration( scene_graph=self._scene_graph, body=self._plant.GetBodyByName("Link2"), name="foo", length=0.2, radius=0.001, opacity=0.5, X_FT=RigidTransform()) # Check the geometry pose of each axis. inspect = self._scene_graph.model_inspector() self._assert_equal_transform( inspect.GetPoseInFrame(x), self._axis_offsets["x"]) self._assert_equal_transform( inspect.GetPoseInFrame(y), self._axis_offsets["y"]) self._assert_equal_transform( inspect.GetPoseInFrame(z), self._axis_offsets["z"]) # Check the geometry details of each axis. for i, char in enumerate(("x", "y", "z")): geom_id = [x, y, z][i] frame_name = inspect.GetName(inspect.GetFrameId(geom_id)) self.assertEqual(frame_name, "acrobot::Link2") self.assertEqual(inspect.GetName(geom_id), f"_frames::foo::{char}-axis") self.assertEqual(inspect.GetShape(geom_id).length(), 0.2) self.assertEqual(inspect.GetShape(geom_id).radius(), 0.001) props = inspect.GetIllustrationProperties(geom_id) self.assertEqual(props.GetProperty("phong", "diffuse"), Rgba(r=(i == 0), g=(i == 1), b=(i == 2), a=0.5)) def test_via_frame(self): # Illustrate our custom added frame. X_FT = RigidTransform([0.1, 0.2, 0.3]) x, y, z = mut.AddFrameTriadIllustration( scene_graph=self._scene_graph, frame=self._frame, length=0.2, X_FT=X_FT) # Check the geometry pose of each axis. inspect = self._scene_graph.model_inspector() X_PT = self._X_PF @ X_FT self._assert_equal_transform( inspect.GetPoseInFrame(x), X_PT @ self._axis_offsets["x"]) self._assert_equal_transform( inspect.GetPoseInFrame(y), X_PT @ self._axis_offsets["y"]) self._assert_equal_transform( inspect.GetPoseInFrame(z), X_PT @ self._axis_offsets["z"]) def test_via_frame_index(self): # Illustrate our custom added frame. X_FT = RigidTransform([0.1, 0.2, 0.3]) x, y, z = mut.AddFrameTriadIllustration( plant=self._plant, scene_graph=self._scene_graph, frame_index=self._frame_index, length=0.2, X_FT=X_FT) # Check the geometry pose of each axis. inspect = self._scene_graph.model_inspector() X_PT = self._X_PF @ X_FT self._assert_equal_transform( inspect.GetPoseInFrame(x), X_PT @ self._axis_offsets["x"]) self._assert_equal_transform( inspect.GetPoseInFrame(y), X_PT @ self._axis_offsets["y"]) self._assert_equal_transform( inspect.GetPoseInFrame(z), X_PT @ self._axis_offsets["z"]) def test_via_frame_id(self): # Illustrate the Link2 geometry frame. body = self._plant.GetBodyByName("Link2") expected_frame = self._plant.GetBodyFrameIdIfExists(body.index()) geom_ids = mut.AddFrameTriadIllustration( plant=self._plant, scene_graph=self._scene_graph, frame_id=expected_frame) # Check that all three geoms were added. self.assertEqual(len(geom_ids), 3) inspect = self._scene_graph.model_inspector() for geom_id in geom_ids: actual_frame = inspect.GetFrameId(geom_id) self.assertEqual(actual_frame, expected_frame) def test_redundant_plant_arg(self): # Pass a plant= even though it's not needed. # It's sliently cross-checked and accepted. mut.AddFrameTriadIllustration( plant=self._plant, scene_graph=self._scene_graph, body=self._plant.GetBodyByName("Link2")) mut.AddFrameTriadIllustration( plant=self._plant, scene_graph=self._scene_graph, frame=self._frame, name="frame 2") def test_wrong_plant_arg(self): # Pass the wrong plant= value and get rejected. wrong_plant = MultibodyPlant(0.0) with self.assertRaisesRegex(ValueError, "Mismatched body="): mut.AddFrameTriadIllustration( plant=wrong_plant, scene_graph=self._scene_graph, body=self._plant.GetBodyByName("Link2")) with self.assertRaisesRegex(ValueError, "Mismatched frame="): mut.AddFrameTriadIllustration( plant=wrong_plant, scene_graph=self._scene_graph, frame=self._frame)
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/plotting_test.py
import pydrake.visualization as mut import matplotlib.pyplot as plt import numpy as np import unittest from pydrake.symbolic import Variable class TestMatplotlibUtil(unittest.TestCase): def test_plot_sublevelset_quadratic(self): fig, ax = plt.subplots() A = np.diag([1., 2.]) b = [3., 4.] c = -5. vertices = 11 facecolor = (0., 0., 1., 1.) polys = mut.plot_sublevelset_quadratic(ax=ax, A=A, b=b, c=c, vertices=vertices, facecolor=facecolor) x = polys[0].get_xy() self.assertEqual(np.size(x, 0), vertices+1) for i in range(vertices): y = x[i, :] val = y.dot(A).dot(y) + y.dot(b) + c np.testing.assert_almost_equal(val, 1.) self.assertEqual(polys[0].get_facecolor(), facecolor) def test_plot_sublevelset_expression_degree_two(self): fig, ax = plt.subplots() x = np.array([Variable("x0"), Variable("x1")]) A = np.diag([1., 2.]) b = [3., 4.] c = -5. e = x.dot(A).dot(x) + x.dot(b) + c vertices = 11 facecolor = (0., 0., 1., 1.) polys = mut.plot_sublevelset_expression(ax=ax, e=e, vertices=vertices, facecolor=facecolor) x = polys[0].get_xy() self.assertEqual(np.size(x, 0), vertices+1) for i in range(np.size(x, 0)): y = x[i, :] val = y.dot(A).dot(y) + y.dot(b) + c np.testing.assert_almost_equal(val, 1.) self.assertEqual(polys[0].get_facecolor(), facecolor) def test_plot_sublevelset_expression(self): x = np.array([Variable("x"), Variable("y")]) # Construct a non-convex 2D level set. A1 = np.array([[1, 2], [3, 4]]) A2 = A1 @ np.array([[-1, 0], [0, 1]]) # mirror about y-axis V = x.dot(A1.T.dot(A1.dot(x))) * x.dot(A2.T.dot(A2.dot(x))) fig, ax = plt.subplots() polys = mut.plot_sublevelset_expression(ax, V, 11) xys = polys[0].get_xy() for i in range(np.size(xys, 0)): env = {x[0]: xys[i, 0], x[1]: xys[i, 1]} np.testing.assert_almost_equal(V.Evaluate(env), 1., 1e-5)
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/multicam_scenario.yaml
# This scenario file with multiple sim cameras is mainly for manual LCM image # visualization testing. Run the scenario with the hardware_sim example by: # bazel run //examples/hardware_sim:demo_py -- \ # --scenario_file /PATH/TO/DRAKE/bindings/pydrake/visualization/test/multicam_scenario.yaml \ # --scenario_name Multicam Multicam: directives: - add_model: name: amazon_table file: package://drake_models/manipulation_station/amazon_table_simplified.sdf - add_weld: parent: world child: amazon_table::amazon_table - add_model: name: iiwa file: package://drake_models/iiwa_description/urdf/iiwa14_primitive_collision.urdf default_joint_positions: iiwa_joint_1: [-0.2] iiwa_joint_2: [0.79] iiwa_joint_3: [0.32] iiwa_joint_4: [-1.76] iiwa_joint_5: [-0.36] iiwa_joint_6: [0.64] iiwa_joint_7: [-0.73] - add_frame: name: iiwa_on_world X_PF: base_frame: world translation: [0, -0.7, 0.1] rotation: !Rpy { deg: [0, 0, 90] } - add_weld: parent: iiwa_on_world child: iiwa::base - add_model: name: wsg file: package://drake_models/wsg_50_description/sdf/schunk_wsg_50_with_tip.sdf default_joint_positions: left_finger_sliding_joint: [-0.02] right_finger_sliding_joint: [0.02] - add_frame: name: wsg_on_iiwa X_PF: base_frame: iiwa_link_7 translation: [0, 0, 0.114] rotation: !Rpy { deg: [90, 0, 90] } - add_weld: parent: wsg_on_iiwa child: wsg::body lcm_buses: driver_traffic: # Use a non-default LCM url to communicate with the robot. lcm_url: udpm://239.241.129.92:20185?ttl=0 # Configure three cameras with different poses and parameters for testing. cameras: camera_0: name: vtk_camera renderer_name: vtk renderer_class: !RenderEngineVtkParams {} width: 640 height: 480 depth: True label: True fps: 10.0 X_PB: translation: [1.5, 0.8, 1.25] rotation: !Rpy { deg: [-120, 5, 125] } camera_1: name: gl_camera_front renderer_name: gl renderer_class: !RenderEngineGlParams {} width: 1000 height: 1000 depth: True fps: 5.0 X_PB: translation: [0, 1.5, 0.5] rotation: !Rpy { deg: [90, 180, 0] } camera_2: name: vtk_camera_top renderer_name: vtk width: 480 height: 320 label: True fps: 15.0 X_PB: translation: [0, -0.7, 2.0] rotation: !Rpy { deg: [180, 0, 0] } model_drivers: iiwa: !IiwaDriver hand_model_name: wsg lcm_bus: driver_traffic wsg: !SchunkWsgDriver lcm_bus: driver_traffic
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/model_visualizer_camera_test.py
import pydrake.visualization as mut import unittest import numpy as np import umsgpack import pydrake.common.test_utilities.numpy_compare as numpy_compare from pydrake.geometry import Meshcat from pydrake.math import ( RigidTransform, RollPitchYaw, RotationMatrix, ) class TestModelVisualizerCamera(unittest.TestCase): """ Tests the camera feature of the ModelVisualizer class. The camera testing is carved into a separate file vs model_visualizer_test because our camera code tends to be flaky when run using the emulated video driver on our continuous integration builds. """ def test_camera(self): """ Checks that the rgbd sensor code tracks the browser's camera pose (and doesn't crash). """ # Create a meshcat instance as if a browser had connected and sent its # camera pose. meshcat = Meshcat() meshcat._InjectWebsocketMessage(message=umsgpack.packb({ "type": "camera_pose", "camera_pose": [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1, ], "is_perspective": True, })) # Transform y-up to z-up, and from facing in the +z direction to the -z # direction (with concomitant flip of the y-axis). X_WB_expected = RigidTransform( R=RotationMatrix(RollPitchYaw(np.pi / 2, np.pi, np.pi)), p=[1.0, -3.0, 2.0]) # N.B. We don't need perception geometry in the scene -- we'll rely on # the RgbdSensor unit tests to check that cameras work as advertised. # Our only goal here is to achieve statement-level code coverage of the # ModelVisualizer code when show_rgbd_sensor=True. model = """<?xml version="1.0"?> <sdf version="1.9"> <model name="sample"> <link name="base"/> </model> </sdf> """ dut = mut.ModelVisualizer(meshcat=meshcat, show_rgbd_sensor=True) dut.parser().AddModelsFromString(model, "sdf") dut.Run(loop_once=True) # Confirm that the pose got updated properly. Updated pose is a proxy # for the full behavior in dut._render_if_necessary(). camera_frame = dut._diagram.plant().GetFrameByName( "$rgbd_sensor_offset") X_WB = camera_frame.GetPoseInParentFrame( dut._diagram.plant().GetMyContextFromRoot( dut._context)) numpy_compare.assert_allclose(X_WB.GetAsMatrix34(), X_WB_expected.GetAsMatrix34(), atol=1e-15)
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/sliders_test.py
from pydrake.visualization import ( MeshcatPoseSliders, ) import unittest import numpy as np from pydrake.geometry import ( Meshcat, ) from pydrake.math import ( RigidTransform, ) class TestSliders(unittest.TestCase): def test_meshcat_pose_sliders(self): # Construct a sliders system, using every available option. meshcat = Meshcat() dut = MeshcatPoseSliders( meshcat=meshcat, initial_pose=RigidTransform(), lower_limit=[-0.5] * 6, upper_limit=[0.5] * 6, step=[0.1] * 6, decrement_keycodes=[ "KeyA", "KeyB", "KeyC", "KeyD", "KeyE", "KeyF" ], increment_keycodes=[ "KeyG", "KeyH", "KeyI", "KeyJ", "KeyK", "KeyL" ], prefix="pre", visible=[False, False, True, True, True, False]) # Various methods should not crash. dut.get_output_port() dut.Delete() # The constructor has default values. dut = MeshcatPoseSliders(meshcat) context = dut.CreateDefaultContext() # The Run function doesn't crash. X = dut.Run(system=dut, context=context, timeout=1.0, stop_button_keycode="ArrowLeft") self.assertTrue(X.IsExactlyIdentity()) X2 = RigidTransform([0.1, 0.2, 0.3]) dut.SetPose(pose=X2) X_out = dut.get_output_port().Eval(context) self.assertTrue(X_out.IsExactlyEqualTo(X2))
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/config_test.py
import pydrake.visualization as mut import copy import unittest from pydrake.geometry import ( Meshcat, Rgba, ) from pydrake.lcm import ( DrakeLcm, ) from pydrake.systems.lcm import ( LcmBuses, ) from pydrake.multibody.plant import ( AddMultibodyPlantSceneGraph, ) from pydrake.systems.framework import ( DiagramBuilder, ) class TestConfig(unittest.TestCase): def test_visualization_config(self): """Confirms that the (slightly unusual) bindings of Rgba values operate as expected. """ dut = mut.VisualizationConfig() self.assertIsInstance(dut.default_illustration_color, Rgba) def test_apply_visualization_config(self): """Exercises VisualizationConfig and ApplyVisualizationConfig. """ builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0) plant.Finalize() lcm_buses = LcmBuses() lcm_buses.Add("default", DrakeLcm()) config = mut.VisualizationConfig(publish_period=0.25) self.assertIn("publish_period", repr(config)) copy.copy(config) mut.ApplyVisualizationConfig( config=config, plant=plant, scene_graph=scene_graph, lcm_buses=lcm_buses, builder=builder) def test_add_default_visualization(self): """Exercises AddDefaultVisualization. """ builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0) plant.Finalize() meshcat = Meshcat() config = mut.AddDefaultVisualization(builder=builder, meshcat=meshcat)
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/meldis_test.py
"""Unit tests for MeLDiS. You can also visualize the LCM test data like so: 1. In a separate terminal, bazel run //tools:meldis -- -w 2. In another terminal, pass the name of a specific test to bazel. For example, bazel run //bindings/pydrake/visualization:py/meldis_test \\ TestMeldis.test_contact_applet_hydroelastic """ import pydrake.visualization as mut import functools import hashlib import json import os from pathlib import Path import tempfile import unittest import numpy as np import umsgpack from drake import ( lcmt_point_cloud, lcmt_viewer_draw, lcmt_viewer_geometry_data, lcmt_viewer_link_data, lcmt_viewer_load_robot, ) from pydrake.geometry import ( DrakeVisualizer, DrakeVisualizerParams, MeshcatParams, Role, ) from pydrake.lcm import ( DrakeLcm, ) from pydrake.multibody.parsing import ( Parser, ) from pydrake.multibody.plant import ( AddMultibodyPlantSceneGraph, ConnectContactResultsToDrakeVisualizer, ) from pydrake.multibody.tree import ( PrismaticJoint, ) from pydrake.perception import ( BaseField, Fields, PointCloud, PointCloudToLcm, ) from pydrake.systems.analysis import ( Simulator, ) from pydrake.systems.framework import ( DiagramBuilder, ) from pydrake.systems.lcm import ( LcmPublisherSystem, ) import pydrake.visualization.meldis # https://bugs.launchpad.net/ubuntu/+source/u-msgpack-python/+bug/1979549 # # Jammy shipped with python3-u-msgpack 2.3.0, which tries to use # `collections.Hashable`, which was removed in Python 3.10. Work around this by # monkey-patching `Hashable` into `umsgpack.collections`. # # TODO(mwoehlke-kitware): Remove this when Jammy's python3-u-msgpack has been # updated to 2.5.2 or later. if not hasattr(umsgpack, 'Hashable'): import collections setattr(umsgpack.collections, 'Hashable', collections.abc.Hashable) class TestMeldis(unittest.TestCase): def _make_diagram(self, *, resource, visualizer_params, lcm): builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0) parser = Parser(plant=plant) parser.AddModels(url=f"package://{resource}") plant.Finalize() DrakeVisualizer.AddToBuilder(builder=builder, scene_graph=scene_graph, params=visualizer_params, lcm=lcm) diagram = builder.Build() return diagram def _create_point_cloud(self, num_fields): if num_fields == 3: cloud_fields = Fields(BaseField.kXYZs) elif num_fields == 4: cloud_fields = Fields(BaseField.kXYZs | BaseField.kRGBs) else: assert num_fields == 7 cloud_fields = Fields( BaseField.kXYZs | BaseField.kRGBs | BaseField.kNormals ) num_points = 10 cloud = PointCloud(num_points, cloud_fields) xyzs = np.random.uniform(-0.1, 0.1, (3, num_points)) cloud.mutable_xyzs()[:] = xyzs if num_fields > 3: rgbs = np.random.randint(0, 255, (3, num_points), dtype=np.uint8) cloud.mutable_rgbs()[:] = rgbs if num_fields > 4: normals = np.random.uniform(-0.1, 0.1, (3, num_points)) cloud.mutable_normals()[:] = normals return cloud def _publish_lcm_point_cloud(self, lcm, channel, cloud): """Given the complexity of the lcmt_point_cloud message format, the easiest way to feed the DUT with a sample point cloud is to use PointCloudToLcmSystem for the point cloud conversion and LcmPublisherSystem to publish the LCM message onto the DUT's LCM bus. """ builder = DiagramBuilder() cloud_to_lcm = builder.AddSystem(PointCloudToLcm(frame_name="world")) cloud_lcm_publisher = builder.AddSystem( LcmPublisherSystem.Make( channel=channel, lcm_type=lcmt_point_cloud, lcm=lcm, publish_period=1.0, use_cpp_serializer=True)) builder.Connect( cloud_to_lcm.get_output_port(), cloud_lcm_publisher.get_input_port()) diagram = builder.Build() # Set input and publish the point cloud. context = diagram.CreateDefaultContext() cloud_context = cloud_to_lcm.GetMyContextFromRoot(context) cloud_to_lcm.get_input_port().FixValue(cloud_context, cloud) diagram.ForcedPublish(context) def test_viewer_applet(self): """Checks that _ViewerApplet doesn't crash when receiving messages. Note that many geometry types are not yet covered by this test. """ # Create the device under test. dut = mut.Meldis() meshcat = dut.meshcat lcm = dut._lcm # Polling before any messages doesn't crash. dut._invoke_poll() # Enqueue the load + draw messages. diagram = self._make_diagram( resource="drake/multibody/benchmarks/acrobot/acrobot.sdf", visualizer_params=DrakeVisualizerParams(), lcm=lcm) context = diagram.CreateDefaultContext() diagram.ForcedPublish(context) # The geometry isn't registered until the load is processed. self.assertEqual(meshcat.HasPath("/DRAKE_VIEWER"), False) link_path = "/DRAKE_VIEWER/2/plant/acrobot/Link2/0" self.assertEqual(meshcat.HasPath(link_path), False) # Process the load + draw; make sure the geometry exists now. lcm.HandleSubscriptions(timeout_millis=0) dut._invoke_subscriptions() self.assertEqual(meshcat.HasPath("/DRAKE_VIEWER"), True) self.assertEqual(meshcat.HasPath(link_path), True) def _check_viewer_applet_on_model(self, resource): """Checks that _ViewerApplet doesn't crash on the given model file. """ dut = mut.Meldis() lcm = dut._lcm diagram = self._make_diagram( resource=resource, visualizer_params=DrakeVisualizerParams(), lcm=lcm) diagram.ForcedPublish(diagram.CreateDefaultContext()) lcm.HandleSubscriptions(timeout_millis=0) dut._invoke_subscriptions() self.assertEqual(dut.meshcat.HasPath("/DRAKE_VIEWER"), True) def test_viewer_applet_plain_meshes(self): """Checks _ViewerApplet support for untextured meshes. """ self._check_viewer_applet_on_model( "drake_models/iiwa_description/urdf/" "iiwa14_no_collision.urdf") def test_viewer_applet_textured_meshes(self): """Checks _ViewerApplet support for textured meshes. """ self._check_viewer_applet_on_model( "drake_models/ycb/004_sugar_box.sdf") def test_viewer_applet_reload_optimization(self): """Checks that loading the identical scene twice is efficient. """ # Create the device under test. dut = mut.Meldis() meshcat = dut.meshcat # Initialize an identical simulation twice in a row. The second time # around should be more efficient. for i in range(2): # To parcel out messages one at a time, we'll have the Diagram send # its messages to a temporary location and then forward them along # one at a time to Meldis. temp_lcm = DrakeLcm() temp_lcm_queue = [] # Tuples of (channel, buffer). for name in ["DRAKE_VIEWER_LOAD_ROBOT", "DRAKE_VIEWER_DRAW"]: def _on_message(channel, data): temp_lcm_queue.append((channel, data)) temp_lcm.Subscribe(channel=name, handler=functools.partial( _on_message, name)) # Create the plant + visualizer. diagram = self._make_diagram( resource="drake/multibody/benchmarks/acrobot/acrobot.sdf", visualizer_params=DrakeVisualizerParams(), lcm=temp_lcm) # Capture the LOAD and DRAW messages via temp_lcm. diagram.ForcedPublish(diagram.CreateDefaultContext()) temp_lcm.HandleSubscriptions(timeout_millis=0) load, draw = temp_lcm_queue assert load[0] == "DRAKE_VIEWER_LOAD_ROBOT" assert draw[0] == "DRAKE_VIEWER_DRAW" # Forward the LOAD message to Meldis. dut._lcm.Publish(*load) dut._lcm.HandleSubscriptions(timeout_millis=0) dut._invoke_subscriptions() # The first time around, the link won't be added until the DRAW # message arrives. The second time around, the link should still # be intact from the first time (i.e., no `Delete` occurred). link_path = "/DRAKE_VIEWER/2/plant/acrobot/Link2/0" if i == 0: self.assertFalse(meshcat.HasPath(link_path)) else: self.assertTrue(meshcat.HasPath(link_path)) # Forward the DRAW message to Meldis. dut._lcm.Publish(*draw) dut._lcm.HandleSubscriptions(timeout_millis=0) dut._invoke_subscriptions() # The link always exists after a DRAW. self.assertTrue(meshcat.HasPath(link_path)) def test_geometry_file_hasher(self): """Checks _GeometryFileHasher's detection of changes to files. """ # A tiny wrapper function to make it easy to compute the hash. def dut(data): hasher = mut._meldis._GeometryFileHasher() hasher.on_viewer_load_robot(data) return hasher.value() # Empty message => empty hash. message = lcmt_viewer_load_robot() empty_hash = hashlib.sha256().hexdigest() self.assertEqual(dut(message), empty_hash) # Message with non-mesh primitive => empty hash. sphere = lcmt_viewer_geometry_data() sphere.type = lcmt_viewer_geometry_data.SPHERE link = lcmt_viewer_link_data() link.geom = [sphere] link.num_geom = len(link.geom) message.link = [link] message.num_links = len(message.link) self.assertEqual(dut(message), empty_hash) # Message with inline mesh => empty hash. mesh = lcmt_viewer_geometry_data() mesh.type = lcmt_viewer_geometry_data.MESH mesh.float_data = [0.0, 0.0] mesh.num_float_data = len(mesh.float_data) link.geom = [mesh] link.num_geom = len(link.geom) message.link = [link] message.num_links = len(message.link) self.assertEqual(dut(message), empty_hash) # Message with invalid mesh filename => empty hash. # (Invalid mesh filenames are not an error.) mesh = lcmt_viewer_geometry_data() mesh.type = lcmt_viewer_geometry_data.MESH mesh.string_data = "no-such-file" link.geom = [mesh] link.num_geom = len(link.geom) message.link = [link] message.num_links = len(message.link) self.assertEqual(dut(message), empty_hash) # Switch to a valid .obj mesh filename => non-empty hash. test_tmpdir = Path(os.environ["TEST_TMPDIR"]) obj_filename = test_tmpdir / "mesh_checksum_test.obj" with open(obj_filename, "w") as f: f.write("foobar") mesh.string_data = str(obj_filename) mesh_hash_1 = dut(message) self.assertNotEqual(mesh_hash_1, empty_hash) # Changing the .obj mesh content changes the checksum. # Invalid mtl filenames are not an error. with open(obj_filename, "w") as f: f.write("foo\n mtllib mesh_checksum_test.mtl \nbar\n") mesh_hash_2 = dut(message) self.assertNotEqual(mesh_hash_2, empty_hash) self.assertNotEqual(mesh_hash_2, mesh_hash_1) # The appearance of the .obj's mtl file changes the checksum. with open(test_tmpdir / "mesh_checksum_test.mtl", "w") as f: f.write("quux") mesh_hash_3 = dut(message) self.assertNotEqual(mesh_hash_3, empty_hash) self.assertNotEqual(mesh_hash_3, mesh_hash_1) self.assertNotEqual(mesh_hash_3, mesh_hash_2) # Now finally, the mtl file has a texture. This time, as a cross-check, # inspect the filenames that were hashed instead of the hash itself. png_filename = test_tmpdir / "mesh_checksum_test.png" with open(test_tmpdir / "mesh_checksum_test.mtl", "w") as f: f.write("map_Kd mesh_checksum_test.png\n") png_filename.touch() hasher = mut._meldis._GeometryFileHasher() hasher.on_viewer_load_robot(message) hashed_names = set([x.name for x in hasher._paths]) self.assertSetEqual(hashed_names, {"mesh_checksum_test.obj", "mesh_checksum_test.mtl", "mesh_checksum_test.png"}) # Message with .gltf mesh that can't be parsed => non-empty hash. # (Invalid glTF content is not an error.) gltf_filename = test_tmpdir / "mesh_checksum_test.gltf" with open(gltf_filename, "w") as f: f.write("I'm adversarially not json. {") mesh.string_data = str(gltf_filename) gltf_hash_1 = dut(message) self.assertNotEqual(gltf_hash_1, empty_hash) # Valid glTF file, but with no external files; the glTF's contents # matter. with open(gltf_filename, "w") as f: f.write("{}") gltf_hash_2 = dut(message) self.assertNotEqual(gltf_hash_2, empty_hash) self.assertNotEqual(gltf_hash_2, gltf_hash_1) # Valid glTF file reference an external image. with open(gltf_filename, "w") as f: f.write(json.dumps({"images": [{"uri": str(png_filename)}]})) gltf_hash_3 = dut(message) self.assertNotEqual(gltf_hash_3, empty_hash) self.assertNotEqual(gltf_hash_3, gltf_hash_2) # Now finally, the glTF file has a .bin. This time, as a cross-check, # inspect the filenames that were hashed instead of the hash itself. bin_filename = test_tmpdir / "mesh_checksum_test.bin" bin_filename.touch() with open(gltf_filename, "w") as f: f.write(json.dumps({ "images": [{"uri": str(png_filename)}], "buffers": [{"uri": str(bin_filename)}] })) hasher = mut._meldis._GeometryFileHasher() hasher.on_viewer_load_robot(message) hashed_names = set([x.name for x in hasher._paths]) self.assertSetEqual(hashed_names, {"mesh_checksum_test.gltf", "mesh_checksum_test.bin", "mesh_checksum_test.png"}) # A message with an unsupported extension => non-empty hash. unsupported_filename = test_tmpdir / "mesh_checksum_test.ply" with open(unsupported_filename, "w") as f: f.write("Non-empty content will not matter.") mesh.string_data = str(unsupported_filename) unsupported_hash = dut(message) self.assertNotEqual(unsupported_hash, empty_hash) def test_viewer_applet_alpha_slider(self): # Create the device under test. dut = mut.Meldis() meshcat = dut.meshcat lcm = dut._lcm # Create a simple scene with an invisible geometry (alpha == 0.0). rgb = [0.0, 0.0, 1.0] builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0) parser = Parser(plant=plant) parser.AddModelsFromString(f""" <?xml version="1.0"?> <sdf version="1.9"> <model name="box"> <link name="box"> <visual name="box"> <geometry> <box> <size>1 1 1</size> </box> </geometry> <material> <diffuse>{rgb[0]} {rgb[1]} {rgb[2]} 0.0</diffuse> </material> </visual> </link> <static>1</static> </model> </sdf> """, "sdf") plant.Finalize() DrakeVisualizer.AddToBuilder(builder=builder, scene_graph=scene_graph, params=DrakeVisualizerParams(), lcm=lcm) diagram = builder.Build() # Process the load + draw messages. context = diagram.CreateDefaultContext() diagram.ForcedPublish(context) lcm.HandleSubscriptions(timeout_millis=0) dut._invoke_subscriptions() # Request a different alpha. new_alpha = 0.5 meshcat.SetSliderValue("Viewer α", new_alpha) dut._invoke_poll() # Confirm the new (modulated) opacity of the box. Note: this doesn't # actually test the resulting opacity of the box, merely that we # called set_property("/DRAKE_VIEWER", "modulated_opacity", new_alpha). # We rely on meshcat to do the "right" thing in response. path = "/DRAKE_VIEWER" self.assertEqual(meshcat.HasPath(path), True) message = meshcat._GetPackedProperty(path, "modulated_opacity") parsed = umsgpack.unpackb(message) self.assertEqual(parsed['value'], new_alpha) def test_inertia_geometry(self): url = "package://drake_models/manipulation_station/sphere.sdf" dut = mut.Meldis() lcm = dut._lcm builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0) parser = Parser(plant=plant) parser.AddModels(url=url) plant.Finalize() config = mut.VisualizationConfig() mut.ApplyVisualizationConfig(config=config, builder=builder, lcm=lcm) diagram = builder.Build() simulator = Simulator(diagram) simulator.AdvanceTo(0.1) with self.assertRaises(SystemExit): dut.serve_forever(idle_timeout=0.001) path = "/Inertia Visualizer/0/inertia_visualizer/InertiaVisualizer" self.assertTrue(dut.meshcat.HasPath(path)) self.assertTrue(dut.meshcat.HasPath(f"{path}/sphere/base_link")) def test_hydroelastic_geometry(self): """Checks that _ViewerApplet doesn't crash when receiving hydroelastic geometry. """ dut = mut.Meldis() lcm = dut._lcm diagram = self._make_diagram( resource="drake/examples/hydroelastic/" "spatula_slip_control/spatula.sdf", visualizer_params=DrakeVisualizerParams( show_hydroelastic=True, role=Role.kProximity), lcm=lcm) context = diagram.CreateDefaultContext() diagram.ForcedPublish(context) lcm.HandleSubscriptions(timeout_millis=0) dut._invoke_subscriptions() def test_contact_applet_point_pair(self): """Checks that _ContactApplet doesn't crash when receiving point contact messages. """ # Create the device under test. dut = mut.Meldis() meshcat = dut.meshcat lcm = dut._lcm # Enqueue a point contact result message. url = "package://drake_models/manipulation_station/sphere.sdf" builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.001) sphere1_model, = Parser(plant, "sphere1").AddModels(url=url) sphere2_model, = Parser(plant, "sphere2").AddModels(url=url) body1 = plant.GetBodyByName("base_link", sphere1_model) body2 = plant.GetBodyByName("base_link", sphere2_model) plant.AddJoint(PrismaticJoint( name="sphere1_x", frame_on_parent=plant.world_body().body_frame(), frame_on_child=body1.body_frame(), axis=[1, 0, 0])) plant.AddJoint(PrismaticJoint( name="sphere2_x", frame_on_parent=plant.world_body().body_frame(), frame_on_child=body2.body_frame(), axis=[1, 0, 0])) plant.Finalize() ConnectContactResultsToDrakeVisualizer( builder=builder, plant=plant, scene_graph=scene_graph, lcm=lcm) diagram = builder.Build() context = diagram.CreateDefaultContext() plant.SetPositions(plant.GetMyMutableContextFromRoot(context), [-0.03, 0.03]) diagram.ForcedPublish(context) # The geometry isn't registered until the load is processed. pair_path = "/CONTACT_RESULTS/point/base_link(2)+base_link(3)" self.assertEqual(meshcat.HasPath(pair_path), False) # Process the load + draw; make sure the geometry exists now. lcm.HandleSubscriptions(timeout_millis=0) dut._invoke_subscriptions() self.assertEqual(meshcat.HasPath(pair_path), True) def test_contact_applet_hydroelastic(self): """Checks that _ContactApplet doesn't crash when receiving hydroelastic messages. """ # Create the device under test. dut = mut.Meldis() meshcat = dut.meshcat lcm = dut._lcm # Enqueue a hydroelastic contact message. url = "package://drake/multibody/meshcat/test/hydroelastic.sdf" builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.001) parser = Parser(plant=plant) parser.AddModels(url=url) body1 = plant.GetBodyByName("body1") body2 = plant.GetBodyByName("body2") plant.AddJoint(PrismaticJoint( name="body1", frame_on_parent=plant.world_body().body_frame(), frame_on_child=body1.body_frame(), axis=[0, 0, 1])) plant.AddJoint(PrismaticJoint( name="body2", frame_on_parent=plant.world_body().body_frame(), frame_on_child=body2.body_frame(), axis=[1, 0, 0])) plant.Finalize() ConnectContactResultsToDrakeVisualizer( builder=builder, plant=plant, scene_graph=scene_graph, lcm=lcm) diagram = builder.Build() context = diagram.CreateDefaultContext() plant.SetPositions(plant.GetMyMutableContextFromRoot(context), [0.1, 0.3]) diagram.ForcedPublish(context) # The geometry isn't registered until the load is processed. hydro_path = "/CONTACT_RESULTS/hydroelastic/" + \ "body1.two_bodies::body1_collision+body2" hydro_path2 = "/CONTACT_RESULTS/hydroelastic/" + \ "body1.two_bodies::body1_collision2+body2" self.assertEqual(meshcat.HasPath(hydro_path), False) self.assertEqual(meshcat.HasPath(hydro_path2), False) # Process the load + draw; contact results should now exist. lcm.HandleSubscriptions(timeout_millis=1) dut._invoke_subscriptions() self.assertEqual(meshcat.HasPath("/CONTACT_RESULTS/hydroelastic"), True) self.assertEqual(meshcat.HasPath(hydro_path), True) self.assertEqual(meshcat.HasPath(hydro_path2), True) def test_deformable(self): """Checks that _ViewerApplet doesn't crash for deformable geometries in DRAKE_VIEWER_DEFORMABLE channel. """ # Create the device under test. dut = mut.Meldis() # Prepare a deformable-geometry message. It is a triangle surface mesh # of a tetrahedron. geom0 = lcmt_viewer_geometry_data() geom0.type = lcmt_viewer_geometry_data.MESH geom0.position = [0.0, 0.0, 0.0] q_wxyz = [1.0, 0.0, 0.0, 0.0] geom0.quaternion = q_wxyz geom0.color = [0.9, 0.9, 0.9, 1.0] geom0.string_data = "tetrahedron" geom0.float_data = [ # 4 vertices and 4 triangles 4.0, 4.0, # 4 vertices at the origin and on the three axes. 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, # 4 triangles, use float for integer vertex indices 0., 2., 1., 0., 1., 3., 0., 3., 2., 1., 2., 3.] geom0.num_float_data = len(geom0.float_data) message = lcmt_viewer_link_data() message.name = "test_deformable_geometry" message.robot_num = 0 message.num_geom = 1 message.geom = [geom0] dut._lcm.Publish(channel="DRAKE_VIEWER_DEFORMABLE", buffer=message.encode()) meshcat_path = f"/DRAKE_VIEWER/{message.robot_num}/{message.name}" # Before the subscribed handlers are called, there is no meshcat path # from the published lcm message. self.assertEqual(dut.meshcat.HasPath(meshcat_path), False) dut._lcm.HandleSubscriptions(timeout_millis=1) dut._invoke_subscriptions() # After the handlers are called, we have the expected meshcat path. self.assertEqual(dut.meshcat.HasPath(meshcat_path), True) def test_point_cloud(self): """Checks that _PointCloudApplet doesn't crash when receiving point cloud messages. """ # Create the device under test. dut = mut.Meldis() test_tuples = ( (3, "DRAKE_POINT_CLOUD", "/POINT_CLOUD/default"), (4, "DRAKE_POINT_CLOUD_XYZRGB", "/POINT_CLOUD/XYZRGB"), (7, "DRAKE_POINT_CLOUD_12345", "/POINT_CLOUD/12345"), ) for num_fields, channel, meshcat_path in test_tuples: with self.subTest(num_fields=num_fields): self.assertEqual(dut.meshcat.HasPath(meshcat_path), False) cloud = self._create_point_cloud(num_fields=num_fields) self._publish_lcm_point_cloud(dut._lcm, channel, cloud) dut._lcm.HandleSubscriptions(timeout_millis=1) dut._invoke_subscriptions() self.assertEqual(dut.meshcat.HasPath(meshcat_path), True) def test_draw_frame_applet(self): """Checks that _DrawFrameApplet doesn't crash when frames are sent in DRAKE_DRAW_FRAMES channel. """ # Create the device under test. dut = mut.Meldis() # Prepare a frame message message = lcmt_viewer_draw() message.position = [[0.0, 0.0, 0.1]] message.quaternion = [[1.0, 0.0, 0.0, 0.0]] message.num_links = 1 message.link_name = ['0'] message.robot_num = [1] dut._lcm.Publish(channel="DRAKE_DRAW_FRAMES", buffer=message.encode()) meshcat_path = f"/DRAKE_DRAW_FRAMES/default/{message.link_name[0]}" # Before the subscribed handlers are called, there is no meshcat path # from the published lcm message. self.assertEqual(dut.meshcat.HasPath(meshcat_path), False) dut._lcm.HandleSubscriptions(timeout_millis=1) dut._invoke_subscriptions() # After the handlers are called, we have the expected meshcat path. self.assertEqual(dut.meshcat.HasPath(meshcat_path), True) def test_args_precedence(self): """Checks that the "kwargs wins" part of our API contract is met. """ # When bad MeshcatParams are used Meldis rejects them, but good kwargs # can override them and win (no errors). bad_host = MeshcatParams(host="8.8.8.8") bad_port = MeshcatParams(port=1) with self.assertRaises(BaseException): mut.Meldis(meshcat_params=bad_host) with self.assertRaises(BaseException): mut.Meldis(meshcat_params=bad_port) mut.Meldis(meshcat_params=bad_host, meshcat_host="localhost") mut.Meldis(meshcat_params=bad_port, meshcat_port=0) def test_command_line_browser_names(self): """Sanity checks our webbrowser names logic. The objective is to return some kind of a list, without crashing. """ names = pydrake.visualization.meldis._available_browsers() self.assertIsInstance(names, list) def test_command_meshcat_params(self): """Confirm that the params plumbing works by feeding in bad params and seeing a validation error be spit out. """ main = pydrake.visualization.meldis._main with tempfile.TemporaryDirectory() as temp: path = Path(temp) / "meshcat_params.yaml" path.write_text("{ port: 1 }", encoding="utf-8") args = [f"--meshcat-params={path}"] with self.assertRaisesRegex(BaseException, "port.*>.*1024"): main(args=args)
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/image_systems_test.py
import math import unittest from pydrake.common.test_utilities import numpy_compare from pydrake.geometry import ( RenderLabel, Rgba, ) from pydrake.systems.sensors import ( ImageDepth16U, ImageDepth32F, ImageLabel16I, ImageRgba8U, ) from pydrake.visualization import ( ColorizeDepthImage, ColorizeLabelImage, ConcatenateImages, ) class TestColorizeDepthImage(unittest.TestCase): def test_properties(self): dut = ColorizeDepthImage() self.assertIsInstance(dut.invalid_color, Rgba) rgba = Rgba(0.1, 0.2, 0.3, 0.4) dut.invalid_color = rgba self.assertEqual(dut.invalid_color, rgba) def test_eval_32f_and_calc_32f(self): dut = ColorizeDepthImage() context = dut.CreateDefaultContext() depth = ImageDepth32F(6, 2) dut.GetInputPort("depth_image_32f").FixValue(context, depth) color = dut.GetOutputPort("color_image").Eval(context) self.assertIsInstance(color, ImageRgba8U) dut.Calc(depth, color) def test_eval_16u_and_calc_16u(self): depth = ImageDepth16U(6, 2) dut = ColorizeDepthImage() context = dut.CreateDefaultContext() dut.GetInputPort("depth_image_16u").FixValue(context, depth) color = dut.GetOutputPort("color_image").Eval(context) self.assertIsInstance(color, ImageRgba8U) dut.Calc(depth, color) class TestColorizeLabelImage(unittest.TestCase): def test_properties(self): dut = ColorizeLabelImage() self.assertIsInstance(dut.background_color, Rgba) rgba = Rgba(0.1, 0.2, 0.3, 0.4) dut.background_color = rgba self.assertEqual(dut.background_color, rgba) def test_eval_and_calc(self): dut = ColorizeLabelImage() context = dut.CreateDefaultContext() label = ImageLabel16I(6, 2) dut.GetInputPort("label_image").FixValue(context, label) color = dut.GetOutputPort("color_image").Eval(context) self.assertIsInstance(color, ImageRgba8U) dut.Calc(label, color) class TestConcatenateImages(unittest.TestCase): def test_smoke(self): rows, cols = (2, 3) dut = ConcatenateImages(rows=rows, cols=cols) # Set the input port values. context = dut.CreateDefaultContext() small = ImageRgba8U(4, 2) for row in range(rows): for col in range(cols): dut.get_input_port(row=row, col=col).FixValue(context, small) # Check the output image. actual = dut.GetOutputPort("color_image").Eval(context) self.assertEqual(actual.width(), small.width() * cols) self.assertEqual(actual.height(), small.height() * rows)
0
/home/johnshepherd/drake/bindings/pydrake/visualization
/home/johnshepherd/drake/bindings/pydrake/visualization/test/video_test.py
import math import os import sys import textwrap import unittest from pydrake.math import RollPitchYaw, RigidTransform 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.visualization import VideoWriter _PLATFORM_SUPPORTS_CV2 = "darwin" not in sys.platform class TestVideoWriter(unittest.TestCase): """Tests for VideoWriter. To view the output videos from the test cases, you can do: unzip bazel-testlogs/bindings/pydrake/visualization/py/video_test/test.outputs/outputs.zip # noqa """ @staticmethod def _cv2(): """On some platforms, we don't have OpenCV as a dependency so we can't import it atop this file as would be usual. """ if _PLATFORM_SUPPORTS_CV2: import cv2 return cv2 else: return None def _test_usage(self, filename, backend, kinds): """Runs through the typical usage and checks that a well-formed video output file was created on disk. """ builder = DiagramBuilder() plant, _ = AddMultibodyPlantSceneGraph(builder, time_step=0.0) models = textwrap.dedent(""" directives: - add_model: name: iiwa file: package://drake_models/iiwa_description/sdf/iiwa14_no_collision.sdf # noqa - add_model: name: wsg file: package://drake_models/wsg_50_description/sdf/schunk_wsg_50.sdf # noqa - add_weld: parent: world child: iiwa::iiwa_link_0 - add_weld: parent: iiwa::iiwa_link_7 child: wsg::body """) Parser(plant).AddModelsFromString(models, "dmd.yaml") plant.Finalize() # Add the video writer. fps = 16 if backend == "cv2" else 10 sensor_pose = RigidTransform( RollPitchYaw([-math.pi/2, 0, math.pi/2]), [2, 0, 0.75]) writer = VideoWriter.AddToBuilder( filename=filename, builder=builder, sensor_pose=sensor_pose, fps=fps, kinds=kinds, backend=backend) # Simulate for one second (add torque to the plant to make it move). diagram = builder.Build() simulator = Simulator(diagram) diagram_context = simulator.get_mutable_context() plant_context = plant.GetMyMutableContextFromRoot(diagram_context) plant.get_actuation_input_port().FixValue( plant_context, [10] * plant.num_positions()) simulator.AdvanceTo(1.0) writer.Save() # The video file should have been created, with non-trivial size. self.assertGreater(os.path.getsize(filename), 5000) # Check that the video can be loaded, and has the correct fps and # number of frames for a 1-second simulation. if _PLATFORM_SUPPORTS_CV2: cv2 = self._cv2() readback = cv2.VideoCapture(filename) self.assertEqual(readback.get(cv2.CAP_PROP_FRAME_COUNT), fps + 1) self.assertEqual(readback.get(cv2.CAP_PROP_FPS), fps) def test_pil_color_only(self): """Tests PIL (gif) output of a color-only camera.""" filename = os.environ["TEST_UNDECLARED_OUTPUTS_DIR"] + "/color.gif" self._test_usage(filename, "PIL", ("color",)) def test_pil_everything(self): """Tests PIL (gif) output of a color+depth+label.""" filename = os.environ["TEST_UNDECLARED_OUTPUTS_DIR"] + "/multi.gif" self._test_usage(filename, "PIL", ("color", "depth", "label")) @unittest.skipUnless(_PLATFORM_SUPPORTS_CV2, "Not tested on this platform") def test_cv2_color_only(self): """Tests cv2 (mp4) output of a color-only camera.""" filename = os.environ["TEST_UNDECLARED_OUTPUTS_DIR"] + "/color.mp4" self._test_usage(filename, "cv2", ("color",)) @unittest.skipUnless(_PLATFORM_SUPPORTS_CV2, "Not tested on this platform") def test_cv2_everything(self): """Tests cv2 (mp4) output of a color+depth+label.""" filename = os.environ["TEST_UNDECLARED_OUTPUTS_DIR"] + "/multi.mp4" self._test_usage(filename, "cv2", ("color", "depth", "label")) @unittest.skipUnless(_PLATFORM_SUPPORTS_CV2, "Not tested on this platform") def test_cv2_bad_fourcc(self): """Tests cv2 sanity checking of fourcc.""" builder = DiagramBuilder() AddMultibodyPlantSceneGraph(builder, time_step=0.0) filename = os.environ["TEST_UNDECLARED_OUTPUTS_DIR"] + "/bad.mp4" with self.assertRaisesRegex(ValueError, "wrong.*must be"): VideoWriter.AddToBuilder( filename=filename, builder=builder, sensor_pose=RigidTransform(), fps=16, backend="cv2", fourcc="wrong") def test_bad_backend(self): """Tests detection of a malformed backend setting.""" builder = DiagramBuilder() AddMultibodyPlantSceneGraph(builder, time_step=0.0) with self.assertRaises(Exception) as cm: VideoWriter.AddToBuilder( filename="file", builder=builder, sensor_pose=RigidTransform(), backend="WRONG") self.assertIn("WRONG", str(cm.exception)) def test_bad_backend(self): """Tests detection of a malformed kinds setting.""" builder = DiagramBuilder() AddMultibodyPlantSceneGraph(builder, time_step=0.0) with self.assertRaises(Exception) as cm: VideoWriter.AddToBuilder( filename="file", builder=builder, sensor_pose=RigidTransform(), kinds=("WRONG",)) self.assertIn("WRONG", str(cm.exception))
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/symbolic/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_library", ) load( "//tools/skylark:drake_py.bzl", "drake_py_library", "drake_py_unittest", ) load( "//tools/skylark:pybind.bzl", "EXTRA_PYBIND_COPTS", "get_pybind_package_info", ) package(default_visibility = [ "//bindings/pydrake:__pkg__", ]) # This determines how `PYTHONPATH` is configured, and how to install the # bindings. PACKAGE_INFO = get_pybind_package_info("//bindings") # N.B. The `pydrake.symbolic` module is part of the root module dependency # cycle. Refer to bindings/pydrake/common/module_cycle.md for details. drake_cc_library( name = "symbolic_py", srcs = [ "symbolic_py_unapply.h", "symbolic_py_unapply.cc", # TODO(jwnimmer-tri) Split the monolith into pieces. "symbolic_py_monolith.cc", ], hdrs = [ "symbolic_py.h", ], copts = EXTRA_PYBIND_COPTS, declare_installed_headers = False, visibility = [ "//bindings/pydrake/common:__pkg__", ], deps = [ "//bindings/pydrake:documentation_pybind", "//bindings/pydrake:math_operators_pybind", "//bindings/pydrake:symbolic_types_pybind", "//bindings/pydrake/common:eigen_pybind", "@pybind11", ], ) drake_py_library( name = "symbolic_extra", srcs = [ "_symbolic_extra.py", "_symbolic_sympy.py", ], visibility = [ "//bindings/pydrake/common:__pkg__", ], ) install( name = "install", targets = [":symbolic_extra"], py_dest = PACKAGE_INFO.py_dest, ) drake_py_unittest( name = "symbolic_test", deps = [ "//bindings/pydrake/common/test_utilities", "//bindings/pydrake/common/test_utilities:algebra_test_util_py", ], ) drake_py_unittest( name = "sympy_test", deps = [ "//bindings/pydrake:module_py", # We'll run the unit test against the latest (pinned) version of SymPy, # even if the host system has a different version installed already. "@mpmath_py_internal//:mpmath_py", "@sympy_py_internal//:sympy_py", ], ) add_lint_tests_pydrake()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/symbolic/_symbolic_extra.py
# See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and # rationale. import functools import operator import typing import sys def logical_and(*formulas): assert len(formulas) >= 1, "Must supply at least one operand" return functools.reduce(__logical_and, formulas) def logical_or(*formulas): assert len(formulas) >= 1, "Must supply at least one operand" return functools.reduce(__logical_or, formulas) def _reduce_add(*args): return functools.reduce(operator.add, args) def _reduce_mul(*args): return functools.reduce(operator.mul, args) # Drake's SymPy support is loaded lazily (on demand), so that Drake does not # directly depend on SymPy. The implementation lives in `_symbolic_sympy.py`. _symbolic_sympy_defer = None def to_sympy( x: typing.Union[float, int, bool, Variable, Expression, Formula], *, memo: typing.Dict = None ) -> typing.Union[float, int, bool, "sympy.Expr"]: """Converts a pydrake object to the corresponding SymPy Expr. Certain expressions are not supported and will raise NotImplementedError. (Most acutely, note that `int` is not yet supported.) This function aims to support the latest contemporaneous version of SymPy as of Drake's release date. Args: x: The pydrake object to be converted. memo: (Optional) Mapping between Drake variables and SymPy variables. Converting a ``pydrake.symbolic.Variable`` to SymPy will look up the Drake variable's ``v.get_id()`` as a key in this dictionary. If a value is found, it will be used as the SymPy atom for that Drake variable. Otherwise, a new SymPy variable will be created and used, and both mappings ``{drake_var.get_id(): sympy_var}`` and ``{sympy_var: drake_var}`` will be inserted into ``memo``. See also :meth:`pydrake.symbolic.from_sympy`. """ global _symbolic_sympy_defer if _symbolic_sympy_defer is None: from pydrake.symbolic import _symbolic_sympy as _symbolic_sympy_defer if memo is None: memo = dict() return _symbolic_sympy_defer._to_sympy(x, memo=memo) def from_sympy( x: typing.Union[float, int, bool, "sympy.Expr"], *, memo: typing.Dict = None ) -> typing.Union[float, int, bool, Variable, Expression, Formula]: """Converts a SymPy Expr to the corresponding pydrake object. Certain expressions are not supported and will raise NotImplementedError. This function aims to support the latest contemporaneous version of SymPy as of Drake's release date. Args: x: The SymPy object to be converted. memo: (Optional) Mapping between SymPy variables and Drake variables. Converting a SymPy variable to a ``pydrake.symbolic.Variable`` will look up the SymPy variable as a key in this dictionary. If a value is found, then it will be used as the Drake variable. If no value is found, then (for now) raises an exception. In the future, we might support automatically creating variables, but that is not yet implemented. See also :meth:`pydrake.symbolic.to_sympy`. """ global _symbolic_sympy_defer if _symbolic_sympy_defer is None: from pydrake.symbolic import _symbolic_sympy as _symbolic_sympy_defer if memo is None: memo = dict() return _symbolic_sympy_defer._from_sympy(x, memo=memo) # 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] + "/symbolic"]
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/symbolic/symbolic_py_unapply.h
#pragma once #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/bindings/pydrake/symbolic_types_pybind.h" namespace drake { namespace pydrake { namespace internal { constexpr char kUnapplyExpressionDoc[] = R"""( Given an expression, returns a tuple (ctor, args) that would re-create an equivalent expression when called as ctor(*args). This is a useful way to unpack the contents of a compound expression, e.g., to obtain the terms of an addition. In many cases (all arithmetic operators, trig functions, max, min, sqrt, etc.), the returned args will all be either Expressions or floats; in other cases (e.g., if_then_else) some args will other types (e.g., a Formula). To check the form (i.e., kind) of an expression, use e.get_kind(); do not try to infer it from the returned ctor's identity. )"""; // @param m The pydrake.symbolic module. py::object Unapply(py::module m, const symbolic::Expression& e); constexpr char kUnapplyFormulaDoc[] = R"""( Given a formula, returns a tuple (ctor, args) that would re-create an equivalent formula when called as ctor(*args). This is a useful way to unpack the contents of a compound formula, e.g., to obtain the terms of a comparison. For relational formulae (==, <, >, etc.) the returned args will both be of type Expression. For compound formulae (and, or, not) the returned args will be of type Formula. To check the form (i.e., kind) of a formula, use f.get_kind(); do not try to infer it from he returned ctor's identity. )"""; // @param m The pydrake.symbolic module. py::object Unapply(py::module m, const symbolic::Formula& f); } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/symbolic/_symbolic_sympy.py
"""This file contains the implementation of to_sympy and from_sympy as used by `_symbolic_extra.py`. It is loaded is loaded lazily (on demand), so that Drake does not directly depend on SymPy. """ import math import operator from typing import Dict, Union import sympy from sympy.printing.pycode import MpmathPrinter import pydrake.symbolic from pydrake.symbolic import ( Expression, ExpressionKind, Formula, FormulaKind, Variable, ) def _no_change(x): """This function simply returns its argument. It is used below in the table of constructors to signify that no type-conversion is required. """ return x def _handle_constant(x): """This function is used to cast constant expressions to the appropriate sympy type. """ if not math.isinf(x) and not math.isnan(x) and int(x) == x: return sympy.Integer(x) return sympy.Float(x) def _make_sympy_if_then_else(cond: sympy.Expr, expr_then: sympy.Expr, expr_else: sympy.Expr): """Returns the SymPy spelling of `{then_expr} if {cond} else {expr_else}`, also known as the "ternary conditional" operator. """ # N.B. We can't use sympy.ITE -- that operates on three booleans; the Drake # if_then_else operates on (bool, float, float). return sympy.Piecewise((expr_then, cond), (expr_else, True)) # This table maps from ExpressionKind and FormulaKind to the SymPy constructor # for that kind of term; this forms the core of `pydrake.symbolic.to_sympy()`. _SYMPY_CONSTRUCTOR = { ExpressionKind.Constant: _handle_constant, # Like Drake's NaN, the SymPy NaN also rejects, e.g., comparison operators. # That's more like what we want than `math.nan`, which allows comparison. ExpressionKind.NaN: lambda _: sympy.nan, # Use the SymPy preferred spelling of bools. FormulaKind.True_: lambda: sympy.true, FormulaKind.False_: lambda: sympy.false, # SymPy doesn't need any extra call to convert a variable to an expression. ExpressionKind.Var: _no_change, FormulaKind.Var: _no_change, # The rest is all boring stuff, in alphabetical order. ExpressionKind.Abs: sympy.Abs, ExpressionKind.Acos: sympy.acos, ExpressionKind.Add: sympy.Add, ExpressionKind.Asin: sympy.asin, ExpressionKind.Atan: sympy.atan, ExpressionKind.Atan2: sympy.atan2, ExpressionKind.Ceil: sympy.ceiling, ExpressionKind.Cos: sympy.cos, ExpressionKind.Cosh: sympy.cosh, ExpressionKind.Div: operator.truediv, ExpressionKind.Exp: sympy.exp, ExpressionKind.Floor: sympy.floor, ExpressionKind.IfThenElse: _make_sympy_if_then_else, ExpressionKind.Log: sympy.log, ExpressionKind.Max: sympy.Max, ExpressionKind.Min: sympy.Min, ExpressionKind.Mul: sympy.Mul, ExpressionKind.Pow: sympy.Pow, ExpressionKind.Sin: sympy.sin, ExpressionKind.Sinh: sympy.sinh, ExpressionKind.Sqrt: sympy.sqrt, ExpressionKind.Tan: sympy.tan, ExpressionKind.Tanh: sympy.tanh, FormulaKind.And: sympy.And, FormulaKind.Eq: sympy.Equality, FormulaKind.Geq: sympy.GreaterThan, FormulaKind.Gt: sympy.StrictGreaterThan, FormulaKind.Leq: sympy.LessThan, FormulaKind.Lt: sympy.StrictLessThan, FormulaKind.Neq: sympy.Unequality, FormulaKind.Not: sympy.Not, FormulaKind.Or: sympy.Or, # We don't support converting these kinds of terms (yet). ExpressionKind.UninterpretedFunction: None, FormulaKind.Forall: None, FormulaKind.Isnan: None, FormulaKind.PositiveSemidefinite: None, } def _var_to_sympy(drake_var: Variable, *, memo: Dict): """Converts a Drake variable into a SymPy Variable. If the Drake variable was already in the `memo` dict, returns the value in the dict. Otherwise, creates and returns a new sympy.Dummy() variable. """ sympy_var = memo.get(drake_var.get_id()) if sympy_var is None: drake_type = drake_var.get_type() assumptions = { # TODO(jwnimmer-tri) Use drake_type to fill in the assumptions. } sympy_var = sympy.Dummy( name=drake_var.get_name(), dummy_index=drake_var.get_id(), **assumptions) memo[drake_var.get_id()] = sympy_var memo[sympy_var] = drake_var return sympy_var def _var_from_sympy(sympy_var: sympy.Dummy, *, memo: Dict): """Converts a SymPy variable into a Drake Variable. At the moment, the *only* supported conversion is to look up the variable in `memo`, i.e., the user may pre-define the mapping. TODO(jwnimmer-tri) This could probably have a better fallback plan. """ drake_var = memo.get(sympy_var) if drake_var is None: raise NotImplementedError( f"The SymPy variable {sympy_var} is missing from the `memo` dict.") return drake_var def _to_sympy( x: Union[float, int, bool, Variable, Expression, Formula], *, memo: Dict = None ) -> Union[float, int, bool, sympy.Expr]: """This is the private implementation of pydrake.symbolic.to_sympy(). Refer to that module-level function for the full docstring. TODO(jwnimmer-tri) Also support Polynomial, Monomial, etc. """ if isinstance(x, (float, int, bool)): return x if isinstance(x, Variable): return _var_to_sympy(drake_var=x, memo=memo) try: kind = x.get_kind() except AttributeError as e: kind = None if kind is None: raise NotImplementedError( f"Cannot create a SymPy object from the given object {x!r}") sympy_constructor = _SYMPY_CONSTRUCTOR.get(kind) if sympy_constructor is None: raise NotImplementedError( f"Cannot create a SymPy object from " f"the given pydrake {kind} object {x!r}") _, drake_args = x.Unapply() sympy_args = [_to_sympy(arg, memo=memo) for arg in drake_args] return sympy_constructor(*sympy_args) class _DrakePrinter(MpmathPrinter): """A slightly customized Printer class that handles a few unique spellings necessary for writing Drake code. """ def __init__(self): super().__init__({ "fully_qualified_modules": False, "inline": True, "allow_unknown_functions": True, "user_functions": {}, }) def _print_drake_logical_op(self, expr, op): """Uses pydrake.symbolic.logical_{op} instead of the Python built-in boolean operators (`and`, `or`, and `not`). """ args = [self._print(arg) for arg in expr.args] return f"logical_{op}({', '.join(args)})" def _print_And(self, expr): return self._print_drake_logical_op(expr, "and") def _print_Or(self, expr): return self._print_drake_logical_op(expr, "or") def _print_Not(self, expr): return self._print_drake_logical_op(expr, "not") def _print_Piecewise(self, expr): """Undo the effect of _make_sympy_if_then_else, by converting a list of `((cond1, expr1), (cond2, expr2), ...)` pairs into a nested chain of `if_then_else(cond1, expr1, if_then_else(cond2, expr2, ...))` calls. """ assert len(expr.args) > 0 if expr.args[-1].cond not in (True, sympy.true): raise NotImplementedError( "Piecewise functions must always have a value; the final " "condition must be the literal value `True`.") result = [self._print(expr.args[-1].expr)] for arg in reversed(expr.args[:-1]): arg_cond = self._print(arg.cond) arg_expr = self._print(arg.expr) result.insert(0, f"if_then_else({arg_cond}, {arg_expr}, ") result.append(")") return "".join(result) _DRAKE_PRINTER = _DrakePrinter() def _lambdify(*, expr, args): """Wraps sympy.lambdify with extra hard-coded arguments.""" return sympy.lambdify( expr=expr, args=args, modules=pydrake.symbolic, printer=_DRAKE_PRINTER, use_imps=False, docstring_limit=0) def _from_sympy( x: Union[float, int, bool, sympy.Expr], *, memo: Dict = None ) -> Union[float, int, bool, Variable, Expression, Formula]: """This is the private implementation of pydrake.symbolic.from_sympy(). Refer to that module-level function for the full docstring. """ # Return non-SymPy inputs as-is. if isinstance(x, (float, int, bool)): return x # Return constants quickly. if x.is_number: return float(x.evalf()) # Find the SymPy variables in `x` and look up the matching Drake variables. sympy_vars = [] drake_vars = [] for item in x.atoms(): if item.is_number: continue if isinstance(item, sympy.logic.boolalg.BooleanAtom): continue if isinstance(item, sympy.Dummy): sympy_vars.append(item) drake_vars.append(_var_from_sympy(item, memo=memo)) continue raise NotImplementedError(f"Unsupported atom {item!r} ({type(item)})") # Convert the SymPy expression to a Python function of the variables. drake_func = _lambdify(expr=x, args=sympy_vars) # Call the Python function using the Drake variables; this returns the # Drake symbolic expression. return drake_func(*drake_vars)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/symbolic/symbolic_py_monolith.cc
#include <map> #include <string> #include <fmt/format.h> #include "drake/bindings/pydrake/common/eigen_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/math_operators_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/bindings/pydrake/symbolic/symbolic_py_unapply.h" #include "drake/bindings/pydrake/symbolic_types_pybind.h" #include "drake/common/symbolic/decompose.h" #include "drake/common/symbolic/latex.h" #include "drake/common/symbolic/monomial_util.h" #include "drake/common/symbolic/replace_bilinear_terms.h" #include "drake/common/symbolic/trigonometric_polynomial.h" namespace drake { namespace pydrake { namespace internal { using std::map; using std::string; // TODO(eric.cousineau): Use py::self for operator overloads? void DefineSymbolicMonolith(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::symbolic; constexpr auto& doc = pydrake_doc.drake.symbolic; // TODO(m-chaturvedi) Add Pybind11 documentation for operator overloads, etc. py::class_<Variable> var_cls(m, "Variable", doc.Variable.doc); constexpr auto& var_doc = doc.Variable; py::enum_<Variable::Type>(var_cls, "Type") .value( "CONTINUOUS", Variable::Type::CONTINUOUS, var_doc.Type.CONTINUOUS.doc) .value("INTEGER", Variable::Type::INTEGER, var_doc.Type.INTEGER.doc) .value("BINARY", Variable::Type::BINARY, var_doc.Type.BINARY.doc) .value("BOOLEAN", Variable::Type::BOOLEAN, var_doc.Type.BOOLEAN.doc) .value("RANDOM_UNIFORM", Variable::Type::RANDOM_UNIFORM, var_doc.Type.RANDOM_UNIFORM.doc) .value("RANDOM_GAUSSIAN", Variable::Type::RANDOM_GAUSSIAN, var_doc.Type.RANDOM_GAUSSIAN.doc) .value("RANDOM_EXPONENTIAL", Variable::Type::RANDOM_EXPONENTIAL, var_doc.Type.RANDOM_EXPONENTIAL.doc); var_cls .def(py::init<const string&, Variable::Type>(), py::arg("name"), py::arg("type") = Variable::Type::CONTINUOUS, var_doc.ctor.doc_2args) .def("is_dummy", &Variable::is_dummy, var_doc.is_dummy.doc) .def("get_id", &Variable::get_id, var_doc.get_id.doc) .def("get_type", &Variable::get_type, var_doc.get_type.doc) .def("get_name", &Variable::get_name, var_doc.get_name.doc) .def("__str__", &Variable::to_string, var_doc.to_string.doc) .def("__repr__", [](const Variable& self) { return fmt::format( "Variable('{}', {})", self.get_name(), self.get_type()); }) .def("__hash__", [](const Variable& self) { return std::hash<Variable>{}(self); }) // Addition. .def(py::self + py::self) .def(py::self + double()) .def(double() + py::self) // Subtraction. .def(py::self - py::self) .def(py::self - double()) .def(double() - py::self) // Multiplication. .def(py::self * py::self) .def(py::self * double()) .def(double() * py::self) // Division. .def(py::self / py::self) .def(py::self / double()) .def(double() / py::self) // Pow. .def( "__pow__", [](const Variable& self, double other) { return pow(self, other); }, py::is_operator()) .def( "__pow__", [](const Variable& self, const Variable& other) { return pow(self, other); }, py::is_operator()) .def( "__pow__", [](const Variable& self, const Expression& other) { return pow(self, other); }, py::is_operator()) // We add `EqualTo` instead of `equal_to` to maintain consistency among // symbolic classes (Variable, Expression, Formula, Polynomial) on Python // side. This enables us to achieve polymorphism via ducktyping in Python. .def("EqualTo", &Variable::equal_to, var_doc.equal_to.doc) // Unary Plus. .def(+py::self) // Unary Minus. .def(-py::self) // LT(<). // Note that for `double < Variable` case, the reflected op ('>' in this // case) is called. For example, `1 < x` will return `x > 1`. .def(py::self < Expression()) .def(py::self < py::self) .def(py::self < double()) // LE(<=). .def(py::self <= Expression()) .def(py::self <= py::self) .def(py::self <= double()) // GT(>). .def(py::self > Expression()) .def(py::self > py::self) .def(py::self > double()) // GE(>=). .def(py::self >= Expression()) .def(py::self >= py::self) .def(py::self >= double()) // EQ(==). .def(py::self == Expression()) .def(py::self == py::self) .def(py::self == double()) // NE(!=). .def(py::self != Expression()) .def(py::self != py::self) .def(py::self != double()); internal::BindMathOperators<Variable>(&var_cls); DefCopyAndDeepCopy(&var_cls); // Bind the free function TaylorExpand. m.def( "TaylorExpand", [](const symbolic::Expression& f, const symbolic::Environment::map& a, int order) { return symbolic::TaylorExpand(f, symbolic::Environment(a), order); }, py::arg("f"), py::arg("a"), py::arg("order"), doc.TaylorExpand.doc); // Bind the free functions for Make(Vector|Matrix)(...)Variable. m // BR .def( "MakeMatrixVariable", [](int rows, int cols, const std::string& name, Variable::Type type) { return symbolic::MakeMatrixVariable(rows, cols, name, type); }, py::arg("rows"), py::arg("cols"), py::arg("name"), py::arg("type") = symbolic::Variable::Type::CONTINUOUS, doc.MakeMatrixVariable.doc_4args) .def( "MakeMatrixBinaryVariable", [](int rows, int cols, const std::string& name) { return symbolic::MakeMatrixBinaryVariable(rows, cols, name); }, py::arg("rows"), py::arg("cols"), py::arg("name"), doc.MakeMatrixBinaryVariable.doc_3args) .def( "MakeMatrixContinuousVariable", [](int rows, int cols, const std::string& name) { return symbolic::MakeMatrixContinuousVariable(rows, cols, name); }, py::arg("rows"), py::arg("cols"), py::arg("name"), doc.MakeMatrixContinuousVariable.doc_3args) .def( "MakeMatrixBooleanVariable", [](int rows, int cols, const std::string& name) { return symbolic::MakeMatrixBooleanVariable(rows, cols, name); }, py::arg("rows"), py::arg("cols"), py::arg("name"), doc.MakeMatrixBooleanVariable.doc_3args) .def( "MakeVectorVariable", [](int rows, const std::string& name, Variable::Type type) { return symbolic::MakeVectorVariable(rows, name, type); }, py::arg("rows"), py::arg("name"), py::arg("type") = symbolic::Variable::Type::CONTINUOUS, doc.MakeVectorVariable.doc_3args) .def( "MakeVectorBinaryVariable", [](int rows, const std::string& name) { return symbolic::MakeVectorBinaryVariable(rows, name); }, py::arg("rows"), py::arg("name"), doc.MakeVectorBinaryVariable.doc_2args) .def( "MakeVectorBooleanVariable", [](int rows, const std::string& name) { return symbolic::MakeVectorBooleanVariable(rows, name); }, py::arg("rows"), py::arg("name"), doc.MakeVectorBooleanVariable.doc_2args) .def( "MakeVectorContinuousVariable", [](int rows, const std::string& name) { return symbolic::MakeVectorContinuousVariable(rows, name); }, py::arg("rows"), py::arg("name"), doc.MakeVectorContinuousVariable.doc_2args); // TODO(m-chaturvedi) Add Pybind11 documentation for operator overloads, // etc. py::class_<Variables>(m, "Variables", doc.Variables.doc) .def(py::init<>(), doc.Variables.ctor.doc_0args) .def(py::init<const Eigen::Ref<const VectorX<Variable>>&>(), doc.Variables.ctor.doc_1args_vec) .def("size", &Variables::size, doc.Variables.size.doc) .def("__len__", &Variables::size, doc.Variables.size.doc) .def("empty", &Variables::empty, doc.Variables.empty.doc) .def("__str__", &Variables::to_string, doc.Variables.to_string.doc) .def("__repr__", [](const Variables& self) { return fmt::format("<Variables \"{}\">", self); }) .def("to_string", &Variables::to_string, doc.Variables.to_string.doc) .def("__hash__", [](const Variables& self) { return std::hash<Variables>{}(self); }) .def( "insert", [](Variables& self, const Variable& var) { self.insert(var); }, py::arg("var"), doc.Variables.insert.doc_1args_var) .def( "insert", [](Variables& self, const Variables& vars) { self.insert(vars); }, py::arg("vars"), doc.Variables.insert.doc_1args_vars) .def( "erase", [](Variables& self, const Variable& key) { return self.erase(key); }, py::arg("key"), doc.Variables.erase.doc_1args_key) .def( "erase", [](Variables& self, const Variables& vars) { return self.erase(vars); }, py::arg("vars"), doc.Variables.erase.doc_1args_vars) .def("include", &Variables::include, py::arg("key"), doc.Variables.include.doc) .def("__contains__", &Variables::include) .def("IsSubsetOf", &Variables::IsSubsetOf, py::arg("vars"), doc.Variables.IsSubsetOf.doc) .def("IsSupersetOf", &Variables::IsSupersetOf, py::arg("vars"), doc.Variables.IsSupersetOf.doc) .def("IsStrictSubsetOf", &Variables::IsStrictSubsetOf, py::arg("vars"), doc.Variables.IsStrictSubsetOf.doc) .def("IsStrictSupersetOf", &Variables::IsStrictSupersetOf, py::arg("vars"), doc.Variables.IsStrictSupersetOf.doc) .def("EqualTo", [](const Variables& self, const Variables& vars) { return self == vars; }) .def( "__iter__", [](const Variables& vars) { return py::make_iterator(vars.begin(), vars.end()); }, // Keep alive, reference: `return` keeps `self` alive py::keep_alive<0, 1>()) .def(py::self == py::self) .def(py::self < py::self) .def(py::self + py::self) .def(py::self + Variable()) .def(Variable() + py::self) .def(py::self - py::self) .def(py::self - Variable()); m.def( "intersect", [](const Variables& vars1, const Variables& vars2) { return intersect(vars1, vars2); }, py::arg("vars1"), py::arg("vars2"), doc.intersect.doc); { constexpr auto& cls_doc = doc.ExpressionKind; py::enum_<ExpressionKind>(m, "ExpressionKind", doc.ExpressionKind.doc) .value("Constant", ExpressionKind::Constant, cls_doc.Constant.doc) .value("Var", ExpressionKind::Var, cls_doc.Var.doc) .value("Add", ExpressionKind::Add, cls_doc.Add.doc) .value("Mul", ExpressionKind::Mul, cls_doc.Mul.doc) .value("Div", ExpressionKind::Div, cls_doc.Div.doc) .value("Log", ExpressionKind::Log, cls_doc.Log.doc) .value("Abs", ExpressionKind::Abs, cls_doc.Abs.doc) .value("Exp", ExpressionKind::Exp, cls_doc.Exp.doc) .value("Sqrt", ExpressionKind::Sqrt, cls_doc.Sqrt.doc) .value("Pow", ExpressionKind::Pow, cls_doc.Pow.doc) .value("Sin", ExpressionKind::Sin, cls_doc.Sin.doc) .value("Cos", ExpressionKind::Cos, cls_doc.Cos.doc) .value("Tan", ExpressionKind::Tan, cls_doc.Tan.doc) .value("Asin", ExpressionKind::Asin, cls_doc.Asin.doc) .value("Acos", ExpressionKind::Acos, cls_doc.Acos.doc) .value("Atan", ExpressionKind::Atan, cls_doc.Atan.doc) .value("Atan2", ExpressionKind::Atan2, cls_doc.Atan2.doc) .value("Sinh", ExpressionKind::Sinh, cls_doc.Sinh.doc) .value("Cosh", ExpressionKind::Cosh, cls_doc.Cosh.doc) .value("Tanh", ExpressionKind::Tanh, cls_doc.Tanh.doc) .value("Min", ExpressionKind::Min, cls_doc.Min.doc) .value("Max", ExpressionKind::Max, cls_doc.Max.doc) .value("Ceil", ExpressionKind::Ceil, cls_doc.Ceil.doc) .value("Floor", ExpressionKind::Floor, cls_doc.Floor.doc) .value("IfThenElse", ExpressionKind::IfThenElse, cls_doc.IfThenElse.doc) .value("NaN", ExpressionKind::NaN, cls_doc.NaN.doc) .value("UninterpretedFunction", ExpressionKind::UninterpretedFunction, cls_doc.UninterpretedFunction.doc); } // TODO(m-chaturvedi) Add Pybind11 documentation for operator overloads, etc. py::class_<Expression> expr_cls(m, "Expression", doc.Expression.doc); expr_cls.def(py::init<>(), doc.Expression.ctor.doc_0args) .def(py::init<double>(), py::arg("constant"), doc.Expression.ctor.doc_1args_constant) .def(py::init<const Variable&>(), py::arg("var"), doc.Expression.ctor.doc_1args_var) .def("__str__", &Expression::to_string, doc.Expression.to_string.doc) .def("__repr__", [](const Expression& self) { return fmt::format("<Expression \"{}\">", self.to_string()); }) .def( "__copy__", [](const Expression& self) -> Expression { return self; }) .def("get_kind", &Expression::get_kind, doc.Expression.get_kind.doc) .def("to_string", &Expression::to_string, doc.Expression.to_string.doc) .def( "Unapply", [m](const symbolic::Expression& e) { return internal::Unapply(m, e); }, internal::kUnapplyExpressionDoc) .def("Expand", &Expression::Expand, doc.Expression.Expand.doc) .def( "Evaluate", [](const Expression& self, const Environment::map& env, RandomGenerator* generator) { return self.Evaluate(Environment{env}, generator); }, py::arg("env") = Environment::map{}, py::arg("generator") = nullptr, doc.Expression.Evaluate.doc_2args) .def( "Evaluate", [](const Expression& self, RandomGenerator* generator) { return self.Evaluate(generator); }, py::arg("generator"), doc.Expression.Evaluate.doc_1args) .def( "EvaluatePartial", [](const Expression& self, const Environment::map& env) { return self.EvaluatePartial(Environment{env}); }, py::arg("env"), doc.Expression.EvaluatePartial.doc) .def("GetVariables", &Expression::GetVariables, doc.Expression.GetVariables.doc) .def( "Substitute", [](const Expression& self, const Variable& var, const Expression& e) { return self.Substitute(var, e); }, py::arg("var"), py::arg("e"), doc.Expression.Substitute.doc_2args) .def( "Substitute", [](const Expression& self, const Substitution& s) { return self.Substitute(s); }, py::arg("s"), doc.Expression.Substitute.doc_1args) .def("EqualTo", &Expression::EqualTo, doc.Expression.EqualTo.doc) .def("is_polynomial", &Expression::is_polynomial, doc.Expression.is_polynomial.doc) // Addition .def(py::self + py::self) .def(py::self + Variable()) .def(py::self + double()) .def(Variable() + py::self) .def(double() + py::self) .def(py::self += py::self) .def(py::self += Variable()) .def(py::self += double()) // Subtraction. .def(py::self - py::self) .def(py::self - Variable()) .def(py::self - double()) .def(Variable() - py::self) .def(double() - py::self) .def(py::self -= py::self) .def(py::self -= Variable()) .def(py::self -= double()) // Multiplication. .def(py::self * py::self) .def(py::self * Variable()) .def(py::self * double()) .def(Variable() * py::self) .def(double() * py::self) .def(py::self *= py::self) .def(py::self *= Variable()) .def(py::self *= double()) // Division. .def(py::self / py::self) .def(py::self / Variable()) .def(py::self / double()) .def(Variable() / py::self) .def(double() / py::self) .def(py::self /= py::self) .def(py::self /= Variable()) .def(py::self /= double()) // Pow. .def("__pow__", [](const Expression& self, const double other) { return pow(self, other); }) .def("__pow__", [](const Expression& self, const Variable& other) { return pow(self, other); }) .def("__pow__", [](const Expression& self, const Expression& other) { return pow(self, other); }) // Unary Plus. .def(+py::self) // Unary Minus. .def(-py::self) // LT(<). // // Note that for `double < Expression` case, the reflected op ('>' in this // case) is called. For example, `1 < x * y` will return `x * y > 1`. .def(py::self < py::self) .def(py::self < Variable()) .def(py::self < double()) // LE(<=). .def(py::self <= py::self) .def(py::self <= Variable()) .def(py::self <= double()) // GT(>). .def(py::self > py::self) .def(py::self > Variable()) .def(py::self > double()) // GE(>=). .def(py::self >= py::self) .def(py::self >= Variable()) .def(py::self >= double()) // EQ(==). .def(py::self == py::self) .def(py::self == Variable()) .def(py::self == double()) // NE(!=) .def(py::self != py::self) .def(py::self != Variable()) .def(py::self != double()) .def("Differentiate", &Expression::Differentiate, py::arg("x"), doc.Expression.Differentiate.doc) .def("Jacobian", &Expression::Jacobian, py::arg("vars"), doc.Expression.Jacobian.doc); // TODO(eric.cousineau): Clean this overload stuff up (#15041). pydrake::internal::BindMathOperators<Expression>(&expr_cls); pydrake::internal::BindMathOperators<Expression>(&m); DefCopyAndDeepCopy(&expr_cls); m.def("if_then_else", &symbolic::if_then_else, py::arg("f_cond"), py::arg("e_then"), py::arg("e_else"), doc.if_then_else.doc); m.def("uninterpreted_function", &symbolic::uninterpreted_function, py::arg("name"), py::arg("arguments"), doc.uninterpreted_function.doc); m.def( "Jacobian", [](const Eigen::Ref<const VectorX<Expression>>& f, const Eigen::Ref<const VectorX<Variable>>& vars) { return Jacobian(f, vars); }, py::arg("f"), py::arg("vars"), doc.Jacobian.doc); m.def( "IsAffine", [](const Eigen::Ref<const MatrixX<Expression>>& M, const Variables& vars) { return IsAffine(M, vars); }, py::arg("m"), py::arg("vars"), doc.IsAffine.doc_2args); m.def( "IsAffine", [](const Eigen::Ref<const MatrixX<Expression>>& M) { return IsAffine(M); }, py::arg("m"), doc.IsAffine.doc_1args); m.def( "Evaluate", [](const MatrixX<Expression>& M, const Environment::map& env, RandomGenerator* random_generator) { return Evaluate(M, Environment{env}, random_generator); }, py::arg("m"), py::arg("env") = Environment::map{}, py::arg("generator") = nullptr, doc.Evaluate.doc_expression); m.def("GetVariableVector", &symbolic::GetVariableVector, py::arg("expressions"), doc.GetVariableVector.doc); m.def( "Substitute", [](const MatrixX<Expression>& M, const Substitution& subst) { return Substitute(M, subst); }, py::arg("m"), py::arg("subst"), doc.Substitute.doc_2args); m.def( "Substitute", [](const MatrixX<Expression>& M, const Variable& var, const Expression& e) { return Substitute(M, var, e); }, py::arg("m"), py::arg("var"), py::arg("e"), doc.Substitute.doc_3args); { using Enum = SinCosSubstitutionType; constexpr auto& enum_doc = doc.SinCosSubstitutionType; py::enum_<Enum> enum_py(m, "SinCosSubstitutionType", enum_doc.doc); enum_py // BR .value("kAngle", Enum::kAngle, enum_doc.kAngle.doc) .value("kHalfAnglePreferSin", Enum::kHalfAnglePreferSin, enum_doc.kHalfAnglePreferSin.doc) .value("kHalfAnglePreferCos", Enum::kHalfAnglePreferCos, enum_doc.kHalfAnglePreferCos.doc); } py::class_<SinCos>(m, "SinCos", doc.SinCos.doc) .def(py::init<Variable, Variable, SinCosSubstitutionType>(), py::arg("s"), py::arg("c"), py::arg("type") = SinCosSubstitutionType::kAngle, doc.SinCos.ctor.doc) .def_readwrite("s", &SinCos::s, doc.SinCos.s.doc) .def_readwrite("c", &SinCos::c, doc.SinCos.c.doc) .def_readwrite("type", &SinCos::type, doc.SinCos.type.doc); m.def( "Substitute", [](const Expression& e, const SinCosSubstitution& subs) { return Substitute(e, subs); }, py::arg("e"), py::arg("subs"), doc.Substitute.doc_sincos); m.def( "Substitute", [](const MatrixX<Expression>& M, const SinCosSubstitution& subs) { return Substitute(M, subs); }, py::arg("m"), py::arg("subs"), doc.Substitute.doc_sincos_matrix); m.def( "SubstituteStereographicProjection", [](const symbolic::Polynomial& e, const std::vector<SinCos>& sin_cos, const VectorX<symbolic::Variable>& t) { return symbolic::SubstituteStereographicProjection(e, sin_cos, t); }, py::arg("e"), py::arg("sin_cos"), py::arg("t"), doc.SubstituteStereographicProjection.doc); { constexpr auto& cls_doc = doc.FormulaKind; py::enum_<FormulaKind>(m, "FormulaKind", doc.FormulaKind.doc) // `True` and `False` are reserved keywords as of Python3. .value("False_", FormulaKind::False, cls_doc.False.doc) .value("True_", FormulaKind::True, cls_doc.True.doc) .value("Var", FormulaKind::Var, cls_doc.Var.doc) .value("Eq", FormulaKind::Eq, cls_doc.Eq.doc) .value("Neq", FormulaKind::Neq, cls_doc.Neq.doc) .value("Gt", FormulaKind::Gt, cls_doc.Gt.doc) .value("Geq", FormulaKind::Geq, cls_doc.Geq.doc) .value("Lt", FormulaKind::Lt, cls_doc.Lt.doc) .value("Leq", FormulaKind::Leq, cls_doc.Leq.doc) .value("And", FormulaKind::And, cls_doc.And.doc) .value("Or", FormulaKind::Or, cls_doc.Or.doc) .value("Not", FormulaKind::Not, cls_doc.Not.doc) .value("Forall", FormulaKind::Forall, cls_doc.Forall.doc) .value("Isnan", FormulaKind::Isnan, cls_doc.Isnan.doc) .value("PositiveSemidefinite", FormulaKind::PositiveSemidefinite, cls_doc.PositiveSemidefinite.doc); } py::class_<Formula> formula_cls(m, "Formula", doc.Formula.doc); formula_cls.def(py::init<>(), doc.Formula.ctor.doc_0args) .def(py::init<bool>(), py::arg("value").noconvert(), doc.Formula.ctor.doc_1args_value) .def(py::init<const Variable&>(), py::arg("var"), doc.Formula.ctor.doc_1args_var) .def( "Unapply", [m](const symbolic::Formula& f) { return internal::Unapply(m, f); }, internal::kUnapplyFormulaDoc) .def("get_kind", &Formula::get_kind, doc.Formula.get_kind.doc) .def("GetFreeVariables", &Formula::GetFreeVariables, doc.Formula.GetFreeVariables.doc) .def("EqualTo", &Formula::EqualTo, doc.Formula.EqualTo.doc) .def( "Evaluate", [](const Formula& self, const Environment::map& env) { return self.Evaluate(Environment{env}); }, py::arg("env") = Environment::map{}, doc.Formula.Evaluate.doc_2args) .def( "Substitute", [](const Formula& self, const Variable& var, const Expression& e) { return self.Substitute(var, e); }, py::arg("var"), py::arg("e"), doc.Formula.Substitute.doc_2args) .def( "Substitute", [](const Formula& self, const Variable& var1, const Variable& var2) { return self.Substitute(var1, var2); }, py::arg("var"), py::arg("e"), doc.Formula.Substitute.doc_2args) .def( "Substitute", [](const Formula& self, const Variable& var, const double c) { return self.Substitute(var, c); }, py::arg("var"), py::arg("e"), doc.Formula.Substitute.doc_2args) .def( "Substitute", [](const Formula& self, const Substitution& s) { return self.Substitute(s); }, py::arg("s"), doc.Formula.Substitute.doc_1args) .def("to_string", &Formula::to_string, doc.Formula.to_string.doc) .def("__str__", &Formula::to_string) .def("__repr__", [](const Formula& self) { return fmt::format("<Formula \"{}\">", self.to_string()); }) .def("__eq__", [](const Formula& self, const Formula& other) { return self.EqualTo(other); }) .def("__ne__", [](const Formula& self, const Formula& other) { return !self.EqualTo(other); }) .def("__hash__", [](const Formula& self) { return std::hash<Formula>{}(self); }) // `True` and `False` are reserved keywords as of Python3. .def_static("True_", &Formula::True, doc.FormulaTrue.doc) .def_static("False_", &Formula::False, doc.FormulaFalse.doc) .def("__nonzero__", [](const Formula&) { throw std::runtime_error( "You should not call `__bool__` / `__nonzero__` on `Formula`. " "If you are trying to make a map with `Variable`, `Expression`, " "or `Polynomial` as keys (and then access the map in Python), " "please use pydrake.common.containers.EqualToDict`."); }); formula_cls.attr("__bool__") = formula_cls.attr("__nonzero__"); py::implicitly_convertible<bool, Formula>(); py::implicitly_convertible<Variable, Formula>(); // Cannot overload logical operators: http://stackoverflow.com/a/471561 // Defining custom function for clarity. // Could use bitwise operators: // https://docs.python.org/2/library/operator.html#operator.__and__ // However, this may reduce clarity and introduces constraints on order of // operations. m // Hide AND and OR to permit us to make it accept 1 or more arguments in // Python (and not have to handle type safety within C++). .def("__logical_and", [](const Formula& a, const Formula& b) { return a && b; }) .def("__logical_or", [](const Formula& a, const Formula& b) { return a || b; }) .def("logical_not", [](const Formula& a) { return !a; }); m.def("isnan", &symbolic::isnan, py::arg("e"), doc.isnan.doc); m.def("forall", &symbolic::forall, py::arg("vars"), py::arg("f"), doc.forall.doc); m.def("positive_semidefinite", overload_cast_explicit<Formula, const Eigen::Ref<const MatrixX<Expression>>&>( &symbolic::positive_semidefinite), py::arg("m"), doc.positive_semidefinite.doc_1args_m); // TODO(m-chaturvedi) Add Pybind11 documentation for operator overloads, etc. py::class_<Monomial>(m, "Monomial", doc.Monomial.doc) .def(py::init<>(), doc.Monomial.ctor.doc_0args) .def(py::init<const Variable&>(), py::arg("var"), doc.Monomial.ctor.doc_1args_var) .def(py::init<const Variable&, int>(), py::arg("var"), py::arg("exponent"), doc.Monomial.ctor.doc_2args_var_exponent) .def(py::init<const map<Variable, int>&>(), py::arg("powers"), doc.Monomial.ctor.doc_1args_powers) .def(py::init<const Eigen::Ref<const VectorX<Variable>>&, const Eigen::Ref<const Eigen::VectorXi>&>(), py::arg("vars"), py::arg("exponents"), doc.Monomial.ctor.doc_2args_vars_exponents) .def("degree", &Monomial::degree, py::arg("v"), doc.Monomial.degree.doc) .def("total_degree", &Monomial::total_degree, doc.Monomial.total_degree.doc) .def(py::self * py::self) .def(py::self *= py::self) .def(py::self * double{}) .def(double{} * py::self) .def(py::self * Expression()) .def(Expression() * py::self) .def(py::self + Expression()) .def(Expression() + py::self) .def(py::self - Expression()) .def(Expression() - py::self) .def(py::self / Expression()) .def(Expression() / py::self) .def(py::self == py::self) .def(py::self != py::self) .def("__hash__", [](const Monomial& self) { return std::hash<Monomial>{}(self); }) .def(py::self != py::self) .def("__str__", [](const Monomial& self) { return fmt::format("{}", self); }) .def("__repr__", [](const Monomial& self) { return fmt::format("<Monomial \"{}\">", self); }) .def( "EqualTo", [](const Monomial& self, const Monomial& monomial) { return self == monomial; }) .def("GetVariables", &Monomial::GetVariables, doc.Monomial.GetVariables.doc) .def("get_powers", &Monomial::get_powers, py_rvp::reference_internal, doc.Monomial.get_powers.doc) .def("ToExpression", &Monomial::ToExpression, doc.Monomial.ToExpression.doc) .def( "Evaluate", [](const Monomial& self, const Environment::map& env) { return self.Evaluate(Environment{env}); }, py::arg("env"), doc.Monomial.Evaluate.doc_1args) .def( "Evaluate", [](const Monomial& self, const Eigen::Ref<const VectorX<symbolic::Variable>>& vars, const Eigen::Ref<const Eigen::MatrixXd>& vars_values) { return self.Evaluate(vars, vars_values); }, py::arg("vars"), py::arg("vars_values"), doc.Monomial.Evaluate.doc_2args) .def( "EvaluatePartial", [](const Monomial& self, const Environment::map& env) { return self.EvaluatePartial(Environment{env}); }, py::arg("env"), doc.Monomial.EvaluatePartial.doc) .def("pow_in_place", &Monomial::pow_in_place, py_rvp::reference_internal, py::arg("p"), doc.Monomial.pow_in_place.doc) .def("__pow__", [](const Monomial& self, const int p) { return pow(self, p); }); m // BR .def( "MonomialBasis", [](const Eigen::Ref<const VectorX<Variable>>& vars, const int degree) { return MonomialBasis(Variables{vars}, degree); }, py::arg("vars"), py::arg("degree"), doc.MonomialBasis.doc_2args_vars_degree) .def( "MonomialBasis", [](const Variables& vars, const int degree) { return MonomialBasis(vars, degree); }, py::arg("vars"), py::arg("degree"), doc.MonomialBasis.doc_2args_vars_degree) .def( "MonomialBasis", [](const std::unordered_map<Variables, int>& vars_degree) { return MonomialBasis(vars_degree); }, py::arg("vars_degree"), doc.MonomialBasis.doc_1args_variables_degree) .def("EvenDegreeMonomialBasis", &symbolic::EvenDegreeMonomialBasis, py::arg("vars"), py::arg("degree"), doc.EvenDegreeMonomialBasis.doc) .def("OddDegreeMonomialBasis", &symbolic::OddDegreeMonomialBasis, py::arg("vars"), py::arg("degree"), doc.OddDegreeMonomialBasis.doc) .def("CalcMonomialBasisOrderUpToOne", &symbolic::CalcMonomialBasisOrderUpToOne, py::arg("x"), py::arg("sort_monomial") = false, doc.CalcMonomialBasisOrderUpToOne.doc); using symbolic::Polynomial; // TODO(m-chaturvedi) Add Pybind11 documentation for operator overloads, etc. py::class_<Polynomial> polynomial_cls(m, "Polynomial", doc.Polynomial.doc); polynomial_cls.def(py::init<>(), doc.Polynomial.ctor.doc_0args) .def(py::init<Polynomial::MapType>(), py::arg("map"), doc.Polynomial.ctor.doc_1args_map) .def(py::init<const Monomial&>(), py::arg("m"), doc.Polynomial.ctor.doc_1args_m) .def(py::init<const Expression&>(), py::arg("e"), doc.Polynomial.ctor.doc_1args_e) .def(py::init<const Expression&, const Variables&>(), py::arg("e"), py::arg("indeterminates"), doc.Polynomial.ctor.doc_2args_e_indeterminates) .def(py::init([](const Expression& e, const Eigen::Ref<const VectorX<Variable>>& vars) { return Polynomial{e, Variables{vars}}; }), py::arg("e"), py::arg("indeterminates"), doc.Polynomial.ctor.doc_2args_e_indeterminates) .def("indeterminates", &Polynomial::indeterminates, doc.Polynomial.indeterminates.doc) .def("decision_variables", &Polynomial::decision_variables, doc.Polynomial.decision_variables.doc) .def("SetIndeterminates", &Polynomial::SetIndeterminates, py::arg("new_indeterminates"), doc.Polynomial.SetIndeterminates.doc) .def("Degree", &Polynomial::Degree, py::arg("v"), doc.Polynomial.Degree.doc) .def("TotalDegree", &Polynomial::TotalDegree, doc.Polynomial.TotalDegree.doc) .def("monomial_to_coefficient_map", &Polynomial::monomial_to_coefficient_map, doc.Polynomial.monomial_to_coefficient_map.doc) .def("ToExpression", &Polynomial::ToExpression, doc.Polynomial.ToExpression.doc) .def("Differentiate", &Polynomial::Differentiate, py::arg("x"), doc.Polynomial.Differentiate.doc) .def( "Integrate", [](const Polynomial& self, const Variable& var) { return self.Integrate(var); }, py::arg("x"), doc.Polynomial.Integrate.doc_1args) .def( "Integrate", [](const Polynomial& self, const Variable& var, double a, double b) { return self.Integrate(var, a, b); }, py::arg("x"), py::arg("a"), py::arg("b"), doc.Polynomial.Integrate.doc_3args) .def("AddProduct", &Polynomial::AddProduct, py::arg("coeff"), py::arg("m"), doc.Polynomial.AddProduct.doc) .def("Expand", &Polynomial::Expand, doc.Polynomial.Expand.doc) .def("SubstituteAndExpand", &Polynomial::SubstituteAndExpand, py::arg("indeterminate_substitution"), py::arg("substitutions_cached_data") = std::nullopt, doc.Polynomial.SubstituteAndExpand.doc) .def("RemoveTermsWithSmallCoefficients", &Polynomial::RemoveTermsWithSmallCoefficients, py::arg("coefficient_tol"), doc.Polynomial.RemoveTermsWithSmallCoefficients.doc) .def("IsEven", &Polynomial::IsEven, doc.Polynomial.IsEven.doc) .def("IsOdd", &Polynomial::IsOdd, doc.Polynomial.IsOdd.doc) .def("Roots", &Polynomial::Roots, doc.Polynomial.Roots.doc) .def("CoefficientsAlmostEqual", &Polynomial::CoefficientsAlmostEqual, py::arg("p"), py::arg("tolerance"), doc.Polynomial.CoefficientsAlmostEqual.doc) .def(py::self + py::self) .def(py::self + Monomial()) .def(Monomial() + py::self) .def(py::self + double()) .def(double() + py::self) .def(py::self + Variable()) .def(Variable() + py::self) .def(py::self + Expression()) .def(Expression() + py::self) .def(py::self - py::self) .def(py::self - Monomial()) .def(Monomial() - py::self) .def(py::self - double()) .def(double() - py::self) .def(py::self - Variable()) .def(Variable() - py::self) .def(py::self - Expression()) .def(Expression() - py::self) .def(py::self * py::self) .def(py::self * Monomial()) .def(Monomial() * py::self) .def(py::self * double()) .def(double() * py::self) .def(py::self * Variable()) .def(Variable() * py::self) .def(py::self * Expression()) .def(Expression() * py::self) .def(-py::self) .def(py::self / double()) .def(double() / py::self) .def(py::self / Expression()) .def(Expression() / py::self) .def("EqualTo", &Polynomial::EqualTo, doc.Polynomial.EqualTo.doc) .def(py::self == py::self) .def(py::self != py::self) .def("__hash__", [](const Polynomial& self) { return std::hash<Polynomial>{}(self); }) .def("__str__", [](const Polynomial& self) { return fmt::format("{}", self); }) .def("__repr__", [](const Polynomial& self) { return fmt::format("<Polynomial \"{}\">", self); }) .def("__pow__", [](const Polynomial& self, const int n) { return pow(self, n); }) .def( "Evaluate", [](const Polynomial& self, const Environment::map& env) { return self.Evaluate(Environment{env}); }, py::arg("env"), doc.Polynomial.Evaluate.doc) // TODO(Eric.Cousineau): add python binding for symbolic::Environment. .def( "EvaluatePartial", [](const Polynomial& self, const Environment::map& env) { return self.EvaluatePartial(Environment{env}); }, py::arg("env"), doc.Polynomial.EvaluatePartial.doc_1args) .def( "EvaluatePartial", [](const Polynomial& self, const Variable& var, double c) { return self.EvaluatePartial(var, c); }, py::arg("var"), py::arg("c"), doc.Polynomial.EvaluatePartial.doc_2args) .def( "EvaluateIndeterminates", [](const Polynomial& self, const Eigen::Ref<const VectorX<symbolic::Variable>>& indeterminates, const Eigen::Ref<const Eigen::MatrixXd>& indeterminates_values) { return self.EvaluateIndeterminates( indeterminates, indeterminates_values); }, py::arg("indeterminates"), py::arg("indeterminates_values"), doc.Polynomial.EvaluateIndeterminates.doc) .def( "EvaluateWithAffineCoefficients", [](const symbolic::Polynomial& self, const Eigen::Ref<const VectorX<symbolic::Variable>>& indeterminates, const Eigen::Ref<const Eigen::MatrixXd>& indeterminates_values) { Eigen::MatrixXd A; VectorX<symbolic::Variable> decision_variables; Eigen::VectorXd b; self.EvaluateWithAffineCoefficients(indeterminates, indeterminates_values, &A, &decision_variables, &b); return std::make_tuple(A, decision_variables, b); }, py::arg("indeterminates"), py::arg("indeterminates_values"), doc.Polynomial.EvaluateWithAffineCoefficients.doc) .def( "Jacobian", [](const Polynomial& p, const Eigen::Ref<const VectorX<Variable>>& vars) { return p.Jacobian(vars); }, py::arg("vars"), doc.Polynomial.Jacobian.doc); py::class_<Polynomial::SubstituteAndExpandCacheData>(m, "SubstituteAndExpandCacheData", doc.Polynomial.SubstituteAndExpandCacheData.doc) .def(py::init<>()) .def("get_data", &Polynomial::SubstituteAndExpandCacheData::get_data, py_rvp::reference); // Bind CalcPolynomialWLowerTriangularPart m.def( "CalcPolynomialWLowerTriangularPart", [](const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis, const Eigen::Ref<const Eigen::VectorXd>& gram_lower) { return CalcPolynomialWLowerTriangularPart(monomial_basis, gram_lower); }, py::arg("monomial_basis"), py::arg("gram_lower"), doc.CalcPolynomialWLowerTriangularPart.doc) .def( "CalcPolynomialWLowerTriangularPart", [](const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis, const Eigen::Ref<const VectorX<symbolic::Variable>>& gram_lower) { return CalcPolynomialWLowerTriangularPart( monomial_basis, gram_lower); }, py::arg("monomial_basis"), py::arg("gram_lower"), doc.CalcPolynomialWLowerTriangularPart.doc) .def( "CalcPolynomialWLowerTriangularPart", [](const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis, const Eigen::Ref<const VectorX<symbolic::Expression>>& gram_lower) { return CalcPolynomialWLowerTriangularPart( monomial_basis, gram_lower); }, py::arg("monomial_basis"), py::arg("gram_lower"), doc.CalcPolynomialWLowerTriangularPart.doc); py::class_<RationalFunction> rat_fun_cls( m, "RationalFunction", doc.RationalFunction.doc); rat_fun_cls.def(py::init<>(), doc.RationalFunction.ctor.doc_0args) .def(py::init<Polynomial, Polynomial>(), py::arg("numerator"), py::arg("denominator"), doc.RationalFunction.ctor.doc_2args_numerator_denominator) .def(py::init<const Polynomial&>(), py::arg("p"), doc.RationalFunction.ctor.doc_1args_p) .def(py::init<const Monomial&>(), py::arg("m"), doc.RationalFunction.ctor.doc_1args_m) .def(py::init<double>(), py::arg("c"), doc.RationalFunction.ctor.doc_1args_c) .def(py::init<>(), doc.RationalFunction.ctor.doc_0args) .def("numerator", &RationalFunction::numerator, doc.RationalFunction.numerator.doc) .def("denominator", &RationalFunction::denominator, doc.RationalFunction.denominator.doc) .def("SetIndeterminates", &RationalFunction::SetIndeterminates, py::arg("new_indeterminates"), doc.RationalFunction.SetIndeterminates.doc) .def("__str__", [](const RationalFunction& self) { return fmt::format("{}", self); }) .def("__repr__", [](const RationalFunction& self) { return fmt::format("<RationalFunction \"{}\">", self); }) .def( "Evaluate", [](const RationalFunction& self, const Environment::map& env) { return self.Evaluate(Environment{env}); }, py::arg("env"), doc.RationalFunction.Evaluate.doc) .def("ToExpression", &RationalFunction::ToExpression, doc.RationalFunction.ToExpression.doc) .def("EqualTo", &RationalFunction::EqualTo, py::arg("f"), doc.RationalFunction.EqualTo.doc) .def(-py::self) // Addition .def(py::self + py::self) .def(py::self + double()) .def(double() + py::self) .def(py::self + Polynomial()) .def(Polynomial() + py::self) .def(py::self + Monomial()) .def(Monomial() + py::self) // Subtraction .def(py::self - py::self) .def(py::self - double()) .def(double() - py::self) .def(py::self - Polynomial()) .def(Polynomial() - py::self) .def(py::self - Monomial()) .def(Monomial() - py::self) // Multiplication .def(py::self * py::self) .def(py::self * double()) .def(double() * py::self) .def(py::self * Polynomial()) .def(Polynomial() * py::self) .def(py::self * Monomial()) .def(Monomial() * py::self) // Division .def(py::self / py::self) .def(py::self / double()) .def(double() / py::self) .def(py::self / Polynomial()) .def(Polynomial() / py::self) .def(py::self / Monomial()) .def(Monomial() / py::self) // Logical comparison .def(py::self == py::self) .def(py::self != py::self); m.def( "Evaluate", [](const MatrixX<Polynomial>& M, const Environment::map& env) { return Evaluate(M, Environment{env}); }, py::arg("m"), py::arg("env"), doc.Evaluate.doc_polynomial); m.def( "Jacobian", [](const Eigen::Ref<const VectorX<Polynomial>>& f, const Eigen::Ref<const VectorX<Variable>>& vars) { return Jacobian(f, vars); }, py::arg("f"), py::arg("vars"), doc.Jacobian.doc_polynomial); m.def("ToLatex", overload_cast_explicit<std::string, const Expression&, int>(&ToLatex), py::arg("e"), py::arg("precision") = 3, doc.ToLatex.doc_expression); m.def("ToLatex", overload_cast_explicit<std::string, const Formula&, int>(&ToLatex), py::arg("f"), py::arg("precision") = 3, doc.ToLatex.doc_formula); m.def( "ToLatex", [](const MatrixX<Expression>& M, int precision) { return ToLatex(M, precision); }, py::arg("M"), py::arg("precision") = 3, doc.ToLatex.doc_matrix); m.def( "ToLatex", [](const MatrixX<double>& M, int precision) { return ToLatex(M, precision); }, py::arg("M"), py::arg("precision") = 3, doc.ToLatex.doc_matrix); // We have this line because pybind11 does not permit transitive // conversions. See // https://github.com/pybind/pybind11/blob/289e5d9cc2a4545d832d3c7fb50066476bce3c1d/include/pybind11/pybind11.h#L1629. py::implicitly_convertible<int, drake::symbolic::Expression>(); py::implicitly_convertible<double, drake::symbolic::Expression>(); py::implicitly_convertible<drake::symbolic::Variable, drake::symbolic::Expression>(); py::implicitly_convertible<drake::symbolic::Monomial, drake::symbolic::Polynomial>(); // Bind the free functions in symbolic/decompose.h m // BR .def( "DecomposeLinearExpressions", [](const Eigen::Ref<const VectorX<symbolic::Expression>>& expressions, const Eigen::Ref<const VectorX<Variable>>& vars) { Eigen::MatrixXd M(expressions.rows(), vars.rows()); symbolic::DecomposeLinearExpressions(expressions, vars, &M); return M; }, py::arg("expressions"), py::arg("vars"), doc.DecomposeLinearExpressions.doc) .def( "DecomposeAffineExpressions", [](const Eigen::Ref<const VectorX<symbolic::Expression>>& expressions, const Eigen::Ref<const VectorX<symbolic::Variable>>& vars) { Eigen::MatrixXd M(expressions.rows(), vars.rows()); Eigen::VectorXd v(expressions.rows()); symbolic::DecomposeAffineExpressions(expressions, vars, &M, &v); return std::make_pair(M, v); }, py::arg("expressions"), py::arg("vars"), doc.DecomposeAffineExpressions.doc_4args_expressions_vars_M_v) .def( "ExtractVariablesFromExpression", [](const symbolic::Expression& e) { return symbolic::ExtractVariablesFromExpression(e); }, py::arg("e"), doc.ExtractVariablesFromExpression.doc_1args_e) .def( "ExtractVariablesFromExpression", [](const Eigen::Ref<const VectorX<symbolic::Expression>>& expressions) { return symbolic::ExtractVariablesFromExpression(expressions); }, py::arg("expressions"), doc.ExtractVariablesFromExpression.doc_1args_expressions) .def( "DecomposeQuadraticPolynomial", [](const symbolic::Polynomial& poly, const std::unordered_map<symbolic::Variable::Id, int>& map_var_to_index) { const int num_vars = map_var_to_index.size(); Eigen::MatrixXd Q(num_vars, num_vars); Eigen::VectorXd b(num_vars); double c; symbolic::DecomposeQuadraticPolynomial( poly, map_var_to_index, &Q, &b, &c); return std::make_tuple(Q, b, c); }, py::arg("poly"), py::arg("map_var_to_index"), doc.DecomposeQuadraticPolynomial.doc) .def( "DecomposeAffineExpressions", [](const Eigen::Ref<const VectorX<symbolic::Expression>>& v) { Eigen::MatrixXd A; Eigen::VectorXd b; VectorX<Variable> vars; symbolic::DecomposeAffineExpressions(v, &A, &b, &vars); return std::make_tuple(A, b, vars); }, py::arg("v"), doc.DecomposeAffineExpressions.doc_4args_v_A_b_vars) .def( "DecomposeAffineExpression", [](const symbolic::Expression& e, const std::unordered_map<symbolic::Variable::Id, int>& map_var_to_index) { Eigen::RowVectorXd coeffs(map_var_to_index.size()); double constant_term; symbolic::DecomposeAffineExpression( e, map_var_to_index, &coeffs, &constant_term); return std::make_pair(coeffs, constant_term); }, py::arg("e"), py::arg("map_var_to_index"), doc.DecomposeAffineExpression.doc) .def("DecomposeLumpedParameters", &DecomposeLumpedParameters, py::arg("f"), py::arg("parameters"), doc.DecomposeLumpedParameters.doc) .def("DecomposeL2NormExpression", &DecomposeL2NormExpression, py::arg("e"), py::arg("psd_tol") = 1e-8, py::arg("coefficient_tol") = 1e-8, doc.DecomposeL2NormExpression.doc); // Bind free function in replace_bilinear_terms. m.def("ReplaceBilinearTerms", &ReplaceBilinearTerms, py::arg("e"), py::arg("x"), py::arg("y"), py::arg("W"), doc.ReplaceBilinearTerms.doc); // NOLINTNEXTLINE(readability/fn_size) } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/symbolic/symbolic_py.h
#pragma once /* This file declares the functions that bind the drake::symbolic namespace. These functions form a complete partition of the drake::symbolic bindings. The implementations of these functions are parceled out into various *.cc files as indicated in each function's documentation. TODO(jwnimmer-tri) At the moment there is no parceling, just one obnoxiously large file. We should work to split it up. */ #include "drake/bindings/pydrake/pydrake_pybind.h" namespace drake { namespace pydrake { namespace internal { /* Defines bindings per symbolic_py_monolith.cc. */ void DefineSymbolicMonolith(py::module m); } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/symbolic/symbolic_py_unapply.cc
#include "drake/bindings/pydrake/symbolic/symbolic_py_unapply.h" #include <fmt/format.h> namespace drake { namespace pydrake { namespace internal { namespace { using drake::symbolic::Expression; using drake::symbolic::ExpressionKind; using drake::symbolic::Formula; using drake::symbolic::FormulaKind; // Given the pydrake.symbolic module as "m" and an expression "e", returns // the callable object (i.e., factory function or constructor) that would // be able to re-construct the same expression, given appropriate arguments. py::object MakeConstructor(py::module m, const Expression& e) { // This list of cases is in alphabetical order. switch (e.get_kind()) { case ExpressionKind::Abs: return m.attr("abs"); case ExpressionKind::Acos: return m.attr("acos"); case ExpressionKind::Add: return m.attr("_reduce_add"); case ExpressionKind::Asin: return m.attr("asin"); case ExpressionKind::Atan2: return m.attr("atan2"); case ExpressionKind::Atan: return m.attr("atan"); case ExpressionKind::Ceil: return m.attr("ceil"); case ExpressionKind::Constant: return m.attr("Expression"); case ExpressionKind::Cos: return m.attr("cos"); case ExpressionKind::Cosh: return m.attr("cosh"); case ExpressionKind::Div: return m.attr("operator").attr("truediv"); case ExpressionKind::Exp: return m.attr("exp"); case ExpressionKind::Floor: return m.attr("floor"); case ExpressionKind::IfThenElse: return m.attr("if_then_else"); case ExpressionKind::Log: return m.attr("log"); case ExpressionKind::Max: return m.attr("max"); case ExpressionKind::Min: return m.attr("min"); case ExpressionKind::Mul: return m.attr("_reduce_mul"); case ExpressionKind::NaN: return m.attr("Expression"); case ExpressionKind::Pow: return m.attr("pow"); case ExpressionKind::Sin: return m.attr("sin"); case ExpressionKind::Sinh: return m.attr("sinh"); case ExpressionKind::Sqrt: return m.attr("sqrt"); case ExpressionKind::Tan: return m.attr("tan"); case ExpressionKind::Tanh: return m.attr("tanh"); case ExpressionKind::UninterpretedFunction: return m.attr("uninterpreted_function"); case ExpressionKind::Var: return m.attr("Expression"); } DRAKE_UNREACHABLE(); } // Given the expression "e", returns an extracted list of arguments that would // be able to re-construct the same expression, when passed to the result of // MakeConstructor. py::list MakeArgs(const Expression& e) { py::list result; switch (e.get_kind()) { // The only cases where the result is not a list of sub-Expressions are // constants and variables. case ExpressionKind::Constant: { result.append(get_constant_value(e)); break; } case ExpressionKind::NaN: { result.append(NAN); break; } case ExpressionKind::Var: { result.append(get_variable(e)); break; } // These are all UnaryExpressionCell. case ExpressionKind::Abs: case ExpressionKind::Acos: case ExpressionKind::Asin: case ExpressionKind::Atan: case ExpressionKind::Ceil: case ExpressionKind::Cos: case ExpressionKind::Cosh: case ExpressionKind::Exp: case ExpressionKind::Floor: case ExpressionKind::Log: case ExpressionKind::Sin: case ExpressionKind::Sinh: case ExpressionKind::Sqrt: case ExpressionKind::Tan: case ExpressionKind::Tanh: { result.append(get_argument(e)); break; } // These are all BinaryExpressionCell. case ExpressionKind::Atan2: case ExpressionKind::Div: case ExpressionKind::Max: case ExpressionKind::Min: case ExpressionKind::Pow: { result.append(get_first_argument(e)); result.append(get_second_argument(e)); break; } // Add and Mul are reductions over lists of expressions. case ExpressionKind::Add: { result.append(get_constant_in_addition(e)); for (const auto& [expr, coeff] : get_expr_to_coeff_map_in_addition(e)) { result.append(coeff * expr); } break; } case ExpressionKind::Mul: { result.append(get_constant_in_multiplication(e)); for (const auto& [base, exp] : get_base_to_exponent_map_in_multiplication(e)) { result.append(symbolic::pow(base, exp)); } break; } // Special forms. case ExpressionKind::IfThenElse: { result.append(get_conditional_formula(e)); result.append(get_then_expression(e)); result.append(get_else_expression(e)); break; } case ExpressionKind::UninterpretedFunction: { py::list function_args; for (const auto& expr : get_uninterpreted_function_arguments(e)) { function_args.append(expr); } result.append(get_uninterpreted_function_name(e)); result.append(function_args); break; } } return result; } // Given the pydrake.symbolic module as "m" and a formula "f", returns // the callable object (i.e., factory function or constructor) that would // be able to re-construct the same formula, given appropriate arguments. py::object MakeConstructor(py::module m, const Formula& f) { switch (f.get_kind()) { case FormulaKind::False: return m.attr("Formula").attr("False_"); case FormulaKind::True: return m.attr("Formula").attr("True_"); case FormulaKind::Var: return m.attr("Formula"); case FormulaKind::Eq: return m.attr("operator").attr("eq"); case FormulaKind::Neq: return m.attr("operator").attr("ne"); case FormulaKind::Gt: return m.attr("operator").attr("gt"); case FormulaKind::Geq: return m.attr("operator").attr("ge"); case FormulaKind::Lt: return m.attr("operator").attr("lt"); case FormulaKind::Leq: return m.attr("operator").attr("le"); case FormulaKind::And: return m.attr("logical_and"); case FormulaKind::Or: return m.attr("logical_or"); case FormulaKind::Not: return m.attr("logical_not"); case FormulaKind::Forall: return m.attr("forall"); case FormulaKind::Isnan: return m.attr("isnan"); case FormulaKind::PositiveSemidefinite: return m.attr("positive_semidefinite"); } DRAKE_UNREACHABLE(); } // Given the formula "f", returns an extracted list of arguments that would // be able to re-construct the same formula, when passed to the result of // MakeConstructor. py::list MakeArgs(const Formula& f) { py::list result; switch (f.get_kind()) { case FormulaKind::False: case FormulaKind::True: { break; } case FormulaKind::Var: { result.append(get_variable(f)); break; } case FormulaKind::Eq: case FormulaKind::Neq: case FormulaKind::Gt: case FormulaKind::Geq: case FormulaKind::Lt: case FormulaKind::Leq: { result.append(get_lhs_expression(f)); result.append(get_rhs_expression(f)); break; } case FormulaKind::And: case FormulaKind::Or: { for (const Formula& operand : get_operands(f)) { result.append(operand); } break; } case FormulaKind::Not: { result.append(get_operand(f)); break; } case FormulaKind::Forall: { result.append(get_quantified_variables(f)); result.append(get_quantified_formula(f)); break; } case FormulaKind::Isnan: { result.append(get_unary_expression(f)); break; } case FormulaKind::PositiveSemidefinite: { result.append(get_matrix_in_positive_semidefinite(f)); break; } } return result; } } // namespace py::object Unapply(py::module m, const Expression& e) { return py::make_tuple(MakeConstructor(m, e), MakeArgs(e)); } py::object Unapply(py::module m, const symbolic::Formula& f) { return py::make_tuple(MakeConstructor(m, f), MakeArgs(f)); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake/symbolic
/home/johnshepherd/drake/bindings/pydrake/symbolic/test/symbolic_test.py
# -*- coding: utf-8 -*- import copy import itertools import unittest import warnings import numpy as np import pydrake.symbolic as sym import pydrake.common from pydrake.common.test_utilities.algebra_test_util import ( ScalarAlgebra, VectorizedAlgebra, ) import pydrake.math as drake_math from pydrake.common.containers import EqualToDict from pydrake.common.deprecation import install_numpy_warning_filters from pydrake.common.test_utilities import numpy_compare # TODO(eric.cousineau): Replace usages of `sym` math functions with the # overloads from `pydrake.math`. # Define global variables to make the tests less verbose. x = sym.Variable("x") y = sym.Variable("y") z = sym.Variable("z") w = sym.Variable("w") a = sym.Variable("a") b = sym.Variable("b") c = sym.Variable("c") e_x = sym.Expression(x) e_y = sym.Expression(y) p_x = sym.Polynomial(x) m_x = sym.Monomial(x) boolean = sym.Variable(name="boolean", type=sym.Variable.Type.BOOLEAN) class TestSymbolicVariable(unittest.TestCase): def test_is_dummy(self): self.assertFalse(a.is_dummy()) def test_get_name(self): self.assertEqual(a.get_name(), "a") self.assertEqual(b.get_name(), "b") self.assertEqual(c.get_name(), "c") def test_addition(self): numpy_compare.assert_equal(x + y, "(x + y)") numpy_compare.assert_equal(x + 1, "(1 + x)") numpy_compare.assert_equal(1 + x, "(1 + x)") def test_subtraction(self): numpy_compare.assert_equal(x - y, "(x - y)") numpy_compare.assert_equal(x - 1, "(-1 + x)") numpy_compare.assert_equal(1 - x, "(1 - x)") def test_multiplication(self): numpy_compare.assert_equal(x * y, "(x * y)") numpy_compare.assert_equal(x * 1, "x") numpy_compare.assert_equal(1 * x, "x") def test_division(self): numpy_compare.assert_equal(x / y, "(x / y)") numpy_compare.assert_equal(x / 1, "x") numpy_compare.assert_equal(1 / x, "(1 / x)") def test_unary_operators(self): numpy_compare.assert_equal(+x, "x") numpy_compare.assert_equal(-x, "(-1 * x)") def test_relational_operators(self): # Variable rop float numpy_compare.assert_equal(x >= 1, "(x >= 1)") numpy_compare.assert_equal(x > 1, "(x > 1)") numpy_compare.assert_equal(x <= 1, "(x <= 1)") numpy_compare.assert_equal(x < 1, "(x < 1)") numpy_compare.assert_equal(x == 1, "(x == 1)") numpy_compare.assert_equal(x != 1, "(x != 1)") # float rop Variable numpy_compare.assert_equal(1 < y, "(y > 1)") numpy_compare.assert_equal(1 <= y, "(y >= 1)") numpy_compare.assert_equal(1 > y, "(y < 1)") numpy_compare.assert_equal(1 >= y, "(y <= 1)") numpy_compare.assert_equal(1 == y, "(y == 1)") numpy_compare.assert_equal(1 != y, "(y != 1)") # Variable rop Variable numpy_compare.assert_equal(x < y, "(x < y)") numpy_compare.assert_equal(x <= y, "(x <= y)") numpy_compare.assert_equal(x > y, "(x > y)") numpy_compare.assert_equal(x >= y, "(x >= y)") numpy_compare.assert_equal(x == y, "(x == y)") numpy_compare.assert_equal(x != y, "(x != y)") def test_get_type(self): i = sym.Variable('i', sym.Variable.Type.INTEGER) self.assertEqual(i.get_type(), sym.Variable.Type.INTEGER) g = sym.Variable('g', sym.Variable.Type.RANDOM_GAUSSIAN) self.assertEqual(g.get_type(), sym.Variable.Type.RANDOM_GAUSSIAN) def test_repr(self): self.assertEqual(repr(x), "Variable('x', Continuous)") def test_simplify(self): numpy_compare.assert_equal(0 * (x + y), "0") numpy_compare.assert_equal(x + y - x - y, "0") numpy_compare.assert_equal(x / x - 1, "0") numpy_compare.assert_equal(x / x, "1") def test_expand(self): ex = 2 * (x + y) numpy_compare.assert_equal(ex, "(2 * (x + y))") numpy_compare.assert_equal(ex.Expand(), "(2 * x + 2 * y)") def test_pow(self): numpy_compare.assert_equal(x**2, "pow(x, 2)") numpy_compare.assert_equal(x**y, "pow(x, y)") numpy_compare.assert_equal((x + 1)**(y - 1), "pow((1 + x), (-1 + y))") def test_neg(self): numpy_compare.assert_equal(-(x + 1), "(-1 - x)") def test_equalto(self): self.assertTrue(x.EqualTo(x)) self.assertFalse(x.EqualTo(y)) def test_is_polynomial(self): self.assertTrue((x*y).is_polynomial()) self.assertFalse((x/y).is_polynomial()) def test_logical(self): numpy_compare.assert_equal( sym.logical_not(x == 0), "!((x == 0))") # Test single-operand logical statements numpy_compare.assert_equal(sym.logical_and(x >= 1), "(x >= 1)") numpy_compare.assert_equal(sym.logical_or(x >= 1), "(x >= 1)") # Test binary operand logical statements numpy_compare.assert_equal( sym.logical_and(x >= 1, x <= 2), "((x >= 1) and (x <= 2))") numpy_compare.assert_equal( sym.logical_or(x <= 1, x >= 2), "((x >= 2) or (x <= 1))") # Test multiple operand logical statements numpy_compare.assert_equal( sym.logical_and(x >= 1, x <= 2, y == 2), "((y == 2) and (x >= 1) and (x <= 2))") numpy_compare.assert_equal( sym.logical_or(x >= 1, x <= 2, y == 2), "((y == 2) or (x >= 1) or (x <= 2))") def test_functions_with_variable(self): numpy_compare.assert_equal(sym.abs(x), "abs(x)") numpy_compare.assert_equal(sym.exp(x), "exp(x)") numpy_compare.assert_equal(np.exp(x), "exp(x)") numpy_compare.assert_equal(sym.sqrt(x), "sqrt(x)") numpy_compare.assert_equal(np.sqrt(x), "sqrt(x)") numpy_compare.assert_equal(sym.pow(x, y), "pow(x, y)") numpy_compare.assert_equal(sym.sin(x), "sin(x)") numpy_compare.assert_equal(np.sin(x), "sin(x)") numpy_compare.assert_equal(sym.cos(x), "cos(x)") numpy_compare.assert_equal(np.cos(x), "cos(x)") numpy_compare.assert_equal(sym.tan(x), "tan(x)") numpy_compare.assert_equal(np.tan(x), "tan(x)") numpy_compare.assert_equal(sym.asin(x), "asin(x)") numpy_compare.assert_equal(np.arcsin(x), "asin(x)") numpy_compare.assert_equal(sym.acos(x), "acos(x)") numpy_compare.assert_equal(np.arccos(x), "acos(x)") numpy_compare.assert_equal(sym.atan(x), "atan(x)") numpy_compare.assert_equal(np.arctan(x), "atan(x)") numpy_compare.assert_equal(sym.atan2(x, y), "atan2(x, y)") numpy_compare.assert_equal(sym.sinh(x), "sinh(x)") numpy_compare.assert_equal(np.sinh(x), "sinh(x)") numpy_compare.assert_equal(sym.cosh(x), "cosh(x)") numpy_compare.assert_equal(np.cosh(x), "cosh(x)") numpy_compare.assert_equal(sym.tanh(x), "tanh(x)") numpy_compare.assert_equal(np.tanh(x), "tanh(x)") numpy_compare.assert_equal(sym.min(x, y), "min(x, y)") numpy_compare.assert_equal(sym.max(x, y), "max(x, y)") numpy_compare.assert_equal(sym.ceil(x), "ceil(x)") numpy_compare.assert_equal(sym.floor(x), "floor(x)") numpy_compare.assert_equal( sym.if_then_else(x > y, x, y), "(if (x > y) then x else y)") numpy_compare.assert_equal( sym.if_then_else(f_cond=x > y, e_then=x, e_else=y), "(if (x > y) then x else y)") numpy_compare.assert_equal( sym.uninterpreted_function(name="func_name", arguments=[e_x, e_y]), "func_name(x, y)") def test_array_str(self): # Addresses #8729. value = str(np.array([x, y])) self.assertIn("Variable('x', Continuous)", value) self.assertIn("Variable('y', Continuous)", value) class TestMakeMatrixVariable(unittest.TestCase): # Test both MakeMatrixVariable and MakeVectorVariable (and the variations) def test_make_matrix_variable(self): # Call MakeMatrixVariable with default variable type. A = sym.MakeMatrixVariable(3, 2, "A") self.assertEqual(A.shape, (3, 2)) for i in range(3): for j in range(2): self.assertEqual( repr(A[i, j]), f"Variable('A({i}, {j})', Continuous)") # Call MakeMatrixVariable with specified variable type. A = sym.MakeMatrixVariable(3, 2, "A", sym.Variable.Type.BINARY) self.assertEqual(A.shape, (3, 2)) for i in range(3): for j in range(2): self.assertEqual( repr(A[i, j]), f"Variable('A({i}, {j})', Binary)") def test_make_matrix_continuous_variable(self): A = sym.MakeMatrixContinuousVariable(3, 2, "A") self.assertEqual(A.shape, (3, 2)) for i in range(3): for j in range(2): self.assertEqual( repr(A[i, j]), f"Variable('A({i}, {j})', Continuous)") def test_make_matrix_binary_variable(self): A = sym.MakeMatrixBinaryVariable(3, 2, "A") self.assertEqual(A.shape, (3, 2)) for i in range(3): for j in range(2): self.assertEqual( repr(A[i, j]), f"Variable('A({i}, {j})', Binary)") def test_make_matrix_boolean_variable(self): A = sym.MakeMatrixBooleanVariable(3, 2, "A") self.assertEqual(A.shape, (3, 2)) for i in range(3): for j in range(2): self.assertEqual( repr(A[i, j]), f"Variable('A({i}, {j})', Boolean)") def test_make_vector_variable(self): # Call MakeVectorVariable with default variable type. a = sym.MakeVectorVariable(3, "a") self.assertEqual(a.shape, (3,)) for i in range(3): self.assertEqual(repr(a[i]), f"Variable('a({i})', Continuous)") # Call MakeVectorVariable with specified type. a = sym.MakeVectorVariable(3, "a", sym.Variable.Type.BINARY) self.assertEqual(a.shape, (3,)) for i in range(3): self.assertEqual(repr(a[i]), f"Variable('a({i})', Binary)") def test_make_vector_continuous_variable(self): a = sym.MakeVectorContinuousVariable(3, "a") self.assertEqual(a.shape, (3,)) for i in range(3): self.assertEqual(repr(a[i]), f"Variable('a({i})', Continuous)") def test_make_vector_binary_variable(self): a = sym.MakeVectorBinaryVariable(3, "a") self.assertEqual(a.shape, (3,)) for i in range(3): self.assertEqual(repr(a[i]), f"Variable('a({i})', Binary)") def test_make_vector_boolean_variable(self): a = sym.MakeVectorBooleanVariable(3, "a") self.assertEqual(a.shape, (3,)) for i in range(3): self.assertEqual(repr(a[i]), f"Variable('a({i})', Boolean)") class TestSymbolicVariables(unittest.TestCase): def test_default_constructor(self): vars = sym.Variables() self.assertEqual(vars.size(), 0) self.assertTrue(vars.empty()) def test_constructor_list(self): vars = sym.Variables([x, y, z]) self.assertEqual(vars.size(), 3) self.assertEqual(len(vars), 3) def test_to_string(self): vars = sym.Variables([x, y, z]) self.assertEqual(vars.to_string(), "{x, y, z}") self.assertEqual("{}".format(vars), "{x, y, z}") def test_repr(self): vars = sym.Variables([x, y, z]) self.assertEqual(repr(vars), '<Variables "{x, y, z}">') def test_insert1(self): vars = sym.Variables() vars.insert(x) self.assertEqual(vars.size(), 1) vars.insert(var=y) self.assertEqual(vars.size(), 2) def test_insert2(self): vars = sym.Variables([x]) vars.insert(sym.Variables([y, z])) self.assertEqual(vars.size(), 3) vars.insert(vars=sym.Variables([a, b, c])) self.assertEqual(vars.size(), 6) def test_erase1(self): vars = sym.Variables([x, y, z]) count = vars.erase(x) self.assertEqual(count, 1) self.assertEqual(vars.size(), 2) count = vars.erase(key=y) self.assertEqual(count, 1) self.assertEqual(vars.size(), 1) def test_erase2(self): vars1 = sym.Variables([x, y, z]) vars2 = sym.Variables([w, z]) count = vars1.erase(vars2) self.assertEqual(count, 1) self.assertEqual(vars1.size(), 2) def test_erase2_kwarg(self): vars1 = sym.Variables([x, y, z]) vars2 = sym.Variables([x, y]) count = vars1.erase(vars=vars2) self.assertEqual(count, 2) self.assertEqual(vars1.size(), 1) def test_include(self): vars = sym.Variables([x, y, z]) self.assertTrue(vars.include(y)) self.assertTrue(vars.include(key=x)) self.assertTrue(z in vars) def test_equalto(self): vars1 = sym.Variables([x, y, z]) vars2 = sym.Variables([y, z]) vars3 = sym.Variables([x, y, z]) self.assertTrue(vars1.EqualTo(vars3)) self.assertFalse(vars1.EqualTo(vars2)) def test_to_string(self): vars = sym.Variables() vars.insert(x) vars.insert(y) vars.insert(z) self.assertEqual(vars.to_string(), "{x, y, z}") def test_subset_properties(self): vars1 = sym.Variables([x, y, z]) vars2 = sym.Variables([x, y]) self.assertFalse(vars1.IsSubsetOf(vars2)) self.assertFalse(vars1.IsSubsetOf(vars=vars2)) self.assertFalse(vars1.IsStrictSubsetOf(vars2)) self.assertFalse(vars1.IsStrictSubsetOf(vars=vars2)) self.assertTrue(vars1.IsSupersetOf(vars2)) self.assertTrue(vars1.IsSupersetOf(vars=vars2)) self.assertTrue(vars1.IsStrictSupersetOf(vars2)) self.assertTrue(vars1.IsStrictSupersetOf(vars=vars2)) def test_eq(self): vars1 = sym.Variables([x, y, z]) vars2 = sym.Variables([x, y]) self.assertFalse(vars1 == vars2) def test_lt(self): vars1 = sym.Variables([x, y]) vars2 = sym.Variables([x, y, z]) self.assertTrue(vars1 < vars2) def test_add(self): vars1 = sym.Variables([x, y]) vars2 = sym.Variables([y, z]) vars3 = vars1 + vars2 # [x, y, z] self.assertEqual(vars3.size(), 3) vars4 = vars1 + z # [x, y, z] self.assertEqual(vars4.size(), 3) vars5 = x + vars1 # [x, y] self.assertEqual(vars5.size(), 2) def test_add_assignment(self): vars = sym.Variables([x]) vars += y self.assertEqual(vars.size(), 2) vars += sym.Variables([x, z]) self.assertEqual(vars.size(), 3) def test_sub(self): vars1 = sym.Variables([x, y]) vars2 = sym.Variables([y, z]) vars3 = vars1 - vars2 # [x] self.assertEqual(vars3, sym.Variables([x])) vars4 = vars1 - y # [x] self.assertEqual(vars4, sym.Variables([x])) def test_sub_assignment(self): vars = sym.Variables([x, y, z]) vars -= y # = [x, z] self.assertEqual(vars, sym.Variables([x, z])) vars -= sym.Variables([x]) # = [z] self.assertEqual(vars, sym.Variables([z])) def test_intersect(self): vars1 = sym.Variables([x, y, z]) vars2 = sym.Variables([y, w]) vars3 = sym.intersect(vars1, vars2) # = [y] self.assertEqual(vars3, sym.Variables([y])) vars4 = sym.intersect(vars1=vars1, vars2=vars2) self.assertEqual(vars4, sym.Variables([y])) def test_iterable(self): vars = sym.Variables([x, y, z]) count = 0 for var in vars: self.assertTrue(var in vars) count = count + 1 self.assertEqual(count, 3) class TestSymbolicExpression(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) # For some reason, something in how `unittest` tries to scope warnings # causes the previous filters to be lost. Re-install here. install_numpy_warning_filters(force=True) def test_constructor(self): sym.Expression(z) sym.Expression(var=z) sym.Expression(2.2) sym.Expression(constant=2.2) def _check_algebra(self, algebra): xv = algebra.to_algebra(x) yv = algebra.to_algebra(y) zv = algebra.to_algebra(z) wv = algebra.to_algebra(w) av = algebra.to_algebra(a) bv = algebra.to_algebra(b) cv = algebra.to_algebra(c) e_xv = algebra.to_algebra(e_x) e_yv = algebra.to_algebra(e_y) # Addition. numpy_compare.assert_equal(e_xv + e_yv, "(x + y)") numpy_compare.assert_equal(e_xv + yv, "(x + y)") numpy_compare.assert_equal(e_xv + 1, "(1 + x)") numpy_compare.assert_equal(xv + e_yv, "(x + y)") numpy_compare.assert_equal(1 + e_xv, "(1 + x)") # - In place. e = copy.copy(xv) e += e_yv numpy_compare.assert_equal(e, "(x + y)") e += zv numpy_compare.assert_equal(e, "(x + y + z)") e += 1 numpy_compare.assert_equal(e, "(1 + x + y + z)") # Subtraction. numpy_compare.assert_equal(e_xv - e_yv, "(x - y)") numpy_compare.assert_equal(e_xv - yv, "(x - y)") numpy_compare.assert_equal(e_xv - 1, "(-1 + x)") numpy_compare.assert_equal(xv - e_yv, "(x - y)") numpy_compare.assert_equal(1 - e_xv, "(1 - x)") # - In place. e = copy.copy(xv) e -= e_yv numpy_compare.assert_equal(e, (x - y)) e -= zv numpy_compare.assert_equal(e, (x - y - z)) e -= 1 numpy_compare.assert_equal(e, (x - y - z - 1)) # Multiplication. numpy_compare.assert_equal(e_xv * e_yv, "(x * y)") numpy_compare.assert_equal(e_xv * yv, "(x * y)") numpy_compare.assert_equal(e_xv * 1, "x") numpy_compare.assert_equal(xv * e_yv, "(x * y)") numpy_compare.assert_equal(1 * e_xv, "x") # - In place. e = copy.copy(xv) e *= e_yv numpy_compare.assert_equal(e, "(x * y)") e *= zv numpy_compare.assert_equal(e, "(x * y * z)") e *= 1 numpy_compare.assert_equal(e, "(x * y * z)") # Division numpy_compare.assert_equal(e_xv / e_yv, (x / y)) numpy_compare.assert_equal(e_xv / yv, (x / y)) numpy_compare.assert_equal(e_xv / 1, "x") numpy_compare.assert_equal(xv / e_yv, (x / y)) numpy_compare.assert_equal(1 / e_xv, (1 / x)) # - In place. e = copy.copy(xv) e /= e_yv numpy_compare.assert_equal(e, (x / y)) e /= zv numpy_compare.assert_equal(e, (x / y / z)) e /= 1 numpy_compare.assert_equal(e, ((x / y) / z)) # Unary numpy_compare.assert_equal(+e_xv, "x") numpy_compare.assert_equal(-e_xv, "(-1 * x)") # Comparison. For `VectorizedAlgebra`, uses `np.vectorize` workaround # for #8315. # TODO(eric.cousineau): `BaseAlgebra.check_logical` is designed for # AutoDiffXd (float-convertible), not for symbolic (not always # float-convertible). numpy_compare.assert_equal(algebra.lt(e_xv, e_yv), "(x < y)") numpy_compare.assert_equal(algebra.le(e_xv, e_yv), "(x <= y)") numpy_compare.assert_equal(algebra.eq(e_xv, e_yv), "(x == y)") numpy_compare.assert_equal(algebra.ne(e_xv, e_yv), "(x != y)") numpy_compare.assert_equal(algebra.ge(e_xv, e_yv), "(x >= y)") numpy_compare.assert_equal(algebra.gt(e_xv, e_yv), "(x > y)") # Math functions. numpy_compare.assert_equal(algebra.abs(e_xv), "abs(x)") numpy_compare.assert_equal(algebra.exp(e_xv), "exp(x)") numpy_compare.assert_equal(algebra.sqrt(e_xv), "sqrt(x)") numpy_compare.assert_equal(algebra.pow(e_xv, e_yv), "pow(x, y)") numpy_compare.assert_equal(algebra.sin(e_xv), "sin(x)") numpy_compare.assert_equal(algebra.cos(e_xv), "cos(x)") numpy_compare.assert_equal(algebra.tan(e_xv), "tan(x)") numpy_compare.assert_equal(algebra.arcsin(e_xv), "asin(x)") numpy_compare.assert_equal(algebra.arccos(e_xv), "acos(x)") numpy_compare.assert_equal(algebra.arctan2(e_xv, e_yv), "atan2(x, y)") numpy_compare.assert_equal(algebra.sinh(e_xv), "sinh(x)") numpy_compare.assert_equal(algebra.cosh(e_xv), "cosh(x)") numpy_compare.assert_equal(algebra.tanh(e_xv), "tanh(x)") numpy_compare.assert_equal(algebra.ceil(e_xv), "ceil(x)") numpy_compare.assert_equal(algebra.floor(e_xv), "floor(x)") if isinstance(algebra, ScalarAlgebra): # TODO(eric.cousineau): Uncomment these lines if we can teach numpy # that reduction is not just selection. numpy_compare.assert_equal(algebra.min(e_xv, e_yv), "min(x, y)") numpy_compare.assert_equal(algebra.max(e_xv, e_yv), "max(x, y)") # TODO(eric.cousineau): Add broadcasting functions for these # operations. numpy_compare.assert_equal(sym.atan(e_xv), "atan(x)") numpy_compare.assert_equal( sym.if_then_else(e_xv > e_yv, e_xv, e_yv), "(if (x > y) then x else y)") return xv, e_xv def test_scalar_algebra(self): xv, e_xv = self._check_algebra(ScalarAlgebra()) self.assertIsInstance(xv, sym.Variable) self.assertIsInstance(e_xv, sym.Expression) def test_array_algebra(self): xv, e_xv = self._check_algebra(VectorizedAlgebra()) self.assertEqual(xv.shape, (2,)) self.assertIsInstance(xv[0], sym.Variable) self.assertEqual(e_xv.shape, (2,)) self.assertIsInstance(e_xv[0], sym.Expression) def make_matrix_variable(self, rows, cols): M = np.zeros((rows, cols), dtype=object) for i in range(rows): for j in range(cols): M[i, j] = sym.Variable(f"m{i}{j}") return M def check_matrix_inversion(self, N): Mvar = self.make_matrix_variable(N, N) subst = {} for i in range(N * N): subst[Mvar.flat[i]] = i ** (N - 1) to_expr = np.vectorize(sym.Expression) M = to_expr(Mvar) Minv = drake_math.inv(M) np.testing.assert_allclose( sym.Evaluate(Minv, subst), np.linalg.inv(sym.Evaluate(M, subst)), rtol=0, atol=1e-10, ) def test_matrix_inversion(self): self.check_matrix_inversion(1) self.check_matrix_inversion(2) self.check_matrix_inversion(3) self.check_matrix_inversion(4) with self.assertRaises(RuntimeError) as cm: self.check_matrix_inversion(5) self.assertIn( "does not have an entry for the variable", str(cm.exception) ) def test_vectorized_binary_operator_type_combinatorics(self): """ Tests vectorized binary operator via brute-force combinatorics per #15549. This complements test with the same name in ``autodiffutils_test.py``. """ def expand_values(value): return ( # Scalar. value, # Scalar array. np.array(value), # Size-1 array. np.array([value]), # Size-2 array. np.array([value, value]), ) operators = drake_math._OPERATORS operators_reverse = drake_math._OPERATORS_REVERSE T_operands_x = ( # Variable. expand_values(x) # Expression. + expand_values(e_x) ) T_operands_y = ( # Variable. expand_values(y) # Expression. + expand_values(e_y) ) numeric_operands = ( # Float. # - Native. expand_values(1.0) # - np.generic + expand_values(np.float64(1.0)) # Int. # - Native. + expand_values(1) # - np.generic + expand_values(np.int64(1.0)) ) @np.vectorize def assert_nontrivial_formula(value): self.assertIsInstance(value, sym.Formula) self.assertNotEqual(value, sym.Formula.True_()) self.assertNotEqual(value, sym.Formula.False_()) def check_operands(op, lhs_operands, rhs_operands): operand_combinatorics_iter = itertools.product( lhs_operands, rhs_operands ) op_reverse = operators_reverse[op] for lhs, rhs in operand_combinatorics_iter: hint_for_error = f"{op.__doc__}: {repr(lhs)}, {repr(rhs)}" with numpy_compare.soft_sub_test(hint_for_error): value = op(lhs, rhs) assert_nontrivial_formula(value) reverse_value = op_reverse(rhs, lhs) assert_nontrivial_formula(reverse_value) numpy_compare.assert_equal(value, reverse_value) # Combinations (unordered) that we're interested in. operand_combinations = ( (T_operands_x, T_operands_y), (T_operands_x, numeric_operands), ) for op in operators: for (op_a, op_b) in operand_combinations: check_operands(op, op_a, op_b) check_operands(op, op_b, op_a) def test_equalto(self): self.assertTrue((x + y).EqualTo(x + y)) self.assertFalse((x + y).EqualTo(x - y)) self.assertTrue(sym.Formula(True).EqualTo(True)) self.assertTrue(sym.Formula(boolean).EqualTo(boolean)) def test_get_kind(self): self.assertEqual((x + y).get_kind(), sym.ExpressionKind.Add) self.assertEqual((x * y).get_kind(), sym.ExpressionKind.Mul) def test_get_variables(self): vars = e_x.GetVariables() self.assertEqual(len(vars), 1) self.assertTrue(list(vars)[0].EqualTo(x)) def test_get_variable_vector(self): vars_ = sym.GetVariableVector([e_x, e_y]) self.assertEqual(len(vars_), 2) if vars_[0].get_id() == x.get_id(): self.assertEqual(vars_[1].get_id(), y.get_id()) else: self.assertEqual(vars_[0].get_id(), y.get_id()) self.assertEqual(vars_[1].get_id(), x.get_id()) def test_relational_operators(self): # TODO(eric.cousineau): Use `VectorizedAlgebra` overloads once #8315 is # resolved. # Expression rop Expression numpy_compare.assert_equal(e_x < e_y, "(x < y)") numpy_compare.assert_equal(e_x <= e_y, "(x <= y)") numpy_compare.assert_equal(e_x > e_y, "(x > y)") numpy_compare.assert_equal(e_x >= e_y, "(x >= y)") numpy_compare.assert_equal(e_x == e_y, "(x == y)") numpy_compare.assert_equal(e_x != e_y, "(x != y)") # Expression rop Variable numpy_compare.assert_equal(e_x < y, "(x < y)") numpy_compare.assert_equal(e_x <= y, "(x <= y)") numpy_compare.assert_equal(e_x > y, "(x > y)") numpy_compare.assert_equal(e_x >= y, "(x >= y)") numpy_compare.assert_equal(e_x == y, "(x == y)") numpy_compare.assert_equal(e_x != y, "(x != y)") # Variable rop Expression numpy_compare.assert_equal(x < e_y, "(x < y)") numpy_compare.assert_equal(x <= e_y, "(x <= y)") numpy_compare.assert_equal(x > e_y, "(x > y)") numpy_compare.assert_equal(x >= e_y, "(x >= y)") numpy_compare.assert_equal(x == e_y, "(x == y)") numpy_compare.assert_equal(x != e_y, "(x != y)") # Expression rop float numpy_compare.assert_equal(e_x < 1, "(x < 1)") numpy_compare.assert_equal(e_x <= 1, "(x <= 1)") numpy_compare.assert_equal(e_x > 1, "(x > 1)") numpy_compare.assert_equal(e_x >= 1, "(x >= 1)") numpy_compare.assert_equal(e_x == 1, "(x == 1)") numpy_compare.assert_equal(e_x != 1, "(x != 1)") # float rop Expression numpy_compare.assert_equal(1 < e_y, "(y > 1)") numpy_compare.assert_equal(1 <= e_y, "(y >= 1)") numpy_compare.assert_equal(1 > e_y, "(y < 1)") numpy_compare.assert_equal(1 >= e_y, "(y <= 1)") numpy_compare.assert_equal(1 == e_y, "(y == 1)") numpy_compare.assert_equal(1 != e_y, "(y != 1)") def test_relational_operators_nonzero(self): # For issues #8135 and #8491. See `pydrake.math` for operator overloads # that work around this, which are tested in `_check_algebra`. # Ensure that we throw on `__nonzero__`. with self.assertRaises(RuntimeError) as cm: value = bool(e_x == e_x) message = str(cm.exception) self.assertTrue( all([s in message for s in ["__nonzero__", "EqualToDict"]]), message) # Ensure that compound formulas fail (#8536). with self.assertRaises(RuntimeError): value = 0 < e_y < e_y # Indication of #8135. Ideally, these would all be arrays of formulas. e_xv = np.array([e_x, e_x]) e_yv = np.array([e_y, e_y]) # N.B. In some versions of NumPy, `!=` for dtype=object implies ID # comparison (e.g. `is`). Depending on the verison of numpy, we might # see either a DeprecationWarning from numpy or the __nonzero__ error # from our code. Once we're at numpy >= 1.25 as our minimum version # (approximately 2026-05-01) we can probably simplify these checks. # - All false. with self.assertRaisesRegex((DeprecationWarning, RuntimeError), "(elementwise comparison|__nonzero__)"): value = (e_xv == e_yv) # - True + False. with self.assertRaisesRegex((DeprecationWarning, RuntimeError), "(elementwise comparison|__nonzero__)"): e_xyv = np.array([e_x, e_y]) value = (e_xv == e_xyv) # - All true. with self.assertRaisesRegex((DeprecationWarning, RuntimeError), "(elementwise comparison|__nonzero__)"): value = (e_xv == e_xv) def test_functions_with_float(self): # TODO(eric.cousineau): Use concrete values once vectorized methods are # supported. v_x = 1.0 v_y = 1.0 numpy_compare.assert_equal(sym.abs(v_x), np.abs(v_x)) numpy_compare.assert_not_equal(sym.abs(v_x), 0.5*np.abs(v_x)) numpy_compare.assert_equal(sym.abs(v_x), np.abs(v_x)) numpy_compare.assert_equal(sym.abs(v_x), np.abs(v_x)) numpy_compare.assert_equal(sym.exp(v_x), np.exp(v_x)) numpy_compare.assert_equal(sym.sqrt(v_x), np.sqrt(v_x)) numpy_compare.assert_equal(sym.pow(v_x, v_y), v_x ** v_y) numpy_compare.assert_equal(sym.sin(v_x), np.sin(v_x)) numpy_compare.assert_equal(sym.cos(v_x), np.cos(v_x)) numpy_compare.assert_float_allclose(sym.tan(v_x), np.tan(v_x)) numpy_compare.assert_equal(sym.asin(v_x), np.arcsin(v_x)) numpy_compare.assert_equal(sym.acos(v_x), np.arccos(v_x)) numpy_compare.assert_equal(sym.atan(v_x), np.arctan(v_x)) numpy_compare.assert_equal(sym.atan2(v_x, v_y), np.arctan2(v_x, v_y)) numpy_compare.assert_equal(sym.sinh(v_x), np.sinh(v_x)) numpy_compare.assert_equal(sym.cosh(v_x), np.cosh(v_x)) numpy_compare.assert_equal(sym.tanh(v_x), np.tanh(v_x)) numpy_compare.assert_equal(sym.min(v_x, v_y), min(v_x, v_y)) numpy_compare.assert_equal(sym.max(v_x, v_y), max(v_x, v_y)) numpy_compare.assert_equal(sym.ceil(v_x), np.ceil(v_x)) numpy_compare.assert_equal(sym.floor(v_x), np.floor(v_x)) numpy_compare.assert_equal( sym.if_then_else( sym.Expression(v_x) > sym.Expression(v_y), v_x, v_y), v_x if v_x > v_y else v_y) def test_non_method_jacobian(self): # Jacobian([x * cos(y), x * sin(y), x ** 2], [x, y]) returns # the following 3x2 matrix: # # = |cos(y) -x * sin(y)| # |sin(y) x * cos(y)| # | 2 * x 0| def check_jacobian(J): numpy_compare.assert_equal(J[0, 0], sym.cos(y)) numpy_compare.assert_equal(J[1, 0], sym.sin(y)) numpy_compare.assert_equal(J[2, 0], 2 * x) numpy_compare.assert_equal(J[0, 1], - x * sym.sin(y)) numpy_compare.assert_equal(J[1, 1], x * sym.cos(y)) numpy_compare.assert_equal(J[2, 1], sym.Expression(0)) f = [x * sym.cos(y), x * sym.sin(y), x ** 2] vars = [x, y] check_jacobian(sym.Jacobian(f, vars)) check_jacobian(sym.Jacobian(f=f, vars=vars)) def test_method_jacobian(self): # (x * cos(y)).Jacobian([x, y]) returns [cos(y), -x * sin(y)]. def check_jacobian(J): numpy_compare.assert_equal(J[0], sym.cos(y)) numpy_compare.assert_equal(J[1], -x * sym.sin(y)) e = x * sym.cos(y) vars = [x, y] check_jacobian(e.Jacobian(vars)) check_jacobian(e.Jacobian(vars=vars)) def test_is_affine(self): M = np.array([[a * a * x, 3 * x], [2 * x, 3 * a]]) vars = sym.Variables([x]) self.assertTrue(sym.IsAffine(M, vars)) self.assertTrue(sym.IsAffine(m=M, vars=vars)) self.assertFalse(sym.IsAffine(M)) self.assertFalse(sym.IsAffine(m=M)) def test_differentiate(self): e = x * x numpy_compare.assert_equal(e.Differentiate(x), 2 * x) numpy_compare.assert_equal(e.Differentiate(x=x), 2 * x) def test_repr(self): self.assertEqual(repr(e_x), '<Expression "x">') def test_to_string(self): e = (x + y) self.assertEqual(e.to_string(), "(x + y)") self.assertEqual(str(e), "(x + y)") def test_evaluate(self): env = {x: 3.0, y: 4.0} self.assertEqual((x + y).Evaluate(env), env[x] + env[y]) def test_evaluate_with_random_generator(self): g = pydrake.common.RandomGenerator() uni = sym.Variable("uni", sym.Variable.Type.RANDOM_UNIFORM) gau = sym.Variable("gau", sym.Variable.Type.RANDOM_GAUSSIAN) exp = sym.Variable("exp", sym.Variable.Type.RANDOM_EXPONENTIAL) # Checks if we can evaluate an expression with a random number # generator. (uni + gau + exp).Evaluate(g) (uni + gau + exp).Evaluate(generator=g) env = {x: 3.0, y: 4.0} # Checks if we can evaluate an expression with an environment and a # random number generator. (x + y + uni + gau + exp).Evaluate(env, g) (x + y + uni + gau + exp).Evaluate(env=env, generator=g) def test_evaluate_partial(self): env = {x: 3.0, y: 4.0} partial_evaluated = (x + y + z).EvaluatePartial(env) expected = env[x] + env[y] + z self.assertTrue(partial_evaluated.EqualTo(expected)) partial_evaluated = (x + y + z).EvaluatePartial(env=env) self.assertTrue(partial_evaluated.EqualTo(expected)) def test_evaluate_exception_np_nan(self): env = {x: np.nan} with self.assertRaises(RuntimeError): (x + 1).Evaluate(env) def test_evaluate_exception_python_nan(self): env = {x: float('nan')} with self.assertRaises(RuntimeError): (x + 1).Evaluate(env) def test_substitute_with_pair(self): e = x + y numpy_compare.assert_equal(e.Substitute(x, x + 5), x + y + 5) numpy_compare.assert_equal(e.Substitute(var=x, e=(x + 5)), x + y + 5) numpy_compare.assert_equal(e.Substitute(y, z), x + z) numpy_compare.assert_equal(e.Substitute(var=y, e=z), x + z) numpy_compare.assert_equal(e.Substitute(y, 3), x + 3) numpy_compare.assert_equal(e.Substitute(var=y, e=3), x + 3) def test_substitute_with_dict(self): e = x + y env = {x: x + 2, y: y + 3} numpy_compare.assert_equal(e.Substitute(env), x + y + 5) numpy_compare.assert_equal(e.Substitute(s=env), x + y + 5) def test_copy(self): numpy_compare.assert_equal(copy.copy(e_x), e_x) numpy_compare.assert_equal(copy.deepcopy(e_x), e_x) def test_taylor_expand(self): e = sym.sin(x) env = {x: 0} numpy_compare.assert_equal( sym.TaylorExpand(f=e, a=env, order=1), sym.Expression(x)) # See `math_overloads_test` for more comprehensive checks on math # functions. class TestSymbolicFormula(unittest.TestCase): def test_constructor(self): sym.Formula() sym.Formula(value=True) sym.Formula(var=boolean) def test_factory_functions(self): f = sym.forall(vars=sym.Variables([x]), f=(x > 0)) self.assertEqual(f.get_kind(), sym.FormulaKind.Forall) f = sym.isnan(e_x) self.assertEqual(f.get_kind(), sym.FormulaKind.Isnan) f = sym.positive_semidefinite([e_x]) self.assertEqual(f.get_kind(), sym.FormulaKind.PositiveSemidefinite) def test_get_kind(self): self.assertEqual((x > y).get_kind(), sym.FormulaKind.Gt) def test_get_free_variables(self): f = x > y self.assertEqual(f.GetFreeVariables(), sym.Variables([x, y])) def test_substitute_with_pair(self): f = x > y self.assertEqual(f.Substitute(y, y + 5), x > y + 5) self.assertEqual(f.Substitute(var=y, e=y + 5), x > y + 5) self.assertEqual(f.Substitute(y, z), x > z) self.assertEqual(f.Substitute(var=y, e=z), x > z) self.assertEqual(f.Substitute(y, 3), x > 3) self.assertEqual(f.Substitute(var=y, e=3), x > 3) def test_substitute_with_dict(self): f = x + y > z s = {x: x + 2, y: y + 3} self.assertEqual(f.Substitute(s), x + y + 5 > z) self.assertEqual(f.Substitute(s=s), x + y + 5 > z) def test_to_string(self): f = x > y self.assertEqual(f.to_string(), "(x > y)") self.assertEqual("{}".format(f), "(x > y)") def test_equality_inequality_hash(self): f1 = x > y f2 = x > y f3 = x >= y self.assertTrue(f1.EqualTo(f2)) self.assertEqual(hash(f1), hash(f2)) self.assertTrue(f1 == f2) self.assertFalse(f1.EqualTo(f3)) self.assertNotEqual(hash(f1), hash(f3)) self.assertTrue(f1 != f3) def test_static_true_false(self): tt = sym.Formula.True_() ff = sym.Formula.False_() self.assertEqual(x == x, tt) self.assertEqual(x != x, ff) def test_repr(self): self.assertEqual(repr(x > y), '<Formula "(x > y)">') def test_evaluate(self): env = {x: 3.0, y: 4.0} self.assertEqual((x > y).Evaluate(env), env[x] > env[y]) self.assertEqual((x < y).Evaluate(env=env), env[x] < env[y]) self.assertTrue(sym.Formula.True_().Evaluate()) def test_evaluate_exception_np_nan(self): env = {x: np.nan} with self.assertRaises(RuntimeError): (x > 1).Evaluate(env) def test_evaluate_exception_python_nan(self): env = {x: float('nan')} with self.assertRaises(RuntimeError): (x > 1).Evaluate(env) class TestSymbolicMonomial(unittest.TestCase): def test_constructor_empty(self): m = sym.Monomial() # m = 1 self.assertEqual(m.GetVariables().size(), 0) self.assertEqual(m.total_degree(), 0) def test_constructor_variable(self): def check_monomial(m): # m = x¹ self.assertEqual(m.degree(x), 1) self.assertEqual(m.total_degree(), 1) check_monomial(sym.Monomial(x)) check_monomial(sym.Monomial(var=x)) def test_constructor_variable_int(self): def check_monomial(m): # m = x² self.assertEqual(m.degree(x), 2) self.assertEqual(m.total_degree(), 2) check_monomial(sym.Monomial(x, 2)) check_monomial(sym.Monomial(var=x, exponent=2)) def test_constructor_map(self): def check_monomial(m): powers_out = EqualToDict(m.get_powers()) self.assertEqual(powers_out[x], 2) self.assertEqual(powers_out[y], 3) self.assertEqual(powers_out[z], 4) powers_in = {x: 2, y: 3, z: 4} check_monomial(sym.Monomial(powers_in)) check_monomial(sym.Monomial(powers=powers_in)) def test_constructor_vars_exponents(self): m = sym.Monomial([x, y], [1, 2]) powers_out = EqualToDict(m.get_powers()) self.assertEqual(powers_out[x], 1) self.assertEqual(powers_out[y], 2) def test_comparison(self): # m1 = m2 = x² m1 = sym.Monomial(x, 2) m2 = sym.Monomial(x, 2) m3 = sym.Monomial(x, 1) m4 = sym.Monomial(y, 2) # Test operator== self.assertIsInstance(m1 == m2, bool) self.assertTrue(m1 == m2) self.assertFalse(m1 == m3) self.assertFalse(m1 == m4) self.assertFalse(m2 == m3) self.assertFalse(m2 == m4) self.assertFalse(m3 == m4) # Test operator!= self.assertIsInstance(m1 != m2, bool) self.assertFalse(m1 != m2) self.assertTrue(m1 != m3) self.assertTrue(m1 != m4) self.assertTrue(m2 != m3) self.assertTrue(m2 != m4) self.assertTrue(m3 != m4) def test_equalto(self): m1 = sym.Monomial(x, 2) m2 = sym.Monomial(x, 1) m3 = sym.Monomial(x, 2) self.assertTrue(m1.EqualTo(m3)) self.assertFalse(m1.EqualTo(m2)) def test_str(self): m1 = sym.Monomial(x, 2) numpy_compare.assert_equal(m1, "x^2") m2 = m1 * sym.Monomial(y) numpy_compare.assert_equal(m2, "x^2 * y") def test_repr(self): m = sym.Monomial(x, 2) self.assertEqual(repr(m), '<Monomial "x^2">') def test_multiplication1(self): m1 = sym.Monomial(x, 2) m2 = sym.Monomial(y, 3) m3 = m1 * m2 self.assertEqual(m3.degree(x), 2) self.assertEqual(m3.degree(v=y), 3) # NOTE: tests kwarg v binding. def test_multiplication2(self): m1 = sym.Monomial(x, 2) m2 = m1 * sym.Monomial(y) m3 = sym.Monomial(y) * m1 self.assertEqual(m2.degree(x), 2) self.assertEqual(m2.degree(y), 1) self.assertEqual(m2, m3) def test_multiplication_float(self): # Test monomial multiplies with a float. Should return a polynomial. m1 = sym.Monomial(x, 2) p1 = m1 * 3 self.assertIsInstance(p1, sym.Polynomial) self.assertEqual(len(p1.monomial_to_coefficient_map()), 1) numpy_compare.assert_equal( p1.monomial_to_coefficient_map()[m1], sym.Expression(3)) p2 = 3 * m1 self.assertIsInstance(p2, sym.Polynomial) self.assertEqual(len(p2.monomial_to_coefficient_map()), 1) numpy_compare.assert_equal( p2.monomial_to_coefficient_map()[m1], sym.Expression(3)) def test_multiplication_expr(self): m = sym.Monomial(x, 2) e = sym.Expression(y) numpy_compare.assert_equal(m * e, sym.Polynomial(m).ToExpression() * e) numpy_compare.assert_equal(e * m, e * sym.Polynomial(m).ToExpression()) def test_addition_expr(self): m = sym.Monomial(x, 2) e = sym.Expression(y) numpy_compare.assert_equal(m + e, sym.Polynomial(m).ToExpression() + e) numpy_compare.assert_equal(e + m, e + sym.Polynomial(m).ToExpression()) def test_subtraction_expr(self): m = sym.Monomial(x, 2) e = sym.Expression(y) numpy_compare.assert_equal(m - e, sym.Polynomial(m).ToExpression() - e) numpy_compare.assert_equal(e - m, e - sym.Polynomial(m).ToExpression()) def test_division_expr(self): m = sym.Monomial(x, 2) e = sym.Expression(y) numpy_compare.assert_equal(m / e, sym.Polynomial(m).ToExpression() / e) numpy_compare.assert_equal(e / m, e / sym.Polynomial(m).ToExpression()) def test_multiplication_assignment1(self): m = sym.Monomial(x, 2) m *= sym.Monomial(y, 3) self.assertEqual(m.degree(x), 2) self.assertEqual(m.degree(y), 3) def test_multiplication_assignment2(self): m = sym.Monomial(x, 2) m *= sym.Monomial(y) self.assertEqual(m.degree(x), 2) self.assertEqual(m.degree(y), 1) def test_pow(self): m1 = sym.Monomial(x, 2) * sym.Monomial(y) # m1 = x²y m2 = m1 ** 2 # m2 = x⁴y² self.assertEqual(m2.degree(x), 4) self.assertEqual(m2.degree(y), 2) def test_pow_in_place(self): m1 = sym.Monomial(x, 2) * sym.Monomial(y) # m1 = x²y m2 = m1.pow_in_place(2) # m1 = m2 = x⁴y² self.assertEqual(m1.degree(x), 4) self.assertEqual(m1.degree(y), 2) self.assertEqual(m2.degree(x), 4) self.assertEqual(m2.degree(y), 2) # Test repeated for testing kwarg p=2. m3 = m1.pow_in_place(p=2) self.assertEqual(m1.degree(x), 8) self.assertEqual(m1.degree(y), 4) self.assertEqual(m3.degree(x), 8) self.assertEqual(m3.degree(y), 4) def test_get_powers(self): m = sym.Monomial(x, 2) * sym.Monomial(y) # m = x²y powers = EqualToDict(m.get_powers()) self.assertEqual(powers[x], 2) self.assertEqual(powers[y], 1) def test_to_expression(self): m = sym.Monomial(x, 3) * sym.Monomial(y) # m = x³y e = m.ToExpression() numpy_compare.assert_equal(e, "(pow(x, 3) * y)") def test_get_variables(self): m = sym.Monomial(x, 3) * sym.Monomial(y) # m = x³y vars = m.GetVariables() # = [x, y] self.assertEqual(vars.size(), 2) def test_monomial_basis(self): vars = sym.Variables([x, y, z]) basis1 = sym.MonomialBasis(vars, 3) basis2 = sym.MonomialBasis(vars=vars, degree=3) basis3 = sym.MonomialBasis([x, y, z], 3) basis4 = sym.MonomialBasis(vars=[x, y, z], degree=3) self.assertEqual(basis1.size, 20) self.assertEqual(basis2.size, 20) self.assertEqual(basis3.size, 20) self.assertEqual(basis4.size, 20) basis5 = sym.MonomialBasis( vars_degree={sym.Variables([x]): 2, sym.Variables([y]): 1}) self.assertEqual(basis5.size, 6) # x²y, x², xy, x, y, 1 def test_even_degree_monomial_basis(self): vars = sym.Variables([x, y]) basis = sym.EvenDegreeMonomialBasis(vars, 2) self.assertEqual(basis.size, 4) def test_off_degree_monomial_basis(self): vars = sym.Variables([x, y]) basis = sym.OddDegreeMonomialBasis(vars, 3) self.assertEqual(basis.size, 6) def test_calc_monomial_basis_order_up_to_one(self): basis = sym.CalcMonomialBasisOrderUpToOne( x=sym.Variables([x, y, z]), sort_monomial=False) self.assertEqual(basis.size, 8) def test_evaluate(self): m = sym.Monomial(x, 3) * sym.Monomial(y) # m = x³y env = {x: 2.0, y: 3.0} self.assertEqual(m.Evaluate(env), env[x] ** 3 * env[y]) self.assertEqual(m.Evaluate(env=env), env[x] ** 3 * env[y]) def test_evaluate_batch(self): m = sym.Monomial(x, 3) * sym.Monomial(y) monomial_vals = m.Evaluate( vars=[x, y], vars_values=[[1, 2, 3], [4, 5, 6]]) np.testing.assert_array_equal(monomial_vals, [4, 8 * 5, 27 * 6]) def test_evaluate_exception_np_nan(self): m = sym.Monomial(x, 3) env = {x: np.nan} with self.assertRaises(RuntimeError): m.Evaluate(env) def test_evaluate_exception_python_nan(self): m = sym.Monomial(x, 3) env = {x: float('nan')} with self.assertRaises(RuntimeError): m.Evaluate(env) def test_evaluate_partial(self): m = sym.Monomial(x, 3) * sym.Monomial(y, 2) # m = x³y² env = {x: 2.0, y: 3.0} d_72, m_1 = m.EvaluatePartial(env) self.assertEqual(d_72, 72.0) self.assertEqual(m_1, sym.Monomial()) # Monomial{} = 1 d_8, y_2 = m.EvaluatePartial(env={x: 2.0}) self.assertEqual(d_8, 8.0) self.assertEqual(y_2, sym.Monomial(y, 2)) class TestSymbolicPolynomial(unittest.TestCase): def test_default_constructor(self): p = sym.Polynomial() numpy_compare.assert_equal(p.ToExpression(), sym.Expression()) def test_constructor_maptype(self): m = {sym.Monomial(x): sym.Expression(3), sym.Monomial(y): sym.Expression(2)} # 3x + 2y p1 = sym.Polynomial(m) p2 = sym.Polynomial(map=m) expected = 3 * x + 2 * y numpy_compare.assert_equal(p1.ToExpression(), expected) numpy_compare.assert_equal(p2.ToExpression(), expected) def test_constructor_monomial(self): m = sym.Monomial(x, 2) p1 = sym.Polynomial(m) p2 = sym.Polynomial(m=m) expected = "pow(x, 2)" numpy_compare.assert_equal(p1.ToExpression(), expected) numpy_compare.assert_equal(p2.ToExpression(), expected) def test_constructor_expression(self): e = 2 * x + 3 * y p1 = sym.Polynomial(e) p2 = sym.Polynomial(e=e) numpy_compare.assert_equal(p1.ToExpression(), e) numpy_compare.assert_equal(p2.ToExpression(), e) def test_constructor_expression_indeterminates(self): e = a * x + b * y + c * z p1 = sym.Polynomial(e, sym.Variables([x, y, z])) p2 = sym.Polynomial(e=e, indeterminates=sym.Variables([x, y, z])) p3 = sym.Polynomial(e=e, indeterminates=[x, y, z]) decision_vars = sym.Variables([a, b, c]) indeterminates = sym.Variables([x, y, z]) self.assertEqual(p1.indeterminates(), indeterminates) self.assertEqual(p1.decision_variables(), decision_vars) self.assertEqual(p2.indeterminates(), indeterminates) self.assertEqual(p2.decision_variables(), decision_vars) self.assertEqual(p3.indeterminates(), indeterminates) self.assertEqual(p3.decision_variables(), decision_vars) def test_set_indeterminates(self): e = a * x * x + b * y + c * z indeterminates1 = sym.Variables([x, y, z]) p = sym.Polynomial(e, indeterminates1) self.assertEqual(p.TotalDegree(), 2) indeterminates2 = sym.Variables([a, b, c]) p.SetIndeterminates(indeterminates2) self.assertEqual(p.TotalDegree(), 1) p.SetIndeterminates(new_indeterminates=indeterminates1) self.assertEqual(p.TotalDegree(), 2) def test_degree_total_degree(self): e = a * (x ** 2) + b * (y ** 3) + c * z p = sym.Polynomial(e, [x, y, z]) self.assertEqual(p.Degree(x), 2) self.assertEqual(p.Degree(v=y), 3) self.assertEqual(p.TotalDegree(), 3) def test_monomial_to_coefficient_map(self): m = sym.Monomial(x, 2) e = a * (x ** 2) p = sym.Polynomial(e, [x]) the_map = p.monomial_to_coefficient_map() numpy_compare.assert_equal(the_map[m], a) def test_differentiate(self): e = a * (x ** 2) p = sym.Polynomial(e, [x]) # p = ax² result = p.Differentiate(x) # = 2ax numpy_compare.assert_equal(result.ToExpression(), 2 * a * x) result = p.Differentiate(x=x) numpy_compare.assert_equal(result.ToExpression(), 2 * a * x) def test_integrate(self): e = 3 * a * (x ** 2) p = sym.Polynomial(e, [x]) result = p.Integrate(x) # = ax³ numpy_compare.assert_equal(result.ToExpression(), a * x**3) result = p.Integrate(x, -1, 1) # = 2a numpy_compare.assert_equal(result.ToExpression(), 2 * a) result = p.Integrate(x=x, a=-1, b=1) numpy_compare.assert_equal(result.ToExpression(), 2 * a) def test_add_product(self): p = sym.Polynomial() m = sym.Monomial(x) p.AddProduct(sym.Expression(3), m) # p += 3 * x numpy_compare.assert_equal(p.ToExpression(), 3 * x) p.AddProduct(coeff=sym.Expression(3), m=m) # p += 3 * x numpy_compare.assert_equal(p.ToExpression(), 6 * x) def test_expand(self): a = sym.Variable("a") x = sym.Variable("x") p = sym.Polynomial({ sym.Monomial(): a ** 2 - 1 - (a+1) * (a-1), sym.Monomial(x): a + 2}) p_expand = p.Expand() self.assertEqual(len(p_expand.monomial_to_coefficient_map()), 1) self.assertTrue( p_expand.monomial_to_coefficient_map()[ sym.Monomial(x)].EqualTo(a+2)) def test_substitute_and_expand(self): a = sym.Variable("a") x = sym.Variable("x") x_sub = sym.Polynomial(a**2 - 1) p = sym.Polynomial({ sym.Monomial(): 1, sym.Monomial({x: 2}): 1}) indeterminates_sub = {x: x_sub} cached_data = sym.SubstituteAndExpandCacheData() p_sub1 = p.SubstituteAndExpand( indeterminate_substitution=indeterminates_sub) p_sub2 = p.SubstituteAndExpand( indeterminate_substitution=indeterminates_sub, substitutions_cached_data=cached_data) # Check that the data in cached_data grew # (i.e. was modified by SubstituteAndExpand) len_data = len(cached_data.get_data()) self.assertTrue(len_data > 1) p_sub3 = p.SubstituteAndExpand( indeterminate_substitution=indeterminates_sub, substitutions_cached_data=cached_data) # Check that the data in cached_data did not grow since we should # already have the expansion saved. self.assertEqual(len(cached_data.get_data()), len_data) p_expected = sym.Polynomial({ sym.Monomial(): 2, sym.Monomial({a: 2}): -2, sym.Monomial({a: 4}): 1, }) self.assertTrue(p_expected.EqualTo(p_sub1)) self.assertTrue(p_expected.EqualTo(p_sub2)) self.assertTrue(p_expected.EqualTo(p_sub3)) def test_remove_terms_with_small_coefficients(self): e = 3 * x + 1e-12 * y p = sym.Polynomial(e, [x, y]) q = p.RemoveTermsWithSmallCoefficients(1e-6) numpy_compare.assert_equal(q.ToExpression(), 3 * x) e = 3 * x + 1e-12 * y p = sym.Polynomial(e, [x, y]) q = p.RemoveTermsWithSmallCoefficients(coefficient_tol=1e-6) numpy_compare.assert_equal(q.ToExpression(), 3 * x) def test_even_odd(self): p = sym.Polynomial() self.assertTrue(p.IsEven()) self.assertTrue(p.IsOdd()) def test_roots(self): p = sym.Polynomial(x**4 - 1) roots = p.Roots() numpy_compare.assert_allclose(np.sort_complex(roots), [-1, -1j, 1j, 1], rtol=1e-14, atol=1e-14) def test_comparison(self): p = sym.Polynomial() numpy_compare.assert_equal(p, p) self.assertIsInstance(p == p, sym.Formula) self.assertEqual(p == p, sym.Formula.True_()) self.assertTrue(p.EqualTo(p)) q = sym.Polynomial(sym.Expression(10)) numpy_compare.assert_not_equal(p, q) self.assertIsInstance(p != q, sym.Formula) self.assertEqual(p != q, sym.Formula.True_()) self.assertFalse(p.EqualTo(q)) self.assertTrue( p.CoefficientsAlmostEqual(p + sym.Polynomial(1e-7), 1e-6)) self.assertTrue( p.CoefficientsAlmostEqual(p + sym.Polynomial(1e-7 * x), 1e-6)) self.assertFalse( p.CoefficientsAlmostEqual( p=(p + sym.Polynomial(2e-6 * x)), tolerance=1e-6)) a = sym.Variable("a") p_not_expand = sym.Polynomial( {sym.Monomial(): a ** 2 - 1 - (a-1) * (a+1)}) p_expand = sym.Polynomial({sym.Monomial(): 0}) self.assertFalse(p_not_expand.EqualTo(p_expand)) def test_repr(self): p = sym.Polynomial() self.assertEqual(repr(p), '<Polynomial "0">') def test_addition(self): p = sym.Polynomial(0.0, [x]) numpy_compare.assert_equal(p + p, p) m = sym.Monomial(x) numpy_compare.assert_equal(m + p, sym.Polynomial(1 * x)) numpy_compare.assert_equal(p + m, sym.Polynomial(1 * x)) numpy_compare.assert_equal(p + 0, p) numpy_compare.assert_equal(0 + p, p) numpy_compare.assert_equal(x + p, sym.Polynomial(x) + p) numpy_compare.assert_equal(p + x, p + sym.Polynomial(x)) numpy_compare.assert_equal(p + e_x, p.ToExpression() + e_x) numpy_compare.assert_equal(e_x + p, e_x + p.ToExpression()) def test_subtraction(self): p = sym.Polynomial(0.0, [x]) numpy_compare.assert_equal(p - p, p) m = sym.Monomial(x) numpy_compare.assert_equal(m - p, sym.Polynomial(1 * x)) numpy_compare.assert_equal(p - m, sym.Polynomial(-1 * x)) numpy_compare.assert_equal(p - 0, p) numpy_compare.assert_equal(0 - p, -p) numpy_compare.assert_equal(x - p, sym.Polynomial(x)) numpy_compare.assert_equal(p - x, sym.Polynomial(-x)) numpy_compare.assert_equal(p - e_x, p.ToExpression() - e_x) numpy_compare.assert_equal(e_x - p, e_x - p.ToExpression()) def test_multiplication(self): p = sym.Polynomial(0.0, [x]) numpy_compare.assert_equal(p * p, p) m = sym.Monomial(x) numpy_compare.assert_equal(m * p, p) numpy_compare.assert_equal(p * m, p) numpy_compare.assert_equal(p * 0, p) numpy_compare.assert_equal(0 * p, p) numpy_compare.assert_equal(sym.Polynomial(x) * x, sym.Polynomial(x * x)) numpy_compare.assert_equal(x * sym.Polynomial(x), sym.Polynomial(x * x)) numpy_compare.assert_equal(p * e_x, p.ToExpression() * e_x) numpy_compare.assert_equal(e_x * p, e_x * p.ToExpression()) def test_division(self): p = sym.Polynomial(x * x + x) numpy_compare.assert_equal(p / 2, sym.Polynomial(1 / 2 * x * x + 1 / 2 * x)) numpy_compare.assert_equal(2 / p, 2 / p.ToExpression()) numpy_compare.assert_equal(p / e_x, p.ToExpression() / e_x) numpy_compare.assert_equal(e_x / p, e_x / p.ToExpression()) def test_addition_assignment(self): p = sym.Polynomial() p += p numpy_compare.assert_equal(p, sym.Polynomial()) p += sym.Monomial(x) numpy_compare.assert_equal(p, sym.Polynomial(1 * x)) p += 3 numpy_compare.assert_equal(p, sym.Polynomial(3 + 1 * x)) def test_subtraction_assignment(self): p = sym.Polynomial() p -= p numpy_compare.assert_equal(p, sym.Polynomial()) p -= sym.Monomial(x) numpy_compare.assert_equal(p, sym.Polynomial(-1 * x)) p -= 3 numpy_compare.assert_equal(p, sym.Polynomial(-1 * x - 3)) def test_multiplication_assignment(self): p = sym.Polynomial() p *= p numpy_compare.assert_equal(p, sym.Polynomial()) p *= sym.Monomial(x) numpy_compare.assert_equal(p, sym.Polynomial()) p *= 3 numpy_compare.assert_equal(p, sym.Polynomial()) def test_pow(self): e = a * (x ** 2) p = sym.Polynomial(e, [x]) # p = ax² p = pow(p, 2) # p = a²x⁴ numpy_compare.assert_equal(p.ToExpression(), (a ** 2) * (x ** 4)) def test_jacobian_vector(self): e = 5 * x ** 2 + 4 * y ** 2 + 8 * x * y p = sym.Polynomial(e, [x, y]) # p = 5x² + 4y² + 8xy p_dx = sym.Polynomial(10 * x + 8 * y, [x, y]) # ∂p/∂x = 10x + 8y p_dy = sym.Polynomial(8 * y + 8 * x, [x, y]) # ∂p/∂y = 8y + 8x def check_jacobian(J): numpy_compare.assert_equal(J[0], p_dx) numpy_compare.assert_equal(J[1], p_dy) vars = [x, y] check_jacobian(p.Jacobian(vars)) check_jacobian(p.Jacobian(vars=vars)) def test_jacobian_matrix(self): p1 = sym.Polynomial(x * x + y, [x, y]) # p1 = x² + y p2 = sym.Polynomial(2 * x + y * y, [x, y]) # p2 = 2x + y² p1_dx = sym.Polynomial(2 * x, [x, y]) # ∂p1/∂x = 2x p1_dy = sym.Polynomial(1.0, [x, y]) # ∂p1/∂y = 1 p2_dx = sym.Polynomial(2, [x, y]) # ∂p1/∂x = 2 p2_dy = sym.Polynomial(2 * y, [x, y]) # ∂p1/∂y = 2y def check_jacobian(J): numpy_compare.assert_equal(J[0, 0], p1_dx) numpy_compare.assert_equal(J[0, 1], p1_dy) numpy_compare.assert_equal(J[1, 0], p2_dx) numpy_compare.assert_equal(J[1, 1], p2_dy) f = [p1, p2] vars = [x, y] check_jacobian(sym.Jacobian(f, vars)) check_jacobian(sym.Jacobian(f=f, vars=vars)) def test_evaluate_polynomial_matrix(self): p1 = sym.Polynomial(x * x + y, [x, y]) # p1 = x² + y p2 = sym.Polynomial(2 * x + y * y, [x, y]) # p2 = 2x + y² env = {x: 1.0, y: 2.0} result = sym.Evaluate([p1, p2], env) numpy_compare.assert_equal(result, [[3.0], [6.0]]) def test_matrix_substitute_with_substitution(self): m = np.array([[x + y, x * y]]) env = {x: x + 2, y: y + 3} substituted = sym.Substitute(m, env) numpy_compare.assert_equal(substituted[0, 0], m[0, 0].Substitute(env)) numpy_compare.assert_equal(substituted[0, 1], m[0, 1].Substitute(env)) def test_matrix_substitute_with_variable_and_expression(self): m = np.array([[x + y, x * y]]) substituted = sym.Substitute(m, x, 3.0) numpy_compare.assert_equal( substituted[0, 0], m[0, 0].Substitute(x, 3.0)) numpy_compare.assert_equal( substituted[0, 1], m[0, 1].Substitute(x, 3.0)) def test_matrix_evaluate_without_env(self): m = np.array([[3, 4]]) evaluated1 = sym.Evaluate(m) evaluated2 = sym.Evaluate(m=m) self.assertTrue(np.array_equal(evaluated1, m)) self.assertTrue(np.array_equal(evaluated2, m)) def test_matrix_evaluate_with_env(self): m = np.array([[x + y, x * y]]) env = {x: 3.0, y: 4.0} expected = np.array([[m[0, 0].Evaluate(env), m[0, 1].Evaluate(env)]]) evaluated1 = sym.Evaluate(m, env) evaluated2 = sym.Evaluate(m=m, env=env) self.assertTrue(np.array_equal(evaluated1, expected)) self.assertTrue(np.array_equal(evaluated2, expected)) def test_matrix_evaluate_with_random_generator(self): u = sym.Variable("uni", sym.Variable.Type.RANDOM_UNIFORM) m = np.array([[x + u, x - u]]) env = {x: 3.0} g = pydrake.common.RandomGenerator() evaluated1 = sym.Evaluate(m, env, g) evaluated2 = sym.Evaluate(m=m, env=env, generator=g) self.assertEqual(evaluated1[0, 0] + evaluated1[0, 1], 2 * env[x]) self.assertEqual(evaluated2[0, 0] + evaluated2[0, 1], 2 * env[x]) def test_hash(self): p1 = sym.Polynomial(x * x, [x]) p2 = sym.Polynomial(x * x, [x]) numpy_compare.assert_equal(p1, p2) self.assertEqual(hash(p1), hash(p2)) p1 += 1 numpy_compare.assert_not_equal(p1, p2) self.assertNotEqual(hash(p1), hash(p2)) def test_polynomial_evaluate(self): p = sym.Polynomial(a * x * x + b * x + c, [x]) env = {a: 2.0, b: 3.0, c: 5.0, x: 2.0} self.assertEqual(p.Evaluate(env), env[a] * env[x] * env[x] + env[b] * env[x] + env[c]) self.assertEqual(p.Evaluate(env=env), env[a] * env[x] * env[x] + env[b] * env[x] + env[c]) def test_evaluate_exception_np_nan(self): p = sym.Polynomial(x * x, [x]) env = {x: np.nan} with self.assertRaises(RuntimeError): p.Evaluate(env) def test_evaluate_exception_python_nan(self): p = sym.Polynomial(x * x, [x]) env = {x: float('nan')} with self.assertRaises(RuntimeError): p.Evaluate(env) def test_polynomial_evaluate_partial(self): p = sym.Polynomial(a * x * x + b * x + c, [x]) env = {a: 2.0, b: 3.0, c: 5.0} numpy_compare.assert_equal( p.EvaluatePartial(env), sym.Polynomial(env[a] * x * x + env[b] * x + env[c], [x])) numpy_compare.assert_equal( p.EvaluatePartial(env=env), sym.Polynomial(env[a] * x * x + env[b] * x + env[c], [x])) numpy_compare.assert_equal( p.EvaluatePartial(a, 2), sym.Polynomial(2 * x * x + b * x + c, [x])) numpy_compare.assert_equal( p.EvaluatePartial(var=a, c=2), sym.Polynomial(2 * x * x + b * x + c, [x])) def test_evaluate_indeterminates(self): p = sym.Polynomial(2 * x * x, [x]) p_values = p.EvaluateIndeterminates( indeterminates=[x], indeterminates_values=[[1, 2, 3]]) self.assertEqual(p_values.shape, ((3,))) def test_evaluate_w_affine_coefficients(self): p = sym.Polynomial(a * x * x + b * x, [x]) indeterminates_values = np.array([[1., 2., 3.]]) (A_coeff, decision_variables, b_coeff) = p.EvaluateWithAffineCoefficients( indeterminates=[x], indeterminates_values=indeterminates_values) self.assertEqual(A_coeff.shape, (3, 2)) self.assertEqual(b_coeff.shape, (3,)) self.assertEqual(decision_variables.shape, (2,)) for i in range(indeterminates_values.shape[1]): self.assertTrue( p.ToExpression().EvaluatePartial( {x: indeterminates_values[0, i]}).Expand().EqualTo( (A_coeff[i].dot(decision_variables) + b_coeff[i]).Expand()) ) def test_calc_polynomial_w_gram_lower(self): monomial_basis = np.array([sym.Monomial(x, 2), sym.Monomial(x)]) Q1_lower = np.array([1., 2., 3.]) poly1 = sym.CalcPolynomialWLowerTriangularPart( monomial_basis=monomial_basis, gram_lower=Q1_lower) Q2_lower = np.array([a, b, c]) poly2 = sym.CalcPolynomialWLowerTriangularPart( monomial_basis=monomial_basis, gram_lower=Q2_lower) Q3_lower = np.array([a+b, b, 2*b]) poly3 = sym.CalcPolynomialWLowerTriangularPart( monomial_basis=monomial_basis, gram_lower=Q3_lower) class TestSymbolicRationalFunction(unittest.TestCase): def test_default_constructor(self): r = sym.RationalFunction() numpy_compare.assert_equal(r.ToExpression(), sym.Expression()) def test_polynomial_constructor(self): m = {sym.Monomial(x): sym.Expression(3), sym.Monomial(y): sym.Expression(2)} # 3x + 2y p = sym.Polynomial(m) r = sym.RationalFunction(p=p) expected = 3 * x + 2 * y numpy_compare.assert_equal(r.ToExpression(), expected) def test_numerator_denominator_constructor(self): m1 = {sym.Monomial(x): sym.Expression(3), sym.Monomial(y): sym.Expression(2)} # 3x + 2y p = sym.Polynomial(m1) m2 = {sym.Monomial(z): sym.Expression(5)} # 5z q = sym.Polynomial(m2) r = sym.RationalFunction(numerator=p, denominator=q) expected = (3 * x + 2 * y) / (5 * z) numpy_compare.assert_equal(r.ToExpression(), expected) def test_monomial_constructor(self): r = sym.RationalFunction(m=sym.Monomial(x)) expected = sym.Expression(x) numpy_compare.assert_equal(r.ToExpression(), expected) def test_double_constructor(self): r = sym.RationalFunction(c=3) expected = sym.Expression(3) numpy_compare.assert_equal(r.ToExpression(), expected) def test_get_numerator_denominator(self): m1 = {sym.Monomial(x): sym.Expression(3), sym.Monomial(y): sym.Expression(2)} # 3x + 2y p = sym.Polynomial(m1) m2 = {sym.Monomial(z): sym.Expression(5)} # 5z q = sym.Polynomial(m2) r = sym.RationalFunction(p, q) numpy_compare.assert_equal(r.numerator().ToExpression(), p.ToExpression()) numpy_compare.assert_equal(r.denominator().ToExpression(), q.ToExpression()) def test_set_indeterminates(self): e_num = a * x * x + b * y + c * z e_den = a * b * x * y * z indeterminates1 = sym.Variables([x, y, z]) p = sym.Polynomial(e_num) q = sym.Polynomial(e_den) r = sym.RationalFunction(p, q) r.SetIndeterminates(new_indeterminates=indeterminates1) self.assertEqual(r.numerator().TotalDegree(), 2) self.assertEqual(r.denominator().TotalDegree(), 3) indeterminates2 = sym.Variables([a, b, c]) r.SetIndeterminates(indeterminates2) self.assertEqual(r.numerator().TotalDegree(), 1) self.assertEqual(r.denominator().TotalDegree(), 2) def test_repr(self): r = sym.RationalFunction() self.assertEqual(repr(r), '<RationalFunction "(0) / (1*1)">') def test_addition(self): r = sym.RationalFunction(sym.Polynomial(0.0, [x])) r2 = sym.RationalFunction(sym.Polynomial(1 * x)) # Test RationalFunction + RationalFunction numpy_compare.assert_equal(r + r, r) numpy_compare.assert_equal(r2 + r, r) numpy_compare.assert_equal(r + r2, r) # Test RationalFunction + Polynomial numpy_compare.assert_equal(p_x + r, r2) numpy_compare.assert_equal(r + p_x, r2) # Test RationalFunction + Monomial numpy_compare.assert_equal(m_x + r, r2) numpy_compare.assert_equal(r + m_x, r2) # Test RationalFunction + double numpy_compare.assert_equal(r + 0, r) numpy_compare.assert_equal(0 + r, r) def test_subtraction(self): r = sym.RationalFunction(sym.Polynomial(0.0, [x])) r2 = sym.RationalFunction(p_x) # Test RationalFunction - RationalFunction numpy_compare.assert_equal(r - r, r) numpy_compare.assert_equal(r2 - r, sym.RationalFunction(p_x)) numpy_compare.assert_equal(r - r2, sym.RationalFunction(-p_x)) # Test RationalFunction - Polynomial numpy_compare.assert_equal(p_x - r, sym.RationalFunction(p_x)) numpy_compare.assert_equal(r - p_x, sym.RationalFunction(-p_x)) # Test RationalFunction - Monomial numpy_compare.assert_equal(m_x - r, sym.RationalFunction(m_x)) numpy_compare.assert_equal(r - m_x, -sym.RationalFunction(m_x)) # Test RationalFunction - double numpy_compare.assert_equal(r - 0, r) numpy_compare.assert_equal(0 - r, -r) def test_multiplication(self): r = sym.RationalFunction(sym.Polynomial(0.0, [x])) # Test RationalFunction * RationalFunction numpy_compare.assert_equal(r * r, r) numpy_compare.assert_equal(sym.RationalFunction(p_x) * p_x, sym.RationalFunction(sym.Polynomial(x * x))) numpy_compare.assert_equal(p_x * sym.RationalFunction(p_x), sym.RationalFunction(sym.Polynomial(x * x))) numpy_compare.assert_equal( sym.RationalFunction(p_x) * sym.RationalFunction(p_x), sym.RationalFunction(sym.Polynomial(x * x))) # Test RationalFunction * Polynomial numpy_compare.assert_equal(p_x * r, r) numpy_compare.assert_equal(r * p_x, r) # Test RationalFunction * Monomial numpy_compare.assert_equal(m_x * r, r) numpy_compare.assert_equal(r * m_x, r) # Test RationalFunction * double numpy_compare.assert_equal(r * 0, r) numpy_compare.assert_equal(0 * r, r) def test_division(self): p1 = sym.Polynomial(x * x + x) p2 = sym.Polynomial(y) r1 = sym.RationalFunction(p1) r2 = sym.RationalFunction(p2) # Test RationalFunction / RationalFunction numpy_compare.assert_equal(r1 / r2, sym.RationalFunction(p1, p2)) # Test RationalFunction / Polynomial numpy_compare.assert_equal(r1 / p2, sym.RationalFunction(p1, p2)) # Test Polynomial / RationalFunction numpy_compare.assert_equal(p2 / r1, sym.RationalFunction(p1, p2)) # Test RationalFunction / Monomial numpy_compare.assert_equal(r2 / m_x, sym.RationalFunction(p2, m_x)) numpy_compare.assert_equal(m_x / r2, sym.RationalFunction(m_x, p2)) # Test RationalFunction / double numpy_compare.assert_equal(r1 / 2, sym.RationalFunction(p1, sym.Polynomial(2))) numpy_compare.assert_equal(2 / r1, sym.RationalFunction(sym.Polynomial(2), p1)) def test_addition_assignment(self): r = sym.RationalFunction() r += r numpy_compare.assert_equal(r, sym.RationalFunction()) r += sym.Polynomial(x) numpy_compare.assert_equal(r, sym.RationalFunction(sym.Polynomial(1 * x))) r += sym.Monomial(x) numpy_compare.assert_equal(r, sym.RationalFunction(sym.Monomial(x))) r += 3 numpy_compare.assert_equal(r, sym.RationalFunction( sym.Polynomial(1 * x + 3))) def test_subtraction_assignment(self): r = sym.RationalFunction() r -= r numpy_compare.assert_equal(r, sym.RationalFunction()) r -= sym.Polynomial(x) numpy_compare.assert_equal( r, sym.RationalFunction(sym.Polynomial(-1 * x))) r -= sym.Monomial(x) numpy_compare.assert_equal( r, -sym.RationalFunction(sym.Monomial(x))) r -= 3 numpy_compare.assert_equal( r, sym.RationalFunction(sym.Polynomial(-1 * x - 3))) def test_multiplication_assignment(self): r = sym.RationalFunction() r *= r numpy_compare.assert_equal(r, sym.RationalFunction()) r *= sym.Monomial(x) numpy_compare.assert_equal(r, sym.RationalFunction()) r *= sym.Polynomial(x) numpy_compare.assert_equal(r, sym.RationalFunction()) r *= 3 numpy_compare.assert_equal(r, sym.RationalFunction()) def test_division_assignment(self): r = sym.RationalFunction(1) r /= sym.RationalFunction(1) numpy_compare.assert_equal(r, sym.RationalFunction(1)) r /= sym.Monomial(x) numpy_compare.assert_equal(r, sym.RationalFunction(sym.Polynomial(1), sym.Polynomial(x))) r = sym.RationalFunction(1) r /= sym.Polynomial(x) numpy_compare.assert_equal(r, sym.RationalFunction(sym.Polynomial(1), sym.Polynomial(x))) r = sym.RationalFunction(1) r /= 3 numpy_compare.assert_equal(r, sym.RationalFunction(1/3)) def test_comparison(self): r = sym.RationalFunction() numpy_compare.assert_equal(r, r) self.assertIsInstance(r == r, sym.Formula) self.assertEqual(r == r, sym.Formula.True_()) self.assertTrue(r.EqualTo(r)) q = sym.RationalFunction(sym.Polynomial(10)) numpy_compare.assert_not_equal(r, q) self.assertIsInstance(r != q, sym.Formula) self.assertEqual(r != q, sym.Formula.True_()) self.assertFalse(r.EqualTo(q)) def test_rational_function_evaluate(self): p = sym.Polynomial(a * x * x + b * x + c, [x]) q = sym.Polynomial(b * x * z, [x, z]) r = sym.RationalFunction(p, q) env = {a: 2.0, b: 3.0, c: 5.0, x: 2.0, z: 5.0} expected_num = env[a] * env[x] * env[x] + env[b] * env[x] + env[c] expected_den = env[b] * env[x] * env[z] self.assertEqual(r.Evaluate(env=env), expected_num/expected_den) def test_evaluate_exception_np_nan(self): r = sym.RationalFunction(sym.Polynomial(x * x, [x])) env = {x: np.nan} with self.assertRaises(RuntimeError): r.Evaluate(env) def test_evaluate_exception_python_nan(self): r = sym.RationalFunction(sym.Polynomial(x * x, [x])) env = {x: float('nan')} with self.assertRaises(RuntimeError): r.Evaluate(env=env) class TestExtractVariablesFromExpression(unittest.TestCase): def test(self): x = sym.Variable("x") y = sym.Variable("y") e = x + sym.sin(y) + x*y variables, map_var_to_index = sym.ExtractVariablesFromExpression(e) self.assertEqual(variables.shape, (2,)) self.assertNotEqual(variables[0].get_id(), variables[1].get_id()) self.assertEqual(len(map_var_to_index), 2) for i in range(2): self.assertEqual(map_var_to_index[variables[i].get_id()], i) variables, map_var_to_index = sym.ExtractVariablesFromExpression( expressions=np.array([x + x * y, y+1])) self.assertEqual(variables.shape, (2,)) class TestDecomposeAffineExpression(unittest.TestCase): def test(self): x = sym.Variable("x") y = sym.Variable("y") e = 2 * x + 3 * y + 4 variables, map_var_to_index = sym.ExtractVariablesFromExpression(e) coeffs, constant_term = sym.DecomposeAffineExpression( e, map_var_to_index) self.assertEqual(constant_term, 4) self.assertEqual(coeffs.shape, (2,)) self.assertEqual(coeffs[map_var_to_index[x.get_id()]], 2) self.assertEqual(coeffs[map_var_to_index[y.get_id()]], 3) class TestDecomposeAffineExpressions(unittest.TestCase): def test(self): x = sym.Variable("x") y = sym.Variable("y") e = [2 * x + 3 * y + 4, 4 * x + 2 * y, 3 * x + 5] M, v = sym.DecomposeAffineExpressions(e, [x, y]) np.testing.assert_allclose(M, np.array([[2, 3], [4., 2.], [3., 0.]])) np.testing.assert_allclose(v, np.array([4., 0., 5.])) A, b, variables = sym.DecomposeAffineExpressions(e) self.assertEqual(variables.shape, (2,)) np.testing.assert_allclose(b, np.array([4., 0., 5.])) if variables[0].get_id() == x.get_id(): np.testing.assert_allclose( A, np.array([[2., 3.], [4., 2.], [3., 0.]])) self.assertEqual(variables[1].get_id(), y.get_id()) else: np.testing.assert_allclose( A, np.array([[3., 2.], [2., 4.], [0., 3.]])) self.assertEqual(variables[0].get_id(), y.get_id()) self.assertEqual(variables[1].get_id(), x.get_id()) class TestDecomposeLinearExpressions(unittest.TestCase): def test(self): x = sym.Variable("x") y = sym.Variable("y") e = [2 * x + 3 * y, 4 * x + 2 * y, 3 * x] M = sym.DecomposeLinearExpressions(e, [x, y]) np.testing.assert_array_equal( M, np.array([[2, 3], [4., 2.], [3., 0.]])) class TestDecomposeQuadraticPolynomial(unittest.TestCase): def test(self): x = sym.Variable("x") y = sym.Variable("y") e = x * x + 2 * y * y + 4 * x * y + 3 * x + 2 * y + 4 poly = sym.Polynomial(e, [x, y]) variables, map_var_to_index = sym.ExtractVariablesFromExpression(e) Q, b, c = sym.DecomposeQuadraticPolynomial(poly, map_var_to_index) self.assertEqual(c, 4) x_idx = map_var_to_index[x.get_id()] y_idx = map_var_to_index[y.get_id()] self.assertEqual(Q[x_idx, x_idx], 2) self.assertEqual(Q[x_idx, y_idx], 4) self.assertEqual(Q[y_idx, x_idx], 4) self.assertEqual(Q[y_idx, y_idx], 4) self.assertEqual(Q.shape, (2, 2)) self.assertEqual(b[x_idx], 3) self.assertEqual(b[y_idx], 2) self.assertEqual(b.shape, (2,)) class TestDecomposeLumpedParameters(unittest.TestCase): def test(self): x = sym.Variable("x") a = sym.Variable("a") b = sym.Variable("b") f = [a + x, a*a*x*x] [W, alpha, w0] = sym.DecomposeLumpedParameters(f, [a, b]) numpy_compare.assert_equal(W, [[sym.Expression(1), sym.Expression(0)], [sym.Expression(0), x*x]]) numpy_compare.assert_equal(alpha, [sym.Expression(a), a*a]) numpy_compare.assert_equal(w0, [sym.Expression(x), sym.Expression(0)]) class TestDecomposeL2NormExpression(unittest.TestCase): def test(self): x = sym.MakeVectorVariable(2, "x") [is_l2norm, A, b, vars] = sym.DecomposeL2NormExpression( e=np.linalg.norm(x), psd_tol=1e-8, coefficient_tol=1e-8) self.assertTrue(is_l2norm) numpy_compare.assert_equal(A, np.eye(2)) numpy_compare.assert_equal(b, [0, 0]) numpy_compare.assert_equal(vars, x) class TestUnapplyExpression(unittest.TestCase): def setUp(self): # For these kinds of expressions, the unapplied args should only ever # be of type Expression or float. self._composite_expressions = [ # Abs sym.abs(e_x), # Acos sym.acos(e_x), # Add 1.0 + (2.0 * x) + (3.0 * y * z), # Asin sym.asin(e_x), # Atan sym.atan(e_x), # Atan2 sym.atan2(e_x, e_y), # Ceil sym.ceil(e_x), # Constant sym.Expression(1.0), # Cos sym.cos(e_x), # Cosh sym.cosh(e_x), # Div e_x / e_y, # Exp sym.exp(e_x), # Floor sym.floor(e_x), # Log sym.log(e_x), # Max sym.max(e_x, e_y), # Min sym.min(e_x, e_y), # Mul 2.0 * x * sym.pow(y, z), # NaN sym.Expression(np.nan), # Pow sym.pow(e_x, e_y), # Sin sym.sin(e_x), # Sinh sym.sinh(e_x), # Sqrt sym.sqrt(e_x), # Tan sym.tan(e_x), # Tanh sym.tanh(e_x), ] # For these kinds of expressions, at least one of the unapplied args # will not be an Expression nor float. self._other_expressions = [ # IfThenElse sym.if_then_else(e_x < e_y, e_x, e_y), # UninterpretedFunction sym.uninterpreted_function("name", [e_x, e_y]), # Var e_x, ] def test_round_trip(self): """Focused unit test to check each kind of Expression at least once.""" for e in self._composite_expressions + self._other_expressions: with self.subTest(e=e): self._check_one_round_trip(e) def _check_one_round_trip(self, e): ctor, args = e.Unapply() result = ctor(*args) self.assertTrue(e.EqualTo(result), msg=repr(result)) def test_is_composite(self): """Confirms that some kinds of expressions have only expressions or floats as children. """ for e in self._composite_expressions: with self.subTest(e=e): self._check_one_composite(e) def _check_one_composite(self, e): ctor, args = e.Unapply() self.assertGreater(len(args), 0) for arg in args: self.assertIsInstance(arg, (sym.Expression, float)) def test_replace(self): """Acceptance test that shows how to perform substitutions.""" e1 = x * sym.sin(y) + 2.0 * sym.exp(sym.sin(y)) sy = sym.Variable("sy") e2 = self._replace(e1, sym.sin(y), sy).Expand() self.assertEqual(str(e2), "((x * sy) + 2 * exp(sy))") def _replace(self, expr, old_subexpr, new_subexpr): if not isinstance(expr, sym.Expression): return expr if expr.EqualTo(old_subexpr): return new_subexpr ctor, old_args = expr.Unapply() new_args = [ self._replace(arg, old_subexpr, new_subexpr) for arg in old_args ] return ctor(*new_args) class TestUnapplyFormula(unittest.TestCase): def setUp(self): self._relational_formulas = [ x == y, x != y, x > y, x >= y, x < y, x <= y, ] self._compound_formulas = [ sym.logical_and((x > y), (x > z)), sym.logical_or((x > y), (x > z)), sym.logical_not(x < y), ] self._misc_formulas = [ sym.Formula.False_(), sym.Formula.True_(), sym.Formula(boolean), sym.forall(vars=sym.Variables([x]), f=(x > 0)), sym.isnan(e_x), sym.positive_semidefinite([e_x]), ] self._all_formulas = ( self._relational_formulas + self._compound_formulas + self._misc_formulas ) def test_round_trip(self): """Focused unit test to check each kind of Formula at least once.""" for f in self._all_formulas: with self.subTest(f=f): self._check_one_round_trip(f) def _check_one_round_trip(self, f): ctor, args = f.Unapply() result = ctor(*args) self.assertTrue(f.EqualTo(result), msg=repr(result)) def test_all_relational(self): """Relational formulas should have Expression args.""" for f in self._relational_formulas: with self.subTest(f=f): self._check_one_relational(f) def _check_one_relational(self, f): ctor, args = f.Unapply() self.assertEqual(len(args), 2) self.assertIsInstance(args[0], sym.Expression) self.assertIsInstance(args[1], sym.Expression) def test_all_compound(self): """Relational formulas should have Formula args.""" for f in self._compound_formulas: with self.subTest(f=f): self._check_one_compound(f) def _check_one_compound(self, f): ctor, args = f.Unapply() self.assertGreaterEqual(len(args), 1) for arg in args: self.assertIsInstance(arg, sym.Formula) class TestToLatex(unittest.TestCase): def test_basics(self): x = sym.Variable("x") y = sym.Variable("y") b = sym.Variable("b", sym.Variable.Type.BOOLEAN) # Expressions self.assertEqual(sym.ToLatex(x), "x") self.assertEqual(sym.ToLatex(1.0), "1") self.assertEqual(sym.ToLatex(1.0, 1), "1") self.assertEqual(sym.ToLatex(1.01), "1.010") self.assertEqual(sym.ToLatex(1.01, 1), "1.0") self.assertEqual(sym.ToLatex(x + y), "(x + y)") self.assertEqual(sym.ToLatex(x + 2.3), "(2.300 + x)") self.assertEqual(sym.ToLatex(x - y), "(x - y)") self.assertEqual(sym.ToLatex(x - 2 * y), "(x - 2y)") self.assertEqual(sym.ToLatex(2 * x + 3 * x + 4 * y), "(5x + 4y)") self.assertEqual(sym.ToLatex(2.1 * x + 3.2 * y * y, 1), "(2.1x + 3.2y^{2})") self.assertEqual(sym.ToLatex(x * pow(y, 2)), "x y^{2}") self.assertEqual(sym.ToLatex(2 * x * y), "2 x y") self.assertEqual(sym.ToLatex(pow(x, 3)), "x^{3}") self.assertEqual(sym.ToLatex(pow(x, 3.1)), "x^{3.100}") self.assertEqual(sym.ToLatex(x / y), R"\frac{x}{y}") self.assertEqual(sym.ToLatex(sym.abs(x)), "|x|") self.assertEqual(sym.ToLatex(sym.log(x)), R"\log{x}") self.assertEqual(sym.ToLatex(sym.exp(x)), "e^{x}") self.assertEqual(sym.ToLatex(sym.sqrt(x)), R"\sqrt{x}") self.assertEqual(sym.ToLatex(sym.sin(x)), R"\sin{x}") self.assertEqual(sym.ToLatex(sym.cos(x)), R"\cos{x}") self.assertEqual(sym.ToLatex(sym.tan(x)), R"\tan{x}") self.assertEqual(sym.ToLatex(sym.asin(x)), R"\asin{x}") self.assertEqual(sym.ToLatex(sym.acos(x)), R"\acos{x}") self.assertEqual(sym.ToLatex(sym.atan(x)), R"\atan{x}") self.assertEqual(sym.ToLatex(sym.atan2(y, x)), R"\atan{\frac{y}{x}}") self.assertEqual(sym.ToLatex(sym.sinh(x)), R"\sinh{x}") self.assertEqual(sym.ToLatex(sym.cosh(x)), R"\cosh{x}") self.assertEqual(sym.ToLatex(sym.tanh(x)), R"\tanh{x}") self.assertEqual(sym.ToLatex(sym.min(x, y)), R"\min\{x, y\}") self.assertEqual(sym.ToLatex(sym.max(x, y)), R"\max\{x, y\}") self.assertEqual(sym.ToLatex(sym.ceil(x)), R"\lceil x \rceil") self.assertEqual(sym.ToLatex(sym.floor(x)), R"\lfloor x \rfloor") self.assertEqual( sym.ToLatex(sym.if_then_else(x > y, 2 * x, 3)), R"\begin{cases} 2 x & \text{if } x > y, \\" R" 3 & \text{otherwise}.\end{cases}") # Formulas self.assertEqual(sym.ToLatex(sym.Formula.False_()), R"\text{false}") self.assertEqual(sym.ToLatex(sym.Formula.True_()), R"\text{true}") self.assertEqual(sym.ToLatex(sym.Formula(b)), R"b") self.assertEqual(sym.ToLatex(x == y), R"x = y") self.assertEqual(sym.ToLatex(2.5 * x == y, 2), R"2.50 x = y") self.assertEqual(sym.ToLatex(2 * x != y), R"2 x \neq y") self.assertEqual(sym.ToLatex(2 * x > y), R"2 x > y") self.assertEqual(sym.ToLatex(2 * x >= y), R"2 x \ge y") self.assertEqual(sym.ToLatex(2 * x < y), R"2 x < y") self.assertEqual(sym.ToLatex(2 * x <= y), R"2 x \le y") self.assertEqual(sym.ToLatex(sym.logical_and(x == y, x * y > x)), R"x = y \land x y > x") self.assertEqual( sym.ToLatex(sym.logical_not(sym.logical_and(x == y, x * y > x))), R"x \neq y \lor x y \le x") self.assertEqual(sym.ToLatex(sym.logical_or(x == y, x * y < x)), R"x = y \lor x y < x") self.assertEqual( sym.ToLatex(sym.logical_not(sym.logical_or(x == y, x * y < x))), R"x \neq y \land x y \ge x") self.assertEqual(sym.ToLatex(sym.logical_not(x == y)), R"x \neq y") self.assertEqual(sym.ToLatex(sym.forall(sym.Variables([x, y]), x > y)), R"\forall x, y: (x > y)") self.assertEqual(sym.ToLatex(sym.isnan(x)), R"\text{isnan}(x)") self.assertEqual(sym.ToLatex(sym.logical_not(sym.isnan(x))), R"\neg \text{isnan}(x)") # Matrix<double> M = np.array([[1.2, 3], [4.56, 7]]) self.assertEqual(sym.ToLatex(M, 1), R"\begin{bmatrix} 1.2 & 3 \\ 4.6 & 7 \end{bmatrix}") # Matrix<Expression> Me = np.array([[x, 2.3 * y], [2.3 * y, x + y]]) self.assertEqual( sym.ToLatex(Me, 1), R"\begin{bmatrix} x & 2.3 y \\ 2.3 y & (x + y) \end{bmatrix}") # Formula with a PSD Matrix. self.assertEqual( sym.ToLatex(sym.positive_semidefinite(Me), 1), R"\begin{bmatrix} x & 2.3 y \\ 2.3 y & (x + y) \end{bmatrix}" R" \succeq 0") class TestSinCosSubstitution(unittest.TestCase): def test_basics(self): x = sym.Variable("x") y = sym.Variable("y") sx = sym.Variable("sx") sy = sym.Variable("sy") cx = sym.Variable("cx") cy = sym.Variable("cy") subs = {x: sym.SinCos(s=sx, c=cx), y: sym.SinCos(s=sy, c=cy)} self.assertTrue( sym.Substitute(e=np.sin(x + y), subs=subs).EqualTo(sx * cy + cx * sy)) m = np.array([np.sin(x), np.cos(y), 1, np.sin(2*x)]) me = np.array([ sym.Expression(sx), sym.Expression(cy), sym.Expression(1), 2 * sx * cx ]) msubs = sym.Substitute(m=m, subs=subs) self.assertEqual(msubs.shape, (4, 1)) for i in range(4): self.assertTrue(msubs[i, 0].EqualTo(me[i])) def test_halfangle(self): x = sym.Variable("x") y = sym.Variable("y") sx = sym.Variable("sx") sy = sym.Variable("sy") cx = sym.Variable("cx") cy = sym.Variable("cy") subs = { x: sym.SinCos(s=sx, c=cx, type=sym.SinCosSubstitutionType.kHalfAnglePreferSin), y: sym.SinCos(s=sy, c=cy, type=sym.SinCosSubstitutionType.kHalfAnglePreferCos) } self.assertTrue( sym.Substitute(e=np.sin(x), subs=subs).EqualTo(2 * sx * cx)) self.assertTrue( sym.Substitute(e=np.cos(x), subs=subs).EqualTo(1 - 2 * sx * sx)) self.assertTrue( sym.Substitute(e=np.cos(y), subs=subs).EqualTo(2 * cy * cy - 1)) m = np.array([np.sin(0.5*x), np.cos(0.5*y), 1, np.cos(x)]) me = np.array([sx, cy, 1, 1 - 2 * sx**2]) msubs = sym.Substitute(m=m, subs=subs) self.assertEqual(msubs.shape, (4, 1)) for i in range(4): self.assertTrue(msubs[i, 0].EqualTo(me[i])) class TestStereographicSubstitution(unittest.TestCase): def test(self): x = sym.Variable("x") y = sym.Variable("y") sx = sym.Variable("sx") sy = sym.Variable("sy") cx = sym.Variable("cx") cy = sym.Variable("cy") tx = sym.Variable("tx") ty = sym.Variable("ty") p = sym.Polynomial(2*sx+sy*cx) r = sym.SubstituteStereographicProjection( e=p, sin_cos=[sym.SinCos(s=sx, c=cx), sym.SinCos(s=sy, c=cy)], t=[tx, ty]) self.assertTrue(r.numerator().Expand().EqualTo( sym.Polynomial(4*tx*(1+ty*ty) + 2*ty * (1-tx*tx)).Expand())) self.assertTrue(r.denominator().Expand().EqualTo( sym.Polynomial((1+ty*ty)*(1+tx*tx)).Expand())) e = 2 * np.sin(x) + np.sin(y) * np.cos(x) self.assertTrue(r.numerator().Expand().EqualTo( sym.Polynomial(4*tx*(1+ty*ty) + 2*ty * (1-tx*tx)).Expand())) self.assertTrue(r.denominator().Expand().EqualTo( sym.Polynomial((1+ty*ty)*(1+tx*tx)).Expand())) class TestReplaceBilinearTerms(unittest.TestCase): def test(self): x = np.array([sym.Variable("x0"), sym.Variable("x1")]) y = np.array([ sym.Variable("y0"), sym.Variable("y1"), sym.Variable("y2")]) W = np.empty((2, 3), dtype=object) for i in range(2): for j in range(3): W[i, j] = sym.Variable(f"W({i}, {j})") e = x[0]*y[1] * 3 + x[1]*y[2] * 4 e_replace = sym.ReplaceBilinearTerms(e=e, x=x, y=y, W=W) self.assertTrue(e_replace.EqualTo(W[0, 1]*3 + W[1, 2]*4)) class TestIssue17898(unittest.TestCase): def test_numpy_dtype_object_operations_no_warnings(self): """ Tests that operations like `np.matmul`, `np.sqrt`, etc. do not issue warnings when using Drake-specified dtype=object types. See #17898 for more context. """ with warnings.catch_warnings(record=True) as w: v = sym.MakeVectorVariable(2, "v") np.eye(2) @ v np.sqrt(v) # Ensure no user-visible warnings occur. self.assertEqual(len(w), 0)
0
/home/johnshepherd/drake/bindings/pydrake/symbolic
/home/johnshepherd/drake/bindings/pydrake/symbolic/test/sympy_test.py
import pydrake.symbolic as mut import numpy as np import unittest import sympy from pydrake.symbolic import ( Expression, ExpressionKind, Formula, Variable, ) BOOLEAN = Variable.Type.BOOLEAN class TestSympy(unittest.TestCase): def test_round_trip(self): x, y, z = [Variable(name) for name in "x y z".split()] q, r = [Variable(name, BOOLEAN) for name in "q r".split()] inputs = [ # Constants. 1, 1.0, np.nan, Expression(1.0), Expression(np.nan), True, False, Formula(True), Formula(False), # Variables. x, Expression(x), q, Formula(q), # Arithmetic. x + y, y * z, x + y * z, x - y, x / y, x - y / z, x ** y, # Unary and binary functions, ordered to match ExpressionKind. mut.log(x), mut.abs(x), mut.exp(x), mut.sqrt(x), mut.pow(x, y), mut.sin(x), mut.cos(x), mut.tan(x), mut.asin(x), mut.acos(x), mut.atan(x), mut.atan2(x, y), mut.sinh(x), mut.cosh(x), mut.tanh(x), mut.min(y, x), mut.max(y, x), mut.ceil(x), mut.floor(x), mut.if_then_else(q, x, y), # Boolean functions, ordered to match FormulaKind. # First with op(x, y). x == y, x != y, x > y, x >= y, x < y, x <= y, # Next with op(y, x). y == x, y != x, y > x, y >= x, y < x, y <= x, # Next the module functions. mut.logical_and(q, r), mut.logical_or(q, r), mut.logical_and(r, q), mut.logical_or(r, q), mut.logical_not(q), # Combine and nest multiple kinds of functions. mut.if_then_else(y > x, x + mut.pow(y, 3), mut.exp(z)), ] for item in inputs: with self.subTest(item=item): self._test_one_round_trip(item) self._test_one_eval(item) def _test_one_round_trip(self, item): memo = dict() converted = mut.to_sympy(item, memo=memo) readback = mut.from_sympy(converted, memo=memo) # When the input was a built-in type, np.testing works well. if isinstance(item, (float, int, bool)): np.testing.assert_equal(item, readback) return # When the input was a Drake type, check for structral equality. item_str = f"item={item!r} ({type(item)})" converted_str = f"converted={converted!r} ({type(converted)})" readback_str = f"readback={readback!r} ({type(readback)})" try: self.assertTrue(item.EqualTo(readback), msg=f"Got {readback_str} (from {converted_str})") return except TypeError as e: # We'll do a self.fail(), but outside the except. Otherwise we are # bombarded by Python's "a new exception happened in the middle of # handling a prior exception" vomit that isn't useful in this case. pass self.fail(f"Incomparable {item_str} with " f"{readback_str} (from {converted_str})") def _test_one_eval(self, item): if isinstance(item, (float, int, bool, Variable)): # Skip this case. Evaluation is not particularly interesting. return if isinstance(item, Formula): # TODO(jwnimmer-tri) Figure out how to eval a SymPy formula. The # naive evalf with bools in `subs` does not work. return assert isinstance(item, Expression), repr(item) if item.get_kind() == ExpressionKind.IfThenElse: # TODO(jwnimmer-tri) Figure out how to eval a SymPy formula. The # naive evalf with bools in `subs` does not work. return # Create a handy dictionary of Variable Id => Variable. drake_vars = dict([ (var.get_id(), var) for var in item.GetVariables() ]) if not drake_vars: # Skip this case. Evaluation is not particularly interesting. return # Evaluate the `item` using Drake's evaluation function. drake_env = dict() for i, var in enumerate(drake_vars.values()): assert var.get_type() == Variable.Type.CONTINUOUS drake_env[var] = (i + 1) * 0.1 drake_value = item.Evaluate(drake_env) # Convert to SymPy. memo = dict() sympy_item = mut.to_sympy(item, memo=memo) # Evaluate the `sympy_item` using SymPy's evaluation function. sympy_env = dict() for drake_var_id, drake_var in drake_vars.items(): sympy_var = memo[drake_var_id] sympy_env[sympy_var] = drake_env[drake_var] sympy_value = sympy_item.evalf(subs=sympy_env) # The two evaluations must match. self.assertAlmostEqual(drake_value, sympy_value) def test_constant_to_sympy(self): converted = mut.to_sympy(Expression(2)) self.assertEqual(type(converted), sympy.Integer) converted = mut.to_sympy(Expression(2.1)) self.assertEqual(type(converted), sympy.Float)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py_scene_graph.cc
/* @file This includes the SceneGraph class and the major components of its API: SceneGraphInspector and QueryObject for examining its state and performing queries, and the query result types as well. They can be found in the pydrake.geometry module. */ #include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/common/serialize_pybind.h" #include "drake/bindings/pydrake/common/type_pack.h" #include "drake/bindings/pydrake/common/value_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/geometry/geometry_frame.h" #include "drake/geometry/scene_graph.h" #include "drake/geometry/scene_graph_config.h" namespace drake { namespace pydrake { namespace { using systems::Context; using systems::LeafSystem; void DoScalarIndependentDefinitions(py::module m) { constexpr auto& doc = pydrake_doc.drake.geometry; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; // HydroelasticContactRepresentation enumeration { using Class = HydroelasticContactRepresentation; constexpr auto& cls_doc = doc.HydroelasticContactRepresentation; py::enum_<Class>(m, "HydroelasticContactRepresentation", cls_doc.doc) .value("kTriangle", Class::kTriangle, cls_doc.kTriangle.doc) .value("kPolygon", Class::kPolygon, cls_doc.kPolygon.doc); } { using Class = geometry::DefaultProximityProperties; constexpr auto& cls_doc = doc.DefaultProximityProperties; py::class_<Class> cls(m, "DefaultProximityProperties", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } { using Class = geometry::SceneGraphConfig; constexpr auto& cls_doc = doc.SceneGraphConfig; py::class_<Class> cls(m, "SceneGraphConfig", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } } template <typename T> void DoScalarDependentDefinitions(py::module m, T) { py::tuple param = GetPyParam<T>(); constexpr auto& doc = pydrake_doc.drake.geometry; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; // SceneGraphInspector { using Class = SceneGraphInspector<T>; constexpr auto& cls_doc = doc.SceneGraphInspector; auto cls = DefineTemplateClassWithDefault<Class>( m, "SceneGraphInspector", param, cls_doc.doc); cls // BR // Scene-graph wide data. .def("num_sources", &Class::num_sources, cls_doc.num_sources.doc) .def("num_frames", &Class::num_frames, cls_doc.num_frames.doc) .def("GetAllSourceIds", &Class::GetAllSourceIds, cls_doc.GetAllSourceIds.doc) .def("GetAllFrameIds", &Class::GetAllFrameIds, cls_doc.GetAllFrameIds.doc) .def("world_frame_id", &Class::world_frame_id, cls_doc.world_frame_id.doc) .def("num_geometries", &Class::num_geometries, cls_doc.num_geometries.doc) .def("GetAllGeometryIds", &Class::GetAllGeometryIds, py::arg("role") = std::nullopt, cls_doc.GetAllGeometryIds.doc) .def("GetGeometryIds", &Class::GetGeometryIds, py::arg("geometry_set"), py::arg("role") = std::nullopt, cls_doc.GetGeometryIds.doc) .def("NumGeometriesWithRole", &Class::NumGeometriesWithRole, py::arg("role"), cls_doc.NumGeometriesWithRole.doc) .def("NumDynamicGeometries", &Class::NumDynamicGeometries, cls_doc.NumDynamicGeometries.doc) .def("NumAnchoredGeometries", &Class::NumAnchoredGeometries, cls_doc.NumAnchoredGeometries.doc) .def("GetCollisionCandidates", &Class::GetCollisionCandidates, cls_doc.GetCollisionCandidates.doc) // Sources and source-related data. .def("SourceIsRegistered", &Class::SourceIsRegistered, py::arg("source_id"), cls_doc.SourceIsRegistered.doc) .def("GetName", overload_cast_explicit<const std::string&, SourceId>( &Class::GetName), py_rvp::reference_internal, py::arg("source_id"), cls_doc.GetName.doc_1args_source_id) .def("NumFramesForSource", &Class::NumFramesForSource, py::arg("source_id"), cls_doc.NumFramesForSource.doc) .def("FramesForSource", &Class::FramesForSource, py::arg("source_id"), cls_doc.FramesForSource.doc) // Frames and their properties. .def("BelongsToSource", overload_cast_explicit<bool, FrameId, SourceId>( &Class::BelongsToSource), py::arg("frame_id"), py::arg("source_id"), cls_doc.BelongsToSource.doc_2args_frame_id_source_id) .def("GetOwningSourceName", overload_cast_explicit<const std::string&, FrameId>( &Class::GetOwningSourceName), py_rvp::reference_internal, py::arg("frame_id"), cls_doc.GetOwningSourceName.doc_1args_frame_id) .def("GetName", overload_cast_explicit<const std::string&, FrameId>( &Class::GetName), py_rvp::reference_internal, py::arg("frame_id"), cls_doc.GetName.doc_1args_frame_id) .def("GetFrameGroup", &Class::GetFrameGroup, py::arg("frame_id"), cls_doc.GetFrameGroup.doc) .def("NumGeometriesForFrame", &Class::NumGeometriesForFrame, py::arg("frame_id"), cls_doc.NumGeometriesForFrame.doc) .def("NumGeometriesForFrameWithRole", &Class::NumGeometriesForFrameWithRole, py::arg("frame_id"), py::arg("role"), cls_doc.NumGeometriesForFrameWithRole.doc) .def("GetGeometries", &Class::GetGeometries, py::arg("frame_id"), py::arg("role") = std::nullopt, cls_doc.GetGeometries.doc) .def("GetGeometryIdByName", &Class::GetGeometryIdByName, py::arg("frame_id"), py::arg("role"), py::arg("name"), cls_doc.GetGeometryIdByName.doc) // Geometries and their properties. .def("BelongsToSource", overload_cast_explicit<bool, GeometryId, SourceId>( &Class::BelongsToSource), py::arg("geometry_id"), py::arg("source_id"), cls_doc.BelongsToSource.doc_2args_geometry_id_source_id) .def("GetOwningSourceName", overload_cast_explicit<const std::string&, GeometryId>( &Class::GetOwningSourceName), py_rvp::reference_internal, py::arg("geometry_id"), cls_doc.GetOwningSourceName.doc_1args_geometry_id) .def("GetFrameId", &Class::GetFrameId, py::arg("geometry_id"), cls_doc.GetFrameId.doc) .def("GetName", overload_cast_explicit<const std::string&, GeometryId>( &Class::GetName), py_rvp::reference_internal, py::arg("geometry_id"), cls_doc.GetName.doc_1args_geometry_id) .def("GetShape", &Class::GetShape, py_rvp::reference_internal, py::arg("geometry_id"), cls_doc.GetShape.doc) .def("GetPoseInFrame", &Class::GetPoseInFrame, py_rvp::reference_internal, py::arg("geometry_id"), cls_doc.GetPoseInFrame.doc) .def("maybe_get_hydroelastic_mesh", &Class::maybe_get_hydroelastic_mesh, py::arg("geometry_id"), py_rvp::reference_internal, cls_doc.maybe_get_hydroelastic_mesh.doc) .def("GetProperties", &Class::GetProperties, py_rvp::reference_internal, py::arg("geometry_id"), py::arg("role"), cls_doc.GetProperties.doc) .def("GetProximityProperties", &Class::GetProximityProperties, py_rvp::reference_internal, py::arg("geometry_id"), cls_doc.GetProximityProperties.doc) .def("GetIllustrationProperties", &Class::GetIllustrationProperties, py_rvp::reference_internal, py::arg("geometry_id"), cls_doc.GetIllustrationProperties.doc) .def("GetPerceptionProperties", &Class::GetPerceptionProperties, py_rvp::reference_internal, py::arg("geometry_id"), cls_doc.GetPerceptionProperties.doc) .def("CollisionFiltered", &Class::CollisionFiltered, py::arg("geometry_id1"), py::arg("geometry_id2"), cls_doc.CollisionFiltered.doc) .def("CloneGeometryInstance", &Class::CloneGeometryInstance, py::arg("geometry_id"), cls_doc.CloneGeometryInstance.doc) .def("geometry_version", &Class::geometry_version, py_rvp::reference_internal, cls_doc.geometry_version.doc); } // SceneGraph { using Class = SceneGraph<T>; constexpr auto& cls_doc = doc.SceneGraph; auto cls = DefineTemplateClassWithDefault<Class, LeafSystem<T>>( m, "SceneGraph", param, cls_doc.doc); cls // BR .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<const SceneGraphConfig&>(), py::arg("config"), cls_doc.ctor.doc_1args) .def("set_config", &Class::set_config, py::arg("config"), cls_doc.set_config.doc) .def("get_config", overload_cast_explicit<const SceneGraphConfig&>(&Class::get_config), py_rvp::reference_internal, cls_doc.get_config.doc_0args) .def("get_config", overload_cast_explicit<const SceneGraphConfig&, const systems::Context<T>&>(&Class::get_config), cls_doc.get_config.doc_1args) .def("get_source_pose_port", &Class::get_source_pose_port, py_rvp::reference_internal, cls_doc.get_source_pose_port.doc) .def("get_source_configuration_port", &Class::get_source_configuration_port, py_rvp::reference_internal, cls_doc.get_source_configuration_port.doc); cls // BR .def("get_query_output_port", &Class::get_query_output_port, py_rvp::reference_internal, cls_doc.get_query_output_port.doc) .def("model_inspector", &Class::model_inspector, py_rvp::reference_internal, cls_doc.model_inspector.doc) .def("RegisterSource", py::overload_cast<const std::string&>( // BR &Class::RegisterSource), py::arg("name") = "", cls_doc.RegisterSource.doc) .def("RegisterFrame", py::overload_cast<SourceId, const GeometryFrame&>( &Class::RegisterFrame), py::arg("source_id"), py::arg("frame"), cls_doc.RegisterFrame.doc_2args) .def("RegisterFrame", py::overload_cast<SourceId, FrameId, const GeometryFrame&>( &Class::RegisterFrame), py::arg("source_id"), py::arg("parent_id"), py::arg("frame"), cls_doc.RegisterFrame.doc_3args) .def("RenameFrame", &Class::RenameFrame, py::arg("frame_id"), py::arg("name"), cls_doc.RenameFrame.doc) .def("RegisterGeometry", py::overload_cast<SourceId, FrameId, std::unique_ptr<GeometryInstance>>(&Class::RegisterGeometry), py::arg("source_id"), py::arg("frame_id"), py::arg("geometry"), cls_doc.RegisterGeometry.doc_3args) .def("RegisterGeometry", overload_cast_explicit<GeometryId, systems::Context<T>*, SourceId, FrameId, std::unique_ptr<GeometryInstance>>( &Class::RegisterGeometry), py::arg("context"), py::arg("source_id"), py::arg("frame_id"), py::arg("geometry"), cls_doc.RegisterGeometry.doc_4args) .def("RegisterAnchoredGeometry", py::overload_cast<SourceId, std::unique_ptr<GeometryInstance>>( &Class::RegisterAnchoredGeometry), py::arg("source_id"), py::arg("geometry"), cls_doc.RegisterAnchoredGeometry.doc) .def("RenameGeometry", &Class::RenameGeometry, py::arg("geometry_id"), py::arg("name"), cls_doc.RenameGeometry.doc) .def("ChangeShape", py::overload_cast<SourceId, GeometryId, const Shape&, std::optional<math::RigidTransform<double>>>( &Class::ChangeShape), py::arg("source_id"), py::arg("geometry_id"), py::arg("shape"), py::arg("X_FG") = std::nullopt, cls_doc.ChangeShape.doc_model) .def("ChangeShape", overload_cast_explicit<void, systems::Context<T>*, SourceId, GeometryId, const Shape&, std::optional<math::RigidTransform<double>>>( &Class::ChangeShape), py::arg("context"), py::arg("source_id"), py::arg("geometry_id"), py::arg("shape"), py::arg("X_FG") = std::nullopt, cls_doc.ChangeShape.doc_context) .def("RemoveGeometry", py::overload_cast<SourceId, GeometryId>(&Class::RemoveGeometry), py::arg("source_id"), py::arg("geometry_id"), cls_doc.RemoveGeometry.doc_2args) .def("RemoveGeometry", overload_cast_explicit<void, systems::Context<T>*, SourceId, GeometryId>(&Class::RemoveGeometry), py::arg("context"), py::arg("source_id"), py::arg("geometry_id"), cls_doc.RemoveGeometry.doc_3args) .def("collision_filter_manager", overload_cast_explicit<CollisionFilterManager, Context<T>*>( &Class::collision_filter_manager), py::arg("context"), cls_doc.collision_filter_manager.doc_1args) .def("collision_filter_manager", overload_cast_explicit<CollisionFilterManager>( &Class::collision_filter_manager), cls_doc.collision_filter_manager.doc_0args) .def("AddRenderer", overload_cast_explicit<void, std::string, std::unique_ptr<render::RenderEngine>>(&Class::AddRenderer), py::arg("name"), py::arg("renderer"), cls_doc.AddRenderer.doc_2args) .def("AddRenderer", overload_cast_explicit<void, systems::Context<T>*, std::string, std::unique_ptr<render::RenderEngine>>(&Class::AddRenderer), py::arg("context"), py::arg("name"), py::arg("renderer"), cls_doc.AddRenderer.doc_3args) .def("RemoveRenderer", overload_cast_explicit<void, const std::string&>( &Class::RemoveRenderer), py::arg("name"), cls_doc.RemoveRenderer.doc_1args) .def("RemoveRenderer", overload_cast_explicit<void, systems::Context<T>*, const std::string&>(&Class::RemoveRenderer), py::arg("context"), py::arg("name"), cls_doc.RemoveRenderer.doc_2args) .def("HasRenderer", overload_cast_explicit<bool, const std::string&>( &Class::HasRenderer), py::arg("name"), cls_doc.HasRenderer.doc_1args) .def("HasRenderer", overload_cast_explicit<bool, const systems::Context<T>&, const std::string&>(&Class::HasRenderer), py::arg("context"), py::arg("name"), cls_doc.HasRenderer.doc_2args) .def("RendererCount", overload_cast_explicit<int>(&Class::RendererCount), cls_doc.RendererCount.doc_0args) .def("RendererCount", overload_cast_explicit<int, const systems::Context<T>&>( &Class::RendererCount), py::arg("context"), cls_doc.RendererCount.doc_1args) .def("GetRendererTypeName", overload_cast_explicit<std::string, const std::string&>( &Class::GetRendererTypeName), py::arg("name"), cls_doc.GetRendererTypeName.doc_1args) .def("GetRendererTypeName", overload_cast_explicit<std::string, const systems::Context<T>&, const std::string&>(&Class::GetRendererTypeName), py::arg("context"), py::arg("name"), cls_doc.GetRendererTypeName.doc_2args) // - Begin: AssignRole Overloads. // - - Proximity. .def( "AssignRole", [](Class& self, SourceId source_id, GeometryId geometry_id, ProximityProperties properties, RoleAssign assign) { self.AssignRole(source_id, geometry_id, properties, assign); }, py::arg("source_id"), py::arg("geometry_id"), py::arg("properties"), py::arg("assign") = RoleAssign::kNew, cls_doc.AssignRole.doc_proximity_direct) .def( "AssignRole", [](Class& self, Context<T>* context, SourceId source_id, GeometryId geometry_id, ProximityProperties properties, RoleAssign assign) { self.AssignRole( context, source_id, geometry_id, properties, assign); }, py::arg("context"), py::arg("source_id"), py::arg("geometry_id"), py::arg("properties"), py::arg("assign") = RoleAssign::kNew, cls_doc.AssignRole.doc_proximity_context) // - - Perception. .def( "AssignRole", [](Class& self, SourceId source_id, GeometryId geometry_id, PerceptionProperties properties, RoleAssign assign) { self.AssignRole(source_id, geometry_id, properties, assign); }, py::arg("source_id"), py::arg("geometry_id"), py::arg("properties"), py::arg("assign") = RoleAssign::kNew, cls_doc.AssignRole.doc_perception_direct) .def( "AssignRole", [](Class& self, Context<T>* context, SourceId source_id, GeometryId geometry_id, PerceptionProperties properties, RoleAssign assign) { self.AssignRole( context, source_id, geometry_id, properties, assign); }, py::arg("context"), py::arg("source_id"), py::arg("geometry_id"), py::arg("properties"), py::arg("assign") = RoleAssign::kNew, cls_doc.AssignRole.doc_perception_context) // - - Illustration. .def( "AssignRole", [](Class& self, SourceId source_id, GeometryId geometry_id, IllustrationProperties properties, RoleAssign assign) { self.AssignRole(source_id, geometry_id, properties, assign); }, py::arg("source_id"), py::arg("geometry_id"), py::arg("properties"), py::arg("assign") = RoleAssign::kNew, cls_doc.AssignRole.doc_illustration_direct) .def( "AssignRole", [](Class& self, Context<T>* context, SourceId source_id, GeometryId geometry_id, IllustrationProperties properties, RoleAssign assign) { self.AssignRole( context, source_id, geometry_id, properties, assign); }, py::arg("context"), py::arg("source_id"), py::arg("geometry_id"), py::arg("properties"), py::arg("assign") = RoleAssign::kNew, cls_doc.AssignRole.doc_illustration_context) // - End: AssignRole Overloads. // - Begin: RemoveRole Overloads // - - FrameId. .def( "RemoveRole", [](Class& self, SourceId source_id, FrameId frame_id, Role role) { return self.RemoveRole(source_id, frame_id, role); }, py::arg("source_id"), py::arg("frame_id"), py::arg("role"), cls_doc.RemoveRole.doc_frame_direct) .def( "RemoveRole", [](Class& self, Context<T>* context, SourceId source_id, FrameId frame_id, Role role) { return self.RemoveRole(context, source_id, frame_id, role); }, py::arg("context"), py::arg("source_id"), py::arg("frame_id"), py::arg("role"), cls_doc.RemoveRole.doc_frame_context) // - - GeometryId. .def( "RemoveRole", [](Class& self, SourceId source_id, GeometryId geometry_id, Role role) { return self.RemoveRole(source_id, geometry_id, role); }, py::arg("source_id"), py::arg("geometry_id"), py::arg("role"), cls_doc.RemoveRole.doc_geometry_direct) .def( "RemoveRole", [](Class& self, Context<T>* context, SourceId source_id, GeometryId geometry_id, Role role) { return self.RemoveRole(context, source_id, geometry_id, role); }, py::arg("context"), py::arg("source_id"), py::arg("geometry_id"), py::arg("role"), cls_doc.RemoveRole.doc_geometry_context) // - End: RemoveRole Overloads. .def_static("world_frame_id", &Class::world_frame_id, cls_doc.world_frame_id.doc); } // FramePoseVector { using Class = FramePoseVector<T>; auto cls = DefineTemplateClassWithDefault<Class>( m, "FramePoseVector", param, doc.KinematicsVector.doc); cls // BR .def(py::init<>(), doc.KinematicsVector.ctor.doc_0args) .def( "clear", &FramePoseVector<T>::clear, doc.KinematicsVector.clear.doc) .def( "set_value", [](Class* self, FrameId id, const math::RigidTransform<T>& value) { self->set_value(id, value); }, py::arg("id"), py::arg("value"), doc.KinematicsVector.set_value.doc) .def("size", &FramePoseVector<T>::size, doc.KinematicsVector.size.doc) // This intentionally copies the value to avoid segfaults from accessing // the result after clear() is called. (see #11583) .def("value", &FramePoseVector<T>::value, py::arg("id"), doc.KinematicsVector.value.doc) .def("has_id", &FramePoseVector<T>::has_id, py::arg("id"), doc.KinematicsVector.has_id.doc) .def("ids", &FramePoseVector<T>::ids, doc.KinematicsVector.ids.doc); AddValueInstantiation<FramePoseVector<T>>(m); } // QueryObject { using Class = QueryObject<T>; constexpr auto& cls_doc = doc.QueryObject; auto cls = DefineTemplateClassWithDefault<Class>( m, "QueryObject", param, cls_doc.doc); cls // BR .def(py::init(), cls_doc.ctor.doc) .def("inspector", &QueryObject<T>::inspector, py_rvp::reference_internal, cls_doc.inspector.doc) .def("GetPoseInWorld", overload_cast_explicit<const math::RigidTransform<T>&, FrameId>( &Class::GetPoseInWorld), py::arg("frame_id"), py_rvp::reference_internal, cls_doc.GetPoseInWorld.doc_1args_frame_id) .def("GetPoseInParent", &Class::GetPoseInParent, py::arg("frame_id"), py_rvp::reference_internal, cls_doc.GetPoseInParent.doc) .def("GetPoseInWorld", overload_cast_explicit<const math::RigidTransform<T>&, GeometryId>( &Class::GetPoseInWorld), py::arg("geometry_id"), py_rvp::reference_internal, cls_doc.GetPoseInWorld.doc_1args_geometry_id) .def("ComputeSignedDistancePairwiseClosestPoints", &QueryObject<T>::ComputeSignedDistancePairwiseClosestPoints, py::arg("max_distance") = std::numeric_limits<double>::infinity(), cls_doc.ComputeSignedDistancePairwiseClosestPoints.doc) .def("ComputeSignedDistancePairClosestPoints", &QueryObject<T>::ComputeSignedDistancePairClosestPoints, py::arg("geometry_id_A"), py::arg("geometry_id_B"), cls_doc.ComputeSignedDistancePairClosestPoints.doc) .def("ComputePointPairPenetration", &QueryObject<T>::ComputePointPairPenetration, cls_doc.ComputePointPairPenetration.doc) .def("ComputeSignedDistanceToPoint", &QueryObject<T>::ComputeSignedDistanceToPoint, py::arg("p_WQ"), py::arg("threshold") = std::numeric_limits<double>::infinity(), cls_doc.ComputeSignedDistanceToPoint.doc) .def("FindCollisionCandidates", &QueryObject<T>::FindCollisionCandidates, cls_doc.FindCollisionCandidates.doc) .def("HasCollisions", &QueryObject<T>::HasCollisions, cls_doc.HasCollisions.doc) .def( "RenderColorImage", [](const Class* self, const render::ColorRenderCamera& camera, FrameId parent_frame, const math::RigidTransformd& X_PC) { systems::sensors::ImageRgba8U img( camera.core().intrinsics().width(), camera.core().intrinsics().height()); self->RenderColorImage(camera, parent_frame, X_PC, &img); return img; }, py::arg("camera"), py::arg("parent_frame"), py::arg("X_PC"), cls_doc.RenderColorImage.doc) .def( "RenderDepthImage", [](const Class* self, const render::DepthRenderCamera& camera, FrameId parent_frame, const math::RigidTransformd& X_PC) { systems::sensors::ImageDepth32F img( camera.core().intrinsics().width(), camera.core().intrinsics().height()); self->RenderDepthImage(camera, parent_frame, X_PC, &img); return img; }, py::arg("camera"), py::arg("parent_frame"), py::arg("X_PC"), cls_doc.RenderDepthImage.doc) .def( "RenderLabelImage", [](const Class* self, const render::ColorRenderCamera& camera, FrameId parent_frame, const math::RigidTransformd& X_PC) { systems::sensors::ImageLabel16I img( camera.core().intrinsics().width(), camera.core().intrinsics().height()); self->RenderLabelImage(camera, parent_frame, X_PC, &img); return img; }, py::arg("camera"), py::arg("parent_frame"), py::arg("X_PC"), cls_doc.RenderLabelImage.doc); if constexpr (scalar_predicate<T>::is_bool) { cls // BR .def("ComputeContactSurfaces", &Class::template ComputeContactSurfaces<T>, py::arg("representation"), cls_doc.ComputeContactSurfaces.doc) .def( "ComputeContactSurfacesWithFallback", [](const Class* self, HydroelasticContactRepresentation representation) { // For the Python bindings, we'll use return values instead of // output pointers. std::vector<ContactSurface<T>> surfaces; std::vector<PenetrationAsPointPair<T>> point_pairs; self->template ComputeContactSurfacesWithFallback<T>( representation, &surfaces, &point_pairs); return std::make_pair( std::move(surfaces), std::move(point_pairs)); }, py::arg("representation"), cls_doc.ComputeContactSurfacesWithFallback.doc); } AddValueInstantiation<QueryObject<T>>(m); } // SignedDistancePair { using Class = SignedDistancePair<T>; auto cls = DefineTemplateClassWithDefault<Class>( m, "SignedDistancePair", param, doc.SignedDistancePair.doc); cls // BR .def(ParamInit<Class>(), doc.SignedDistancePair.ctor.doc) .def_readwrite("id_A", &SignedDistancePair<T>::id_A, doc.SignedDistancePair.id_A.doc) .def_readwrite("id_B", &SignedDistancePair<T>::id_B, doc.SignedDistancePair.id_B.doc) .def_readwrite("p_ACa", &SignedDistancePair<T>::p_ACa, return_value_policy_for_scalar_type<T>(), doc.SignedDistancePair.p_ACa.doc) .def_readwrite("p_BCb", &SignedDistancePair<T>::p_BCb, return_value_policy_for_scalar_type<T>(), doc.SignedDistancePair.p_BCb.doc) .def_readwrite("distance", &SignedDistancePair<T>::distance, doc.SignedDistancePair.distance.doc) .def_readwrite("nhat_BA_W", &SignedDistancePair<T>::nhat_BA_W, return_value_policy_for_scalar_type<T>(), doc.SignedDistancePair.nhat_BA_W.doc); } // SignedDistanceToPoint { using Class = SignedDistanceToPoint<T>; auto cls = DefineTemplateClassWithDefault<Class>( m, "SignedDistanceToPoint", param, doc.SignedDistanceToPoint.doc); cls // BR .def(ParamInit<Class>(), doc.SignedDistanceToPoint.ctor.doc) .def_readwrite("id_G", &SignedDistanceToPoint<T>::id_G, doc.SignedDistanceToPoint.id_G.doc) .def_readwrite("p_GN", &SignedDistanceToPoint<T>::p_GN, return_value_policy_for_scalar_type<T>(), doc.SignedDistanceToPoint.p_GN.doc) .def_readwrite("distance", &SignedDistanceToPoint<T>::distance, doc.SignedDistanceToPoint.distance.doc) .def_readwrite("grad_W", &SignedDistanceToPoint<T>::grad_W, return_value_policy_for_scalar_type<T>(), doc.SignedDistanceToPoint.grad_W.doc); } // PenetrationAsPointPair { using Class = PenetrationAsPointPair<T>; auto cls = DefineTemplateClassWithDefault<Class>( m, "PenetrationAsPointPair", param, doc.PenetrationAsPointPair.doc); cls // BR .def(ParamInit<Class>()) .def_readwrite("id_A", &PenetrationAsPointPair<T>::id_A, doc.PenetrationAsPointPair.id_A.doc) .def_readwrite("id_B", &PenetrationAsPointPair<T>::id_B, doc.PenetrationAsPointPair.id_B.doc) .def_readwrite("p_WCa", &PenetrationAsPointPair<T>::p_WCa, py::return_value_policy::copy, doc.PenetrationAsPointPair.p_WCa.doc) .def_readwrite("p_WCb", &PenetrationAsPointPair<T>::p_WCb, py::return_value_policy::copy, doc.PenetrationAsPointPair.p_WCb.doc) .def_readwrite("nhat_BA_W", &PenetrationAsPointPair<T>::nhat_BA_W, doc.PenetrationAsPointPair.nhat_BA_W.doc) .def_readwrite("depth", &PenetrationAsPointPair<T>::depth, doc.PenetrationAsPointPair.depth.doc); } // ContactSurface // Currently we do not bind the constructor because users do not need to // construct it directly yet. We can get it from ComputeContactSurface*(). if constexpr (scalar_predicate<T>::is_bool) { using Class = ContactSurface<T>; constexpr auto& cls_doc = doc.ContactSurface; auto cls = DefineTemplateClassWithDefault<Class>( m, "ContactSurface", param, cls_doc.doc); cls // BR // The two overloaded constructors are not bound yet. .def("id_M", &Class::id_M, cls_doc.id_M.doc) .def("id_N", &Class::id_N, cls_doc.id_N.doc) .def("num_faces", &Class::num_faces, cls_doc.num_faces.doc) .def("num_vertices", &Class::num_vertices, cls_doc.num_vertices.doc) .def("area", &Class::area, py::arg("face_index"), cls_doc.area.doc) .def("total_area", &Class::total_area, cls_doc.total_area.doc) .def("face_normal", &Class::face_normal, py::arg("face_index"), cls_doc.face_normal.doc) .def("centroid", overload_cast_explicit<Vector3<T>, int>(&Class::centroid), py::arg("face_index"), cls_doc.centroid.doc) .def("centroid", overload_cast_explicit<const Vector3<T>&>(&Class::centroid), cls_doc.centroid.doc) .def("is_triangle", &Class::is_triangle, cls_doc.is_triangle.doc) .def("representation", &Class::representation, cls_doc.representation.doc) .def("tri_mesh_W", &Class::tri_mesh_W, py_rvp::reference_internal, cls_doc.tri_mesh_W.doc) .def("tri_e_MN", &Class::tri_e_MN, py_rvp::reference_internal, cls_doc.tri_e_MN.doc) .def("poly_mesh_W", &Class::poly_mesh_W, py_rvp::reference_internal, cls_doc.poly_mesh_W.doc) .def("poly_e_MN", &Class::poly_e_MN, py_rvp::reference_internal, cls_doc.poly_e_MN.doc) .def("HasGradE_M", &Class::HasGradE_M, cls_doc.HasGradE_M.doc) .def("HasGradE_N", &Class::HasGradE_N, cls_doc.HasGradE_N.doc) .def("EvaluateGradE_M_W", &Class::EvaluateGradE_M_W, py::arg("index"), cls_doc.EvaluateGradE_M_W.doc) .def("EvaluateGradE_N_W", &Class::EvaluateGradE_N_W, py::arg("index"), cls_doc.EvaluateGradE_N_W.doc) .def("Equal", &Class::Equal, py::arg("surface"), cls_doc.Equal.doc); DefCopyAndDeepCopy(&cls); } } // NOLINT(readability/fn_size) } // namespace void DefineGeometrySceneGraph(py::module m) { py::module::import("pydrake.systems.framework"); DoScalarIndependentDefinitions(m); type_visit([m](auto dummy) { DoScalarDependentDefinitions(m, dummy); }, CommonScalarPack{}); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py.h
#pragma once /** @file This files declares the functions which bind various portions of the geometry namespace. These functions form a complete partition of all geometry bindings. The implementation of these methods 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 { /** Defines the common elements in the drake::geometry namespace. See geometry_py_common.cc. */ void DefineGeometryCommon(py::module m); /** Defines all of the hydroelastic-specific entities. See geometry_py_hydro.cc */ void DefineGeometryHydro(py::module m); /** Defines the basic mesh types (and some parsing operations) on those types. See geometry_py_meshes.cc. */ void DefineGeometryMeshes(py::module m); /** Defines all elements in the drake::geometry::optimization namespace. See geometry_py_optimization.cc. */ void DefineGeometryOptimization(py::module m); /** Binds the public API of the drake/geometry/render and drake/geometry/render_* directories. See geometry_py_render.cc. */ void DefineGeometryRender(py::module m); /** Binds SceneGraph and its query-related classes. See geometry_py_scene_graph.cc. */ void DefineGeometrySceneGraph(py::module m); /** Binds the visualizers in drake::geometry. See geometry_py_visualizers.cc. */ void DefineGeometryVisualizers(py::module m); } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py_optimization.cc
/* @file The contains all of the public entities found in the drake::geometry::optimization namespace. They can be found in the pydrake.geometry.optimization module. */ #include "drake/bindings/pydrake/common/cpp_template_pybind.h" #include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/common/deprecation_pybind.h" #include "drake/bindings/pydrake/common/identifier_pybind.h" #include "drake/bindings/pydrake/common/serialize_pybind.h" #include "drake/bindings/pydrake/common/sorted_pair_pybind.h" #include "drake/bindings/pydrake/common/value_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/bindings/pydrake/geometry/geometry_py.h" #include "drake/bindings/pydrake/geometry/optimization_pybind.h" #include "drake/bindings/pydrake/polynomial_types_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/common/yaml/yaml_io.h" #include "drake/geometry/optimization/affine_ball.h" #include "drake/geometry/optimization/affine_subspace.h" #include "drake/geometry/optimization/c_iris_collision_geometry.h" #include "drake/geometry/optimization/cartesian_product.h" #include "drake/geometry/optimization/cspace_free_polytope.h" #include "drake/geometry/optimization/cspace_free_polytope_base.h" #include "drake/geometry/optimization/cspace_free_structs.h" #include "drake/geometry/optimization/cspace_separating_plane.h" #include "drake/geometry/optimization/geodesic_convexity.h" #include "drake/geometry/optimization/graph_of_convex_sets.h" #include "drake/geometry/optimization/hpolyhedron.h" #include "drake/geometry/optimization/hyperellipsoid.h" #include "drake/geometry/optimization/hyperrectangle.h" #include "drake/geometry/optimization/intersection.h" #include "drake/geometry/optimization/iris.h" #include "drake/geometry/optimization/minkowski_sum.h" #include "drake/geometry/optimization/point.h" #include "drake/geometry/optimization/spectrahedron.h" #include "drake/geometry/optimization/vpolytope.h" namespace drake { namespace pydrake { // CSpaceSeparatingPlane, CIrisSeparatingPlane template <typename T> void DoSeparatingPlaneDeclaration(py::module m, T) { constexpr auto& doc = pydrake_doc.drake.geometry.optimization; py::tuple param = GetPyParam<T>(); using Class = geometry::optimization::CSpaceSeparatingPlane<T>; constexpr auto& base_cls_doc = doc.CSpaceSeparatingPlane; { auto cls = DefineTemplateClassWithDefault<Class>( m, "CSpaceSeparatingPlane", param, base_cls_doc.doc) // Use py_rvp::copy here because numpy.ndarray with dtype=object // arrays must be copied, and cannot be referenced. .def_readonly("a", &Class::a, py_rvp::copy, base_cls_doc.a.doc) .def_readonly("b", &Class::b, base_cls_doc.b.doc) .def_readonly("positive_side_geometry", &Class::positive_side_geometry, base_cls_doc.positive_side_geometry.doc) .def_readonly("negative_side_geometry", &Class::negative_side_geometry, base_cls_doc.negative_side_geometry.doc) .def_readonly("expressed_body", &Class::expressed_body, base_cls_doc.expressed_body.doc) .def_readonly("plane_degree", &Class::plane_degree) // Use py_rvp::copy here because numpy.ndarray with dtype=object // arrays must be copied, and cannot be referenced. .def_readonly("decision_variables", &Class::decision_variables, py_rvp::copy, base_cls_doc.a.doc); DefCopyAndDeepCopy(&cls); AddValueInstantiation<Class>(m); } } void DefineGeometryOptimization(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry::optimization; m.doc() = "Local bindings for `drake::geometry::optimization`"; constexpr auto& doc = pydrake_doc.drake.geometry.optimization; py::module::import("pydrake.solvers"); // SampledVolume. This struct must be declared before ConvexSet as methods in // ConvexSet depend on this struct. { py::class_<SampledVolume>(m, "SampledVolume", doc.SampledVolume.doc) .def_readwrite( "volume", &SampledVolume::volume, doc.SampledVolume.volume.doc) .def_readwrite("rel_accuracy", &SampledVolume::rel_accuracy, doc.SampledVolume.rel_accuracy.doc) .def_readwrite("num_samples", &SampledVolume::num_samples, doc.SampledVolume.num_samples.doc); } // ConvexSet { const auto& cls_doc = doc.ConvexSet; py::class_<ConvexSet>(m, "ConvexSet", cls_doc.doc) .def("Clone", &ConvexSet::Clone, cls_doc.Clone.doc) .def("ambient_dimension", &ConvexSet::ambient_dimension, cls_doc.ambient_dimension.doc) .def("IntersectsWith", &ConvexSet::IntersectsWith, py::arg("other"), cls_doc.IntersectsWith.doc) .def("IsBounded", &ConvexSet::IsBounded, cls_doc.IsBounded.doc) .def("IsEmpty", &ConvexSet::IsEmpty, cls_doc.IsEmpty.doc) .def("MaybeGetPoint", &ConvexSet::MaybeGetPoint, cls_doc.MaybeGetPoint.doc) .def("MaybeGetFeasiblePoint", &ConvexSet::MaybeGetFeasiblePoint, cls_doc.MaybeGetFeasiblePoint.doc) .def("PointInSet", &ConvexSet::PointInSet, py::arg("x"), py::arg("tol") = 1e-8, cls_doc.PointInSet.doc) .def("AddPointInSetConstraints", &ConvexSet::AddPointInSetConstraints, py::arg("prog"), py::arg("vars"), cls_doc.AddPointInSetConstraints.doc) .def("AddPointInNonnegativeScalingConstraints", overload_cast_explicit< std::vector<solvers::Binding<solvers::Constraint>>, solvers::MathematicalProgram*, const Eigen::Ref<const solvers::VectorXDecisionVariable>&, const symbolic::Variable&>( &ConvexSet::AddPointInNonnegativeScalingConstraints), py::arg("prog"), py::arg("x"), py::arg("t"), cls_doc.AddPointInNonnegativeScalingConstraints.doc_3args) .def("AddPointInNonnegativeScalingConstraints", overload_cast_explicit< std::vector<solvers::Binding<solvers::Constraint>>, solvers::MathematicalProgram*, const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::VectorXd>&, const Eigen::Ref<const Eigen::VectorXd>&, double, const Eigen::Ref<const solvers::VectorXDecisionVariable>&, const Eigen::Ref<const solvers::VectorXDecisionVariable>&>( &ConvexSet::AddPointInNonnegativeScalingConstraints), py::arg("prog"), py::arg("A"), py::arg("b"), py::arg("c"), py::arg("d"), py::arg("x"), py::arg("t"), cls_doc.AddPointInNonnegativeScalingConstraints.doc_7args) .def("ToShapeWithPose", &ConvexSet::ToShapeWithPose, cls_doc.ToShapeWithPose.doc) .def("CalcVolume", &ConvexSet::CalcVolume, cls_doc.CalcVolume.doc) .def("CalcVolumeViaSampling", &ConvexSet::CalcVolumeViaSampling, py::arg("generator"), py::arg("desired_rel_accuracy") = 1e-2, py::arg("max_num_samples") = 1e4, cls_doc.CalcVolumeViaSampling.doc) .def("Projection", &ConvexSet::Projection, py::arg("points"), cls_doc.Projection.doc); } // There is a dependency cycle between Hyperellipsoid and AffineBall, so we // need to "forward declare" the Hyperellipsoid class here. py::class_<Hyperellipsoid, ConvexSet> hyperellipsoid_cls( m, "Hyperellipsoid", doc.Hyperellipsoid.doc); // AffineBall { const auto& cls_doc = doc.AffineBall; py::class_<AffineBall, ConvexSet> cls(m, "AffineBall", cls_doc.doc); cls // BR .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::VectorXd>&>(), py::arg("B"), py::arg("center"), cls_doc.ctor.doc_2args) .def(py::init<const Hyperellipsoid&>(), py::arg("ellipsoid"), cls_doc.ctor.doc_1args) .def("B", &AffineBall::B, py_rvp::reference_internal, cls_doc.B.doc) .def("center", &AffineBall::center, py_rvp::reference_internal, cls_doc.center.doc) .def_static("MinimumVolumeCircumscribedEllipsoid", &AffineBall::MinimumVolumeCircumscribedEllipsoid, py::arg("points"), py::arg("rank_tol") = 1e-6, cls_doc.MinimumVolumeCircumscribedEllipsoid.doc) .def_static("MakeAxisAligned", &AffineBall::MakeAxisAligned, py::arg("radius"), py::arg("center"), cls_doc.MakeAxisAligned.doc) .def_static("MakeHypersphere", &AffineBall::MakeHypersphere, py::arg("radius"), py::arg("center"), cls_doc.MakeHypersphere.doc) .def_static("MakeUnitBall", &AffineBall::MakeUnitBall, py::arg("dim"), cls_doc.MakeUnitBall.doc); DefClone(&cls); } // AffineSubspace { const auto& cls_doc = doc.AffineSubspace; py::class_<AffineSubspace, ConvexSet> cls(m, "AffineSubspace", cls_doc.doc); cls // BR .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::VectorXd>&>(), py::arg("basis"), py::arg("translation"), cls_doc.ctor.doc_2args_basis_translation) .def(py::init<const ConvexSet&, double>(), py::arg("set"), py::arg("tol") = 1E-12, cls_doc.ctor.doc_2args_set_tol) .def("basis", &AffineSubspace::basis, py_rvp::reference_internal, cls_doc.basis.doc) .def("translation", &AffineSubspace::translation, py_rvp::reference_internal, cls_doc.translation.doc) .def("AffineDimension", &AffineSubspace::AffineDimension, cls_doc.AffineDimension.doc); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" cls // BR .def("Project", WrapDeprecated( cls_doc.Project.doc_deprecated, &AffineSubspace::Project), py::arg("x"), cls_doc.Project.doc_deprecated); #pragma GCC diagnostic pop cls // BR .def("ToLocalCoordinates", &AffineSubspace::ToLocalCoordinates, py::arg("x"), cls_doc.ToLocalCoordinates.doc) .def("ToGlobalCoordinates", &AffineSubspace::ToGlobalCoordinates, py::arg("y"), cls_doc.ToGlobalCoordinates.doc) .def("ContainedIn", &AffineSubspace::ContainedIn, py::arg("other"), py::arg("tol") = 1e-15, cls_doc.ContainedIn.doc) .def("IsNearlyEqualTo", &AffineSubspace::IsNearlyEqualTo, py::arg("other"), py::arg("tol") = 1e-15, cls_doc.ContainedIn.doc) .def("OrthogonalComplementBasis", &AffineSubspace::OrthogonalComplementBasis, cls_doc.OrthogonalComplementBasis.doc); DefClone(&cls); } // CartesianProduct { const auto& cls_doc = doc.CartesianProduct; py::class_<CartesianProduct, ConvexSet>(m, "CartesianProduct", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init([](const std::vector<ConvexSet*>& sets) { return std::make_unique<CartesianProduct>(CloneConvexSets(sets)); }), py::arg("sets"), cls_doc.ctor.doc_1args_sets) .def(py::init<const ConvexSet&, const ConvexSet&>(), py::arg("setA"), py::arg("setB"), cls_doc.ctor.doc_2args_setA_setB) .def(py::init([](const std::vector<ConvexSet*>& sets, const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::VectorXd>& b) { return std::make_unique<CartesianProduct>( CloneConvexSets(sets), A, b); }), py::arg("sets"), py::arg("A"), py::arg("b"), cls_doc.ctor.doc_3args_sets_A_b) .def(py::init<const QueryObject<double>&, GeometryId, std::optional<FrameId>>(), py::arg("query_object"), py::arg("geometry_id"), py::arg("reference_frame") = std::nullopt, cls_doc.ctor.doc_3args_query_object_geometry_id_reference_frame) .def("num_factors", &CartesianProduct::num_factors, cls_doc.num_factors.doc) .def("factor", &CartesianProduct::factor, py_rvp::reference_internal, py::arg("index"), cls_doc.factor.doc); } // HPolyhedron { const auto& cls_doc = doc.HPolyhedron; py::class_<HPolyhedron, ConvexSet>(m, "HPolyhedron", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::VectorXd>&>(), py::arg("A"), py::arg("b"), cls_doc.ctor.doc_2args_A_b) .def(py::init<const QueryObject<double>&, GeometryId, std::optional<FrameId>>(), py::arg("query_object"), py::arg("geometry_id"), py::arg("reference_frame") = std::nullopt, cls_doc.ctor.doc_3args_query_object_geometry_id_reference_frame) .def(py::init<const VPolytope&, double>(), py::arg("vpoly"), py::arg("tol") = 1E-9, cls_doc.ctor.doc_2args_vpoly_tol) .def(py::init<const solvers::MathematicalProgram&>(), py::arg("prog"), cls_doc.ctor.doc_1args_prog) .def("A", &HPolyhedron::A, cls_doc.A.doc) .def("b", &HPolyhedron::b, cls_doc.b.doc) .def("ContainedIn", &HPolyhedron::ContainedIn, py::arg("other"), py::arg("tol") = 1E-9, cls_doc.ContainedIn.doc) .def("Intersection", &HPolyhedron::Intersection, py::arg("other"), py::arg("check_for_redundancy") = false, py::arg("tol") = 1E-9, cls_doc.Intersection.doc) .def("ReduceInequalities", &HPolyhedron::ReduceInequalities, py::arg("tol") = 1E-9, cls_doc.ReduceInequalities.doc) .def("FindRedundant", &HPolyhedron::FindRedundant, py::arg("tol") = 1E-9, cls_doc.FindRedundant.doc) .def("SimplifyByIncrementalFaceTranslation", &HPolyhedron::SimplifyByIncrementalFaceTranslation, py::arg("min_volume_ratio") = 0.1, py::arg("do_affine_transformation") = true, py::arg("max_iterations") = 10, py::arg("points_to_contain") = Eigen::MatrixXd(), py::arg("intersecting_polytopes") = std::vector<HPolyhedron>(), py::arg("keep_whole_intersection") = false, py::arg("intersection_padding") = 1e-4, py::arg("random_seed") = 0, cls_doc.SimplifyByIncrementalFaceTranslation.doc) .def("MaximumVolumeInscribedAffineTransformation", &HPolyhedron::MaximumVolumeInscribedAffineTransformation, py::arg("circumbody"), cls_doc.MaximumVolumeInscribedAffineTransformation.doc) .def("MaximumVolumeInscribedEllipsoid", &HPolyhedron::MaximumVolumeInscribedEllipsoid, cls_doc.MaximumVolumeInscribedEllipsoid.doc) .def("ChebyshevCenter", &HPolyhedron::ChebyshevCenter, cls_doc.ChebyshevCenter.doc) .def("Scale", &HPolyhedron::Scale, py::arg("scale"), py::arg("center") = std::nullopt, cls_doc.Scale.doc) .def("CartesianProduct", &HPolyhedron::CartesianProduct, py::arg("other"), cls_doc.CartesianProduct.doc) .def("CartesianPower", &HPolyhedron::CartesianPower, py::arg("n"), cls_doc.CartesianPower.doc) .def("PontryaginDifference", &HPolyhedron::PontryaginDifference, py::arg("other"), cls_doc.PontryaginDifference.doc) .def("UniformSample", overload_cast_explicit<Eigen::VectorXd, RandomGenerator*, const Eigen::Ref<const Eigen::VectorXd>&, int>( &HPolyhedron::UniformSample), py::arg("generator"), py::arg("previous_sample"), py::arg("mixing_steps") = 10, cls_doc.UniformSample.doc_3args) .def("UniformSample", overload_cast_explicit<Eigen::VectorXd, RandomGenerator*, int>( &HPolyhedron::UniformSample), py::arg("generator"), py::arg("mixing_steps") = 10, cls_doc.UniformSample.doc_2args) .def_static("MakeBox", &HPolyhedron::MakeBox, py::arg("lb"), py::arg("ub"), cls_doc.MakeBox.doc) .def_static("MakeUnitBox", &HPolyhedron::MakeUnitBox, py::arg("dim"), cls_doc.MakeUnitBox.doc) .def_static("MakeL1Ball", &HPolyhedron::MakeL1Ball, py::arg("dim"), cls_doc.MakeL1Ball.doc) .def(py::pickle( [](const HPolyhedron& self) { return std::make_pair(self.A(), self.b()); }, [](std::pair<Eigen::MatrixXd, Eigen::VectorXd> args) { return HPolyhedron(std::get<0>(args), std::get<1>(args)); })); } // Hyperellipsoid { const auto& cls_doc = doc.Hyperellipsoid; hyperellipsoid_cls // BR .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::VectorXd>&>(), py::arg("A"), py::arg("center"), cls_doc.ctor.doc_2args) .def(py::init<const QueryObject<double>&, GeometryId, std::optional<FrameId>>(), py::arg("query_object"), py::arg("geometry_id"), py::arg("reference_frame") = std::nullopt, cls_doc.ctor.doc_3args) .def(py::init<const AffineBall&>(), py::arg("ellipsoid"), cls_doc.ctor.doc_1args) .def("A", &Hyperellipsoid::A, cls_doc.A.doc) .def("center", &Hyperellipsoid::center, cls_doc.center.doc) .def("MinimumUniformScalingToTouch", &Hyperellipsoid::MinimumUniformScalingToTouch, py::arg("other"), cls_doc.MinimumUniformScalingToTouch.doc) .def_static("MakeAxisAligned", &Hyperellipsoid::MakeAxisAligned, py::arg("radius"), py::arg("center"), cls_doc.MakeAxisAligned.doc) .def_static("MakeHypersphere", &Hyperellipsoid::MakeHypersphere, py::arg("radius"), py::arg("center"), cls_doc.MakeHypersphere.doc) .def_static("MakeUnitBall", &Hyperellipsoid::MakeUnitBall, py::arg("dim"), cls_doc.MakeUnitBall.doc) .def_static("MinimumVolumeCircumscribedEllipsoid", &Hyperellipsoid::MinimumVolumeCircumscribedEllipsoid, py::arg("points"), py::arg("rank_tol") = 1e-6, cls_doc.MinimumVolumeCircumscribedEllipsoid.doc) .def(py::pickle( [](const Hyperellipsoid& self) { return std::make_pair(self.A(), self.center()); }, [](std::pair<Eigen::MatrixXd, Eigen::VectorXd> args) { return Hyperellipsoid(std::get<0>(args), std::get<1>(args)); })); } // Hyperrectangle { const auto& cls_doc = doc.Hyperrectangle; py::class_<Hyperrectangle, ConvexSet>(m, "Hyperrectangle", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<const Eigen::Ref<const Eigen::VectorXd>&, const Eigen::Ref<const Eigen::VectorXd>&>(), py::arg("lb"), py::arg("ub"), cls_doc.ctor.doc_2args) .def("lb", &Hyperrectangle::lb, cls_doc.lb.doc) .def("ub", &Hyperrectangle::ub, cls_doc.ub.doc) .def("UniformSample", &Hyperrectangle::UniformSample, py::arg("generator"), cls_doc.UniformSample.doc) .def("Center", &Hyperrectangle::Center, cls_doc.Center.doc) .def("MaybeGetIntersection", &Hyperrectangle::MaybeGetIntersection, cls_doc.MaybeGetIntersection.doc) .def("MakeHPolyhedron", &Hyperrectangle::MakeHPolyhedron, cls_doc.MakeHPolyhedron.doc) .def(py::pickle( [](const Hyperrectangle& self) { return std::make_pair(self.lb(), self.ub()); }, [](std::pair<Eigen::VectorXd, Eigen::VectorXd> args) { return Hyperrectangle(std::get<0>(args), std::get<1>(args)); })) .def_static("MaybeCalcAxisAlignedBoundingBox", &Hyperrectangle::MaybeCalcAxisAlignedBoundingBox, py::arg("set"), cls_doc.MaybeCalcAxisAlignedBoundingBox.doc); } // Intersection { const auto& cls_doc = doc.Intersection; py::class_<Intersection, ConvexSet>(m, "Intersection", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init([](const std::vector<ConvexSet*>& sets) { return std::make_unique<Intersection>(CloneConvexSets(sets)); }), py::arg("sets"), cls_doc.ctor.doc_1args) .def(py::init<const ConvexSet&, const ConvexSet&>(), py::arg("setA"), py::arg("setB"), cls_doc.ctor.doc_2args) .def("num_elements", &Intersection::num_elements, cls_doc.num_elements.doc) .def("element", &Intersection::element, py_rvp::reference_internal, py::arg("index"), cls_doc.element.doc); } // MinkowskiSum { const auto& cls_doc = doc.MinkowskiSum; py::class_<MinkowskiSum, ConvexSet>(m, "MinkowskiSum", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init([](const std::vector<ConvexSet*>& sets) { return std::make_unique<MinkowskiSum>(CloneConvexSets(sets)); }), py::arg("sets"), cls_doc.ctor.doc_1args) .def(py::init<const ConvexSet&, const ConvexSet&>(), py::arg("setA"), py::arg("setB"), cls_doc.ctor.doc_2args) .def(py::init<const QueryObject<double>&, GeometryId, std::optional<FrameId>>(), py::arg("query_object"), py::arg("geometry_id"), py::arg("reference_frame") = std::nullopt, cls_doc.ctor.doc_3args) .def("num_terms", &MinkowskiSum::num_terms, cls_doc.num_terms.doc) .def("term", &MinkowskiSum::term, py_rvp::reference_internal, py::arg("index"), cls_doc.term.doc); } // Point { const auto& cls_doc = doc.Point; py::class_<Point, ConvexSet>(m, "Point", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<const Eigen::Ref<const Eigen::VectorXd>&>(), py::arg("x"), cls_doc.ctor.doc_1args) .def(py::init<const QueryObject<double>&, GeometryId, std::optional<FrameId>, double>(), py::arg("query_object"), py::arg("geometry_id"), py::arg("reference_frame") = std::nullopt, py::arg("maximum_allowable_radius") = 0.0, cls_doc.ctor.doc_4args) .def("x", &Point::x, cls_doc.x.doc) .def("set_x", &Point::set_x, py::arg("x"), cls_doc.set_x.doc) .def(py::pickle([](const Point& self) { return self.x(); }, [](Eigen::VectorXd arg) { return Point(arg); })); } // Spectrahedron { const auto& cls_doc = doc.Spectrahedron; py::class_<Spectrahedron, ConvexSet>(m, "Spectrahedron", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<const solvers::MathematicalProgram&>(), py::arg("prog"), cls_doc.ctor.doc_1args); } // VPolytope { const auto& cls_doc = doc.VPolytope; py::class_<VPolytope, ConvexSet>(m, "VPolytope", cls_doc.doc) .def(py::init<>(), cls_doc.ctor.doc) .def(py::init<const Eigen::Ref<const Eigen::MatrixXd>&>(), py::arg("vertices"), cls_doc.ctor.doc_vertices) .def(py::init<const HPolyhedron&>(), py::arg("H"), cls_doc.ctor.doc_hpolyhedron) .def(py::init<const QueryObject<double>&, GeometryId, std::optional<FrameId>>(), py::arg("query_object"), py::arg("geometry_id"), py::arg("reference_frame") = std::nullopt, cls_doc.ctor.doc_scenegraph) .def("GetMinimalRepresentation", &VPolytope::GetMinimalRepresentation, cls_doc.GetMinimalRepresentation.doc) .def("vertices", &VPolytope::vertices, cls_doc.vertices.doc) .def_static("MakeBox", &VPolytope::MakeBox, py::arg("lb"), py::arg("ub"), cls_doc.MakeBox.doc) .def_static("MakeUnitBox", &VPolytope::MakeUnitBox, py::arg("dim"), cls_doc.MakeUnitBox.doc) .def("WriteObj", &VPolytope::WriteObj, py::arg("filename"), cls_doc.WriteObj.doc) .def(py::pickle([](const VPolytope& self) { return self.vertices(); }, [](Eigen::MatrixXd arg) { return VPolytope(arg); })); } { const auto& cls_doc = doc.IrisOptions; py::class_<IrisOptions> iris_options(m, "IrisOptions", cls_doc.doc); iris_options.def(ParamInit<IrisOptions>()) .def_readwrite("require_sample_point_is_contained", &IrisOptions::require_sample_point_is_contained, cls_doc.require_sample_point_is_contained.doc) .def_readwrite("iteration_limit", &IrisOptions::iteration_limit, cls_doc.iteration_limit.doc) .def_readwrite("termination_threshold", &IrisOptions::termination_threshold, cls_doc.termination_threshold.doc) .def_readwrite("relative_termination_threshold", &IrisOptions::relative_termination_threshold, cls_doc.relative_termination_threshold.doc) .def_readwrite("configuration_space_margin", &IrisOptions::configuration_space_margin, cls_doc.configuration_space_margin.doc) .def_readwrite("num_collision_infeasible_samples", &IrisOptions::num_collision_infeasible_samples, cls_doc.num_collision_infeasible_samples.doc) .def_property( "configuration_obstacles", [](const IrisOptions& self) { std::vector<const ConvexSet*> convex_sets; for (const copyable_unique_ptr<ConvexSet>& convex_set : self.configuration_obstacles) { convex_sets.push_back(convex_set.get()); } py::object self_py = py::cast(self, py_rvp::reference); // Keep alive, ownership: each item in `convex_sets` keeps `self` // alive. return py::cast(convex_sets, py_rvp::reference_internal, self_py); }, [](IrisOptions& self, const std::vector<ConvexSet*>& sets) { self.configuration_obstacles = CloneConvexSets(sets); }, cls_doc.configuration_obstacles.doc) .def_readwrite("starting_ellipse", &IrisOptions::starting_ellipse, cls_doc.starting_ellipse.doc) .def_readwrite("bounding_region", &IrisOptions::bounding_region, cls_doc.bounding_region.doc) .def_readwrite("num_additional_constraint_infeasible_samples", &IrisOptions::num_additional_constraint_infeasible_samples, cls_doc.num_additional_constraint_infeasible_samples.doc) .def_readwrite( "random_seed", &IrisOptions::random_seed, cls_doc.random_seed.doc) .def_readwrite("mixing_steps", &IrisOptions::mixing_steps, cls_doc.mixing_steps.doc) .def_readwrite("solver_options", &IrisOptions::solver_options, cls_doc.solver_options.doc) .def("__repr__", [](const IrisOptions& self) { return py::str( "IrisOptions(" "require_sample_point_is_contained={}, " "iteration_limit={}, " "termination_threshold={}, " "relative_termination_threshold={}, " "configuration_space_margin={}, " "num_collision_infeasible_samples={}, " "configuration_obstacles {}, " "prog_with_additional_constraints {}, " "num_additional_constraint_infeasible_samples={}, " "random_seed={}, " "mixing_steps={}" ")") .format(self.require_sample_point_is_contained, self.iteration_limit, self.termination_threshold, self.relative_termination_threshold, self.configuration_space_margin, self.num_collision_infeasible_samples, self.configuration_obstacles, self.prog_with_additional_constraints ? "is set" : "is not set", self.num_additional_constraint_infeasible_samples, self.random_seed, self.mixing_steps); }); DefReadWriteKeepAlive(&iris_options, "prog_with_additional_constraints", &IrisOptions::prog_with_additional_constraints, cls_doc.prog_with_additional_constraints.doc); } m.def( "Iris", [](const std::vector<ConvexSet*>& obstacles, const Eigen::Ref<const Eigen::VectorXd>& sample, const HPolyhedron& domain, const IrisOptions& options) { return Iris(CloneConvexSets(obstacles), sample, domain, options); }, py::arg("obstacles"), py::arg("sample"), py::arg("domain"), py::arg("options") = IrisOptions(), doc.Iris.doc); m.def( "MakeIrisObstacles", [](const QueryObject<double>& query_object, std::optional<FrameId> reference_frame) { std::vector<copyable_unique_ptr<ConvexSet>> copyable_result = MakeIrisObstacles(query_object, reference_frame); std::vector<std::unique_ptr<ConvexSet>> result( std::make_move_iterator(copyable_result.begin()), std::make_move_iterator(copyable_result.end())); return result; }, py::arg("query_object"), py::arg("reference_frame") = std::nullopt, doc.MakeIrisObstacles.doc); m.def("IrisInConfigurationSpace", py::overload_cast<const multibody::MultibodyPlant<double>&, const systems::Context<double>&, const IrisOptions&>( &IrisInConfigurationSpace), py::arg("plant"), py::arg("context"), py::arg("options") = IrisOptions(), doc.IrisInConfigurationSpace.doc); // TODO(#19597) Deprecate and remove these functions once Python // can natively handle the file I/O. m.def( "SaveIrisRegionsYamlFile", [](const std::filesystem::path& filename, const IrisRegions& regions, const std::optional<std::string>& child_name) { yaml::SaveYamlFile(filename, regions, child_name); }, py::arg("filename"), py::arg("regions"), py::arg("child_name") = std::nullopt, "Calls SaveYamlFile() to serialize an IrisRegions object."); m.def( "LoadIrisRegionsYamlFile", [](const std::filesystem::path& filename, const std::optional<std::string>& child_name) { return yaml::LoadYamlFile<IrisRegions>(filename, child_name); }, py::arg("filename"), py::arg("child_name") = std::nullopt, "Calls LoadYamlFile() to deserialize an IrisRegions object."); // GraphOfConvexSetsOptions { const auto& cls_doc = doc.GraphOfConvexSetsOptions; py::class_<GraphOfConvexSetsOptions> gcs_options( m, "GraphOfConvexSetsOptions", cls_doc.doc); gcs_options.def(py::init<>()) .def_readwrite("convex_relaxation", &GraphOfConvexSetsOptions::convex_relaxation, cls_doc.convex_relaxation.doc) .def_readwrite("preprocessing", &GraphOfConvexSetsOptions::preprocessing, cls_doc.preprocessing.doc) .def_readwrite("max_rounded_paths", &GraphOfConvexSetsOptions::max_rounded_paths, cls_doc.max_rounded_paths.doc) .def_readwrite("max_rounding_trials", &GraphOfConvexSetsOptions::max_rounding_trials, cls_doc.max_rounding_trials.doc) .def_readwrite("flow_tolerance", &GraphOfConvexSetsOptions::flow_tolerance, cls_doc.flow_tolerance.doc) .def_readwrite("rounding_seed", &GraphOfConvexSetsOptions::rounding_seed, cls_doc.rounding_seed.doc) .def_property("solver_options", py::cpp_function( [](GraphOfConvexSetsOptions& self) { return &(self.solver_options); }, py_rvp::reference_internal), py::cpp_function([](GraphOfConvexSetsOptions& self, solvers::SolverOptions solver_options) { self.solver_options = std::move(solver_options); }), cls_doc.solver_options.doc) .def_property("restriction_solver_options", py::cpp_function( [](GraphOfConvexSetsOptions& self) { return &(self.restriction_solver_options); }, py_rvp::reference_internal), py::cpp_function( [](GraphOfConvexSetsOptions& self, solvers::SolverOptions restriction_solver_options) { self.restriction_solver_options = std::move(restriction_solver_options); }), cls_doc.restriction_solver_options.doc) .def("__repr__", [](const GraphOfConvexSetsOptions& self) { return py::str( "GraphOfConvexSetsOptions(" "convex_relaxation={}, " "preprocessing={}, " "max_rounded_paths={}, " "max_rounding_trials={}, " "flow_tolerance={}, " "rounding_seed={}, " "solver={}, " "restriction_solver={}, " "solver_options={}, " "restriction_solver_options={}, " ")") .format(self.convex_relaxation, self.preprocessing, self.max_rounded_paths, self.max_rounding_trials, self.flow_tolerance, self.rounding_seed, self.solver, self.restriction_solver, self.solver_options, self.restriction_solver_options); }); DefReadWriteKeepAlive(&gcs_options, "solver", &GraphOfConvexSetsOptions::solver, cls_doc.solver.doc); DefReadWriteKeepAlive(&gcs_options, "restriction_solver", &GraphOfConvexSetsOptions::restriction_solver, cls_doc.restriction_solver.doc); } // GraphOfConvexSets { const std::unordered_set<GraphOfConvexSets::Transcription> all_transcriptions = {GraphOfConvexSets::Transcription::kMIP, GraphOfConvexSets::Transcription::kRelaxation, GraphOfConvexSets::Transcription::kRestriction}; const auto& cls_doc = doc.GraphOfConvexSets; py::class_<GraphOfConvexSets> graph_of_convex_sets( m, "GraphOfConvexSets", cls_doc.doc); BindIdentifier<GraphOfConvexSets::VertexId>( graph_of_convex_sets, "VertexId", doc.GraphOfConvexSets.VertexId.doc); BindIdentifier<GraphOfConvexSets::EdgeId>( graph_of_convex_sets, "EdgeId", doc.GraphOfConvexSets.EdgeId.doc); // Transcription constexpr auto& enum_doc = doc.GraphOfConvexSets.Transcription; py::enum_<GraphOfConvexSets::Transcription> enum_py( graph_of_convex_sets, "Transcription", enum_doc.doc); enum_py // BR .value( "kMIP", GraphOfConvexSets::Transcription::kMIP, enum_doc.kMIP.doc) .value("kRelaxation", GraphOfConvexSets::Transcription::kRelaxation, enum_doc.kRelaxation.doc) .value("kRestriction", GraphOfConvexSets::Transcription::kRestriction, enum_doc.kRestriction.doc); // Vertex const auto& vertex_doc = doc.GraphOfConvexSets.Vertex; py::class_<GraphOfConvexSets::Vertex>( graph_of_convex_sets, "Vertex", vertex_doc.doc) .def("id", &GraphOfConvexSets::Vertex::id, vertex_doc.id.doc) .def("ambient_dimension", &GraphOfConvexSets::Vertex::ambient_dimension, vertex_doc.ambient_dimension.doc) .def("name", &GraphOfConvexSets::Vertex::name, vertex_doc.name.doc) // As in trajectory_optimization_py.cc, we use a lambda to *copy* // the decision variables; otherwise we get dtype=object arrays // cannot be referenced. .def( "x", [](const GraphOfConvexSets::Vertex& self) -> const VectorX<symbolic::Variable> { return self.x(); }, vertex_doc.x.doc) .def("set", &GraphOfConvexSets::Vertex::set, py_rvp::reference_internal, vertex_doc.set.doc) .def("AddCost", py::overload_cast<const symbolic::Expression&>( &GraphOfConvexSets::Vertex::AddCost), py::arg("e"), vertex_doc.AddCost.doc_expression) .def("AddCost", py::overload_cast<const solvers::Binding<solvers::Cost>&>( &GraphOfConvexSets::Vertex::AddCost), py::arg("binding"), vertex_doc.AddCost.doc_binding) .def("AddConstraint", overload_cast_explicit<solvers::Binding<solvers::Constraint>, const symbolic::Formula&, const std::unordered_set<GraphOfConvexSets::Transcription>&>( &GraphOfConvexSets::Vertex::AddConstraint), py::arg("f"), py::arg("use_in_transcription") = all_transcriptions, vertex_doc.AddConstraint.doc_formula) .def("AddConstraint", overload_cast_explicit<solvers::Binding<solvers::Constraint>, const solvers::Binding<solvers::Constraint>&, const std::unordered_set<GraphOfConvexSets::Transcription>&>( &GraphOfConvexSets::Vertex::AddConstraint), py::arg("binding"), py::arg("use_in_transcription") = all_transcriptions, vertex_doc.AddConstraint.doc_binding) .def("GetCosts", &GraphOfConvexSets::Vertex::GetCosts, vertex_doc.GetCosts.doc) .def("GetConstraints", &GraphOfConvexSets::Vertex::GetConstraints, py::arg("used_in_transcription") = all_transcriptions, vertex_doc.GetConstraints.doc) .def("GetSolutionCost", &GraphOfConvexSets::Vertex::GetSolutionCost, py::arg("result"), vertex_doc.GetSolutionCost.doc) .def("GetSolution", &GraphOfConvexSets::Vertex::GetSolution, py::arg("result"), vertex_doc.GetSolution.doc) .def("incoming_edges", &GraphOfConvexSets::Vertex::incoming_edges, py_rvp::reference_internal, vertex_doc.incoming_edges.doc) .def("outgoing_edges", &GraphOfConvexSets::Vertex::outgoing_edges, py_rvp::reference_internal, vertex_doc.outgoing_edges.doc); // Edge const auto& edge_doc = doc.GraphOfConvexSets.Edge; py::class_<GraphOfConvexSets::Edge>( graph_of_convex_sets, "Edge", edge_doc.doc) .def("id", &GraphOfConvexSets::Edge::id, edge_doc.id.doc) .def("name", &GraphOfConvexSets::Edge::name, edge_doc.name.doc) .def("u", overload_cast_explicit<GraphOfConvexSets::Vertex&>( &GraphOfConvexSets::Edge::u), py_rvp::reference_internal, edge_doc.u.doc_0args_nonconst) .def("v", overload_cast_explicit<GraphOfConvexSets::Vertex&>( &GraphOfConvexSets::Edge::v), py_rvp::reference_internal, edge_doc.v.doc_0args_nonconst) .def("phi", &GraphOfConvexSets::Edge::phi, py_rvp::reference_internal, edge_doc.phi.doc) .def( "xu", [](const GraphOfConvexSets::Edge& self) -> const VectorX<symbolic::Variable> { return self.xu(); }, edge_doc.xu.doc) .def( "xv", [](const GraphOfConvexSets::Edge& self) -> const VectorX<symbolic::Variable> { return self.xv(); }, edge_doc.xv.doc) .def("AddCost", py::overload_cast<const symbolic::Expression&>( &GraphOfConvexSets::Edge::AddCost), py::arg("e"), edge_doc.AddCost.doc_expression) .def("AddCost", py::overload_cast<const solvers::Binding<solvers::Cost>&>( &GraphOfConvexSets::Edge::AddCost), py::arg("binding"), edge_doc.AddCost.doc_binding) .def("AddConstraint", overload_cast_explicit<solvers::Binding<solvers::Constraint>, const symbolic::Formula&, const std::unordered_set<GraphOfConvexSets::Transcription>&>( &GraphOfConvexSets::Edge::AddConstraint), py::arg("f"), py::arg("use_in_transcription") = all_transcriptions, edge_doc.AddConstraint.doc_formula) .def("AddConstraint", overload_cast_explicit<solvers::Binding<solvers::Constraint>, const solvers::Binding<solvers::Constraint>&, const std::unordered_set<GraphOfConvexSets::Transcription>&>( &GraphOfConvexSets::Edge::AddConstraint), py::arg("binding"), py::arg("use_in_transcription") = all_transcriptions, edge_doc.AddConstraint.doc_binding) .def("AddPhiConstraint", &GraphOfConvexSets::Edge::AddPhiConstraint, py::arg("phi_value"), edge_doc.AddPhiConstraint.doc) .def("ClearPhiConstraints", &GraphOfConvexSets::Edge::ClearPhiConstraints, edge_doc.ClearPhiConstraints.doc) .def("GetCosts", &GraphOfConvexSets::Edge::GetCosts, edge_doc.GetCosts.doc) .def("GetConstraints", &GraphOfConvexSets::Edge::GetConstraints, py::arg("used_in_transcription") = all_transcriptions, edge_doc.GetConstraints.doc) .def("GetSolutionCost", &GraphOfConvexSets::Edge::GetSolutionCost, py::arg("result"), edge_doc.GetSolutionCost.doc) .def("GetSolutionPhiXu", &GraphOfConvexSets::Edge::GetSolutionPhiXu, py::arg("result"), edge_doc.GetSolutionPhiXu.doc) .def("GetSolutionPhiXv", &GraphOfConvexSets::Edge::GetSolutionPhiXv, py::arg("result"), edge_doc.GetSolutionPhiXv.doc); graph_of_convex_sets // BR .def(py::init<>(), cls_doc.ctor.doc) .def("AddVertex", &GraphOfConvexSets::AddVertex, py::arg("set"), py::arg("name") = "", py_rvp::reference_internal, cls_doc.AddVertex.doc) .def("AddEdge", py::overload_cast<GraphOfConvexSets::Vertex*, GraphOfConvexSets::Vertex*, std::string>( &GraphOfConvexSets::AddEdge), py::arg("u"), py::arg("v"), py::arg("name") = "", py_rvp::reference_internal, cls_doc.AddEdge.doc) .def("RemoveVertex", py::overload_cast<GraphOfConvexSets::Vertex*>( &GraphOfConvexSets::RemoveVertex), py::arg("vertex"), cls_doc.RemoveVertex.doc) .def("RemoveEdge", py::overload_cast<GraphOfConvexSets::Edge*>( &GraphOfConvexSets::RemoveEdge), py::arg("edge"), cls_doc.RemoveEdge.doc) .def("Vertices", overload_cast_explicit<std::vector<GraphOfConvexSets::Vertex*>>( &GraphOfConvexSets::Vertices), py_rvp::reference_internal, cls_doc.Vertices.doc) .def("Edges", overload_cast_explicit<std::vector<GraphOfConvexSets::Edge*>>( &GraphOfConvexSets::Edges), py_rvp::reference_internal, cls_doc.Edges.doc) .def("ClearAllPhiConstraints", &GraphOfConvexSets::ClearAllPhiConstraints, cls_doc.ClearAllPhiConstraints.doc) .def("GetGraphvizString", &GraphOfConvexSets::GetGraphvizString, py::arg("result") = std::nullopt, py::arg("show_slacks") = true, py::arg("precision") = 3, py::arg("scientific") = false, cls_doc.GetGraphvizString.doc) .def("SolveShortestPath", overload_cast_explicit<solvers::MathematicalProgramResult, const GraphOfConvexSets::Vertex&, const GraphOfConvexSets::Vertex&, const GraphOfConvexSetsOptions&>( &GraphOfConvexSets::SolveShortestPath), py::arg("source"), py::arg("target"), py::arg("options") = GraphOfConvexSetsOptions(), cls_doc.SolveShortestPath.doc) .def("GetSolutionPath", &GraphOfConvexSets::GetSolutionPath, py::arg("source"), py::arg("target"), py::arg("result"), py::arg("tolerance") = 1e-3, py_rvp::reference_internal, cls_doc.GetSolutionPath.doc) .def("SolveConvexRestriction", &GraphOfConvexSets::SolveConvexRestriction, py::arg("active_edges"), py::arg("options") = GraphOfConvexSetsOptions(), cls_doc.SolveConvexRestriction.doc); } { // Definitions for c_iris_collision_geometry.h/cc py::enum_<PlaneSide>(m, "PlaneSide", doc.PlaneSide.doc) .value("kPositive", PlaneSide::kPositive) .value("kNegative", PlaneSide::kNegative); py::enum_<CIrisGeometryType>( m, "CIrisGeometryType", doc.CIrisGeometryType.doc) .value("kPolytope", CIrisGeometryType::kPolytope, doc.CIrisGeometryType.kPolytope.doc) .value("kSphere", CIrisGeometryType::kSphere, doc.CIrisGeometryType.kSphere.doc) .value("kCylinder", CIrisGeometryType::kCylinder, doc.CIrisGeometryType.kCylinder.doc) .value("kCapsule", CIrisGeometryType::kCapsule, doc.CIrisGeometryType.kCapsule.doc); py::class_<CIrisCollisionGeometry>( m, "CIrisCollisionGeometry", doc.CIrisCollisionGeometry.doc) .def("type", &CIrisCollisionGeometry::type, doc.CIrisCollisionGeometry.type.doc) .def("geometry", &CIrisCollisionGeometry::geometry, py_rvp::reference_internal, doc.CIrisCollisionGeometry.geometry.doc) .def("body_index", &CIrisCollisionGeometry::body_index, doc.CIrisCollisionGeometry.body_index.doc) .def("id", &CIrisCollisionGeometry::id, doc.CIrisCollisionGeometry.id.doc) .def("X_BG", &CIrisCollisionGeometry::X_BG, doc.CIrisCollisionGeometry.X_BG.doc) .def("num_rationals", &CIrisCollisionGeometry::num_rationals, doc.CIrisCollisionGeometry.num_rationals.doc); } { py::enum_<SeparatingPlaneOrder>( m, "SeparatingPlaneOrder", doc.SeparatingPlaneOrder.doc) .value("kAffine", SeparatingPlaneOrder::kAffine, doc.SeparatingPlaneOrder.kAffine.doc); type_visit([m](auto dummy) { DoSeparatingPlaneDeclaration(m, dummy); }, type_pack<double, symbolic::Variable>()); } { // Definitions for cpsace_free_structs.h/cc constexpr auto& prog_doc = doc.SeparationCertificateProgramBase; auto prog_cls = py::class_<SeparationCertificateProgramBase>( m, "SeparationCertificateProgramBase", prog_doc.doc) .def( "prog", [](const SeparationCertificateProgramBase* self) { return self->prog.get(); }, py_rvp::reference_internal) .def_readonly("plane_index", &SeparationCertificateProgramBase::plane_index); constexpr auto& result_doc = doc.SeparationCertificateResultBase; auto result_cls = py::class_<SeparationCertificateResultBase>( m, "SeparationCertificateResultBase", result_doc.doc) .def_readonly("a", &SeparationCertificateResultBase::a) .def_readonly("b", &SeparationCertificateResultBase::b) .def_readonly("plane_decision_var_vals", &SeparationCertificateResultBase::plane_decision_var_vals) .def_readonly("result", &SeparationCertificateResultBase::result); constexpr auto& find_options_doc = doc.FindSeparationCertificateOptions; auto find_options_cls = py::class_<FindSeparationCertificateOptions>( m, "FindSeparationCertificateOptions", find_options_doc.doc) .def(py::init<>()) .def_readwrite( "parallelism", &FindSeparationCertificateOptions::parallelism) .def_readwrite( "verbose", &FindSeparationCertificateOptions::verbose) .def_readwrite( "solver_id", &FindSeparationCertificateOptions::solver_id) .def_readwrite("terminate_at_failure", &FindSeparationCertificateOptions::terminate_at_failure) .def_readwrite("solver_options", &FindSeparationCertificateOptions::solver_options); } { using BaseClass = CspaceFreePolytopeBase; const auto& base_cls_doc = doc.CspaceFreePolytopeBase; py::class_<BaseClass> cspace_free_polytope_base_cls( m, "CspaceFreePolytopeBase", base_cls_doc.doc); cspace_free_polytope_base_cls // TODO(Alexandre.Amice): Bind rational_forward_kinematics to resolve // #20025. .def("map_geometries_to_separating_planes", &BaseClass::map_geometries_to_separating_planes, base_cls_doc.map_geometries_to_separating_planes.doc) .def("separating_planes", &BaseClass::separating_planes, base_cls_doc.separating_planes.doc) .def("y_slack", &BaseClass::y_slack, base_cls_doc.y_slack.doc); { const auto& options_cls_doc = base_cls_doc.Options; py::class_<BaseClass::Options> options_cls( cspace_free_polytope_base_cls, "Options", options_cls_doc.doc); options_cls // BR .def(py::init<>(), options_cls_doc.ctor.doc) .def_readwrite("with_cross_y", &BaseClass::Options::with_cross_y, options_cls_doc.with_cross_y.doc); DefReprUsingSerialize(&options_cls); } using Class = CspaceFreePolytope; const auto& cls_doc = doc.CspaceFreePolytope; py::class_<Class, BaseClass> cspace_free_polytope_cls( m, "CspaceFreePolytope", cls_doc.doc); cspace_free_polytope_cls .def(py::init<const multibody::MultibodyPlant<double>*, const geometry::SceneGraph<double>*, SeparatingPlaneOrder, const Eigen::Ref<const Eigen::VectorXd>&, const Class::Options&>(), py::arg("plant"), py::arg("scene_graph"), py::arg("plane_order"), py::arg("q_star"), py::arg("options") = Class::Options(), // Keep alive, reference: `self` keeps `plant` alive. py::keep_alive<1, 2>(), // Keep alive, reference: `self` keeps `scene_graph` alive. py::keep_alive<1, 3>(), cls_doc.ctor.doc) .def( "FindSeparationCertificateGivenPolytope", [](const CspaceFreePolytope* self, const Eigen::Ref<const Eigen::MatrixXd>& C, const Eigen::Ref<const Eigen::VectorXd>& d, const CspaceFreePolytope::IgnoredCollisionPairs& ignored_collision_pairs, const CspaceFreePolytope:: FindSeparationCertificateGivenPolytopeOptions& options) { std::unordered_map<SortedPair<geometry::GeometryId>, CspaceFreePolytope::SeparationCertificateResult> certificates; bool success = self->FindSeparationCertificateGivenPolytope( C, d, ignored_collision_pairs, options, &certificates); return std::pair(success, certificates); }, py::arg("C"), py::arg("d"), py::arg("ignored_collision_pairs"), py::arg("options"), // The `options` contains a `Parallelism`; we must release the GIL. py::call_guard<py::gil_scoped_release>(), cls_doc.FindSeparationCertificateGivenPolytope.doc) .def("SearchWithBilinearAlternation", &Class::SearchWithBilinearAlternation, py::arg("ignored_collision_pairs"), py::arg("C_init"), py::arg("d_init"), py::arg("options"), cls_doc.SearchWithBilinearAlternation.doc) .def("BinarySearch", &Class::BinarySearch, py::arg("ignored_collision_pairs"), py::arg("C"), py::arg("d"), py::arg("s_center"), py::arg("options"), cls_doc.BinarySearch.doc) .def("MakeIsGeometrySeparableProgram", &Class::MakeIsGeometrySeparableProgram, py::arg("geometry_pair"), py::arg("C"), py::arg("d"), cls_doc.MakeIsGeometrySeparableProgram.doc) .def("SolveSeparationCertificateProgram", &Class::SolveSeparationCertificateProgram, py::arg("certificate_program"), py::arg("options"), // The `options` contains a `Parallelism`; we must release the GIL. py::call_guard<py::gil_scoped_release>(), cls_doc.SolveSeparationCertificateProgram.doc); py::class_<Class::SeparatingPlaneLagrangians>(cspace_free_polytope_cls, "SeparatingPlaneLagrangians", cls_doc.SeparatingPlaneLagrangians.doc) .def(py::init<int, int>(), py::arg("C_rows"), py::arg("s_size"), cls_doc.SeparatingPlaneLagrangians.ctor.doc) .def("GetSolution", &Class::SeparatingPlaneLagrangians::GetSolution, py::arg("result"), cls_doc.SeparatingPlaneLagrangians.GetSolution.doc) // Use py_rvp::copy here because numpy.ndarray with dtype=object arrays // must be copied, and cannot be referenced. .def("polytope", &Class::SeparatingPlaneLagrangians::mutable_polytope, py_rvp::copy) .def("s_lower", &Class::SeparatingPlaneLagrangians::mutable_s_lower) .def("s_upper", &Class::SeparatingPlaneLagrangians::mutable_s_upper); using SepCertClass = Class::SeparationCertificateResult; py::class_<SepCertClass>(cspace_free_polytope_cls, "SeparationCertificateResult", cls_doc.SeparationCertificateResult.doc) .def_readonly("plane_index", &SepCertClass::plane_index) .def_readonly("positive_side_rational_lagrangians", &Class::SeparationCertificateResult:: positive_side_rational_lagrangians, cls_doc.SeparationCertificateResult .positive_side_rational_lagrangians.doc) .def_readonly("negative_side_rational_lagrangians", &Class::SeparationCertificateResult:: negative_side_rational_lagrangians, cls_doc.SeparationCertificateResult .negative_side_rational_lagrangians.doc) // Use py_rvp::copy here because numpy.ndarray with dtype=object // arrays must be copied, and cannot be referenced. .def_readonly("a", &SepCertClass::a, py_rvp::copy, doc.SeparationCertificateResultBase.a.doc) .def_readonly( "b", &SepCertClass::b, doc.SeparationCertificateResultBase.b.doc) .def_readonly("result", &SepCertClass::result) // Use py_rvp::copy here because numpy.ndarray with dtype=object // arrays must be copied, and cannot be referenced. .def_readonly("plane_decision_var_vals", &SepCertClass::plane_decision_var_vals, py_rvp::copy); py::class_<Class::SeparationCertificate>(cspace_free_polytope_cls, "SeparationCertificate", cls_doc.SeparationCertificate.doc) .def("GetSolution", &Class::SeparationCertificate::GetSolution, py::arg("plane_index"), py::arg("a"), py::arg("b"), py::arg("plane_decision_vars"), py::arg("result"), cls_doc.SeparationCertificate.GetSolution.doc) .def_readwrite("positive_side_rational_lagrangians", &Class::SeparationCertificate::positive_side_rational_lagrangians) .def_readwrite("negative_side_rational_lagrangians", &Class::SeparationCertificate::negative_side_rational_lagrangians); py::class_<Class::SeparationCertificateProgram, SeparationCertificateProgramBase>(cspace_free_polytope_cls, "SeparationCertificateProgram", cls_doc.SeparationCertificateProgram.doc) .def(py::init<>()) .def_readonly( "plane_index", &Class::SeparationCertificateProgram::plane_index) .def_readonly( "certificate", &Class::SeparationCertificateProgram::certificate); py::class_<Class::FindSeparationCertificateGivenPolytopeOptions, FindSeparationCertificateOptions>(cspace_free_polytope_cls, "FindSeparationCertificateGivenPolytopeOptions", cls_doc.FindSeparationCertificateGivenPolytopeOptions.doc) .def(py::init<>()) .def_readwrite("ignore_redundant_C", &Class::FindSeparationCertificateGivenPolytopeOptions:: ignore_redundant_C); py::enum_<Class::EllipsoidMarginCost>(cspace_free_polytope_cls, "EllipsoidMarginCost", cls_doc.EllipsoidMarginCost.doc) .value("kSum", Class::EllipsoidMarginCost::kSum) .value("kGeometricMean", Class::EllipsoidMarginCost::kGeometricMean); py::class_<Class::FindPolytopeGivenLagrangianOptions>( cspace_free_polytope_cls, "FindPolytopeGivenLagrangianOptions", cls_doc.FindPolytopeGivenLagrangianOptions.doc) .def(py::init<>()) .def_readwrite("backoff_scale", &Class::FindPolytopeGivenLagrangianOptions::backoff_scale) .def_readwrite("ellipsoid_margin_epsilon", &Class::FindPolytopeGivenLagrangianOptions:: ellipsoid_margin_epsilon) .def_readwrite( "solver_id", &Class::FindPolytopeGivenLagrangianOptions::solver_id) .def_readwrite("solver_options", &Class::FindPolytopeGivenLagrangianOptions::solver_options) .def_readwrite("s_inner_pts", &Class::FindPolytopeGivenLagrangianOptions::s_inner_pts) .def_readwrite("search_s_bounds_lagrangians", &Class::FindPolytopeGivenLagrangianOptions:: search_s_bounds_lagrangians) .def_readwrite("ellipsoid_margin_cost", &Class::FindPolytopeGivenLagrangianOptions::ellipsoid_margin_cost); py::class_<Class::SearchResult>( cspace_free_polytope_cls, "SearchResult", cls_doc.SearchResult.doc) .def(py::init<>()) .def("C", &Class::SearchResult::C) .def("d", &Class::SearchResult::d) // Use py_rvp::copy here because numpy.ndarray with dtype=object arrays // must be copied, and cannot be referenced. .def("a", &Class::SearchResult::a, py_rvp::copy) .def("b", &Class::SearchResult::b) .def("num_iter", &Class::SearchResult::num_iter) .def("certified_polytope", &Class::SearchResult::certified_polytope); py::class_<Class::BilinearAlternationOptions>(cspace_free_polytope_cls, "BilinearAlternationOptions", cls_doc.BilinearAlternationOptions.doc) .def(py::init<>()) .def_readwrite("max_iter", &Class::BilinearAlternationOptions::max_iter, cls_doc.BilinearAlternationOptions.max_iter.doc) .def_readwrite("convergence_tol", &Class::BilinearAlternationOptions::convergence_tol, cls_doc.BilinearAlternationOptions.convergence_tol.doc) .def_readwrite("find_polytope_options", &Class::BilinearAlternationOptions::find_polytope_options, cls_doc.BilinearAlternationOptions.find_polytope_options.doc) .def_readonly("find_lagrangian_options", &Class::BilinearAlternationOptions::find_lagrangian_options, cls_doc.BilinearAlternationOptions.find_lagrangian_options.doc) .def_readwrite("ellipsoid_scaling", &Class::BilinearAlternationOptions::ellipsoid_scaling, cls_doc.BilinearAlternationOptions.ellipsoid_scaling.doc); py::class_<Class::BinarySearchOptions>(cspace_free_polytope_cls, "BinarySearchOptions", cls_doc.BinarySearchOptions.doc) .def(py::init<>()) .def_readwrite("scale_max", &Class::BinarySearchOptions::scale_max) .def_readwrite("scale_min", &Class::BinarySearchOptions::scale_min) .def_readwrite("max_iter", &Class::BinarySearchOptions::max_iter) .def_readwrite( "convergence_tol", &Class::BinarySearchOptions::convergence_tol) .def_readonly("find_lagrangian_options", &Class::BinarySearchOptions::find_lagrangian_options); } using drake::geometry::optimization::ConvexSet; m.def("CheckIfSatisfiesConvexityRadius", &CheckIfSatisfiesConvexityRadius, py::arg("convex_set"), py::arg("continuous_revolute_joints"), doc.CheckIfSatisfiesConvexityRadius.doc); m.def( "PartitionConvexSet", [](const ConvexSet& convex_set, const std::vector<int>& continuous_revolute_joints, const double epsilon) { std::vector<copyable_unique_ptr<ConvexSet>> copyable_result = PartitionConvexSet(convex_set, continuous_revolute_joints, epsilon); std::vector<std::unique_ptr<ConvexSet>> result( std::make_move_iterator(copyable_result.begin()), std::make_move_iterator(copyable_result.end())); return result; }, py::arg("convex_set"), py::arg("continuous_revolute_joints"), py::arg("epsilon") = 1e-5, doc.PartitionConvexSet .doc_3args_convex_set_continuous_revolute_joints_epsilon); m.def( "PartitionConvexSet", [](const std::vector<ConvexSet*>& convex_sets, const std::vector<int>& continuous_revolute_joints, const double epsilon = 1e-5) { std::vector<copyable_unique_ptr<ConvexSet>> copyable_result = PartitionConvexSet(CloneConvexSets(convex_sets), continuous_revolute_joints, epsilon); std::vector<std::unique_ptr<ConvexSet>> result( std::make_move_iterator(copyable_result.begin()), std::make_move_iterator(copyable_result.end())); return result; }, py::arg("convex_sets"), py::arg("continuous_revolute_joints"), py::arg("epsilon") = 1e-5, doc.PartitionConvexSet .doc_3args_convex_sets_continuous_revolute_joints_epsilon); m.def( "CalcPairwiseIntersections", [](const std::vector<ConvexSet*>& convex_sets_A, const std::vector<ConvexSet*>& convex_sets_B, const std::vector<int>& continuous_revolute_joints) { return CalcPairwiseIntersections(CloneConvexSets(convex_sets_A), CloneConvexSets(convex_sets_B), continuous_revolute_joints); }, py::arg("convex_sets_A"), py::arg("convex_sets_B"), py::arg("continuous_revolute_joints"), doc.CalcPairwiseIntersections.doc_3args); m.def( "CalcPairwiseIntersections", [](const std::vector<ConvexSet*>& convex_sets, const std::vector<int>& continuous_revolute_joints) { return CalcPairwiseIntersections( CloneConvexSets(convex_sets), continuous_revolute_joints); }, py::arg("convex_sets"), py::arg("continuous_revolute_joints"), doc.CalcPairwiseIntersections.doc_2args); // NOLINTNEXTLINE(readability/fn_size) } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/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_library", ) load( "//tools/skylark:drake_py.bzl", "drake_py_unittest", ) load( "//tools/skylark:pybind.bzl", "drake_pybind_library", "get_drake_py_installs", "get_pybind_package_info", ) package(default_visibility = [ "//bindings:__subpackages__", ]) # This determines how `PYTHONPATH` is configured, and how to install the # bindings. PACKAGE_INFO = get_pybind_package_info(base_package = "//bindings") drake_cc_library( name = "optimization_pybind", hdrs = ["optimization_pybind.h"], declare_installed_headers = 0, ) drake_pybind_library( name = "geometry", cc_deps = [ ":optimization_pybind", "//bindings/pydrake:documentation_pybind", "//bindings/pydrake:polynomial_types_pybind", "//bindings/pydrake/common:default_scalars_pybind", "//bindings/pydrake/common:deprecation_pybind", "//bindings/pydrake/common:identifier_pybind", "//bindings/pydrake/common:serialize_pybind", "//bindings/pydrake/common:sorted_pair_pybind", "//bindings/pydrake/common:type_pack", "//bindings/pydrake/common:type_safe_index_pybind", "//bindings/pydrake/common:value_pybind", ], cc_so_name = "__init__", cc_srcs = [ "geometry_py.cc", "geometry_py.h", "geometry_py_common.cc", "geometry_py_hydro.cc", "geometry_py_meshes.cc", "geometry_py_optimization.cc", "geometry_py_render.cc", "geometry_py_scene_graph.cc", "geometry_py_visualizers.cc", ], package_info = PACKAGE_INFO, py_data = [ "//setup:deepnote", ], py_deps = [ "//bindings/pydrake:module_py", "//bindings/pydrake/solvers", "//bindings/pydrake/systems:framework_py", "//bindings/pydrake/systems:lcm_py", ], py_srcs = [ "_geometry_extra.py", ], ) install( name = "install", targets = [":geometry"], py_dest = PACKAGE_INFO.py_dest, deps = get_drake_py_installs([":geometry"]), ) drake_py_unittest( name = "frame_id_test", deps = [ ":geometry", ], ) drake_py_unittest( name = "common_test", deps = [ ":geometry", "//bindings/pydrake/common/test_utilities", "//bindings/pydrake/multibody:parsing_py", "//bindings/pydrake/multibody:plant_py", ], ) drake_py_unittest( name = "hydro_test", data = [ "//geometry:test_obj_files", ], deps = [ ":geometry", "//bindings/pydrake/common/test_utilities", ], ) drake_py_unittest( name = "meshes_test", data = [ "//geometry:test_obj_files", ], deps = [ ":geometry", "//bindings/pydrake/common/test_utilities", ], ) drake_py_unittest( name = "optimization_test", deps = [ ":geometry", "//bindings/pydrake/common/test_utilities:deprecation_py", "//bindings/pydrake/common/test_utilities:pickle_compare_py", "//bindings/pydrake/multibody:inverse_kinematics_py", "//bindings/pydrake/multibody:parsing_py", "//bindings/pydrake/multibody:plant_py", "//bindings/pydrake/solvers", ], ) drake_py_unittest( name = "render_test", allow_network = ["render_gltf_client"], data = [ "//geometry/render:test_models", ], deps = [ ":geometry", "//bindings/pydrake/common/test_utilities", "//bindings/pydrake/systems:sensors_py", ], ) drake_py_unittest( name = "render_engine_gl_test", deps = [ ":geometry", "//bindings/pydrake/common/test_utilities", ], ) drake_py_unittest( name = "render_engine_subclass_test", flaky = True, deps = [ ":geometry", "//bindings/pydrake/common/test_utilities", "//bindings/pydrake/systems:sensors_py", ], ) drake_py_unittest( name = "scene_graph_test", deps = [ ":geometry", "//bindings/pydrake/common/test_utilities", "//bindings/pydrake/systems:sensors_py", ], ) drake_py_unittest( name = "visualizers_test", deps = [ ":geometry", "//bindings/pydrake:lcm_py", "//bindings/pydrake:perception_py", "//bindings/pydrake/common/test_utilities", "//bindings/pydrake/multibody:plant_py", "//bindings/pydrake/systems:analysis_py", "//bindings/pydrake/systems:lcm_py", ], ) add_lint_tests_pydrake()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py_render.cc
/* This contains the bindings for the public API in the drake/geometry/render and drake/geometry/render* directories. They can be found in the pydrake.geometry module. */ #include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/common/deprecation_pybind.h" #include "drake/bindings/pydrake/common/serialize_pybind.h" #include "drake/bindings/pydrake/common/value_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/geometry/render/light_parameter.h" #include "drake/geometry/render/render_engine.h" #include "drake/geometry/render/render_label.h" #include "drake/geometry/render_gl/factory.h" #include "drake/geometry/render_gltf_client/factory.h" #include "drake/geometry/render_vtk/factory.h" namespace drake { namespace pydrake { using Eigen::Vector3d; using geometry::GeometryId; using geometry::PerceptionProperties; using geometry::Shape; using geometry::render::ColorRenderCamera; using geometry::render::DepthRenderCamera; using geometry::render::LightParameter; using geometry::render::LightType; using geometry::render::RenderEngine; using math::RigidTransformd; using systems::sensors::CameraInfo; using systems::sensors::Image; using systems::sensors::ImageDepth32F; using systems::sensors::ImageLabel16I; using systems::sensors::ImageRgba8U; using systems::sensors::PixelType; namespace { class PyRenderEngine : public py::wrapper<RenderEngine> { public: using Base = RenderEngine; using BaseWrapper = py::wrapper<Base>; PyRenderEngine() : BaseWrapper() {} void UpdateViewpoint(RigidTransformd const& X_WR) override { PYBIND11_OVERLOAD_PURE(void, Base, UpdateViewpoint, X_WR); } bool DoRegisterVisual(GeometryId id, Shape const& shape, PerceptionProperties const& properties, RigidTransformd const& X_WG) override { PYBIND11_OVERLOAD_PURE( bool, Base, DoRegisterVisual, id, shape, properties, X_WG); } void DoUpdateVisualPose(GeometryId id, RigidTransformd const& X_WG) override { PYBIND11_OVERLOAD_PURE(void, Base, DoUpdateVisualPose, id, X_WG); } bool DoRemoveGeometry(GeometryId id) override { PYBIND11_OVERLOAD_PURE(bool, Base, DoRemoveGeometry, id); } std::unique_ptr<RenderEngine> DoClone() const override { PYBIND11_OVERLOAD_PURE(std::unique_ptr<RenderEngine>, Base, DoClone); } void DoRenderColorImage(ColorRenderCamera const& camera, ImageRgba8U* color_image_out) const override { PYBIND11_OVERLOAD_PURE( void, Base, DoRenderColorImage, camera, color_image_out); } void DoRenderDepthImage(DepthRenderCamera const& camera, ImageDepth32F* depth_image_out) const override { PYBIND11_OVERLOAD_PURE( void, Base, DoRenderDepthImage, camera, depth_image_out); } void DoRenderLabelImage(ColorRenderCamera const& camera, ImageLabel16I* label_image_out) const override { PYBIND11_OVERLOAD_PURE( void, Base, DoRenderLabelImage, camera, label_image_out); } void SetDefaultLightPosition(Vector3d const& X_DL) override { PYBIND11_OVERLOAD(void, Base, SetDefaultLightPosition, X_DL); } // Expose these protected methods (which are either virtual methods with // default implementations, or helper functions) so that Python // implementations can access them. using Base::GetRenderLabelOrThrow; using Base::SetDefaultLightPosition; template <typename ImageType> static void ThrowIfInvalid(const systems::sensors::CameraInfo& intrinsics, const ImageType* image, const char* image_type) { return Base::ThrowIfInvalid<ImageType>(intrinsics, image, image_type); } }; void DoScalarIndependentDefinitions(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry::render; constexpr auto& doc_geometry = pydrake_doc.drake.geometry; constexpr auto& doc = doc_geometry.render; { using Class = ClippingRange; const auto& cls_doc = doc.ClippingRange; py::class_<Class>(m, "ClippingRange", cls_doc.doc) .def(py::init<Class const&>(), py::arg("other"), "Copy constructor") .def(py::init<double, double>(), py::arg("near"), py::arg("far"), cls_doc.ctor.doc) .def("far", static_cast<double (Class::*)() const>(&Class::far), cls_doc.far.doc) .def("near", static_cast<double (Class::*)() const>(&Class::near), cls_doc.near.doc); } { using Class = ColorRenderCamera; const auto& cls_doc = doc.ColorRenderCamera; py::class_<Class> cls(m, "ColorRenderCamera", cls_doc.doc); cls // BR .def(py::init<Class const&>(), py::arg("other"), "Copy constructor") .def(py::init<RenderCameraCore, bool>(), py::arg("core"), py::arg("show_window") = false, cls_doc.ctor.doc) .def("core", static_cast<RenderCameraCore const& (Class::*)() const>( &Class::core), cls_doc.core.doc) .def("show_window", static_cast<bool (Class::*)() const>(&Class::show_window), cls_doc.show_window.doc); DefCopyAndDeepCopy(&cls); } { using Class = DepthRange; const auto& cls_doc = doc.DepthRange; py::class_<Class> cls(m, "DepthRange"); cls // BR .def(py::init<Class const&>(), py::arg("other"), "Copy constructor") .def(py::init<double, double>(), py::arg("min_in"), py::arg("min_out"), cls_doc.ctor.doc) .def("max_depth", static_cast<double (Class::*)() const>(&Class::max_depth), cls_doc.max_depth.doc) .def("min_depth", static_cast<double (Class::*)() const>(&Class::min_depth), cls_doc.min_depth.doc); DefCopyAndDeepCopy(&cls); } { using Class = DepthRenderCamera; const auto& cls_doc = doc.DepthRenderCamera; py::class_<Class> cls(m, "DepthRenderCamera"); cls // BR .def(py::init<Class const&>(), py::arg("other"), "Copy constructor") .def(py::init<RenderCameraCore, DepthRange>(), py::arg("core"), py::arg("depth_range"), cls_doc.ctor.doc) .def("core", static_cast<RenderCameraCore const& (Class::*)() const>( &Class::core), cls_doc.core.doc) .def("depth_range", static_cast<DepthRange const& (Class::*)() const>( &Class::depth_range), cls_doc.depth_range.doc); DefCopyAndDeepCopy(&cls); } { using Class = RenderCameraCore; const auto& cls_doc = doc.RenderCameraCore; py::class_<Class> cls(m, "RenderCameraCore"); cls // BR .def(py::init<Class const&>(), py::arg("other"), "Copy constructor") .def( py::init<std::string, CameraInfo, ClippingRange, RigidTransformd>(), py::arg("renderer_name"), py::arg("intrinsics"), py::arg("clipping"), py::arg("X_BS"), cls_doc.ctor.doc) .def("clipping", static_cast<ClippingRange const& (Class::*)() const>( &Class::clipping), cls_doc.clipping.doc) .def("intrinsics", static_cast<CameraInfo const& (Class::*)() const>( &Class::intrinsics), cls_doc.intrinsics.doc) .def("renderer_name", static_cast<::std::string const& (Class::*)() const>( &Class::renderer_name), cls_doc.renderer_name.doc) .def("sensor_pose_in_camera_body", static_cast<RigidTransformd const& (Class::*)() const>( &Class::sensor_pose_in_camera_body), cls_doc.sensor_pose_in_camera_body.doc); DefCopyAndDeepCopy(&cls); } { using Class = RenderEngine; const auto& cls_doc = doc.RenderEngine; py::class_<Class, PyRenderEngine> cls(m, "RenderEngine"); cls // BR .def(py::init<>(), cls_doc.ctor.doc) .def("Clone", static_cast<::std::unique_ptr<Class> (Class::*)() const>( &Class::Clone), cls_doc.Clone.doc) .def("RegisterVisual", static_cast<bool (Class::*)(GeometryId, Shape const&, PerceptionProperties const&, RigidTransformd const&, bool)>( &Class::RegisterVisual), py::arg("id"), py::arg("shape"), py::arg("properties"), py::arg("X_WG"), py::arg("needs_updates") = true, cls_doc.RegisterVisual.doc) .def("RemoveGeometry", static_cast<bool (Class::*)(GeometryId)>(&Class::RemoveGeometry), py::arg("id"), cls_doc.RemoveGeometry.doc) .def("has_geometry", static_cast<bool (Class::*)(GeometryId) const>( &Class::has_geometry), py::arg("id"), cls_doc.has_geometry.doc) .def("UpdateViewpoint", static_cast<void (Class::*)(RigidTransformd const&)>( &Class::UpdateViewpoint), py::arg("X_WR"), cls_doc.UpdateViewpoint.doc) .def("RenderColorImage", static_cast<void (Class::*)(ColorRenderCamera const&, ImageRgba8U*) const>(&Class::RenderColorImage), py::arg("camera"), py::arg("color_image_out"), cls_doc.RenderColorImage.doc) .def("RenderDepthImage", static_cast<void (Class::*)(DepthRenderCamera const&, ImageDepth32F*) const>(&Class::RenderDepthImage), py::arg("camera"), py::arg("depth_image_out"), cls_doc.RenderDepthImage.doc) .def("RenderLabelImage", static_cast<void (Class::*)(ColorRenderCamera const&, ImageLabel16I*) const>(&Class::RenderLabelImage), py::arg("camera"), py::arg("label_image_out"), cls_doc.RenderLabelImage.doc) .def("default_render_label", static_cast<RenderLabel (Class::*)() const>( &Class::default_render_label), cls_doc.default_render_label.doc) // N.B. We're binding against the trampoline class PyRenderEngine, // rather than the direct class RenderEngine, solely for protected // helper methods and non-pure virtual functions because we want them // exposed for Python implementations of the interface. .def("GetRenderLabelOrThrow", static_cast<RenderLabel (Class::*)(PerceptionProperties const&) const>(&PyRenderEngine::GetRenderLabelOrThrow), py::arg("properties"), cls_doc.GetRenderLabelOrThrow.doc) .def("SetDefaultLightPosition", static_cast<void (Class::*)(Vector3d const&)>( &PyRenderEngine::SetDefaultLightPosition), py::arg("X_DL"), cls_doc.SetDefaultLightPosition.doc) .def_static("ThrowIfInvalid", static_cast<void (*)(CameraInfo const&, Image<PixelType::kRgba8U> const*, char const*)>( &PyRenderEngine::ThrowIfInvalid<Image<PixelType::kRgba8U>>), py::arg("intrinsics"), py::arg("image"), py::arg("image_type"), cls_doc.ThrowIfInvalid.doc) .def_static("ThrowIfInvalid", static_cast<void (*)(CameraInfo const&, Image<PixelType::kDepth32F> const*, char const*)>( &PyRenderEngine::ThrowIfInvalid<Image<PixelType::kDepth32F>>), py::arg("intrinsics"), py::arg("image"), py::arg("image_type"), cls_doc.ThrowIfInvalid.doc) .def_static("ThrowIfInvalid", static_cast<void (*)(CameraInfo const&, Image<PixelType::kLabel16I> const*, char const*)>( &PyRenderEngine::ThrowIfInvalid<Image<PixelType::kLabel16I>>), py::arg("intrinsics"), py::arg("image"), py::arg("image_type"), cls_doc.ThrowIfInvalid.doc); // Note that we do not bind MakeRgbFromLabel nor MakeLabelFromRgb, because // crossing the C++ <=> Python boundary one pixel at a time would be // extraordinarily inefficient. } { py::class_<RenderLabel> render_label(m, "RenderLabel", doc.RenderLabel.doc); render_label .def(py::init<int>(), py::arg("value"), doc.RenderLabel.ctor.doc_1args) .def("is_reserved", &RenderLabel::is_reserved) .def("__int__", [](const RenderLabel& self) -> int { return self; }) .def("__repr__", [](const RenderLabel& self) -> std::string { if (self == RenderLabel::kEmpty) { return "RenderLabel.kEmpty"; } if (self == RenderLabel::kDoNotRender) { return "RenderLabel.kDoNotRender"; } if (self == RenderLabel::kDontCare) { return "RenderLabel.kDontCare"; } if (self == RenderLabel::kUnspecified) { return "RenderLabel.kUnspecified"; } if (self == RenderLabel::kMaxUnreserved) { return "RenderLabel.kMaxUnreserved"; } return fmt::format("RenderLabel({})", int{self}); }) // EQ(==). .def(py::self == py::self) .def(py::self == int{}) .def(int{} == py::self) // NE(!=). .def(py::self != py::self) .def(py::self != int{}) .def(int{} != py::self); render_label.attr("kEmpty") = RenderLabel::kEmpty; render_label.attr("kDoNotRender") = RenderLabel::kDoNotRender; render_label.attr("kDontCare") = RenderLabel::kDontCare; render_label.attr("kUnspecified") = RenderLabel::kUnspecified; render_label.attr("kMaxUnreserved") = RenderLabel::kMaxUnreserved; } { using Class = geometry::NullTexture; constexpr auto& cls_doc = doc_geometry.NullTexture; py::class_<Class> cls(m, "NullTexture", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } { using Class = geometry::EquirectangularMap; constexpr auto& cls_doc = doc_geometry.EquirectangularMap; py::class_<Class> cls(m, "EquirectangularMap", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } { using Class = geometry::EnvironmentMap; constexpr auto& cls_doc = doc_geometry.EnvironmentMap; py::class_<Class> cls(m, "EnvironmentMap", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } { using Class = geometry::GltfExtension; constexpr auto& cls_doc = doc_geometry.GltfExtension; py::class_<Class> cls(m, "GltfExtension", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } { using Class = geometry::render::LightParameter; constexpr auto& cls_doc = doc.LightParameter; py::class_<Class> cls(m, "LightParameter", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } { using Class = RenderEngineVtkParams; constexpr auto& cls_doc = doc_geometry.RenderEngineVtkParams; py::class_<Class> cls(m, "RenderEngineVtkParams", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } m.def("MakeRenderEngineVtk", &MakeRenderEngineVtk, py::arg("params"), doc_geometry.MakeRenderEngineVtk.doc); { using Class = RenderEngineGlParams; constexpr auto& cls_doc = doc_geometry.RenderEngineGlParams; py::class_<Class> cls(m, "RenderEngineGlParams", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } m.def("MakeRenderEngineGl", &MakeRenderEngineGl, py::arg("params") = RenderEngineGlParams(), doc_geometry.MakeRenderEngineGl.doc); { using Class = RenderEngineGltfClientParams; constexpr auto& cls_doc = doc_geometry.RenderEngineGltfClientParams; py::class_<Class> cls(m, "RenderEngineGltfClientParams", cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } m.def("MakeRenderEngineGltfClient", &MakeRenderEngineGltfClient, py::arg("params") = RenderEngineGltfClientParams(), doc_geometry.MakeRenderEngineGltfClient.doc); AddValueInstantiation<RenderLabel>(m); } } // namespace void DefineGeometryRender(py::module m) { m.doc() = "Local bindings for render artifacts found in `drake::geometry` and " "`drake::geometry::render`"; DoScalarIndependentDefinitions(m); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py_hydro.cc
/* @file This contains the various public components of the hydroelastic contact calculations -- specifically, the mesh field classes and property helper functions. They can be found in the pydrake.geometry module. */ #include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/common/type_pack.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/geometry/proximity/make_convex_hull_mesh.h" #include "drake/geometry/proximity/polygon_surface_mesh_field.h" #include "drake/geometry/proximity/triangle_surface_mesh_field.h" #include "drake/geometry/proximity_properties.h" namespace drake { namespace pydrake { namespace { template <typename T> void DoScalarDependentDefinitions(py::module m, T) { py::tuple param = GetPyParam<T>(); constexpr auto& doc = pydrake_doc.drake.geometry; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; /* A note on the bindings of ***SurfaceMeshFieldLinear. The current binding's purpose is to allow the user to view the fields associated with a ContactSurface. As such: - We don't bind the constructors. - We are only binding *scalar* fields (where the `FieldType` is the same scalar type as the vertex position scalar type). This is sufficient for what ContactSurface uses. - We only bind the Evaluate*** methods. - This leaves out - Transform() (already marked "Advanced" in documentation) - CloneAndSetMesh() - mesh() and values() accessors - Equal() - We steal the documentation from MeshFieldLinear. If we need to support vector fields of arbitrary higher dimension in the future, we can revisit these bindings. Because we can't construct them, we test them in conjunction with testing ContactSurface in geometry_scene_graph_test.py. Differences between the SurfaceMeshFields for Triangle and Polygon: Polygon: - Always has gradients, so EvalauteGradient() is bound. - Has no barycentric coordinates, so Evaluate() is not bound (it would only throw). Triangle: - Has no gradients computed in the creation of a ContactSurface, so EvaluateGradient() is not bound (it would only throw). - Has barycentric coordinates, so Evaluate() is bound. */ // PolygonSurfaceMeshFieldLinear // Currently we do not bind the constructor because users do not need to // construct it directly yet. We can get it from ContactSurface. { using Class = PolygonSurfaceMeshFieldLinear<T, T>; constexpr auto& cls_doc = doc.MeshFieldLinear; auto cls = DefineTemplateClassWithDefault<Class>( m, "PolygonSurfaceMeshFieldLinear", GetPyParam<T, T>(), cls_doc.doc); cls // BR .def("EvaluateAtVertex", &Class::EvaluateAtVertex, py::arg("v"), cls_doc.EvaluateAtVertex.doc) .def("EvaluateGradient", &Class::EvaluateGradient, py::arg("e"), cls_doc.EvaluateGradient.doc) .def( "EvaluateCartesian", [](const Class* self, int e, const Vector3<T>& p_MQ) { return self->EvaluateCartesian(e, p_MQ); }, py::arg("e"), py::arg("p_MQ"), cls_doc.EvaluateCartesian.doc); } // TriangleSurfaceMeshFieldLinear // See also "A note on the bindings of ***SurfaceMeshFieldLinear" above. // Currently we do not bind the constructor because users do not need to // construct it directly yet. We can get it from ContactSurface. { using Class = TriangleSurfaceMeshFieldLinear<T, T>; constexpr auto& cls_doc = doc.MeshFieldLinear; auto cls = DefineTemplateClassWithDefault<Class>( m, "TriangleSurfaceMeshFieldLinear", GetPyParam<T, T>(), cls_doc.doc); using Barycentric = typename TriangleSurfaceMesh<T>::template Barycentric<T>; cls // BR .def("EvaluateAtVertex", &Class::EvaluateAtVertex, py::arg("v"), cls_doc.EvaluateAtVertex.doc) .def( "Evaluate", [](const Class* self, int e, const Barycentric& b) { return self->Evaluate(e, b); }, py::arg("e"), py::arg("b"), cls_doc.Evaluate.doc) .def( "EvaluateCartesian", [](const Class* self, int e, const Vector3<T>& p_MQ) { return self->EvaluateCartesian(e, p_MQ); }, py::arg("e"), py::arg("p_MQ"), cls_doc.EvaluateCartesian.doc); } } void DoScalarIndependentDefinitions(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; constexpr auto& doc = pydrake_doc.drake.geometry; // MakeConvexHull { constexpr char internal_doc[] = "(internal use only)"; m.def("_MakeConvexHull", &drake::geometry::internal::MakeConvexHull, py::arg("shape"), internal_doc); } m.def("AddRigidHydroelasticProperties", py::overload_cast<double, ProximityProperties*>( &AddRigidHydroelasticProperties), py::arg("resolution_hint"), py::arg("properties"), doc.AddRigidHydroelasticProperties.doc_2args); m.def("AddRigidHydroelasticProperties", py::overload_cast<ProximityProperties*>(&AddRigidHydroelasticProperties), py::arg("properties"), doc.AddRigidHydroelasticProperties.doc_1args); m.def("AddCompliantHydroelasticProperties", &AddCompliantHydroelasticProperties, py::arg("resolution_hint"), py::arg("hydroelastic_modulus"), py::arg("properties"), doc.AddCompliantHydroelasticProperties.doc); m.def("AddCompliantHydroelasticPropertiesForHalfSpace", &AddCompliantHydroelasticPropertiesForHalfSpace, py::arg("slab_thickness"), py::arg("hydroelastic_modulus"), py::arg("properties"), doc.AddCompliantHydroelasticPropertiesForHalfSpace.doc); } } // namespace void DefineGeometryHydro(py::module m) { DoScalarIndependentDefinitions(m); type_visit([m](auto dummy) { DoScalarDependentDefinitions(m, dummy); }, NonSymbolicScalarPack{}); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py_meshes.cc
/* @file This contains the various "atomic" mesh types and helper functions. They can be found in the pydrake.geometry module. */ #include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/common/type_pack.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/geometry/proximity/obj_to_surface_mesh.h" #include "drake/geometry/proximity/polygon_surface_mesh.h" #include "drake/geometry/proximity/triangle_surface_mesh.h" #include "drake/geometry/proximity/volume_mesh.h" #include "drake/geometry/proximity/volume_to_surface_mesh.h" namespace drake { namespace pydrake { namespace { template <typename T> void DoScalarDependentDefinitions(py::module m, T) { py::tuple param = GetPyParam<T>(); constexpr auto& doc = pydrake_doc.drake.geometry; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; // PolygonSurfaceMesh { using Class = PolygonSurfaceMesh<T>; constexpr auto& cls_doc = doc.PolygonSurfaceMesh; auto cls = DefineTemplateClassWithDefault<Class>( m, "PolygonSurfaceMesh", param, cls_doc.doc); cls // BR .def( "element", [](Class* self, int e) { // The SurfacePolygon class is non-copyable, so we need to do a // little dance here in order to bind it into pydrake. return self->element(e).copy_to_unique(); }, py::arg("e"), // The return value is a view into the PolygonSurfaceMesh storage. py::keep_alive<0, 1>(), cls_doc.element.doc) .def("vertex", &Class::vertex, py::arg("v"), cls_doc.vertex.doc) .def("num_vertices", &Class::num_vertices, cls_doc.num_vertices.doc) .def("num_elements", &Class::num_elements, cls_doc.num_elements.doc) .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<std::vector<int>, std::vector<Vector3<T>>>(), py::arg("face_data"), py::arg("vertices"), cls_doc.ctor.doc_2args) .def("num_faces", &Class::num_faces, cls_doc.num_faces.doc) .def("area", &Class::area, py::arg("f"), cls_doc.area.doc) .def("total_area", &Class::total_area, cls_doc.total_area.doc) .def("face_normal", &Class::face_normal, py::arg("f"), cls_doc.face_normal.doc) .def("element_centroid", &Class::element_centroid, py::arg("e"), cls_doc.element_centroid.doc) .def("centroid", &Class::centroid, cls_doc.centroid.doc) .def("CalcBoundingBox", &Class::CalcBoundingBox, cls_doc.CalcBoundingBox.doc) .def("Equal", &Class::Equal, py::arg("mesh"), cls_doc.Equal.doc) .def("face_data", &Class::face_data, cls_doc.face_data.doc); DefCopyAndDeepCopy(&cls); } // TriangleSurfaceMesh { using Class = TriangleSurfaceMesh<T>; constexpr auto& cls_doc = doc.TriangleSurfaceMesh; auto cls = DefineTemplateClassWithDefault<Class>( m, "TriangleSurfaceMesh", param, cls_doc.doc); cls // BR .def("element", &Class::element, py::arg("e"), cls_doc.element.doc) .def("vertex", &Class::vertex, py::arg("v"), cls_doc.vertex.doc) .def("num_vertices", &Class::num_vertices, cls_doc.num_vertices.doc) .def("num_elements", &Class::num_elements, cls_doc.num_elements.doc) .def(py::init<std::vector<SurfaceTriangle>, std::vector<Vector3<T>>>(), py::arg("triangles"), py::arg("vertices"), cls_doc.ctor.doc) .def("num_triangles", &Class::num_triangles, cls_doc.num_triangles.doc) .def("area", &Class::area, py::arg("t"), cls_doc.area.doc) .def("total_area", &Class::total_area, cls_doc.total_area.doc) .def("face_normal", &Class::face_normal, py::arg("t"), cls_doc.face_normal.doc) .def("triangles", &Class::triangles, cls_doc.triangles.doc) .def("vertices", &Class::vertices, cls_doc.vertices.doc) .def("centroid", &Class::centroid, cls_doc.centroid.doc) .def("element_centroid", &Class::element_centroid, py::arg("t"), cls_doc.element_centroid.doc) .def("CalcBoundingBox", &Class::CalcBoundingBox, cls_doc.CalcBoundingBox.doc) .def("Equal", &Class::Equal, py::arg("mesh"), cls_doc.Equal.doc) .def( "CalcCartesianFromBarycentric", [](const Class* self, int element_index, const Vector3<T>& b_Q) { return self->template CalcCartesianFromBarycentric( element_index, b_Q); }, py::arg("element_index"), py::arg("b_Q"), cls_doc.CalcCartesianFromBarycentric.doc) .def( "CalcBarycentric", [](const Class* self, const Vector3<T>& p_MQ, int t) { return self->template CalcBarycentric(p_MQ, t); }, py::arg("p_MQ"), py::arg("t"), cls_doc.CalcBarycentric.doc); } // VolumeMesh { using Class = VolumeMesh<T>; constexpr auto& cls_doc = doc.VolumeMesh; auto cls = DefineTemplateClassWithDefault<Class>( m, "VolumeMesh", param, doc.VolumeMesh.doc); cls // BR .def(py::init<std::vector<VolumeElement>, std::vector<Vector3<T>>>(), py::arg("elements"), py::arg("vertices"), cls_doc.ctor.doc) .def("element", &Class::element, py::arg("e"), cls_doc.element.doc) .def("vertex", &Class::vertex, py::arg("v"), cls_doc.vertex.doc) .def("vertices", &Class::vertices, py_rvp::reference_internal, cls_doc.vertices.doc) .def("tetrahedra", &Class::tetrahedra, py_rvp::reference_internal, cls_doc.tetrahedra.doc) .def("num_elements", &Class::num_elements, cls_doc.num_elements.doc) .def("num_vertices", &Class::num_vertices, cls_doc.num_vertices.doc) .def("CalcTetrahedronVolume", &Class::CalcTetrahedronVolume, py::arg("e"), cls_doc.CalcTetrahedronVolume.doc) .def("CalcVolume", &Class::CalcVolume, cls_doc.CalcVolume.doc) .def( "CalcBarycentric", [](const Class* self, const Vector3<T>& p_MQ, int e) { return self->template CalcBarycentric(p_MQ, e); }, py::arg("p_MQ"), py::arg("e"), cls_doc.CalcBarycentric.doc) .def("Equal", &Class::Equal, py::arg("mesh"), py::arg("vertex_tolerance") = 0, cls_doc.Equal.doc); } m.def("ConvertVolumeToSurfaceMesh", &ConvertVolumeToSurfaceMesh<T>, py::arg("volume"), doc.ConvertVolumeToSurfaceMesh.doc); } void DoScalarIndependentDefinitions(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; constexpr auto& doc = pydrake_doc.drake.geometry; // SurfacePolygon { using Class = SurfacePolygon; constexpr auto& cls_doc = doc.SurfacePolygon; py::class_<Class> cls(m, "SurfacePolygon", cls_doc.doc); cls // BR .def("num_vertices", &Class::num_vertices, cls_doc.num_vertices.doc) .def("vertex", &Class::vertex, py::arg("i"), cls_doc.vertex.doc); } // SurfaceTriangle { using Class = SurfaceTriangle; constexpr auto& cls_doc = doc.SurfaceTriangle; py::class_<Class> cls(m, "SurfaceTriangle", cls_doc.doc); cls // BR .def(py::init<int, int, int>(), py::arg("v0"), py::arg("v1"), py::arg("v2"), cls_doc.ctor.doc_3args) .def("num_vertices", &Class::num_vertices, cls_doc.num_vertices.doc) // TODO(SeanCurtis-TRI): Bind constructor that takes array of ints. .def("vertex", &Class::vertex, py::arg("i"), cls_doc.vertex.doc); DefCopyAndDeepCopy(&cls); } // VolumeElement { using Class = VolumeElement; constexpr auto& cls_doc = doc.VolumeElement; py::class_<Class> cls(m, "VolumeElement", cls_doc.doc); cls // BR .def(py::init<int, int, int, int>(), py::arg("v0"), py::arg("v1"), py::arg("v2"), py::arg("v3"), cls_doc.ctor.doc_4args) // TODO(SeanCurtis-TRI): Bind constructor that takes array of ints. .def("vertex", &Class::vertex, py::arg("i"), cls_doc.vertex.doc); DefCopyAndDeepCopy(&cls); } } void DoMeshDependentDefinitions(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; constexpr auto& doc = pydrake_doc.drake.geometry; m.def( "ReadObjToTriangleSurfaceMesh", [](const std::string& filename, double scale) { return geometry::ReadObjToTriangleSurfaceMesh(filename, scale); }, py::arg("filename"), py::arg("scale") = 1.0, // N.B. We have not bound the optional "on_warning" argument. doc.ReadObjToTriangleSurfaceMesh.doc_3args_filename_scale_on_warning); } } // namespace void DefineGeometryMeshes(py::module m) { DoScalarIndependentDefinitions(m); type_visit([m](auto dummy) { DoScalarDependentDefinitions(m, dummy); }, NonSymbolicScalarPack{}); DoMeshDependentDefinitions(m); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/_geometry_extra.py
# See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and # rationale. import os import socket import subprocess import sys from pydrake.common import FindResourceOrThrow def _is_listening(port): """Returns True iff the port number (on localhost) is listening for connections. """ try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return sock.connect_ex(("127.0.0.1", port)) == 0 finally: sock.close() def _install_deepnote_nginx(): """Uses Ubuntu to install the NginX web server and configures it to serve as a reverse proxy for MeshCat on Deepnote. The server will proxy https://DEEPNOTE_PROJECT_ID:8080/PORT/ to http://127.0.0.1:PORT/ so that multiple notebooks can all be served via Deepnote's only open port. """ print("Installing NginX server for MeshCat on Deepnote...") install_nginx = FindResourceOrThrow( "drake/setup/deepnote/install_nginx") proc = subprocess.run( [install_nginx], encoding="utf-8", stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if proc.returncode == 0: return print(proc.stdout, file=sys.stderr, end="") proc.check_returncode() def _start_meshcat_deepnote(*, params=None, restart_nginx=False): """Returns a Meshcat object suitable for use on Deepnote's cloud. The optional arguments are not available to end users but might be helpful when debugging this function. """ from IPython.display import display, HTML host = os.environ["DEEPNOTE_PROJECT_ID"] if params is None: params = MeshcatParams() params.web_url_pattern = f"https://{host}.deepnoteproject.com/{{port}}/" if restart_nginx or not _is_listening(8080): _install_deepnote_nginx() meshcat = Meshcat(params=params) url = meshcat.web_url() display(HTML(f"Meshcat URL: <a href='{url}' target='_blank'>{url}</a>")) return meshcat def StartMeshcat(): """ Constructs a Meshcat instance, with extra support for Deepnote. On most platforms, this function is equivalent to simply constructing a ``pydrake.geometry.Meshcat`` object with default arguments. On Deepnote, however, this does extra work to expose Meshcat to the public internet by setting up a reverse proxy for the single available network port. To access it, you must enable "Allow incoming connections" in the Environment settings pane. """ if "DEEPNOTE_PROJECT_ID" in os.environ: return _start_meshcat_deepnote() return Meshcat()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py_visualizers.cc
/* @file This contains the bindings for the various visualizer System types found in drake::geometry. They can be found in the pydrake.geometry module. */ #include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/common/serialize_pybind.h" #include "drake/bindings/pydrake/common/type_pack.h" #include "drake/bindings/pydrake/common/type_safe_index_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/geometry/drake_visualizer.h" #include "drake/geometry/meshcat.h" #include "drake/geometry/meshcat_animation.h" #include "drake/geometry/meshcat_point_cloud_visualizer.h" #include "drake/geometry/meshcat_visualizer.h" namespace drake { namespace pydrake { namespace { using math::RigidTransformd; using systems::Context; using systems::LeafSystem; template <typename T> void DoScalarDependentDefinitions(py::module m, T) { py::tuple param = GetPyParam<T>(); constexpr auto& doc = pydrake_doc.drake.geometry; // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; py::module::import("pydrake.systems.framework"); py::module::import("pydrake.systems.lcm"); // DrakeVisualizer { using Class = DrakeVisualizer<T>; constexpr auto& cls_doc = doc.DrakeVisualizer; auto cls = DefineTemplateClassWithDefault<Class, LeafSystem<T>>( m, "DrakeVisualizer", param, cls_doc.doc); cls // BR .def(py::init<lcm::DrakeLcmInterface*, DrakeVisualizerParams>(), py::arg("lcm") = nullptr, py::arg("params") = DrakeVisualizerParams{}, // Keep alive, reference: `self` keeps `lcm` alive. py::keep_alive<1, 2>(), // BR cls_doc.ctor.doc) .def("query_object_input_port", &Class::query_object_input_port, py_rvp::reference_internal, cls_doc.query_object_input_port.doc) .def_static("AddToBuilder", py::overload_cast<systems::DiagramBuilder<T>*, const SceneGraph<T>&, lcm::DrakeLcmInterface*, DrakeVisualizerParams>( &DrakeVisualizer<T>::AddToBuilder), py::arg("builder"), py::arg("scene_graph"), py::arg("lcm") = nullptr, py::arg("params") = DrakeVisualizerParams{}, // Keep alive, ownership: `return` keeps `builder` alive. py::keep_alive<0, 1>(), // Keep alive, reference: `builder` keeps `lcm` alive. py::keep_alive<1, 3>(), py_rvp::reference, cls_doc.AddToBuilder.doc_4args_builder_scene_graph_lcm_params) .def_static("AddToBuilder", py::overload_cast<systems::DiagramBuilder<T>*, const systems::OutputPort<T>&, lcm::DrakeLcmInterface*, DrakeVisualizerParams>(&DrakeVisualizer<T>::AddToBuilder), py::arg("builder"), py::arg("query_object_port"), py::arg("lcm") = nullptr, py::arg("params") = DrakeVisualizerParams{}, // Keep alive, ownership: `return` keeps `builder` alive. py::keep_alive<0, 1>(), // Keep alive, reference: `builder` keeps `lcm` alive. py::keep_alive<1, 3>(), py_rvp::reference, cls_doc.AddToBuilder.doc_4args_builder_query_object_port_lcm_params) .def_static("DispatchLoadMessage", &DrakeVisualizer<T>::DispatchLoadMessage, py::arg("scene_graph"), py::arg("lcm"), py::arg("params") = DrakeVisualizerParams{}, cls_doc.DispatchLoadMessage.doc); } // MeshcatPointCloudVisualizer { using Class = MeshcatPointCloudVisualizer<T>; constexpr auto& cls_doc = doc.MeshcatPointCloudVisualizer; auto cls = DefineTemplateClassWithDefault<Class, LeafSystem<T>>( m, "MeshcatPointCloudVisualizer", param, cls_doc.doc); cls // BR .def(py::init<std::shared_ptr<Meshcat>, std::string, double>(), py::arg("meshcat"), py::arg("path"), py::arg("publish_period") = 1 / 32.0, // `meshcat` is a shared_ptr, so does not need a keep_alive. cls_doc.ctor.doc) .def("set_point_size", &Class::set_point_size, cls_doc.set_point_size.doc) .def("set_default_rgba", &Class::set_default_rgba, cls_doc.set_default_rgba.doc) .def("Delete", &Class::Delete, cls_doc.Delete.doc) .def("cloud_input_port", &Class::cloud_input_port, py_rvp::reference_internal, cls_doc.cloud_input_port.doc) .def("pose_input_port", &Class::pose_input_port, py_rvp::reference_internal, cls_doc.pose_input_port.doc); } // MeshcatVisualizer { using Class = MeshcatVisualizer<T>; constexpr auto& cls_doc = doc.MeshcatVisualizer; auto cls = DefineTemplateClassWithDefault<Class, LeafSystem<T>>( m, "MeshcatVisualizer", param, cls_doc.doc); cls // BR .def(py::init<std::shared_ptr<Meshcat>, MeshcatVisualizerParams>(), py::arg("meshcat"), py::arg("params") = MeshcatVisualizerParams{}, // `meshcat` is a shared_ptr, so does not need a keep_alive. cls_doc.ctor.doc) .def("ResetRealtimeRateCalculator", &Class::ResetRealtimeRateCalculator, cls_doc.ResetRealtimeRateCalculator.doc) .def("Delete", &Class::Delete, cls_doc.Delete.doc) .def("StartRecording", &Class::StartRecording, py::arg("set_transforms_while_recording") = true, py_rvp::reference_internal, cls_doc.StartRecording.doc) .def("StopRecording", &Class::StopRecording, cls_doc.StopRecording.doc) .def("PublishRecording", &Class::PublishRecording, cls_doc.PublishRecording.doc) .def("DeleteRecording", &Class::DeleteRecording, cls_doc.DeleteRecording.doc) .def("get_mutable_recording", &Class::get_mutable_recording, py_rvp::reference_internal, cls_doc.get_mutable_recording.doc) .def("query_object_input_port", &Class::query_object_input_port, py_rvp::reference_internal, cls_doc.query_object_input_port.doc) .def_static("AddToBuilder", py::overload_cast<systems::DiagramBuilder<T>*, const SceneGraph<T>&, std::shared_ptr<Meshcat>, MeshcatVisualizerParams>( &MeshcatVisualizer<T>::AddToBuilder), py::arg("builder"), py::arg("scene_graph"), py::arg("meshcat"), py::arg("params") = MeshcatVisualizerParams{}, // Keep alive, ownership: `return` keeps `builder` alive. py::keep_alive<0, 1>(), // `meshcat` is a shared_ptr, so does not need a keep_alive. py_rvp::reference, cls_doc.AddToBuilder.doc_4args_builder_scene_graph_meshcat_params) .def_static("AddToBuilder", py::overload_cast<systems::DiagramBuilder<T>*, const systems::OutputPort<T>&, std::shared_ptr<Meshcat>, MeshcatVisualizerParams>(&MeshcatVisualizer<T>::AddToBuilder), py::arg("builder"), py::arg("query_object_port"), py::arg("meshcat"), py::arg("params") = MeshcatVisualizerParams{}, // Keep alive, ownership: `return` keeps `builder` alive. py::keep_alive<0, 1>(), // `meshcat` is a shared_ptr, so does not need a keep_alive. py_rvp::reference, cls_doc.AddToBuilder .doc_4args_builder_query_object_port_meshcat_params); } } void DoScalarIndependentDefinitions(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; constexpr auto& doc = pydrake_doc.drake.geometry; // DrakeVisualizerParams { using Class = DrakeVisualizerParams; constexpr auto& cls_doc = doc.DrakeVisualizerParams; py::class_<Class> cls( m, "DrakeVisualizerParams", py::dynamic_attr(), cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } // MeshcatParams { using Class = MeshcatParams; constexpr auto& cls_doc = doc.MeshcatParams; py::class_<Class, std::shared_ptr<Class>> cls( m, "MeshcatParams", py::dynamic_attr(), cls_doc.doc); // MeshcatParams::PropertyTuple { using Nested = MeshcatParams::PropertyTuple; constexpr auto& nested_doc = doc.MeshcatParams.PropertyTuple; py::class_<Nested> nested(cls, "PropertyTuple", nested_doc.doc); nested.def(ParamInit<Nested>()); DefAttributesUsingSerialize(&nested, nested_doc); DefReprUsingSerialize(&nested); DefCopyAndDeepCopy(&nested); } cls.def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } // Meshcat { using Class = Meshcat; constexpr auto& cls_doc = doc.Meshcat; py::class_<Class, std::shared_ptr<Class>> meshcat( m, "Meshcat", cls_doc.doc); // Meshcat::SideOfFaceToRender enumeration constexpr auto& side_doc = doc.Meshcat.SideOfFaceToRender; py::enum_<Meshcat::SideOfFaceToRender>( meshcat, "SideOfFaceToRender", side_doc.doc) .value("kFrontSide", Meshcat::SideOfFaceToRender::kFrontSide, side_doc.kFrontSide.doc) .value("kBackSide", Meshcat::SideOfFaceToRender::kBackSide, side_doc.kBackSide.doc) .value("kDoubleSide", Meshcat::SideOfFaceToRender::kDoubleSide, side_doc.kDoubleSide.doc); meshcat // BR .def(py::init<std::optional<int>>(), py::arg("port") = std::nullopt, cls_doc.ctor.doc_1args_port) .def(py::init<const MeshcatParams&>(), py::arg("params"), cls_doc.ctor.doc_1args_params) .def("web_url", &Class::web_url, cls_doc.web_url.doc) .def("port", &Class::port, cls_doc.port.doc) .def("ws_url", &Class::ws_url, cls_doc.ws_url.doc) .def("GetNumActiveConnections", &Class::GetNumActiveConnections, cls_doc.GetNumActiveConnections.doc) .def("Flush", &Class::Flush, // Internally this function both blocks on a worker thread and // sleeps; for both reasons, we must release the GIL. py::call_guard<py::gil_scoped_release>(), cls_doc.Flush.doc) .def("SetObject", py::overload_cast<std::string_view, const Shape&, const Rgba&>( &Class::SetObject), py::arg("path"), py::arg("shape"), py::arg("rgba") = Rgba(.9, .9, .9, 1.), cls_doc.SetObject.doc_shape) .def("SetObject", py::overload_cast<std::string_view, const perception::PointCloud&, double, const Rgba&>(&Class::SetObject), py::arg("path"), py::arg("cloud"), py::arg("point_size") = 0.001, py::arg("rgba") = Rgba(.9, .9, .9, 1.), cls_doc.SetObject.doc_cloud) .def("SetObject", py::overload_cast<std::string_view, const TriangleSurfaceMesh<double>&, const Rgba&, bool, double, Meshcat::SideOfFaceToRender>(&Class::SetObject), py::arg("path"), py::arg("mesh"), py::arg("rgba") = Rgba(0.1, 0.1, 0.1, 1.0), py::arg("wireframe") = false, py::arg("wireframe_line_width") = 1.0, py::arg("side") = Meshcat::SideOfFaceToRender::kDoubleSide, cls_doc.SetObject.doc_triangle_surface_mesh) .def("SetLine", &Class::SetLine, py::arg("path"), py::arg("vertices"), py::arg("line_width") = 1.0, py::arg("rgba") = Rgba(0.1, 0.1, 0.1, 1.0), cls_doc.SetLine.doc) .def("SetLineSegments", &Class::SetLineSegments, py::arg("path"), py::arg("start"), py::arg("end"), py::arg("line_width") = 1.0, py::arg("rgba") = Rgba(0.1, 0.1, 0.1, 1.0), cls_doc.SetLineSegments.doc) .def("SetTriangleMesh", &Class::SetTriangleMesh, py::arg("path"), py::arg("vertices"), py::arg("faces"), py::arg("rgba") = Rgba(0.1, 0.1, 0.1, 1.0), py::arg("wireframe") = false, py::arg("wireframe_line_width") = 1.0, py::arg("side") = Meshcat::SideOfFaceToRender::kDoubleSide, cls_doc.SetTriangleMesh.doc) .def("SetTriangleColorMesh", &Class::SetTriangleColorMesh, py::arg("path"), py::arg("vertices"), py::arg("faces"), py::arg("colors"), py::arg("wireframe") = false, py::arg("wireframe_line_width") = 1.0, py::arg("side") = Meshcat::SideOfFaceToRender::kDoubleSide, cls_doc.SetTriangleColorMesh.doc) .def("PlotSurface", &Class::PlotSurface, py::arg("path"), py::arg("X"), py::arg("Y"), py::arg("Z"), py::arg("rgba") = Rgba(0.1, 0.1, 0.9, 1.0), py::arg("wireframe") = false, py::arg("wireframe_line_width") = 1.0, cls_doc.PlotSurface.doc) .def("SetCamera", py::overload_cast<Meshcat::PerspectiveCamera, std::string>( &Class::SetCamera), py::arg("camera"), py::arg("path") = "/Cameras/default/rotated", cls_doc.SetCamera.doc_perspective) .def("SetCamera", py::overload_cast<Meshcat::OrthographicCamera, std::string>( &Class::SetCamera), py::arg("camera"), py::arg("path") = "/Cameras/default/rotated", cls_doc.SetCamera.doc_orthographic) .def("Set2dRenderMode", &Class::Set2dRenderMode, py::arg("X_WC") = RigidTransformd{Eigen::Vector3d{0, -1, 0}}, py::arg("xmin") = -1.0, py::arg("xmax") = 1.0, py::arg("ymin") = -1.0, py::arg("ymax") = 1.0, cls_doc.Set2dRenderMode.doc) .def("ResetRenderMode", &Class::ResetRenderMode, cls_doc.ResetRenderMode.doc) .def("SetCameraTarget", &Class::SetCameraTarget, py::arg("target_in_world"), cls_doc.SetCameraTarget.doc) .def("SetCameraPose", &Class::SetCameraPose, py::arg("camera_in_world"), py::arg("target_in_world"), cls_doc.SetCameraPose.doc) .def("GetTrackedCameraPose", &Class::GetTrackedCameraPose, cls_doc.GetTrackedCameraPose.doc) .def("SetTransform", py::overload_cast<std::string_view, const math::RigidTransformd&, std::optional<double>>(&Class::SetTransform), py::arg("path"), py::arg("X_ParentPath"), py::arg("time_in_recording") = std::nullopt, cls_doc.SetTransform.doc_RigidTransform) .def("SetTransform", py::overload_cast<std::string_view, const Eigen::Ref<const Eigen::Matrix4d>&>(&Class::SetTransform), py::arg("path"), py::arg("matrix"), cls_doc.SetTransform.doc_matrix) .def("Delete", &Class::Delete, py::arg("path") = "", cls_doc.Delete.doc) .def("SetRealtimeRate", &Class::SetRealtimeRate, py::arg("rate"), cls_doc.SetRealtimeRate.doc) .def("GetRealtimeRate", &Class::GetRealtimeRate, cls_doc.GetRealtimeRate.doc) .def("SetProperty", py::overload_cast<std::string_view, std::string, bool, std::optional<double>>(&Class::SetProperty), py::arg("path"), py::arg("property"), py::arg("value"), py::arg("time_in_recording") = std::nullopt, cls_doc.SetProperty.doc_bool) .def("SetProperty", py::overload_cast<std::string_view, std::string, double, std::optional<double>>(&Class::SetProperty), py::arg("path"), py::arg("property"), py::arg("value"), py::arg("time_in_recording") = std::nullopt, cls_doc.SetProperty.doc_double) .def("SetProperty", py::overload_cast<std::string_view, std::string, const std::vector<double>&, std::optional<double>>( &Class::SetProperty), py::arg("path"), py::arg("property"), py::arg("value"), py::arg("time_in_recording") = std::nullopt, cls_doc.SetProperty.doc_vector_double) .def("SetEnvironmentMap", &Class::SetEnvironmentMap, py::arg("image_path"), cls_doc.SetEnvironmentMap.doc) .def("SetAnimation", &Class::SetAnimation, py::arg("animation"), +cls_doc.SetAnimation.doc) .def("AddButton", &Class::AddButton, py::arg("name"), py::arg("keycode") = "", cls_doc.AddButton.doc) .def("GetButtonClicks", &Class::GetButtonClicks, py::arg("name"), cls_doc.GetButtonClicks.doc) .def("DeleteButton", &Class::DeleteButton, py::arg("name"), cls_doc.DeleteButton.doc) .def("AddSlider", &Class::AddSlider, py::arg("name"), py::arg("min"), py::arg("max"), py::arg("step"), py::arg("value"), py::arg("decrement_keycode") = "", py::arg("increment_keycode") = "", cls_doc.AddSlider.doc) .def("SetSliderValue", &Class::SetSliderValue, py::arg("name"), py::arg("value"), cls_doc.SetSliderValue.doc) .def("GetSliderValue", &Class::GetSliderValue, py::arg("name"), cls_doc.GetSliderValue.doc) .def("GetSliderNames", &Class::GetSliderNames, cls_doc.GetSliderNames.doc) .def("DeleteSlider", &Class::DeleteSlider, py::arg("name"), cls_doc.DeleteSlider.doc) .def("DeleteAddedControls", &Class::DeleteAddedControls, cls_doc.DeleteAddedControls.doc) .def("GetGamepad", &Class::GetGamepad, cls_doc.GetGamepad.doc) .def("StaticHtml", &Class::StaticHtml, // This function costs a non-trivial amount of CPU time and blocks // on a worker thread; for both reasons, we must release the GIL. py::call_guard<py::gil_scoped_release>(), cls_doc.StaticHtml.doc) .def("StartRecording", &Class::StartRecording, py::arg("frames_per_second") = 64.0, py::arg("set_visualizations_while_recording") = true, cls_doc.StartRecording.doc) .def("StopRecording", &Class::StopRecording, cls_doc.StopRecording.doc) .def("PublishRecording", &Class::PublishRecording, cls_doc.PublishRecording.doc) .def("DeleteRecording", &Class::DeleteRecording, cls_doc.DeleteRecording.doc) .def("get_mutable_recording", &Class::get_mutable_recording, py_rvp::reference_internal, cls_doc.get_mutable_recording.doc) .def("HasPath", &Class::HasPath, py::arg("path"), // This function blocks on a worker thread so must release the GIL. py::call_guard<py::gil_scoped_release>(), cls_doc.HasPath.doc); // This helper wraps a Meshcat::GetPacked{Foo} member function to release // the GIL during the call (because the member function blocks to wait for a // worker thread) and then copies the result into py::bytes while holding // the GIL. auto wrap_get_packed_foo = []<typename... Args>(std::string (Class::*member_func)(Args...) const) { return [member_func](const Class& self, Args... args) { std::string result; { py::gil_scoped_release unlock; result = (self.*member_func)(args...); } return py::bytes(result); }; }; // NOLINT(readability/braces) // The remaining methods are intended to primarily for testing. Because they // are excluded from C++ Doxygen, we bind them privately here. meshcat // BR .def("_GetPackedObject", wrap_get_packed_foo(&Class::GetPackedObject), py::arg("path")) .def("_GetPackedTransform", wrap_get_packed_foo(&Class::GetPackedTransform), py::arg("path")) .def("_GetPackedProperty", wrap_get_packed_foo(&Class::GetPackedProperty), py::arg("path"), py::arg("property")) .def( "_InjectWebsocketMessage", [](Class& self, py::bytes message) { std::string_view message_view = message; // This call blocks on a worker thread so must release the GIL. py::gil_scoped_release unlock; self.InjectWebsocketMessage(message_view); }, py::arg("message")); const auto& perspective_camera_doc = doc.Meshcat.PerspectiveCamera; py::class_<Meshcat::PerspectiveCamera> perspective_camera_cls( meshcat, "PerspectiveCamera", perspective_camera_doc.doc); perspective_camera_cls // BR .def(ParamInit<Meshcat::PerspectiveCamera>()); DefAttributesUsingSerialize( &perspective_camera_cls, perspective_camera_doc); DefReprUsingSerialize(&perspective_camera_cls); DefCopyAndDeepCopy(&perspective_camera_cls); const auto& orthographic_camera_doc = doc.Meshcat.OrthographicCamera; py::class_<Meshcat::OrthographicCamera> orthographic_camera_cls( meshcat, "OrthographicCamera", orthographic_camera_doc.doc); orthographic_camera_cls // BR .def(ParamInit<Meshcat::OrthographicCamera>()); DefAttributesUsingSerialize( &orthographic_camera_cls, orthographic_camera_doc); DefReprUsingSerialize(&orthographic_camera_cls); DefCopyAndDeepCopy(&orthographic_camera_cls); const auto& gamepad_doc = doc.Meshcat.Gamepad; py::class_<Meshcat::Gamepad> gamepad_cls( meshcat, "Gamepad", gamepad_doc.doc); gamepad_cls // BR .def(ParamInit<Meshcat::Gamepad>()); DefAttributesUsingSerialize(&gamepad_cls, gamepad_doc); DefReprUsingSerialize(&gamepad_cls); DefCopyAndDeepCopy(&gamepad_cls); } // MeshcatAnimation { using Class = MeshcatAnimation; constexpr auto& cls_doc = doc.MeshcatAnimation; py::class_<Class> cls(m, "MeshcatAnimation", cls_doc.doc); cls // BR .def(py::init<double>(), py::arg("frames_per_second") = 64.0, cls_doc.ctor.doc) .def("frames_per_second", &Class::frames_per_second, cls_doc.frames_per_second.doc) .def("frame", &Class::frame, py::arg("time_from_start"), cls_doc.frame.doc) .def("autoplay", &Class::autoplay, cls_doc.autoplay.doc) .def("loop_mode", &Class::loop_mode, cls_doc.loop_mode.doc) .def("repetitions", &Class::repetitions, cls_doc.repetitions.doc) .def("clamp_when_finished", &Class::clamp_when_finished, cls_doc.clamp_when_finished.doc) .def("set_autoplay", &Class::set_autoplay, py::arg("play"), cls_doc.set_autoplay.doc) .def("set_loop_mode", &Class::set_loop_mode, py::arg("mode"), cls_doc.set_loop_mode.doc) .def("set_repetitions", &Class::set_repetitions, py::arg("repetitions"), cls_doc.set_repetitions.doc) .def("set_clamp_when_finished", &Class::set_clamp_when_finished, py::arg("clamp"), cls_doc.set_clamp_when_finished.doc) .def("SetTransform", &Class::SetTransform, py::arg("frame"), py::arg("path"), py::arg("X_ParentPath"), cls_doc.SetTransform.doc) .def("SetProperty", // Note: overload_cast and overload_cast_explicit did not work here. static_cast<void (Class::*)(int, std::string_view, std::string_view, bool)>(&Class::SetProperty), py::arg("frame"), py::arg("path"), py::arg("property"), py::arg("value"), cls_doc.SetProperty.doc_bool) .def("SetProperty", static_cast<void (Class::*)(int, std::string_view, std::string_view, double)>(&Class::SetProperty), py::arg("frame"), py::arg("path"), py::arg("property"), py::arg("value"), cls_doc.SetProperty.doc_double) .def("SetProperty", static_cast<void (Class::*)(int, std::string_view, std::string_view, const std::vector<double>&)>(&Class::SetProperty), py::arg("frame"), py::arg("path"), py::arg("property"), py::arg("value"), cls_doc.SetProperty.doc_vector_double); // Note: We don't bind get_key_frame and get_javascript_type (at least // not yet); they are meant primarily for testing. // MeshcatAnimation::LoopMode enumeration constexpr auto& loop_doc = doc.MeshcatAnimation.LoopMode; py::enum_<MeshcatAnimation::LoopMode>(cls, "LoopMode", loop_doc.doc) .value("kLoopOnce", MeshcatAnimation::LoopMode::kLoopOnce, loop_doc.kLoopOnce.doc) .value("kLoopRepeat", MeshcatAnimation::LoopMode::kLoopRepeat, loop_doc.kLoopRepeat.doc) .value("kLoopPingPong", MeshcatAnimation::LoopMode::kLoopPingPong, loop_doc.kLoopPingPong.doc); } // MeshcatVisualizerParams { using Class = MeshcatVisualizerParams; constexpr auto& cls_doc = doc.MeshcatVisualizerParams; py::class_<Class> cls( m, "MeshcatVisualizerParams", py::dynamic_attr(), cls_doc.doc); cls // BR .def(ParamInit<Class>()); DefAttributesUsingSerialize(&cls, cls_doc); DefReprUsingSerialize(&cls); DefCopyAndDeepCopy(&cls); } } } // namespace void DefineGeometryVisualizers(py::module m) { DoScalarIndependentDefinitions(m); type_visit([m](auto dummy) { DoScalarDependentDefinitions(m, dummy); }, NonSymbolicScalarPack{}); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py.cc
#include "drake/bindings/pydrake/geometry/geometry_py.h" #include "pybind11/eval.h" #include "drake/bindings/pydrake/pydrake_pybind.h" namespace drake { namespace pydrake { namespace { void def_geometry_all(py::module m) { py::dict vars = m.attr("__dict__"); py::exec( "from pydrake.geometry import *\n" "from pydrake.geometry.optimization import *\n", py::globals(), vars); } } // namespace PYBIND11_MODULE(geometry, m) { PYDRAKE_PREVENT_PYTHON3_MODULE_REIMPORT(m); py::module::import("pydrake.math"); /* The order of execution matters -- a module may rely on the definition of bindings executed prior to it. */ DefineGeometryMeshes(m); DefineGeometryCommon(m); DefineGeometryHydro(m); DefineGeometryRender(m); DefineGeometrySceneGraph(m); DefineGeometryOptimization(m.def_submodule("optimization")); DefineGeometryVisualizers(m); ExecuteExtraPythonCode(m, true); def_geometry_all(m.def_submodule("all")); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/geometry_py_common.cc
/* @file This contains all of the various types in the drake::geometry namespace that represent the "core" geometry concepts: instances, frames, properties. These don't depend on any of geometry's computational structure, but, instead, represent the input values to all of those computations. They can be found in the pydrake.geometry module. */ #include "drake/bindings/pydrake/common/default_scalars_pybind.h" #include "drake/bindings/pydrake/common/identifier_pybind.h" #include "drake/bindings/pydrake/common/serialize_pybind.h" #include "drake/bindings/pydrake/common/value_pybind.h" #include "drake/bindings/pydrake/documentation_pybind.h" #include "drake/geometry/collision_filter_declaration.h" #include "drake/geometry/collision_filter_manager.h" #include "drake/geometry/geometry_frame.h" #include "drake/geometry/geometry_ids.h" #include "drake/geometry/geometry_instance.h" #include "drake/geometry/geometry_properties.h" #include "drake/geometry/geometry_roles.h" #include "drake/geometry/geometry_version.h" #include "drake/geometry/proximity_properties.h" #include "drake/geometry/shape_specification.h" namespace drake { namespace pydrake { namespace { void DoScalarIndependentDefinitions(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::geometry; constexpr auto& doc = pydrake_doc.drake.geometry; // CollisionFilterDeclaration. { using Class = CollisionFilterDeclaration; constexpr auto& cls_doc = doc.CollisionFilterDeclaration; py::class_<Class>(m, "CollisionFilterDeclaration", cls_doc.doc) .def(py::init(), cls_doc.ctor.doc) .def("AllowBetween", &Class::AllowBetween, py::arg("set_A"), py::arg("set_B"), py_rvp::reference, cls_doc.AllowBetween.doc) .def("AllowWithin", &Class::AllowWithin, py::arg("geometry_set"), py_rvp::reference, cls_doc.AllowWithin.doc) .def("ExcludeBetween", &Class::ExcludeBetween, py::arg("set_A"), py::arg("set_B"), py_rvp::reference, cls_doc.ExcludeBetween.doc) .def("ExcludeWithin", &Class::ExcludeWithin, py::arg("geometry_set"), py_rvp::reference, cls_doc.ExcludeWithin.doc); } // CollisionFilterManager { using Class = CollisionFilterManager; constexpr auto& cls_doc = doc.CollisionFilterManager; py::class_<Class>(m, "CollisionFilterManager", cls_doc.doc) .def("Apply", &Class::Apply, py::arg("declaration"), cls_doc.Apply.doc) .def("ApplyTransient", &Class::ApplyTransient, py::arg("declaration"), cls_doc.ApplyTransient.doc) .def("RemoveDeclaration", &Class::RemoveDeclaration, py::arg("filter_id"), cls_doc.RemoveDeclaration.doc) .def("has_transient_history", &Class::has_transient_history, cls_doc.has_transient_history.doc) .def("IsActive", &Class::IsActive, py::arg("filter_id"), cls_doc.IsActive.doc); } // GeometryFrame { using Class = GeometryFrame; constexpr auto& cls_doc = doc.GeometryFrame; py::class_<Class> cls(m, "GeometryFrame", cls_doc.doc); cls // BR .def(py::init<const std::string&, int>(), py::arg("frame_name"), py::arg("frame_group_id") = 0, cls_doc.ctor.doc) .def("id", &Class::id, cls_doc.id.doc) .def("name", &Class::name, cls_doc.name.doc) .def("frame_group", &Class::frame_group, cls_doc.frame_group.doc); DefCopyAndDeepCopy(&cls); } // GeometryInstance { using Class = GeometryInstance; constexpr auto& cls_doc = doc.GeometryInstance; py::class_<Class> cls(m, "GeometryInstance", cls_doc.doc); cls // BR .def(py::init<const math::RigidTransform<double>&, const Shape&, const std::string&>(), py::arg("X_PG"), py::arg("shape"), py::arg("name"), cls_doc.ctor.doc) .def("id", &Class::id, cls_doc.id.doc) .def("pose", &Class::pose, py_rvp::reference_internal, cls_doc.pose.doc) .def( "set_pose", &Class::set_pose, py::arg("X_PG"), cls_doc.set_pose.doc) .def("shape", &Class::shape, py_rvp::reference_internal, cls_doc.shape.doc) .def("name", &Class::name, cls_doc.name.doc) .def("set_name", &Class::set_name, cls_doc.set_name.doc) .def("set_proximity_properties", &Class::set_proximity_properties, py::arg("properties"), cls_doc.set_proximity_properties.doc) .def("set_illustration_properties", &Class::set_illustration_properties, py::arg("properties"), cls_doc.set_illustration_properties.doc) .def("set_perception_properties", &Class::set_perception_properties, py::arg("properties"), cls_doc.set_perception_properties.doc) .def("mutable_proximity_properties", &Class::mutable_proximity_properties, py_rvp::reference_internal, cls_doc.mutable_proximity_properties.doc) .def("proximity_properties", &Class::proximity_properties, py_rvp::reference_internal, cls_doc.proximity_properties.doc) .def("mutable_illustration_properties", &Class::mutable_illustration_properties, py_rvp::reference_internal, cls_doc.mutable_illustration_properties.doc) .def("illustration_properties", &Class::illustration_properties, py_rvp::reference_internal, cls_doc.illustration_properties.doc) .def("mutable_perception_properties", &Class::mutable_perception_properties, py_rvp::reference_internal, cls_doc.mutable_perception_properties.doc) .def("perception_properties", &Class::perception_properties, py_rvp::reference_internal, cls_doc.perception_properties.doc); DefCopyAndDeepCopy(&cls); } // GeometryProperties { using Class = GeometryProperties; constexpr auto& cls_doc = doc.GeometryProperties; py::handle abstract_value_cls = py::module::import("pydrake.common.value").attr("AbstractValue"); py::class_<Class>(m, "GeometryProperties", cls_doc.doc) .def("HasGroup", &Class::HasGroup, py::arg("group_name"), cls_doc.HasGroup.doc) .def("num_groups", &Class::num_groups, cls_doc.num_groups.doc) .def( "GetPropertiesInGroup", [](const Class& self, const std::string& group_name) { py::dict out; py::object py_self = py::cast(&self, py_rvp::reference); for (auto& [name, abstract] : self.GetPropertiesInGroup(group_name)) { out[name.c_str()] = py::cast( abstract.get(), py_rvp::reference_internal, py_self); } return out; }, py::arg("group_name"), cls_doc.GetPropertiesInGroup.doc) .def("GetGroupNames", &Class::GetGroupNames, cls_doc.GetGroupNames.doc) .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) .def( "UpdateProperty", [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.UpdatePropertyAbstract( group_name, name, abstract.cast<const AbstractValue&>()); }, py::arg("group_name"), py::arg("name"), py::arg("value"), cls_doc.UpdateProperty.doc) .def("HasProperty", &Class::HasProperty, py::arg("group_name"), py::arg("name"), cls_doc.HasProperty.doc) .def( "GetProperty", [](const Class& self, const std::string& group_name, const std::string& name) { py::object abstract = py::cast(self.GetPropertyAbstract(group_name, name), py_rvp::reference); return abstract.attr("get_value")(); }, py::arg("group_name"), py::arg("name"), cls_doc.GetProperty.doc) .def( "GetPropertyOrDefault", [](const Class& self, const std::string& group_name, const std::string& name, py::object default_value) { // For now, ignore typing. This is less efficient, but eh, it's // Python. if (self.HasProperty(group_name, name)) { py::object py_self = py::cast(&self, py_rvp::reference); return py_self.attr("GetProperty")(group_name, name); } else { return default_value; } }, py::arg("group_name"), py::arg("name"), py::arg("default_value"), cls_doc.GetPropertyOrDefault.doc) .def("RemoveProperty", &Class::RemoveProperty, py::arg("group_name"), py::arg("name"), cls_doc.RemoveProperty.doc) .def_static("default_group_name", &Class::default_group_name, cls_doc.default_group_name.doc) .def( "__str__", [](const Class& self) { std::stringstream ss; ss << self; return ss.str(); }, "Returns formatted string."); } // GeometrySet { using Class = GeometrySet; constexpr auto& cls_doc = doc.GeometrySet; constexpr char extra_ctor_doc[] = "See main constructor"; // N.B. For containers, we use `std::vector<>` rather than abstract // iterators / containers. py::class_<Class>(m, "GeometrySet", cls_doc.doc) .def(py::init(), cls_doc.ctor.doc) .def(py::init<GeometryId>(), py::arg("geometry_id"), extra_ctor_doc) .def(py::init<FrameId>(), py::arg("frame_id"), extra_ctor_doc) .def(py::init([](std::vector<GeometryId> geometry_ids) { return Class(geometry_ids); }), py::arg("geometry_ids"), extra_ctor_doc) .def(py::init([](std::vector<FrameId> frame_ids) { return Class(frame_ids); }), py::arg("frame_ids"), extra_ctor_doc) .def(py::init([](std::vector<GeometryId> geometry_ids, std::vector<FrameId> frame_ids) { return Class(geometry_ids, frame_ids); }), py::arg("geometry_ids"), py::arg("frame_ids"), extra_ctor_doc) .def( "Add", [](Class* self, const GeometryId& geometry_id) { self->Add(geometry_id); }, py::arg("geometry_id"), cls_doc.Add.doc) .def( "Add", [](Class* self, const FrameId& frame_id) { self->Add(frame_id); }, py::arg("frame_id"), cls_doc.Add.doc) .def( "Add", [](Class* self, std::vector<GeometryId> geometry_ids) { self->Add(geometry_ids); }, py::arg("geometry_ids"), extra_ctor_doc) .def( "Add", [](Class* self, std::vector<FrameId> frame_ids) { self->Add(frame_ids); }, py::arg("frame_ids"), extra_ctor_doc) .def( "Add", [](Class* self, std::vector<GeometryId> geometry_ids, std::vector<FrameId> frame_ids) { self->Add(geometry_ids, frame_ids); }, py::arg("geometry_ids"), py::arg("frame_ids"), extra_ctor_doc); } // GeometryVersion { using Class = GeometryVersion; constexpr auto& cls_doc = doc.GeometryVersion; py::class_<Class> cls(m, "GeometryVersion", cls_doc.doc); cls.def(py::init(), cls_doc.ctor.doc) .def(py::init<const GeometryVersion&>(), py::arg("other"), "Creates a copy of the GeometryVersion.") .def("IsSameAs", &Class::IsSameAs, py::arg("other"), py::arg("role"), cls_doc.IsSameAs.doc); DefCopyAndDeepCopy(&cls); } // Identifiers. { BindIdentifier<FilterId>(m, "FilterId", doc.FilterId.doc); BindIdentifier<SourceId>(m, "SourceId", doc.SourceId.doc); BindIdentifier<FrameId>(m, "FrameId", doc.FrameId.doc); BindIdentifier<GeometryId>(m, "GeometryId", doc.GeometryId.doc); } // IllustrationProperties { py::class_<IllustrationProperties, GeometryProperties> cls( m, "IllustrationProperties", doc.IllustrationProperties.doc); cls.def(py::init(), doc.IllustrationProperties.ctor.doc) .def(py::init<const IllustrationProperties&>(), py::arg("other"), "Creates a copy of the properties"); DefCopyAndDeepCopy(&cls); } // PerceptionProperties { py::class_<PerceptionProperties, GeometryProperties> cls( m, "PerceptionProperties", doc.PerceptionProperties.doc); cls.def(py::init(), doc.PerceptionProperties.ctor.doc) .def(py::init<const PerceptionProperties&>(), py::arg("other"), "Creates a copy of the properties"); DefCopyAndDeepCopy(&cls); } // ProximityProperties { py::class_<ProximityProperties, GeometryProperties> cls( m, "ProximityProperties", doc.ProximityProperties.doc); cls.def(py::init(), doc.ProximityProperties.ctor.doc) .def(py::init<const ProximityProperties&>(), py::arg("other"), "Creates a copy of the properties"); DefCopyAndDeepCopy(&cls); } // Rgba { using Class = Rgba; constexpr auto& cls_doc = doc.Rgba; py::class_<Class> cls(m, "Rgba", cls_doc.doc); cls // BR .def(py::init<>(), cls_doc.ctor.doc_0args) .def(py::init<double, double, double, double>(), py::arg("r"), py::arg("g"), py::arg("b"), py::arg("a") = 1.0, cls_doc.ctor.doc_4args) .def("r", &Class::r, cls_doc.r.doc) .def("g", &Class::g, cls_doc.g.doc) .def("b", &Class::b, cls_doc.b.doc) .def("a", &Class::a, cls_doc.a.doc) .def("set", py::overload_cast<double, double, double, double>(&Class::set), py::arg("r"), py::arg("g"), py::arg("b"), py::arg("a") = 1.0, cls_doc.set.doc_4args) .def("set", py::overload_cast<const Eigen::Ref<const Eigen::VectorXd>&>( &Class::set), py::arg("rgba"), cls_doc.set.doc_1args) .def("update", &Class::update, py::arg("r") = py::none(), py::arg("g") = py::none(), py::arg("b") = py::none(), py::arg("a") = py::none(), cls_doc.update.doc) .def(py::self == py::self) .def(py::self != py::self) .def(py::self * py::self) .def("scale_rgb", &Class::scale_rgb, py::arg("scale"), cls_doc.scale_rgb.doc) .def("__repr__", [](const Class& self) { return py::str("Rgba(r={}, g={}, b={}, a={})") .format(self.r(), self.g(), self.b(), self.a()); }); DefAttributesUsingSerialize(&cls); cls.def_property("rgba", // The Serialize-based binding skips the validity checking; we'll // add it back here by re-binding the property getter and setter. &Class::rgba, py::overload_cast<const Eigen::Ref<const Eigen::VectorXd>&>( &Class::set), "The RGBA value as a property (as np.ndarray)."); DefCopyAndDeepCopy(&cls); AddValueInstantiation<Rgba>(m); } // Role enumeration { constexpr auto& cls_doc = doc.Role; py::enum_<Role>(m, "Role", py::arithmetic(), cls_doc.doc) .value("kUnassigned", Role::kUnassigned, cls_doc.kUnassigned.doc) .value("kProximity", Role::kProximity, cls_doc.kProximity.doc) .value("kIllustration", Role::kIllustration, cls_doc.kIllustration.doc) .value("kPerception", Role::kPerception, cls_doc.kPerception.doc); } // RoleAssign enumeration { constexpr auto& cls_doc = doc.RoleAssign; using Class = RoleAssign; py::enum_<Class>(m, "RoleAssign", cls_doc.doc) .value("kNew", Class::kNew, cls_doc.kNew.doc) .value("kReplace", Class::kReplace, cls_doc.kReplace.doc); } // Shape constructors - ordered alphabetically and not in the order given in // shape_specification.h { py::class_<Shape> shape_cls(m, "Shape", doc.Shape.doc); shape_cls // BR .def("__repr__", [](const Shape& self) { return self.to_string(); }); DefClone(&shape_cls); py::class_<Box, Shape>(m, "Box", doc.Box.doc) .def(py::init<double, double, double>(), py::arg("width"), py::arg("depth"), py::arg("height"), doc.Box.ctor.doc_3args) .def(py::init<const Vector3<double>&>(), py::arg("measures"), doc.Box.ctor.doc_1args) .def("width", &Box::width, doc.Box.width.doc) .def("depth", &Box::depth, doc.Box.depth.doc) .def("height", &Box::height, doc.Box.height.doc) .def("size", &Box::size, py_rvp::reference_internal, doc.Box.size.doc) .def(py::pickle( [](const Box& self) { return std::make_tuple(self.width(), self.depth(), self.height()); }, [](std::tuple<double, double, double> dims) { return Box( std::get<0>(dims), std::get<1>(dims), std::get<2>(dims)); })); py::class_<Capsule, Shape>(m, "Capsule", doc.Capsule.doc) .def(py::init<double, double>(), py::arg("radius"), py::arg("length"), doc.Capsule.ctor.doc_2args) .def(py::init<const Vector2<double>&>(), py::arg("measures"), doc.Capsule.ctor.doc_1args) .def("radius", &Capsule::radius, doc.Capsule.radius.doc) .def("length", &Capsule::length, doc.Capsule.length.doc) .def(py::pickle( [](const Capsule& self) { return std::make_pair(self.radius(), self.length()); }, [](std::pair<double, double> dims) { return Capsule(dims.first, dims.second); })); py::class_<Convex, Shape> convex_cls(m, "Convex", doc.Convex.doc); convex_cls .def(py::init<std::string, double>(), py::arg("filename"), py::arg("scale") = 1.0, doc.Convex.ctor.doc) .def("filename", &Convex::filename, doc.Convex.filename.doc) .def("extension", &Convex::extension, doc.Convex.extension.doc) .def("scale", &Convex::scale, doc.Convex.scale.doc) .def("GetConvexHull", &Convex::GetConvexHull, doc.Convex.GetConvexHull.doc) .def(py::pickle( [](const Convex& self) { return std::make_pair(self.filename(), self.scale()); }, [](std::pair<std::string, double> info) { return Convex(info.first, info.second); })); py::class_<Cylinder, Shape>(m, "Cylinder", doc.Cylinder.doc) .def(py::init<double, double>(), py::arg("radius"), py::arg("length"), doc.Cylinder.ctor.doc_2args) .def(py::init<const Vector2<double>&>(), py::arg("measures"), doc.Cylinder.ctor.doc_1args) .def("radius", &Cylinder::radius, doc.Cylinder.radius.doc) .def("length", &Cylinder::length, doc.Cylinder.length.doc) .def(py::pickle( [](const Cylinder& self) { return std::make_pair(self.radius(), self.length()); }, [](std::pair<double, double> dims) { return Cylinder(dims.first, dims.second); })); py::class_<Ellipsoid, Shape>(m, "Ellipsoid", doc.Ellipsoid.doc) .def(py::init<double, double, double>(), py::arg("a"), py::arg("b"), py::arg("c"), doc.Ellipsoid.ctor.doc_3args) .def(py::init<const Vector3<double>&>(), py::arg("measures"), doc.Ellipsoid.ctor.doc_1args) .def("a", &Ellipsoid::a, doc.Ellipsoid.a.doc) .def("b", &Ellipsoid::b, doc.Ellipsoid.b.doc) .def("c", &Ellipsoid::c, doc.Ellipsoid.c.doc) .def(py::pickle( [](const Ellipsoid& self) { return std::make_tuple(self.a(), self.b(), self.c()); }, [](std::tuple<double, double, double> dims) { return Ellipsoid( std::get<0>(dims), std::get<1>(dims), std::get<2>(dims)); })); py::class_<HalfSpace, Shape>(m, "HalfSpace", doc.HalfSpace.doc) .def(py::init<>(), doc.HalfSpace.ctor.doc) .def_static("MakePose", &HalfSpace::MakePose, py::arg("Hz_dir_F"), py::arg("p_FB"), doc.HalfSpace.MakePose.doc); py::class_<Mesh, Shape> mesh_cls(m, "Mesh", doc.Mesh.doc); mesh_cls .def(py::init<std::string, double>(), py::arg("filename"), py::arg("scale") = 1.0, doc.Mesh.ctor.doc) .def("filename", &Mesh::filename, doc.Mesh.filename.doc) .def("extension", &Mesh::extension, doc.Mesh.extension.doc) .def("scale", &Mesh::scale, doc.Mesh.scale.doc) .def("GetConvexHull", &Mesh::GetConvexHull, doc.Mesh.GetConvexHull.doc) .def(py::pickle( [](const Mesh& self) { return std::make_pair(self.filename(), self.scale()); }, [](std::pair<std::string, double> info) { return Mesh(info.first, info.second); })); py::class_<Sphere, Shape>(m, "Sphere", doc.Sphere.doc) .def(py::init<double>(), py::arg("radius"), doc.Sphere.ctor.doc) .def("radius", &Sphere::radius, doc.Sphere.radius.doc) .def(py::pickle([](const Sphere& self) { return self.radius(); }, [](const double radius) { return Sphere(radius); })); py::class_<MeshcatCone, Shape>(m, "MeshcatCone", doc.MeshcatCone.doc) .def(py::init<double, double, double>(), py::arg("height"), py::arg("a") = 1.0, py::arg("b") = 1.0, doc.MeshcatCone.ctor.doc_3args) .def(py::init<const Vector3<double>&>(), py::arg("measures"), doc.MeshcatCone.ctor.doc_1args) .def("height", &MeshcatCone::height, doc.MeshcatCone.height.doc) .def("a", &MeshcatCone::a, doc.MeshcatCone.a.doc) .def("b", &MeshcatCone::b, doc.MeshcatCone.b.doc) .def(py::pickle( [](const MeshcatCone& self) { return std::make_tuple(self.height(), self.a(), self.b()); }, [](std::tuple<double, double, double> params) { return MeshcatCone(std::get<0>(params), std::get<1>(params), std::get<2>(params)); })); } m.def("CalcVolume", &CalcVolume, py::arg("shape"), doc.CalcVolume.doc); m.def("MakePhongIllustrationProperties", &MakePhongIllustrationProperties, py_rvp::reference_internal, py::arg("diffuse"), doc.MakePhongIllustrationProperties.doc); m.def("AddContactMaterial", py::overload_cast<std::optional<double>, std::optional<double>, const std::optional<multibody::CoulombFriction<double>>&, ProximityProperties*>(&AddContactMaterial), py::arg("dissipation"), py::arg("point_stiffness"), py::arg("friction"), py::arg("properties"), doc.AddContactMaterial.doc); // The C++ function does not offer default arguments, but it's convenient to // default the optional arguments to None in Python because a caller can use // named arguments to disambiguate which arguments get which values. m.def( "AddContactMaterial", [](ProximityProperties* properties, std::optional<double> dissipation, std::optional<double> point_stiffness, const std::optional<multibody::CoulombFriction<double>>& friction) { AddContactMaterial(dissipation, point_stiffness, friction, properties); }, py::arg("properties"), py::arg("dissipation") = std::nullopt, py::arg("point_stiffness") = std::nullopt, py::arg("friction") = std::nullopt, doc.AddContactMaterial.doc); } // Test-only code. namespace testing { // For use with `test_geometry_properties_cpp_types`. template <typename T> void DefGetPropertyCpp(py::module m) { auto func = [](const geometry::GeometryProperties& properties, const std::string& group, const std::string& name) { return properties.GetProperty<T>(group, name); }; AddTemplateFunction(m, "GetPropertyCpp", func, GetPyParam<T>()); } // For use with test_proximity_properties. The hydroelastic compliance type is // internal. But we want to test that the compliance type has been successfully // defined in set of properties. If we ever move HydroelasticType out of // internal and bind it, we can eliminate this helper. // // Return true if the properties indicate being compliant, false if rigid, and // throws if the property isn't set at all (or set to undefined). bool PropertiesIndicateCompliantHydro( const geometry::ProximityProperties& props) { using geometry::internal::HydroelasticType; const HydroelasticType hydro_type = props.GetPropertyOrDefault(geometry::internal::kHydroGroup, geometry::internal::kComplianceType, HydroelasticType::kUndefined); if (hydro_type == HydroelasticType::kUndefined) { throw std::runtime_error("No specification of rigid or compliant"); } return hydro_type == HydroelasticType::kSoft; } void def_testing_module(py::module m) { // The get_constant_id() returns a fresh object every time, but always with // the same underlying get_value(). const auto constant_id = geometry::FilterId::get_new_id(); m.def("get_constant_id", [constant_id]() { return constant_id; }); m.def("PropertiesIndicateCompliantHydro", &PropertiesIndicateCompliantHydro); // For use with `test_geometry_properties_cpp_types`. DefGetPropertyCpp<std::string>(m); DefGetPropertyCpp<bool>(m); DefGetPropertyCpp<double>(m); } } // namespace testing } // namespace void DefineGeometryCommon(py::module m) { m.doc() = "Bindings for `drake::geometry`"; DoScalarIndependentDefinitions(m); testing::def_testing_module(m.def_submodule("_testing")); } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/geometry/optimization_pybind.h
#pragma once #include <vector> #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/geometry/optimization/convex_set.h" namespace drake { namespace pydrake { /** Deep-copies the ConvexSet pointers in the given list into the C++-compatible object ConvexSets (which uses copyable_unique_ptr ownership). This is useful to accept Python-natural function arguments (list of pointers) and then call the C++ API that requires a more complicated type. */ inline geometry::optimization::ConvexSets CloneConvexSets( const std::vector<geometry::optimization::ConvexSet*>& sets_in) { geometry::optimization::ConvexSets sets; sets.reserve(sets_in.size()); for (const geometry::optimization::ConvexSet* set : sets_in) { if (set == nullptr) { sets.emplace_back(nullptr); } else { sets.emplace_back(set->Clone()); } } return sets; } } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/meshes_test.py
import pydrake.geometry as mut import pydrake.geometry._testing as mut_testing import copy import unittest import numpy as np from pydrake.common import FindResourceOrThrow class TestGeometryMeshes(unittest.TestCase): def test_polygon_surface_mesh(self): # Default constructor. mut.PolygonSurfaceMesh() # Construct a single triangle. vertices = [ (0, 0, 0), (1, 0, 0), (0, 1, 0), ] vertex_indices = [0, 1, 2] face_data = [len(vertex_indices)] + vertex_indices dut = mut.PolygonSurfaceMesh(face_data=face_data, vertices=vertices) # Sanity check every accessor. dut.element(e=0) dut.vertex(v=0) dut.num_vertices() dut.num_elements() dut.num_faces() dut.area(f=0) dut.total_area() dut.face_normal(f=0) dut.element_centroid(e=0) dut.centroid() dut.CalcBoundingBox() dut.Equal(mesh=dut) dut.face_data() copy.copy(dut) # Now check the SurfacePolygon bindings. polygon = dut.element(e=0) self.assertEqual(polygon.num_vertices(), 3) self.assertEqual(polygon.vertex(i=1), 1) def test_triangle_surface_mesh(self): # Create a mesh out of two triangles forming a quad. # # 0______1 # |b /| Two triangles: a and b. # | / | Four vertices: 0, 1, 2, and 3. # | /a | # |/___| # 2 3 t_a = mut.SurfaceTriangle(v0=3, v1=1, v2=2) t_b = mut.SurfaceTriangle(v0=2, v1=1, v2=0) self.assertEqual(t_a.vertex(0), 3) self.assertEqual(t_b.vertex(1), 1) v0 = (-1, 1, 0) v1 = (1, 1, 0) v2 = (-1, -1, 0) v3 = (1, -1, 0) self.assertListEqual(list(v0), [-1, 1, 0]) dut = mut.TriangleSurfaceMesh(triangles=(t_a, t_b), vertices=(v0, v1, v2, v3)) # Sanity check every accessor. self.assertIsInstance(dut.element(e=0), mut.SurfaceTriangle) self.assertIsInstance(dut.vertex(v=0), np.ndarray) self.assertIsInstance(dut.num_vertices(), int) self.assertIsInstance(dut.num_elements(), int) self.assertIsInstance(dut.num_triangles(), int) self.assertIsInstance(dut.area(t=0), float) self.assertIsInstance(dut.total_area(), float) self.assertIsInstance(dut.face_normal(t=0), np.ndarray) self.assertIsInstance(dut.element_centroid(t=0), np.ndarray) self.assertIsInstance(dut.centroid(), np.ndarray) # Sanity check some calculations self.assertIsInstance(dut.CalcBoundingBox(), tuple) self.assertTrue(dut.Equal(mesh=dut)) self.assertIsInstance( dut.CalcCartesianFromBarycentric(element_index=1, b_Q=[1/3.0, 1/3.0, 1/3.0]), np.ndarray) self.assertIsInstance( dut.CalcBarycentric(p_MQ=[-1/3.0, 1/3.0, 0], t=1), np.ndarray) self.assertEqual(len(dut.triangles()), 2) self.assertEqual(len(dut.vertices()), 4) self.assertListEqual(list(dut.centroid()), [0, 0, 0]) self.assertListEqual(list(dut.element_centroid(t=1)), [-1/3.0, 1/3.0, 0]) # Now check the SurfaceTriangle bindings. triangle0 = dut.element(e=0) self.assertEqual(triangle0.num_vertices(), 3) self.assertEqual(triangle0.vertex(i=0), 3) def test_volume_mesh(self): # Create a mesh out of two tetrahedra with a single, shared face # (1, 2, 3). # # +y # | # o v2 # | # v4 | v1 v0 # ───o────o─────o── +x # / # / # o v3 # / # +z t_left = mut.VolumeElement(v0=2, v1=1, v2=3, v3=4) t_right = mut.VolumeElement(v0=3, v1=1, v2=2, v3=0) self.assertEqual(t_left.vertex(0), 2) self.assertEqual(t_right.vertex(1), 1) v0 = (1, 0, 0) v1 = (0, 0, 0) v2 = (0, 1, 0) v3 = (0, 0, 1) v4 = (-1, 0, 0) self.assertListEqual(list(v0), [1, 0, 0]) dut = mut.VolumeMesh(elements=(t_left, t_right), vertices=(v0, v1, v2, v3, v4)) # Sanity check every accessor. self.assertIsInstance(dut.element(e=0), mut.VolumeElement) self.assertIsInstance(dut.vertex(v=0), np.ndarray) self.assertIsInstance(dut.num_elements(), int) self.assertIsInstance(dut.num_vertices(), int) # Sanity check some calculations self.assertAlmostEqual(dut.CalcTetrahedronVolume(e=1), 1/6.0, delta=1e-15) self.assertAlmostEqual(dut.CalcVolume(), 1/3.0, delta=1e-15) self.assertIsInstance( dut.CalcBarycentric(p_MQ=[-0.25, 0.25, 0.25], e=0), np.ndarray) self.assertTrue(dut.Equal(mesh=dut)) self.assertEqual(len(dut.tetrahedra()), 2) self.assertIsInstance(dut.tetrahedra()[0], mut.VolumeElement) self.assertEqual(len(dut.vertices()), 5) # Now check the VolumeElement bindings. tetrahedron0 = dut.element(e=0) self.assertEqual(tetrahedron0.vertex(i=0), 2) def test_convert_volume_to_surface_mesh(self): # Use the volume mesh from `test_volume_mesh()`. t_left = mut.VolumeElement(v0=1, v1=2, v2=3, v3=4) t_right = mut.VolumeElement(v0=1, v1=3, v2=2, v3=0) v0 = (1, 0, 0) v1 = (0, 0, 0) v2 = (0, 1, 0) v3 = (0, 0, -1) v4 = (-1, 0, 0) volume_mesh = mut.VolumeMesh(elements=(t_left, t_right), vertices=(v0, v1, v2, v3, v4)) surface_mesh = mut.ConvertVolumeToSurfaceMesh(volume_mesh) self.assertIsInstance(surface_mesh, mut.TriangleSurfaceMesh) def test_read_obj_to_surface_mesh(self): mesh_path = FindResourceOrThrow("drake/geometry/test/quad_cube.obj") mesh = mut.ReadObjToTriangleSurfaceMesh(mesh_path) vertices = mesh.vertices() # This test relies on the specific content of the file quad_cube.obj. # These coordinates came from the first section of quad_cube.obj. expected_vertices = [ [1.000000, -1.000000, -1.000000], [1.000000, -1.000000, 1.000000], [-1.000000, -1.000000, 1.000000], [-1.000000, -1.000000, -1.000000], [1.000000, 1.000000, -1.000000], [1.000000, 1.000000, 1.000000], [-1.000000, 1.000000, 1.000000], [-1.000000, 1.000000, -1.000000], ] for i, expected in enumerate(expected_vertices): self.assertListEqual(list(vertices[i]), expected)
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/visualizers_test.py
import pydrake.geometry as mut import copy import unittest import urllib.request import numpy as np import umsgpack from drake import lcmt_viewer_load_robot, lcmt_viewer_draw from pydrake.autodiffutils import AutoDiffXd from pydrake.common.test_utilities import numpy_compare from pydrake.lcm import DrakeLcm, Subscriber from pydrake.math import RigidTransform from pydrake.perception import PointCloud from pydrake.systems.analysis import Simulator_ from pydrake.systems.framework import DiagramBuilder_, InputPort_ class TestGeometryVisualizers(unittest.TestCase): @numpy_compare.check_nonsymbolic_types def test_drake_visualizer(self, T): # Test visualization API. SceneGraph = mut.SceneGraph_[T] DiagramBuilder = DiagramBuilder_[T] Simulator = Simulator_[T] lcm = DrakeLcm() role = mut.Role.kIllustration params = mut.DrakeVisualizerParams( publish_period=0.1, role=mut.Role.kIllustration, default_color=mut.Rgba(0.1, 0.2, 0.3, 0.4), show_hydroelastic=False, use_role_channel_suffix=False) self.assertIn("publish_period", repr(params)) copy.copy(params) # Add some subscribers to detect message broadcast. load_channel = "DRAKE_VIEWER_LOAD_ROBOT" draw_channel = "DRAKE_VIEWER_DRAW" load_subscriber = Subscriber( lcm, load_channel, lcmt_viewer_load_robot) draw_subscriber = Subscriber( lcm, draw_channel, lcmt_viewer_draw) # There are three ways to configure DrakeVisualizer. def by_hand(builder, scene_graph, params): visualizer = builder.AddSystem( mut.DrakeVisualizer_[T](lcm=lcm, params=params)) builder.Connect(scene_graph.get_query_output_port(), visualizer.query_object_input_port()) def auto_connect_to_system(builder, scene_graph, params): mut.DrakeVisualizer_[T].AddToBuilder(builder=builder, scene_graph=scene_graph, lcm=lcm, params=params) def auto_connect_to_port(builder, scene_graph, params): mut.DrakeVisualizer_[T].AddToBuilder( builder=builder, query_object_port=scene_graph.get_query_output_port(), lcm=lcm, params=params) for func in [by_hand, auto_connect_to_system, auto_connect_to_port]: # Build the diagram. builder = DiagramBuilder() scene_graph = builder.AddSystem(SceneGraph()) func(builder, scene_graph, params) # Simulate to t = 0 to send initial load and draw messages. diagram = builder.Build() Simulator(diagram).AdvanceTo(0) lcm.HandleSubscriptions(0) self.assertEqual(load_subscriber.count, 1) self.assertEqual(draw_subscriber.count, 1) load_subscriber.clear() draw_subscriber.clear() # Ad hoc broadcasting. scene_graph = SceneGraph() mut.DrakeVisualizer_[T].DispatchLoadMessage( scene_graph, lcm, params) lcm.HandleSubscriptions(0) self.assertEqual(load_subscriber.count, 1) self.assertEqual(draw_subscriber.count, 0) load_subscriber.clear() draw_subscriber.clear() def test_meshcat_params(self): prop_a = mut.MeshcatParams.PropertyTuple( path="a", property="p1", value=[1.0, 2.0], ) prop_b = mut.MeshcatParams.PropertyTuple( path="b", property="p2", value="hello", ) prop_c = mut.MeshcatParams.PropertyTuple( path="c", property="p3", value=True, ) prop_d = mut.MeshcatParams.PropertyTuple( path="d", property="p4", value=22.2, ) params = mut.MeshcatParams( host="*", port=7777, web_url_pattern="http://host:{port}", initial_properties=[prop_a, prop_b, prop_c, prop_d], show_stats_plot=False) self.assertIn("port=7777", repr(params)) self.assertIn("path='a'", repr(prop_a)) copy.copy(prop_a) copy.copy(params) def test_meshcat(self): port = 7051 params = mut.MeshcatParams(port=port) meshcat = mut.Meshcat(params=params) self.assertEqual(meshcat.port(), port) self.assertIn("host", repr(params)) copy.copy(params) with self.assertRaises(RuntimeError): meshcat2 = mut.Meshcat(port=port) self.assertIn("http", meshcat.web_url()) self.assertIn("ws", meshcat.ws_url()) meshcat.SetEnvironmentMap(image_path="") meshcat.SetObject(path="/test/box", shape=mut.Box(1, 1, 1), rgba=mut.Rgba(.5, .5, .5)) meshcat.SetTransform(path="/test/box", X_ParentPath=RigidTransform(), time_in_recording=0.2) meshcat.SetTransform(path="/test/box", matrix=np.eye(4)) self.assertTrue(meshcat.HasPath("/test/box")) cloud = PointCloud(4) cloud.mutable_xyzs()[:] = np.zeros((3, 4)) meshcat.SetObject(path="/test/cloud", cloud=cloud, point_size=0.01, rgba=mut.Rgba(.5, .5, .5)) mesh = mut.TriangleSurfaceMesh( triangles=[mut.SurfaceTriangle( 0, 1, 2), mut.SurfaceTriangle(3, 0, 2)], vertices=[[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]]) meshcat.SetObject(path="/test/triangle_surface_mesh", mesh=mesh, rgba=mut.Rgba(0.3, 0.3, 0.3), wireframe=True, wireframe_line_width=2.0, side=meshcat.SideOfFaceToRender.kFrontSide) meshcat.SetLine(path="/test/line", vertices=np.eye(3), line_width=2.0, rgba=mut.Rgba(.3, .3, .3)) meshcat.SetLineSegments(path="/test/line_segments", start=np.eye(3), end=2*np.eye(3), line_width=2.0, rgba=mut.Rgba(.3, .3, .3)) meshcat.SetTriangleMesh( path="/test/triangle_mesh", vertices=np.array([[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]]).T, faces=np.array([[0, 1, 2], [3, 0, 2]]).T, rgba=mut.Rgba(0.3, 0.3, 0.3), wireframe=True, wireframe_line_width=2.0, side=meshcat.SideOfFaceToRender.kBackSide) meshcat.SetTriangleColorMesh( path="/test/triangle_mesh", vertices=np.array([[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]]).T, faces=np.array([[0, 1, 2], [3, 0, 2]]).T, colors=np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0]]).T, wireframe=False, wireframe_line_width=2.0, side=meshcat.SideOfFaceToRender.kDoubleSide) # Plot the six-hump camel xs = np.linspace(-2.2, 2.2, 51) ys = np.linspace(-1.2, 1.2, 51) [X, Y] = np.meshgrid(xs, ys) P = 4 * X**2 + X * Y - 4 * Y**2 - 2.1 * X**4 + 4 * Y**4 + X**6 / 3 meshcat.PlotSurface(path="six_hump_camel", X=X, Y=Y, Z=P, rgba=mut.Rgba(0.3, 0.3, 0.3), wireframe=True, wireframe_line_width=2.0) meshcat.SetProperty(path="/Background", property="visible", value=True, time_in_recording=0.2) meshcat.SetProperty(path="/Lights/DirectionalLight/<object>", property="intensity", value=1.0, time_in_recording=0.2) meshcat.SetProperty(path="/Background", property="top_color", value=[0, 0, 0], time_in_recording=0.2) meshcat.Set2dRenderMode( X_WC=RigidTransform(), xmin=-1, xmax=1, ymin=-1, ymax=1) meshcat.ResetRenderMode() meshcat.SetCameraTarget(target_in_world=[1, 2, 3]) meshcat.SetCameraPose(camera_in_world=[3, 4, 5], target_in_world=[1, 1, 1]) meshcat.AddButton(name="alice", keycode="KeyB") self.assertEqual(meshcat.GetButtonClicks(name="alice"), 0) meshcat._InjectWebsocketMessage(message=umsgpack.packb({ "type": "button", "name": "alice", })) self.assertEqual(meshcat.GetButtonClicks(name="alice"), 1) meshcat.DeleteButton(name="alice") meshcat.AddSlider(name="slider", min=0, max=1, step=0.01, value=0.5, decrement_keycode="ArrowLeft", increment_keycode="ArrowRight") self.assertEqual(meshcat.GetSliderNames(), ["slider"]) meshcat.SetSliderValue(name="slider", value=0.7) self.assertAlmostEqual(meshcat.GetSliderValue( name="slider"), 0.7, delta=1e-14) meshcat.DeleteSlider(name="slider") meshcat.DeleteAddedControls() self.assertIn("data:application/octet-binary;base64", meshcat.StaticHtml()) gamepad = meshcat.GetGamepad() # Check default values (assuming no gamepad messages have arrived): self.assertIsNone(gamepad.index) self.assertEqual(len(gamepad.button_values), 0) self.assertEqual(len(gamepad.axes), 0) meshcat.SetRealtimeRate(1.0) meshcat.GetRealtimeRate() meshcat.Flush() meshcat.StartRecording(frames_per_second=64.0, set_visualizations_while_recording=False) ani = meshcat.get_mutable_recording() self.assertEqual(ani.frames_per_second(), 64.0) meshcat.StopRecording() meshcat.PublishRecording() meshcat.DeleteRecording() # PerspectiveCamera camera = mut.Meshcat.PerspectiveCamera(fov=80, aspect=1.2, near=0.2, far=200, zoom=1.3) self.assertEqual(camera.fov, 80) self.assertEqual(camera.aspect, 1.2) self.assertEqual(camera.near, 0.2) self.assertEqual(camera.far, 200) self.assertEqual(camera.zoom, 1.3) self.assertIn("fov", repr(camera)) copy.copy(camera) meshcat.SetCamera(camera=camera, path="mypath") # OrthographicCamera camera = mut.Meshcat.OrthographicCamera(left=0.1, right=1.3, top=0.3, bottom=1.4, near=0.2, far=200, zoom=1.3) self.assertEqual(camera.left, 0.1) self.assertEqual(camera.right, 1.3) self.assertEqual(camera.top, 0.3) self.assertEqual(camera.bottom, 1.4) self.assertEqual(camera.near, 0.2) self.assertEqual(camera.far, 200) self.assertEqual(camera.zoom, 1.3) self.assertIn("left", repr(camera)) copy.copy(camera) meshcat.SetCamera(camera=camera, path="mypath") packed = meshcat._GetPackedObject(path="/test/box") self.assertGreater(len(packed), 0) packed = meshcat._GetPackedTransform(path="/test/box") self.assertGreater(len(packed), 0) packed = meshcat._GetPackedProperty(path="/Background", property="visible") self.assertGreater(len(packed), 0) # Camera tracking. # The pose is None because no meshcat session has broadcast its pose. self.assertIsNone(meshcat.GetTrackedCameraPose()) def test_meshcat_404(self): meshcat = mut.Meshcat() good_url = meshcat.web_url() with urllib.request.urlopen(good_url) as response: self.assertTrue(response.read(1)) bad_url = f"{good_url}/no_such_file" with self.assertRaisesRegex(Exception, "HTTP.*404"): with urllib.request.urlopen(bad_url) as response: response.read(1) def test_meshcat_animation(self): animation = mut.MeshcatAnimation(frames_per_second=64) self.assertEqual(animation.frames_per_second(), 64) self.assertEqual(animation.frame(1.0), 64) animation.set_autoplay(play=False) self.assertEqual(animation.autoplay(), False) animation.set_loop_mode(mode=mut.MeshcatAnimation.LoopMode.kLoopOnce) animation.set_loop_mode(mode=mut.MeshcatAnimation.LoopMode.kLoopRepeat) animation.set_loop_mode( mode=mut.MeshcatAnimation.LoopMode.kLoopPingPong) self.assertEqual(animation.loop_mode(), mut.MeshcatAnimation.LoopMode.kLoopPingPong) animation.set_repetitions(repetitions=20) self.assertEqual(animation.repetitions(), 20) animation.set_clamp_when_finished(clamp=False) self.assertEqual(animation.clamp_when_finished(), False) animation.SetTransform(frame=0, path="test", X_ParentPath=RigidTransform()) animation.SetProperty(frame=0, path="test", property="bool", value=True) animation.SetProperty(frame=0, path="test", property="double", value=32.0) animation.SetProperty(frame=0, path="test", property="vector_double", value=[1., 2., 3.]) meshcat = mut.Meshcat() meshcat.SetAnimation(animation) @numpy_compare.check_nonsymbolic_types def test_meshcat_visualizer(self, T): meshcat = mut.Meshcat() params = mut.MeshcatVisualizerParams() params.publish_period = 0.123 params.role = mut.Role.kIllustration params.default_color = mut.Rgba(0.5, 0.5, 0.5) params.prefix = "py_visualizer" params.delete_on_initialization_event = False params.visible_by_default = True self.assertIn("publish_period", repr(params)) copy.copy(params) vis = mut.MeshcatVisualizer_[T](meshcat=meshcat, params=params) vis.ResetRealtimeRateCalculator() vis.Delete() self.assertIsInstance(vis.query_object_input_port(), InputPort_[T]) animation = vis.StartRecording(set_transforms_while_recording=True) self.assertIsInstance(animation, mut.MeshcatAnimation) self.assertEqual(animation, vis.get_mutable_recording()) vis.StopRecording() vis.PublishRecording() vis.DeleteRecording() builder = DiagramBuilder_[T]() scene_graph = builder.AddSystem(mut.SceneGraph_[T]()) mut.MeshcatVisualizer_[T].AddToBuilder(builder=builder, scene_graph=scene_graph, meshcat=meshcat, params=params) mut.MeshcatVisualizer_[T].AddToBuilder( builder=builder, query_object_port=scene_graph.get_query_output_port(), meshcat=meshcat, params=params) def test_meshcat_visualizer_scalar_conversion(self): meshcat = mut.Meshcat() vis = mut.MeshcatVisualizer(meshcat) vis_autodiff = vis.ToAutoDiffXd() self.assertIsInstance(vis_autodiff, mut.MeshcatVisualizer_[AutoDiffXd]) @numpy_compare.check_nonsymbolic_types def test_meshcat_point_cloud_visualizer(self, T): meshcat = mut.Meshcat() visualizer = mut.MeshcatPointCloudVisualizer_[T]( meshcat=meshcat, path="cloud", publish_period=1/12.0) visualizer.set_point_size(0.1) visualizer.set_default_rgba(mut.Rgba(0, 0, 1, 1)) context = visualizer.CreateDefaultContext() cloud = PointCloud(4) cloud.mutable_xyzs()[:] = np.zeros((3, 4)) visualizer.cloud_input_port().FixValue(context, cloud) self.assertIsInstance(visualizer.pose_input_port(), InputPort_[T]) visualizer.ForcedPublish(context) visualizer.Delete() if T == float: ad_visualizer = visualizer.ToAutoDiffXd() self.assertIsInstance( ad_visualizer, mut.MeshcatPointCloudVisualizer_[AutoDiffXd]) def test_start_meshcat(self): # StartMeshcat only performs interesting work on cloud notebook hosts. # Here we simply ensure that it runs and is available. meshcat = mut.StartMeshcat() self.assertIsInstance(meshcat, mut.Meshcat) with urllib.request.urlopen(meshcat.web_url()) as response: content_type = response.getheader("Content-Type") some_data = response.read(4096) # This also serves as a regresion test of the C++ code, where parsing # the Content-Type is difficult within its unit test infrastructure. self.assertIn("text/html", content_type) self.assertIn("DOCTYPE html", some_data.decode("utf-8"))
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/render_test.py
import pydrake.geometry as mut import copy import logging import unittest import numpy as np from pydrake.common import FindResourceOrThrow from pydrake.common.test_utilities import numpy_compare from pydrake.common.value import Value from pydrake.math import RigidTransform from pydrake.systems.framework import ( DiagramBuilder, ) from pydrake.systems.sensors import ( CameraInfo, ImageRgba8U, ImageDepth16U, ImageDepth32F, ImageLabel16I, RgbdSensor, ) class TestGeometryRender(unittest.TestCase): def test_light_param(self): # A default constructor exists. mut.LightParameter() # The kwarg constructor also works. light = mut.LightParameter(type='spot', color=mut.Rgba(0.1, 0.2, 0.3), attenuation_values=(1, 2, 3), position=(-1, -2, -3), frame='camera', intensity=0.5, direction=(0, 1, 0), cone_angle=85) # Attributes are bound explicitly, so we'll test them explicitly. self.assertEqual(light.type, 'spot') self.assertEqual(light.color, mut.Rgba(0.1, 0.2, 0.3)) self.assertTupleEqual(tuple(light.attenuation_values), (1, 2, 3)) self.assertTupleEqual(tuple(light.position), (-1, -2, -3)) self.assertEqual(light.frame, 'camera') self.assertEqual(light.intensity, 0.5) self.assertTupleEqual(tuple(light.direction), (0, 1, 0)) self.assertEqual(light.cone_angle, 85) self.assertIn("spot", repr(light)) copy.copy(light) def test_equirectangular_map(self): # A default constructor exists. mut.EquirectangularMap() # The kwarg constructor also works. map = mut.EquirectangularMap(path="test.hdr") self.assertEqual(map.path, "test.hdr") self.assertIn("path", repr(map)) copy.copy(map) def test_environment_map(self): # A default constructor exists. mut.EnvironmentMap() # The kwarg constructor also works. params = mut.EnvironmentMap(skybox=False) self.assertFalse(params.skybox) self.assertIsInstance(params.texture, mut.NullTexture) params = mut.EnvironmentMap( texture=mut.EquirectangularMap(path="test.hdr")) self.assertIn("EquirectangularMap", repr(params)) copy.copy(params) def test_gltf_extension(self): # A default constructor exists. mut.GltfExtension() # The kwarg constructor also works. params = mut.GltfExtension(warn_unimplemented=False) self.assertFalse(params.warn_unimplemented) # The repr and copy both work. self.assertIn("warn_unimplemented=", repr(params)) copy.copy(params) def test_render_engine_vtk_params(self): # Confirm default construction of params. params = mut.RenderEngineVtkParams() self.assertEqual(params.default_diffuse, None) diffuse = np.array((1.0, 0.0, 0.0, 0.0)) params = mut.RenderEngineVtkParams( default_diffuse=diffuse, environment_map=mut.EnvironmentMap( skybox=False, texture=mut.EquirectangularMap(path="local.hdr"))) self.assertTrue((params.default_diffuse == diffuse).all()) self.assertIn("default_diffuse", repr(params)) copy.copy(params) def test_render_vtk_gltf_warnings(self): """The fully_textured_pyramid.gltf offers the basisu extension but our RenderEngineVtk doesn't implement that. The "not implemented" warning is suppressed by default, but if we reset the suppressions it should show up. """ for should_warn in [False, True]: with self.subTest(should_warn=should_warn): self._do_test_render_vtk_gltf_warnings( should_warn=should_warn) def _do_test_render_vtk_gltf_warnings(self, *, should_warn): # Create the render engine. expected_level = logging.WARNING if should_warn else logging.DEBUG params = mut.RenderEngineVtkParams() if should_warn: # All unimplemented extensions will warn. params.gltf_extensions = dict() renderer = mut.MakeRenderEngineVtk(params=params) # Prepare the mesh to be loaded. material = mut.PerceptionProperties() material.AddProperty("label", "id", mut.RenderLabel(1)) geom_id = mut.GeometryId.get_new_id() filename = FindResourceOrThrow( "drake/geometry/render/test/meshes/fully_textured_pyramid.gltf") # Load the mesh, which should emit exactly one log message. with self.assertLogs("drake", logging.DEBUG) as cm: renderer.RegisterVisual( id=geom_id, shape=mut.Mesh(filename), properties=material, X_WG=RigidTransform.Identity(), needs_updates=False) self.assertEqual(len(cm.records), 1, cm) record = cm.records[0] # The message mentioned basisu using the proper severity level. self.assertIn("KHR_texture_basisu", record.msg) self.assertEqual(record.levelno, expected_level) def test_render_engine_gl_params(self): # A default constructor exists. mut.RenderEngineGlParams() # The kwarg constructor also works. diffuse = mut.Rgba(1.0, 0.0, 0.0, 0.0) params = mut.RenderEngineGlParams( default_clear_color=diffuse, default_diffuse=diffuse, ) self.assertEqual(params.default_clear_color, diffuse) self.assertEqual(params.default_diffuse, diffuse) self.assertIn("default_clear_color", repr(params)) copy.copy(params) def test_render_engine_gltf_client_params(self): # A default constructor exists. mut.RenderEngineGltfClientParams() # The kwarg constructor also works. base_url = "http://127.0.0.1:8888" render_endpoint = "render" params = mut.RenderEngineGltfClientParams( base_url=base_url, render_endpoint=render_endpoint, ) self.assertEqual(params.render_endpoint, render_endpoint) self.assertEqual(params.base_url, base_url) self.assertIn("render_endpoint", repr(params)) copy.copy(params) def test_render_label(self): RenderLabel = mut.RenderLabel value = 10 obj = RenderLabel(value) self.assertIs(value, int(obj)) self.assertEqual(value, obj) self.assertEqual(obj, value) self.assertFalse(obj.is_reserved()) self.assertTrue(RenderLabel.kEmpty.is_reserved()) self.assertTrue(RenderLabel.kDoNotRender.is_reserved()) self.assertTrue(RenderLabel.kDontCare.is_reserved()) self.assertTrue(RenderLabel.kUnspecified.is_reserved()) self.assertEqual(RenderLabel(value), RenderLabel(value)) self.assertNotEqual(RenderLabel(value), RenderLabel.kEmpty) # Confirm value instantiation. Value[mut.RenderLabel] def test_render_label_repr(self): RenderLabel = mut.RenderLabel # Special labels should use a non-numeric spelling. special_labels = [ RenderLabel.kEmpty, RenderLabel.kDoNotRender, RenderLabel.kDontCare, RenderLabel.kUnspecified, ] for label in special_labels: self.assertIn("RenderLabel.k", repr(label)) # Any label should round-trip via 'eval'. all_labels = special_labels + [RenderLabel(10)] for label in all_labels: roundtrip = eval(repr(label), dict(RenderLabel=RenderLabel)) self.assertEqual(label, roundtrip) def test_render_engine_api(self): class DummyRenderEngine(mut.RenderEngine): """Mirror of C++ DummyRenderEngine.""" # See comment below about `rgbd_sensor_test.cc`. latest_instance = None def __init__(self, render_label=None): mut.RenderEngine.__init__(self) # N.B. We do not hide these because this is a test class. # Normally, you would want to hide this. self.force_accept = False self.registered_geometries = set() self.updated_ids = {} self.include_group_name = "in_test" self.X_WC = RigidTransform() self.color_count = 0 self.depth_count = 0 self.label_count = 0 self.color_camera = None self.depth_camera = None self.label_camera = None def UpdateViewpoint(self, X_WC): DummyRenderEngine.latest_instance = self self.X_WC = X_WC def ImplementGeometry(self, shape, user_data): DummyRenderEngine.latest_instance = self def DoRegisterVisual(self, id, shape, properties, X_WG): DummyRenderEngine.latest_instance = self mut.GetRenderLabelOrThrow(properties) if self.force_accept or properties.HasGroup( self.include_group_name ): self.registered_geometries.add(id) return True return False def DoUpdateVisualPose(self, id, X_WG): DummyRenderEngine.latest_instance = self self.updated_ids[id] = X_WG def DoRemoveGeometry(self, id): DummyRenderEngine.latest_instance = self self.registered_geometries.remove(id) def DoClone(self): DummyRenderEngine.latest_instance = self new = DummyRenderEngine() new.force_accept = copy.copy(self.force_accept) new.registered_geometries = copy.copy( self.registered_geometries) new.updated_ids = copy.copy(self.updated_ids) new.include_group_name = copy.copy(self.include_group_name) new.X_WC = copy.copy(self.X_WC) new.color_count = copy.copy(self.color_count) new.depth_count = copy.copy(self.depth_count) new.label_count = copy.copy(self.label_count) new.color_camera = copy.copy(self.color_camera) new.depth_camera = copy.copy(self.depth_camera) new.label_camera = copy.copy(self.label_camera) return new def DoRenderColorImage(self, camera, color_image_out): DummyRenderEngine.latest_instance = self self.color_count += 1 self.color_camera = camera def DoRenderDepthImage(self, camera, depth_image_out): DummyRenderEngine.latest_instance = self self.depth_count += 1 self.depth_camera = camera def DoRenderLabelImage(self, camera, label_image_out): DummyRenderEngine.latest_instance = self self.label_count += 1 self.label_camera = camera engine = DummyRenderEngine() self.assertIsInstance(engine, mut.RenderEngine) self.assertIsInstance(engine.Clone(), DummyRenderEngine) # Test implementation of C++ interface by using RgbdSensor. renderer_name = "renderer" builder = DiagramBuilder() scene_graph = builder.AddSystem(mut.SceneGraph()) # N.B. This passes ownership. scene_graph.AddRenderer(renderer_name, engine) sensor = builder.AddSystem(RgbdSensor( parent_id=scene_graph.world_frame_id(), X_PB=RigidTransform(), depth_camera=mut.DepthRenderCamera( mut.RenderCameraCore( renderer_name, CameraInfo(640, 480, np.pi/4), mut.ClippingRange(0.1, 5.0), RigidTransform()), mut.DepthRange(0.1, 5.0)))) builder.Connect( scene_graph.get_query_output_port(), sensor.query_object_input_port(), ) diagram = builder.Build() diagram_context = diagram.CreateDefaultContext() sensor_context = sensor.GetMyContextFromRoot(diagram_context) image = sensor.color_image_output_port().Eval(sensor_context) # N.B. Because there's context cloning going on under the hood, we # won't be interacting with our originally registered instance. # See `rgbd_sensor_test.cc` as well. current_engine = DummyRenderEngine.latest_instance self.assertIsNot(current_engine, engine) self.assertIsInstance(image, ImageRgba8U) self.assertEqual(current_engine.color_count, 1) image = sensor.depth_image_32F_output_port().Eval(sensor_context) self.assertIsInstance(image, ImageDepth32F) self.assertEqual(current_engine.depth_count, 1) image = sensor.depth_image_16U_output_port().Eval(sensor_context) self.assertIsInstance(image, ImageDepth16U) self.assertEqual(current_engine.depth_count, 2) image = sensor.label_image_output_port().Eval(sensor_context) self.assertIsInstance(image, ImageLabel16I) self.assertEqual(current_engine.label_count, 1) # TODO(eric, duy): Test more properties. def test_render_engine_gltf_client_api(self): scene_graph = mut.SceneGraph() params = mut.RenderEngineGltfClientParams() scene_graph.AddRenderer("gltf_renderer", mut.MakeRenderEngineGltfClient(params=params)) self.assertTrue(scene_graph.HasRenderer("gltf_renderer")) self.assertEqual(scene_graph.RendererCount(), 1)
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/common_test.py
import pydrake.geometry as mut import pydrake.geometry._testing as mut_testing import copy import unittest import numpy as np from pydrake.common.test_utilities import numpy_compare from pydrake.common.test_utilities.pickle_compare import assert_pickle from pydrake.common.value import AbstractValue, Value from pydrake.common.yaml import yaml_load_typed from pydrake.math import RigidTransform from pydrake.multibody.plant import CoulombFriction PROPERTY_CLS_LIST = [ mut.ProximityProperties, mut.IllustrationProperties, mut.PerceptionProperties, ] class TestGeometryCore(unittest.TestCase): def test_collision_filtering(self): sg = mut.SceneGraph() sg_context = sg.CreateDefaultContext() geometries = mut.GeometrySet() # Confirm that both invocations provide access. for dut in (sg.collision_filter_manager(), sg.collision_filter_manager(sg_context)): self.assertIsInstance(dut, mut.CollisionFilterManager) # We'll test against the Context-variant, assuming that if the API # works for an instance from one source, it'll work for both. dut = sg.collision_filter_manager(sg_context) dut.Apply( declaration=mut.CollisionFilterDeclaration().ExcludeBetween( geometries, geometries)) dut.Apply( declaration=mut.CollisionFilterDeclaration().ExcludeWithin( geometries)) dut.Apply( declaration=mut.CollisionFilterDeclaration().AllowBetween( set_A=geometries, set_B=geometries)) dut.Apply( declaration=mut.CollisionFilterDeclaration().AllowWithin( geometry_set=geometries)) id = dut.ApplyTransient( declaration=mut.CollisionFilterDeclaration().ExcludeWithin( geometries)) self.assertTrue(dut.has_transient_history()) self.assertTrue(dut.IsActive(filter_id=id)) self.assertTrue(dut.RemoveDeclaration(filter_id=id)) def test_geometry_frame_api(self): frame = mut.GeometryFrame(frame_name="test_frame") self.assertIsInstance(frame.id(), mut.FrameId) self.assertEqual(frame.name(), "test_frame") frame = mut.GeometryFrame(frame_name="test_frame", frame_group_id=1) self.assertEqual(frame.frame_group(), 1) def test_geometry_instance_api(self): geometry = mut.GeometryInstance(X_PG=RigidTransform(), shape=mut.Sphere(1.), name="sphere") self.assertIsInstance(geometry.id(), mut.GeometryId) geometry.set_pose(RigidTransform([1, 0, 0])) self.assertIsInstance(geometry.pose(), RigidTransform) self.assertIsInstance(geometry.shape(), mut.Shape) self.assertEqual(geometry.name(), "sphere") geometry.set_name("funky") self.assertEqual(geometry.name(), "funky") geometry.set_proximity_properties(mut.ProximityProperties()) geometry.set_illustration_properties(mut.IllustrationProperties()) geometry.set_perception_properties(mut.PerceptionProperties()) self.assertIsInstance(geometry.mutable_proximity_properties(), mut.ProximityProperties) self.assertIsInstance(geometry.proximity_properties(), mut.ProximityProperties) self.assertIsInstance(geometry.mutable_illustration_properties(), mut.IllustrationProperties) self.assertIsInstance(geometry.illustration_properties(), mut.IllustrationProperties) self.assertIsInstance(geometry.mutable_perception_properties(), mut.PerceptionProperties) self.assertIsInstance(geometry.perception_properties(), mut.PerceptionProperties) def test_geometry_properties_api(self): # Test perception/ illustration properties (specifically Rgba). test_vector = [0., 0., 1., 1.] test_color = mut.Rgba(0., 0., 1., 1.) phong_props = mut.MakePhongIllustrationProperties(test_vector) self.assertIsInstance(phong_props, mut.IllustrationProperties) actual_color = phong_props.GetProperty("phong", "diffuse") self.assertEqual(actual_color, test_color) # Ensure that we can create it manually. phong_props = mut.IllustrationProperties() phong_props.AddProperty("phong", "diffuse", test_color) actual_color = phong_props.GetProperty("phong", "diffuse") self.assertEqual(actual_color, test_color) # Test proximity properties. prop = mut.ProximityProperties() self.assertEqual(str(prop), "[__default__]") default_group = prop.default_group_name() self.assertTrue(prop.HasGroup(group_name=default_group)) self.assertEqual(prop.num_groups(), 1) self.assertTrue(default_group in prop.GetGroupNames()) prop.AddProperty(group_name=default_group, name="test", value=3) self.assertTrue(prop.HasProperty(group_name=default_group, name="test")) self.assertEqual( prop.GetProperty(group_name=default_group, name="test"), 3) self.assertEqual( prop.GetPropertyOrDefault( group_name=default_group, name="empty", default_value=5), 5) group_values = prop.GetPropertiesInGroup(group_name=default_group) for name, value in group_values.items(): self.assertIsInstance(name, str) self.assertIsInstance(value, AbstractValue) # Remove the property. self.assertTrue(prop.RemoveProperty(group_name=default_group, name="test")) self.assertFalse(prop.HasProperty(group_name=default_group, name="test")) # Update a property. prop.AddProperty(group_name=default_group, name="to_update", value=17) self.assertTrue(prop.HasProperty(group_name=default_group, name="to_update")) self.assertEqual( prop.GetProperty(group_name=default_group, name="to_update"), 17) prop.UpdateProperty(group_name=default_group, name="to_update", value=20) self.assertTrue(prop.HasProperty(group_name=default_group, name="to_update")) self.assertEqual( prop.GetProperty(group_name=default_group, name="to_update"), 20) # Property copying. for property_cls in PROPERTY_CLS_LIST: props = property_cls() props.AddProperty("g", "p", 10) self.assertTrue(props.HasProperty("g", "p")) props_copy = property_cls(other=props) self.assertTrue(props_copy.HasProperty("g", "p")) props_copy2 = copy.copy(props) self.assertTrue(props_copy2.HasProperty("g", "p")) props_copy3 = copy.deepcopy(props) self.assertTrue(props_copy3.HasProperty("g", "p")) def test_geometry_properties_cpp_types(self): """ Confirms that types stored in properties in python, resolve to expected types in C++ (with particular emphasis on python built in types as per issue #15640). """ # TODO(sean.curtis): Clean up test, reduce any possible redundancies. for property_cls in PROPERTY_CLS_LIST: for T in [str, bool, float]: props = property_cls() value = T() props.AddProperty("g", "p", value) # Ensure that direct C++ type access is preserved. value_2 = mut_testing.GetPropertyCpp[T](props, "g", "p") self.assertIsInstance(value_2, T) self.assertEqual(value, value_2) def test_geometry_version_api(self): SceneGraph = mut.SceneGraph_[float] scene_graph = SceneGraph() inspector = scene_graph.model_inspector() version0 = inspector.geometry_version() version1 = copy.deepcopy(version0) self.assertTrue(version0.IsSameAs(other=version1, role=mut.Role.kProximity)) self.assertTrue(version0.IsSameAs(other=version1, role=mut.Role.kPerception)) self.assertTrue(version0.IsSameAs(other=version1, role=mut.Role.kIllustration)) version2 = mut.GeometryVersion(other=version0) self.assertTrue(version0.IsSameAs(other=version2, role=mut.Role.kProximity)) self.assertTrue(version0.IsSameAs(other=version2, role=mut.Role.kPerception)) self.assertTrue(version0.IsSameAs(other=version2, role=mut.Role.kIllustration)) version3 = mut.GeometryVersion() self.assertFalse(version0.IsSameAs(other=version3, role=mut.Role.kProximity)) self.assertFalse(version0.IsSameAs(other=version3, role=mut.Role.kPerception)) self.assertFalse(version0.IsSameAs(other=version3, role=mut.Role.kIllustration)) def test_identifier_api(self): cls_list = [ mut.FilterId, mut.SourceId, mut.FrameId, mut.GeometryId, ] for cls in cls_list: a = cls.get_new_id() self.assertTrue(a.is_valid()) b = cls.get_new_id() self.assertTrue(a == a) self.assertFalse(a == b) # N.B. Creation order does not imply value. self.assertTrue(a < b or b > a) id_1 = mut_testing.get_constant_id() id_2 = mut_testing.get_constant_id() self.assertIsNot(id_1, id_2) self.assertEqual(hash(id_1), hash(id_2)) self.assertIn( f"value={id_1.get_value()}", repr(id_1)) def test_proximity_properties(self): """ Tests the utility functions (not related to hydroelastic contact) for setting values in ProximityProperties (as defined in proximity_properties.h). """ props = mut.ProximityProperties() mut.AddContactMaterial(properties=props) props = mut.ProximityProperties() reference_friction = CoulombFriction(0.25, 0.125) mut.AddContactMaterial(dissipation=2.7, point_stiffness=3.9, friction=reference_friction, properties=props) self.assertTrue( props.HasProperty("material", "hunt_crossley_dissipation")) self.assertEqual( props.GetProperty("material", "hunt_crossley_dissipation"), 2.7) self.assertTrue( props.HasProperty("material", "point_contact_stiffness")) self.assertEqual( props.GetProperty("material", "point_contact_stiffness"), 3.9) self.assertTrue(props.HasProperty("material", "coulomb_friction")) stored_friction = props.GetProperty("material", "coulomb_friction") self.assertEqual(stored_friction.static_friction(), reference_friction.static_friction()) self.assertEqual(stored_friction.dynamic_friction(), reference_friction.dynamic_friction()) props = mut.ProximityProperties() res_hint = 0.175 E = 1e8 mut.AddRigidHydroelasticProperties( resolution_hint=res_hint, properties=props) self.assertTrue(props.HasProperty("hydroelastic", "compliance_type")) self.assertFalse(mut_testing.PropertiesIndicateCompliantHydro(props)) self.assertTrue(props.HasProperty("hydroelastic", "resolution_hint")) self.assertEqual(props.GetProperty("hydroelastic", "resolution_hint"), res_hint) props = mut.ProximityProperties() mut.AddRigidHydroelasticProperties(properties=props) self.assertTrue(props.HasProperty("hydroelastic", "compliance_type")) self.assertFalse(mut_testing.PropertiesIndicateCompliantHydro(props)) self.assertFalse(props.HasProperty("hydroelastic", "resolution_hint")) props = mut.ProximityProperties() res_hint = 0.275 mut.AddCompliantHydroelasticProperties( resolution_hint=res_hint, hydroelastic_modulus=E, properties=props) self.assertTrue(props.HasProperty("hydroelastic", "compliance_type")) self.assertTrue(mut_testing.PropertiesIndicateCompliantHydro(props)) self.assertTrue(props.HasProperty("hydroelastic", "resolution_hint")) self.assertEqual(props.GetProperty("hydroelastic", "resolution_hint"), res_hint) self.assertTrue(props.HasProperty("hydroelastic", "hydroelastic_modulus")) self.assertEqual(props.GetProperty("hydroelastic", "hydroelastic_modulus"), E) props = mut.ProximityProperties() slab_thickness = 0.275 mut.AddCompliantHydroelasticPropertiesForHalfSpace( slab_thickness=slab_thickness, hydroelastic_modulus=E, properties=props) self.assertTrue(props.HasProperty("hydroelastic", "compliance_type")) self.assertTrue(mut_testing.PropertiesIndicateCompliantHydro(props)) self.assertTrue(props.HasProperty("hydroelastic", "slab_thickness")) self.assertEqual(props.GetProperty("hydroelastic", "slab_thickness"), slab_thickness) self.assertTrue(props.HasProperty("hydroelastic", "hydroelastic_modulus")) self.assertEqual(props.GetProperty("hydroelastic", "hydroelastic_modulus"), E) def test_rgba_api(self): default_white = mut.Rgba() self.assertEqual(default_white, mut.Rgba(1, 1, 1, 1)) r, g, b, a = 0.75, 0.5, 0.25, 1.0 color = mut.Rgba(r=r, g=g, b=b) self.assertEqual(color.r(), r) self.assertEqual(color.g(), g) self.assertEqual(color.b(), b) self.assertEqual(color.a(), a) self.assertEqual(color, mut.Rgba(r, g, b, a)) self.assertNotEqual(color, mut.Rgba(r, g, b, 0.0)) self.assertEqual( repr(color), "Rgba(r=0.75, g=0.5, b=0.25, a=1.0)") color.set(r=1.0, g=1.0, b=1.0, a=0.0) self.assertEqual(color, mut.Rgba(1.0, 1.0, 1.0, 0.0)) color.set(rgba=[0.75, 0.5, 0.25]) self.assertEqual(color, mut.Rgba(0.75, 0.5, 0.25, 1.0)) color.update(a=0.5) self.assertEqual(color, mut.Rgba(0.75, 0.5, 0.25, 0.5)) color.update(r=0.1, g=0.2, b=0.3) self.assertEqual(color, mut.Rgba(0.1, 0.2, 0.3, 0.5)) # Property read/write. color.rgba = [0.1, 0.2, 0.3, 0.4] self.assertEqual(color.r(), 0.1) self.assertEqual(color.g(), 0.2) self.assertEqual(color.b(), 0.3) self.assertEqual(color.a(), 0.4) color.rgba = [0.5, 0.6, 0.7] self.assertEqual(color.r(), 0.5) self.assertEqual(color.g(), 0.6) self.assertEqual(color.b(), 0.7) self.assertEqual(color.a(), 1.0) self.assertEqual(color.rgba[0], 0.5) self.assertEqual(color.rgba[1], 0.6) self.assertEqual(color.rgba[2], 0.7) self.assertEqual(color.rgba[3], 1.0) with self.assertRaisesRegex(RuntimeError, ".*range.*"): color.rgba = [-1.0] * 4 with self.assertRaisesRegex(RuntimeError, ".*3 or 4.*"): color.rgba = [1.0] * 2 with self.assertRaisesRegex(RuntimeError, ".*3 or 4.*"): color.rgba = [1.0] * 5 # Modulation. self.assertIsInstance(color * mut.Rgba(0.5, 0.5, 0.5), mut.Rgba) self.assertIsInstance(color.scale_rgb(0.5), mut.Rgba) # Confirm value instantiation. Value[mut.Rgba] def test_rgba_yaml(self): yaml = "rgba: [0.1, 0.2, 0.3, 0.4]" dut = yaml_load_typed(schema=mut.Rgba, data=yaml) self.assertEqual(dut.r(), 0.1) self.assertEqual(dut.g(), 0.2) self.assertEqual(dut.b(), 0.3) self.assertEqual(dut.a(), 0.4) yaml = "rgba: [0.1, 0.2, 0.3]" dut = yaml_load_typed(schema=mut.Rgba, data=yaml) self.assertEqual(dut.r(), 0.1) self.assertEqual(dut.g(), 0.2) self.assertEqual(dut.b(), 0.3) self.assertEqual(dut.a(), 1.0) yaml = "rgba: []" with self.assertRaisesRegex(RuntimeError, ".*3 or 4.*"): yaml_load_typed(schema=mut.Rgba, data=yaml) yaml = "rgba: [0, 1, 2, 3, 4, 5]" with self.assertRaisesRegex(RuntimeError, ".*3 or 4.*"): yaml_load_typed(schema=mut.Rgba, data=yaml) yaml = "rgba: [0, 0, 0, -1]" with self.assertRaisesRegex(RuntimeError, ".*range.*"): yaml_load_typed(schema=mut.Rgba, data=yaml) def test_shape_constructors(self): shapes = [ mut.Sphere(radius=1.0), mut.Cylinder(radius=1.0, length=2.0), mut.Box(width=1.0, depth=2.0, height=3.0), mut.Capsule(radius=1.0, length=2.0), mut.Ellipsoid(a=1.0, b=2.0, c=3.0), mut.HalfSpace(), mut.Mesh(filename="arbitrary/path", scale=1.0), mut.Convex(filename="arbitrary/path", scale=1.0), mut.MeshcatCone(height=1.23, a=3.45, b=6.78) ] for shape in shapes: self.assertIsInstance(shape, mut.Shape) shape_cls = type(shape) shape_cls_name = shape_cls.__name__ shape_clone = shape.Clone() self.assertIsInstance(shape_clone, shape_cls) self.assertIsNot(shape_clone, shape) shape_copy = copy.deepcopy(shape) self.assertIsInstance(shape_copy, shape_cls) self.assertIsNot(shape_copy, shape) new_shape = eval(repr(shape), dict([(shape_cls_name, shape_cls)])) self.assertIsInstance(new_shape, shape_cls) self.assertEqual(repr(new_shape), repr(shape)) def test_shapes(self): # We'll test some invariants on all shapes as inherited from the Shape # API. def assert_shape_api(shape): self.assertIsInstance(shape, mut.Shape) shape_cls = type(shape) shape_copy = shape.Clone() self.assertIsInstance(shape_copy, shape_cls) self.assertIsNot(shape, shape_copy) # Note: these are ordered alphabetical order and not in the declared # order in shape_specification.h box = mut.Box(width=1.0, depth=2.0, height=3.0) assert_shape_api(box) box = mut.Box(measures=(1.0, 2.0, 3.0)) self.assertEqual(box.width(), 1.0) self.assertEqual(box.depth(), 2.0) self.assertEqual(box.height(), 3.0) assert_pickle( self, box, lambda shape: [shape.width(), shape.depth(), shape.height()]) numpy_compare.assert_float_equal(box.size(), np.array([1.0, 2.0, 3.0])) self.assertAlmostEqual(mut.CalcVolume(box), 6.0, 1e-14) capsule = mut.Capsule(radius=1.0, length=2.0) assert_shape_api(capsule) capsule = mut.Capsule(measures=(1.0, 2.0)) self.assertEqual(capsule.radius(), 1.0) self.assertEqual(capsule.length(), 2.0) assert_pickle( self, capsule, lambda shape: [shape.radius(), shape.length()]) junk_path = "arbitrary/path.ext" convex = mut.Convex(filename=junk_path, scale=1.0) assert_shape_api(convex) self.assertIn(junk_path, convex.filename()) self.assertEqual(".ext", convex.extension()) self.assertEqual(convex.scale(), 1.0) with self.assertRaisesRegex(RuntimeError, "MakeConvexHull only applies to"): # We just need evidence that it invokes convex hull machinery; the # exception for a bad extension suffices. convex.GetConvexHull() assert_pickle( self, convex, lambda shape: [shape.filename(), shape.scale()]) cylinder = mut.Cylinder(radius=1.0, length=2.0) assert_shape_api(cylinder) cylinder = mut.Cylinder(measures=(1.0, 2.0)) self.assertEqual(cylinder.radius(), 1.0) self.assertEqual(cylinder.length(), 2.0) assert_pickle( self, cylinder, lambda shape: [shape.radius(), shape.length()]) ellipsoid = mut.Ellipsoid(a=1.0, b=2.0, c=3.0) assert_shape_api(ellipsoid) ellipsoid = mut.Ellipsoid(measures=(1.0, 2.0, 3.0)) self.assertEqual(ellipsoid.a(), 1.0) self.assertEqual(ellipsoid.b(), 2.0) self.assertEqual(ellipsoid.c(), 3.0) assert_pickle( self, ellipsoid, lambda shape: [shape.a(), shape.b(), shape.c()]) X_FH = mut.HalfSpace.MakePose(Hz_dir_F=[0, 1, 0], p_FB=[1, 1, 1]) self.assertIsInstance(X_FH, RigidTransform) mesh = mut.Mesh(filename=junk_path, scale=1.0) assert_shape_api(mesh) self.assertIn(junk_path, mesh.filename()) self.assertEqual(".ext", mesh.extension()) self.assertEqual(mesh.scale(), 1.0) with self.assertRaisesRegex(RuntimeError, "MakeConvexHull only applies to"): # We just need evidence that it invokes convex hull machinery; the # exception for a bad extension suffices. mesh.GetConvexHull() assert_pickle( self, mesh, lambda shape: [shape.filename(), shape.scale()]) sphere = mut.Sphere(radius=1.0) assert_shape_api(sphere) self.assertEqual(sphere.radius(), 1.0) assert_pickle(self, sphere, mut.Sphere.radius) cone = mut.MeshcatCone(height=1.2, a=3.4, b=5.6) assert_shape_api(cone) cone = mut.MeshcatCone(measures=(1.2, 3.4, 5.6)) self.assertEqual(cone.height(), 1.2) self.assertEqual(cone.a(), 3.4) self.assertEqual(cone.b(), 5.6) assert_pickle(self, cone, lambda shape: [ shape.height(), shape.a(), shape.b()])
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/scene_graph_test.py
import pydrake.geometry as mut import unittest from math import pi from pydrake.common.test_utilities import numpy_compare from pydrake.common.value import Value from pydrake.math import RigidTransform_ from pydrake.symbolic import Expression from pydrake.systems.framework import InputPort_, OutputPort_ from pydrake.systems.sensors import ( CameraInfo, ImageRgba8U, ImageDepth32F, ImageLabel16I, ) class TestGeometrySceneGraph(unittest.TestCase): def test_hydroelastic_contact_representation_enum(self): mut.HydroelasticContactRepresentation.kTriangle mut.HydroelasticContactRepresentation.kPolygon @numpy_compare.check_all_types def test_scene_graph_api(self, T): SceneGraph = mut.SceneGraph_[T] InputPort = InputPort_[T] OutputPort = OutputPort_[T] scene_graph = SceneGraph() global_source = scene_graph.RegisterSource("anchored") global_frame = scene_graph.RegisterFrame( source_id=global_source, frame=mut.GeometryFrame("anchored_frame1")) scene_graph.RenameFrame(frame_id=global_frame, name="something") scene_graph.RenameFrame(frame_id=global_frame, name="anchored_frame1") scene_graph.RegisterFrame( source_id=global_source, parent_id=global_frame, frame=mut.GeometryFrame("anchored_frame2")) global_geometry = scene_graph.RegisterGeometry( source_id=global_source, frame_id=global_frame, geometry=mut.GeometryInstance(X_PG=RigidTransform_[float](), shape=mut.Sphere(1.), name="sphere1")) # We'll explicitly give sphere_2 a rigid hydroelastic representation. sphere_2 = scene_graph.RegisterGeometry( source_id=global_source, frame_id=global_frame, geometry=mut.GeometryInstance(X_PG=RigidTransform_[float](), shape=mut.Sphere(1.), name="sphere2")) scene_graph.RenameGeometry(geometry_id=sphere_2, name="else") scene_graph.RenameGeometry(geometry_id=sphere_2, name="sphere2") props = mut.ProximityProperties() mut.AddRigidHydroelasticProperties(resolution_hint=1, properties=props) scene_graph.AssignRole(source_id=global_source, geometry_id=sphere_2, properties=props) # We'll explicitly give sphere_3 a compliant hydroelastic # representation. sphere_3 = scene_graph.RegisterAnchoredGeometry( source_id=global_source, geometry=mut.GeometryInstance(X_PG=RigidTransform_[float](), shape=mut.Sphere(1.), name="sphere3")) props = mut.ProximityProperties() mut.AddCompliantHydroelasticProperties( resolution_hint=1, hydroelastic_modulus=1e8, properties=props) scene_graph.AssignRole(source_id=global_source, geometry_id=sphere_3, properties=props) self.assertIsInstance( scene_graph.get_source_pose_port(global_source), InputPort) self.assertIsInstance( scene_graph.get_source_configuration_port(global_source), InputPort) self.assertIsInstance( scene_graph.get_query_output_port(), OutputPort) # Test limited rendering API. renderer_name = "test_renderer" scene_graph.AddRenderer(renderer_name, mut.MakeRenderEngineVtk( mut.RenderEngineVtkParams())) self.assertTrue(scene_graph.HasRenderer(renderer_name)) self.assertEqual(scene_graph.RendererCount(), 1) renderer_type_name = scene_graph.GetRendererTypeName( name=renderer_name) scene_graph.RemoveRenderer(renderer_name) self.assertFalse(scene_graph.HasRenderer(renderer_name)) self.assertEqual(scene_graph.RendererCount(), 0) # Now add the renderer back. scene_graph.AddRenderer(renderer_name, mut.MakeRenderEngineVtk( mut.RenderEngineVtkParams())) # Test SceneGraphInspector API inspector = scene_graph.model_inspector() self.assertEqual(inspector.num_sources(), 2) self.assertEqual(inspector.num_frames(), 3) self.assertEqual(len(inspector.GetAllSourceIds()), 2) self.assertEqual(len(inspector.GetAllFrameIds()), 3) self.assertTrue(inspector.world_frame_id() in inspector.GetAllFrameIds()) self.assertTrue(global_frame in inspector.GetAllFrameIds()) self.assertIsInstance(inspector.world_frame_id(), mut.FrameId) self.assertEqual(inspector.num_geometries(), 3) self.assertEqual( len(inspector.GetAllGeometryIds()), 3) self.assertEqual( len(inspector.GetAllGeometryIds(role=mut.Role.kProximity)), 2) # Test both GeometrySet API as well as SceneGraphInspector's # GeometrySet API. empty_set = mut.GeometrySet() self.assertEqual( len(inspector.GetGeometryIds(empty_set)), 0) self.assertEqual( len(inspector.GetGeometryIds(empty_set, mut.Role.kProximity)), 0) # Cases 1.a: Explicit frame, constructor # N.B. Only in this case (1.a), do we test for non-kwarg usages of # functions. In other tests, frame_set_options = [ # Frame scalar. mut.GeometrySet(frame_id=global_frame), # Frame list. mut.GeometrySet(frame_ids=[global_frame]), # Frame list, no kwargs. mut.GeometrySet([global_frame]), # Frame list w/ (empty) geometry list. mut.GeometrySet(geometry_ids=[], frame_ids=[global_frame]), # Frame list w/ (empty) geometry list, no kwargs. mut.GeometrySet([], [global_frame]), ] # Case 1.b: Explicit frame, via Add(). # - Frame scalar. cur = mut.GeometrySet() cur.Add(frame_id=global_frame) frame_set_options.append(cur) # - Frame list. cur = mut.GeometrySet() cur.Add(frame_ids=[global_frame]) frame_set_options.append(cur) # - Frame list w/ (empty) geometry list. cur = mut.GeometrySet() cur.Add(geometry_ids=[], frame_ids=[global_frame]) frame_set_options.append(cur) # Cases 1.*: Test 'em all. for frame_set in frame_set_options: ids = inspector.GetGeometryIds(frame_set) # N.B. Per above, we have 2 geometries that have been affixed to # global frame ("sphere1" and "sphere2"). self.assertEqual(len(ids), 2) # Cases 2.a: Explicit geometry, constructor (with non-kwarg check). geometry_set_options = [ # Geometry scalar. mut.GeometrySet(geometry_id=global_geometry), # Geometry list. mut.GeometrySet(geometry_ids=[global_geometry]), # Geometry list, no kwargs. mut.GeometrySet([global_geometry]), # Geometry list w/ (empty) frame list. mut.GeometrySet(geometry_ids=[global_geometry], frame_ids=[]), # Geometry list w/ (empty) frame list, no kwargs. mut.GeometrySet([global_geometry], []), ] # Cases 2.b: Explicit geometry, via Add(). # - Geometry scalar. cur = mut.GeometrySet() cur.Add(geometry_id=global_geometry) geometry_set_options.append(cur) # - Geometry list. cur = mut.GeometrySet() cur.Add(geometry_ids=[global_geometry]) geometry_set_options.append(cur) # - Geometry list w/ (empty) frame list. cur = mut.GeometrySet() cur.Add(geometry_ids=[global_geometry], frame_ids=[]) geometry_set_options.append(cur) # Cases 1.*: Test 'em all. for geometry_set in geometry_set_options: ids = inspector.GetGeometryIds(geometry_set) self.assertEqual(len(ids), 1) # Only the first sphere has no proximity properties. The latter two # have hydroelastic properties (rigid and compliant, respectively). self.assertEqual( inspector.NumGeometriesWithRole(role=mut.Role.kUnassigned), 1) self.assertIsNone( inspector.maybe_get_hydroelastic_mesh( geometry_id=global_geometry)) self.assertIsInstance( inspector.maybe_get_hydroelastic_mesh( geometry_id=sphere_2), mut.TriangleSurfaceMesh) self.assertIsInstance( inspector.maybe_get_hydroelastic_mesh( geometry_id=sphere_3), mut.VolumeMesh) self.assertEqual(inspector.NumDynamicGeometries(), 2) self.assertEqual(inspector.NumAnchoredGeometries(), 1) # Sphere 2 and 3 have proximity roles; the pair is a candidate. self.assertEqual(len(inspector.GetCollisionCandidates()), 1) self.assertTrue(inspector.SourceIsRegistered(source_id=global_source)) # TODO(SeanCurtis-TRI) Remove this call at the same time as deprecating # the subsequent deprecation tests; it is only here to show that the # non-keyword call invokes the non-deprecated overload. self.assertTrue(inspector.SourceIsRegistered(global_source)) self.assertEqual(inspector.NumFramesForSource(source_id=global_source), 2) self.assertTrue(global_frame in inspector.FramesForSource( source_id=global_source)) self.assertTrue(inspector.BelongsToSource( frame_id=global_frame, source_id=global_source)) self.assertEqual(inspector.GetOwningSourceName(frame_id=global_frame), "anchored") self.assertEqual( inspector.GetName(frame_id=global_frame), "anchored_frame1") self.assertEqual(inspector.GetFrameGroup(frame_id=global_frame), 0) self.assertEqual( inspector.NumGeometriesForFrame(frame_id=global_frame), 2) self.assertEqual(inspector.NumGeometriesForFrameWithRole( frame_id=global_frame, role=mut.Role.kProximity), 1) self.assertEqual(len(inspector.GetGeometries(frame_id=global_frame)), 2) self.assertTrue( global_geometry in inspector.GetGeometries(frame_id=global_frame)) self.assertEqual( len(inspector.GetGeometries(frame_id=global_frame, role=mut.Role.kProximity)), 1) self.assertEqual( inspector.GetGeometryIdByName(frame_id=global_frame, role=mut.Role.kUnassigned, name="sphere1"), global_geometry) self.assertTrue(inspector.BelongsToSource( geometry_id=global_geometry, source_id=global_source)) self.assertEqual( inspector.GetOwningSourceName(geometry_id=global_geometry), "anchored") self.assertEqual(inspector.GetFrameId(global_geometry), global_frame) self.assertEqual( inspector.GetName(geometry_id=global_geometry), "sphere1") self.assertIsInstance(inspector.GetShape(geometry_id=global_geometry), mut.Sphere) self.assertIsInstance( inspector.GetPoseInFrame(geometry_id=global_geometry), RigidTransform_[float]) self.assertIsInstance(inspector.geometry_version(), mut.GeometryVersion) # Check AssignRole bits. proximity = mut.ProximityProperties() perception = mut.PerceptionProperties() perception.AddProperty("label", "id", mut.RenderLabel(0)) illustration = mut.IllustrationProperties() props = [ proximity, perception, illustration, ] context = scene_graph.CreateDefaultContext() for prop in props: # Check SceneGraph mutating variant. scene_graph.AssignRole( source_id=global_source, geometry_id=global_geometry, properties=prop, assign=mut.RoleAssign.kNew) # Check Context mutating variant. scene_graph.AssignRole( context=context, source_id=global_source, geometry_id=global_geometry, properties=prop, assign=mut.RoleAssign.kNew) # Check property accessors. self.assertIsInstance( inspector.GetProximityProperties(geometry_id=global_geometry), mut.ProximityProperties) self.assertIsInstance( inspector.GetProperties(geometry_id=global_geometry, role=mut.Role.kProximity), mut.ProximityProperties) self.assertIsInstance( inspector.GetIllustrationProperties(geometry_id=global_geometry), mut.IllustrationProperties) self.assertIsInstance( inspector.GetProperties(geometry_id=global_geometry, role=mut.Role.kIllustration), mut.IllustrationProperties) self.assertIsInstance( inspector.GetPerceptionProperties(geometry_id=global_geometry), mut.PerceptionProperties) self.assertIsInstance( inspector.GetProperties(geometry_id=global_geometry, role=mut.Role.kPerception), mut.PerceptionProperties) self.assertIsInstance( inspector.CloneGeometryInstance(geometry_id=global_geometry), mut.GeometryInstance) self.assertTrue(inspector.CollisionFiltered( geometry_id1=global_geometry, geometry_id2=global_geometry)) roles = [ mut.Role.kProximity, mut.Role.kPerception, mut.Role.kIllustration, ] for i, role in enumerate(roles): # Check GeometryId SceneGraph mutating variant. self.assertEqual( scene_graph.RemoveRole( source_id=global_source, geometry_id=global_geometry, role=role), 1) # Check GeometryId Context mutating variant. self.assertEqual( scene_graph.RemoveRole( context=context, source_id=global_source, geometry_id=global_geometry, role=role), 1) # Check FrameId SceneGraph mutating variant. self.assertEqual( scene_graph.RemoveRole( source_id=global_source, frame_id=global_frame, role=role), 1 if i == 0 else 0) # Check FrameId Context mutating variant. self.assertEqual( scene_graph.RemoveRole( context=context, source_id=global_source, frame_id=global_frame, role=role), 1 if i == 0 else 0) def test_scene_graph_config(self): mut.DefaultProximityProperties() scene_graph_config = mut.SceneGraphConfig() scene_graph = mut.SceneGraph(config=scene_graph_config) got_config = scene_graph.get_config() self.assertEqual( got_config.default_proximity_properties.compliance_type, "undefined") scene_graph_config.default_proximity_properties.compliance_type = \ "compliant" scene_graph.set_config(config=scene_graph_config) got_config = scene_graph.get_config() self.assertEqual( got_config.default_proximity_properties.compliance_type, "compliant") # ParamInit. param_init_props = mut.DefaultProximityProperties( compliance_type="compliant", hydroelastic_modulus=2, resolution_hint=3, slab_thickness=4, dynamic_friction=5, static_friction=6, hunt_crossley_dissipation=7, relaxation_time=None, # Test optionality. point_stiffness=9, ) param_init_scene_graph = mut.SceneGraphConfig( default_proximity_properties=param_init_props) # Spot-check that at least some value got passed through. got_props = param_init_scene_graph.default_proximity_properties self.assertEqual(got_props.relaxation_time, None) self.assertEqual(got_props.point_stiffness, 9) @numpy_compare.check_all_types def test_scene_graph_renderer_with_context(self, T): SceneGraph = mut.SceneGraph_[T] scene_graph = SceneGraph() context = scene_graph.CreateDefaultContext() self.assertEqual(scene_graph.RendererCount(context), 0) render_params = mut.RenderEngineVtkParams() renderer_name = "test_renderer" self.assertFalse( scene_graph.HasRenderer(context=context, name=renderer_name)) scene_graph.AddRenderer( context=context, name=renderer_name, renderer=mut.MakeRenderEngineVtk(params=render_params)) self.assertEqual(scene_graph.RendererCount(context=context), 1) self.assertTrue( scene_graph.HasRenderer(context=context, name=renderer_name)) scene_graph.RemoveRenderer(context=context, name=renderer_name) self.assertEqual(scene_graph.RendererCount(context=context), 0) renderer_type_name = scene_graph.GetRendererTypeName( context=context, name=renderer_name) @numpy_compare.check_all_types def test_scene_graph_register_geometry(self, T): SceneGraph = mut.SceneGraph_[T] scene_graph = SceneGraph() global_source = scene_graph.RegisterSource("anchored") global_frame = scene_graph.world_frame_id() context = scene_graph.CreateDefaultContext() model_inspector = scene_graph.model_inspector() query_object = scene_graph.get_query_output_port().Eval(context) context_inspector = query_object.inspector() self.assertEqual(model_inspector.num_geometries(), 0) self.assertEqual(context_inspector.num_geometries(), 0) # Register with context geometry = mut.GeometryInstance(X_PG=RigidTransform_[float](), shape=mut.Sphere(1.), name="sphere1") global_geometry = scene_graph.RegisterGeometry( context=context, source_id=global_source, frame_id=global_frame, geometry=geometry) self.assertEqual(model_inspector.num_geometries(), 0) self.assertEqual(context_inspector.num_geometries(), 1) # Now register the geometry in scene_graph with a new geometry new_geometry = mut.GeometryInstance(X_PG=RigidTransform_[float](), shape=mut.Sphere(1.), name="sphere1") scene_graph.RegisterGeometry( source_id=global_source, frame_id=global_frame, geometry=new_geometry) self.assertEqual(model_inspector.num_geometries(), 1) self.assertEqual(context_inspector.num_geometries(), 1) @numpy_compare.check_all_types def test_scene_graph_change_shape(self, T): SceneGraph = mut.SceneGraph_[T] RigidTransform = RigidTransform_[float] scene_graph = SceneGraph() source_id = scene_graph.RegisterSource("anchored") frame_id = scene_graph.world_frame_id() identity = RigidTransform() X_FG_alt = RigidTransform(p=(1, 2, 3)) geometry_id = scene_graph.RegisterGeometry( source_id=source_id, frame_id=frame_id, geometry=mut.GeometryInstance(X_PG=identity, shape=mut.Sphere(1.), name="sphere1")) context = scene_graph.CreateDefaultContext() model_inspector = scene_graph.model_inspector() self.assertIsInstance(model_inspector.GetShape(geometry_id), mut.Sphere) scene_graph.ChangeShape(source_id=source_id, geometry_id=geometry_id, shape=mut.Box(1, 2, 3)) self.assertIsInstance(model_inspector.GetShape(geometry_id), mut.Box) scene_graph.ChangeShape(source_id=source_id, geometry_id=geometry_id, shape=mut.Capsule(1, 2), X_FG=X_FG_alt) self.assertIsInstance(model_inspector.GetShape(geometry_id), mut.Capsule) self.assertTrue( (model_inspector.GetPoseInFrame(geometry_id).translation() == X_FG_alt.translation()).all()) query_object = scene_graph.get_query_output_port().Eval(context) context_inspector = query_object.inspector() self.assertIsInstance(context_inspector.GetShape(geometry_id), mut.Sphere) scene_graph.ChangeShape( context=context, source_id=source_id, geometry_id=geometry_id, shape=mut.Box(1, 2, 3)) self.assertIsInstance(context_inspector.GetShape(geometry_id), mut.Box) scene_graph.ChangeShape( context=context, source_id=source_id, geometry_id=geometry_id, shape=mut.Capsule(1, 2), X_FG=X_FG_alt) self.assertIsInstance(context_inspector.GetShape(geometry_id), mut.Capsule) self.assertTrue( (context_inspector.GetPoseInFrame(geometry_id).translation() == X_FG_alt.translation()).all()) @numpy_compare.check_all_types def test_scene_graph_remove_geometry(self, T): SceneGraph = mut.SceneGraph_[T] scene_graph = SceneGraph() global_source = scene_graph.RegisterSource("anchored") global_frame = scene_graph.world_frame_id() global_geometry = scene_graph.RegisterGeometry( source_id=global_source, frame_id=global_frame, geometry=mut.GeometryInstance(X_PG=RigidTransform_[float](), shape=mut.Sphere(1.), name="sphere1")) context = scene_graph.CreateDefaultContext() model_inspector = scene_graph.model_inspector() query_object = scene_graph.get_query_output_port().Eval(context) context_inspector = query_object.inspector() # Call the version that only removes the geometry in the context. scene_graph.RemoveGeometry( context=context, source_id=global_source, geometry_id=global_geometry) self.assertEqual(model_inspector.num_geometries(), 1) self.assertEqual(context_inspector.num_geometries(), 0) # Now remove the geometry in scene_graph scene_graph.RemoveGeometry( source_id=global_source, geometry_id=global_geometry) self.assertEqual(model_inspector.num_geometries(), 0) @numpy_compare.check_all_types def test_frame_pose_vector_api(self, T): FramePoseVector = mut.FramePoseVector_[T] RigidTransform = RigidTransform_[T] obj = FramePoseVector() frame_id = mut.FrameId.get_new_id() obj.set_value(id=frame_id, value=RigidTransform.Identity()) self.assertEqual(obj.size(), 1) self.assertIsInstance(obj.value(id=frame_id), RigidTransform) self.assertTrue(obj.has_id(id=frame_id)) self.assertIsInstance(obj.ids(), list) self.assertIsInstance(obj.ids()[0], mut.FrameId) obj.clear() self.assertEqual(obj.size(), 0) @numpy_compare.check_all_types def test_penetration_as_point_pair_api(self, T): obj = mut.PenetrationAsPointPair_[T]() self.assertIsInstance(obj.id_A, mut.GeometryId) self.assertIsInstance(obj.id_B, mut.GeometryId) self.assertTupleEqual(obj.p_WCa.shape, (3,)) self.assertTupleEqual(obj.p_WCb.shape, (3,)) if T == Expression: self.assertTrue(obj.depth.EqualTo(-1.0)) else: self.assertEqual(obj.depth, -1.0) @numpy_compare.check_all_types def test_signed_distance_api(self, T): obj = mut.SignedDistancePair_[T]() self.assertIsInstance(obj.id_A, mut.GeometryId) self.assertIsInstance(obj.id_B, mut.GeometryId) self.assertTupleEqual(obj.p_ACa.shape, (3,)) self.assertTupleEqual(obj.p_BCb.shape, (3,)) self.assertIsInstance(obj.distance, T) self.assertTupleEqual(obj.nhat_BA_W.shape, (3,)) @numpy_compare.check_all_types def test_signed_distance_to_point_api(self, T): obj = mut.SignedDistanceToPoint_[T]() self.assertIsInstance(obj.id_G, mut.GeometryId) self.assertTupleEqual(obj.p_GN.shape, (3,)) self.assertIsInstance(obj.distance, T) self.assertTupleEqual(obj.grad_W.shape, (3,)) @numpy_compare.check_all_types def test_query_object(self, T): RigidTransform = RigidTransform_[float] SceneGraph = mut.SceneGraph_[T] QueryObject = mut.QueryObject_[T] SceneGraphInspector = mut.SceneGraphInspector_[T] FramePoseVector = mut.FramePoseVector_[T] # First, ensure we can default-construct it. model = QueryObject() self.assertIsInstance(model, QueryObject) scene_graph = SceneGraph() source_id = scene_graph.RegisterSource("source") frame_id = scene_graph.RegisterFrame( source_id=source_id, frame=mut.GeometryFrame("frame")) geometry_id = scene_graph.RegisterGeometry( source_id=source_id, frame_id=frame_id, geometry=mut.GeometryInstance(X_PG=RigidTransform(), shape=mut.Sphere(1.), name="sphere")) render_params = mut.RenderEngineVtkParams() renderer_name = "test_renderer" scene_graph.AddRenderer(renderer_name, mut.MakeRenderEngineVtk(params=render_params)) context = scene_graph.CreateDefaultContext() pose_vector = FramePoseVector() pose_vector.set_value(frame_id, RigidTransform_[T]()) scene_graph.get_source_pose_port(source_id).FixValue( context, pose_vector) query_object = scene_graph.get_query_output_port().Eval(context) self.assertIsInstance(query_object.inspector(), SceneGraphInspector) self.assertIsInstance( query_object.GetPoseInWorld(frame_id=frame_id), RigidTransform_[T]) self.assertIsInstance( query_object.GetPoseInParent(frame_id=frame_id), RigidTransform_[T]) self.assertIsInstance( query_object.GetPoseInWorld(geometry_id=geometry_id), RigidTransform_[T]) # Proximity queries -- all of these will produce empty results. results = query_object.ComputeSignedDistancePairwiseClosestPoints() self.assertEqual(len(results), 0) results = query_object.ComputePointPairPenetration() self.assertEqual(len(results), 0) if T != Expression: hydro_rep = mut.HydroelasticContactRepresentation.kTriangle results = query_object.ComputeContactSurfaces( representation=hydro_rep) self.assertEqual(len(results), 0) surfaces, results = query_object.ComputeContactSurfacesWithFallback( # noqa representation=hydro_rep) self.assertEqual(len(surfaces), 0) self.assertEqual(len(results), 0) results = query_object.ComputeSignedDistanceToPoint(p_WQ=(1, 2, 3)) self.assertEqual(len(results), 0) results = query_object.FindCollisionCandidates() self.assertEqual(len(results), 0) self.assertFalse(query_object.HasCollisions()) # ComputeSignedDistancePairClosestPoints() requires two valid geometry # ids. There are none in this SceneGraph instance. Rather than # populating the SceneGraph, we look for the exception thrown in # response to invalid ids as evidence of correct binding. with self.assertRaisesRegex( RuntimeError, "Referenced geometry .+ has not been registered."): query_object.ComputeSignedDistancePairClosestPoints( geometry_id_A=mut.GeometryId.get_new_id(), geometry_id_B=mut.GeometryId.get_new_id()) # Confirm rendering API returns images of appropriate type. camera_core = mut.RenderCameraCore( renderer_name=renderer_name, intrinsics=CameraInfo(width=10, height=10, fov_y=pi/6), clipping=mut.ClippingRange(0.1, 10.0), X_BS=RigidTransform()) color_camera = mut.ColorRenderCamera( core=camera_core, show_window=False) depth_camera = mut.DepthRenderCamera( core=camera_core, depth_range=mut.DepthRange(0.1, 5.0)) image = query_object.RenderColorImage( camera=color_camera, parent_frame=SceneGraph.world_frame_id(), X_PC=RigidTransform()) self.assertIsInstance(image, ImageRgba8U) image = query_object.RenderDepthImage( camera=depth_camera, parent_frame=SceneGraph.world_frame_id(), X_PC=RigidTransform()) self.assertIsInstance(image, ImageDepth32F) image = query_object.RenderLabelImage( camera=color_camera, parent_frame=SceneGraph.world_frame_id(), X_PC=RigidTransform()) self.assertIsInstance(image, ImageLabel16I) @numpy_compare.check_all_types def test_value_instantiations(self, T): Value[mut.FramePoseVector_[T]] Value[mut.QueryObject_[T]] @numpy_compare.check_nonsymbolic_types def test_contact_surface(self, T): # We can't construct a ContactSurface directly. So, we need to evaluate # hydroelastic contact in order to get a result that we can assess. RigidTransform = RigidTransform_[T] RigidTransformd = RigidTransform_[float] SceneGraph = mut.SceneGraph_[T] FramePoseVector = mut.FramePoseVector_[T] scene_graph = SceneGraph() s_id = scene_graph.RegisterSource("source") # Add a compliant "moving" ball. f_id = scene_graph.RegisterFrame( source_id=s_id, frame=mut.GeometryFrame("frame")) g_id0 = scene_graph.RegisterGeometry( source_id=s_id, frame_id=f_id, geometry=mut.GeometryInstance(X_PG=RigidTransformd(), shape=mut.Sphere(1.), name="sphere")) props = mut.ProximityProperties() mut.AddCompliantHydroelasticProperties( resolution_hint=1.0, hydroelastic_modulus=1e5, properties=props) scene_graph.AssignRole(s_id, g_id0, props) # Add a rigd half space. g_id1 = scene_graph.RegisterAnchoredGeometry( source_id=s_id, geometry=mut.GeometryInstance(X_PG=RigidTransformd(), shape=mut.HalfSpace(), name="plane")) props = mut.ProximityProperties() mut.AddRigidHydroelasticProperties(properties=props) scene_graph.AssignRole(s_id, g_id1, props) context = scene_graph.CreateDefaultContext() # Provide poses so we can evaluate the query object. The poses should # lead to a single collision. poses = FramePoseVector() poses.set_value(id=f_id, value=RigidTransform([0, 0, 0.5])) scene_graph.get_source_pose_port(s_id).FixValue(context, poses) query_object = scene_graph.get_query_output_port().Eval(context) # Test both mesh representations. for rep in (mut.HydroelasticContactRepresentation.kTriangle, mut.HydroelasticContactRepresentation.kPolygon): expect_triangles = ( rep == mut.HydroelasticContactRepresentation.kTriangle) results = query_object.ComputeContactSurfaces(rep) self.assertEqual(len(results), 1) contact_surface = results[0] self.assertLess(g_id0, g_id1) # confirm M = 0 and N = 1. self.assertEqual(contact_surface.id_M(), g_id0) self.assertEqual(contact_surface.id_N(), g_id1) self.assertGreater(contact_surface.num_faces(), 0) self.assertGreater(contact_surface.num_vertices(), 0) self.assertGreater(contact_surface.area(face_index=0), 0) self.assertGreater(contact_surface.total_area(), 0) contact_surface.face_normal(face_index=0) contact_surface.centroid(face_index=0) contact_surface.centroid() self.assertEqual(contact_surface.is_triangle(), expect_triangles) self.assertEqual(contact_surface.representation(), rep) if expect_triangles: # Details of mesh are tested in geometry_hydro_test.py contact_surface.tri_mesh_W() field = contact_surface.tri_e_MN() # Only triangle mesh fields can evaluate barycentric coords. field.Evaluate(e=0, b=(0.25, 0.5, 0.25)) else: # Details of mesh are tested in geometry_hydro_test.py contact_surface.poly_mesh_W() field = contact_surface.poly_e_MN() # Only the Polygonal mesh has gradients pre-computed. field.EvaluateGradient(e=0) # APIs available to both Triangle and Polygon-based fields. field.EvaluateAtVertex(v=0) field.EvaluateCartesian(e=0, p_MQ=(0.25, 0.25, 0))
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/render_engine_subclass_test.py
"""For reasons not yet understood (see issue #14686), the unit tests where we confirm the semantics of deriving a RenderEngine implementation in python are flaky and are therefore being isolated (see issue #14720).""" import pydrake.geometry as mut from math import pi import unittest from pydrake.math import RigidTransform, RigidTransform_ from pydrake.systems.sensors import ( CameraInfo, ImageRgba8U, ImageDepth32F, ImageLabel16I, ) class TestRenderEngineSubclass(unittest.TestCase): def test_unimplemented_rendering(self): """The RenderEngine API throws exceptions for derived implementations that don't override DoRender*Image. This test confirms that behavior propagates down to Python.""" class MinimalEngine(mut.RenderEngine): """Minimal implementation of the RenderEngine virtual API""" def UpdateViewpoint(self, X_WC): pass def DoRegisterVisual(self, id, shape, properties, X_WG): pass def DoUpdateVisualPose(self, id, X_WG): pass def DoRemoveGeometry(self, id): pass def DoClone(self): pass class ColorOnlyEngine(MinimalEngine): """Rendering Depth and Label images should throw""" def DoRenderColorImage(self, camera, image_out): pass class DepthOnlyEngine(MinimalEngine): """Rendering Color and Label images should throw""" def DoRenderDepthImage(self, camera, image_out): pass class LabelOnlyEngine(MinimalEngine): """Rendering Color and Depth images should throw""" def DoRenderLabelImage(self, camera, image_out): pass identity = RigidTransform_[float]() intrinsics = CameraInfo(10, 10, pi / 4) core = mut.RenderCameraCore("n/a", intrinsics, mut.ClippingRange(0.1, 10), identity) color_cam = mut.ColorRenderCamera(core, False) depth_cam = mut.DepthRenderCamera(core, mut.DepthRange(0.1, 9)) color_image = ImageRgba8U(intrinsics.width(), intrinsics.height()) depth_image = ImageDepth32F(intrinsics.width(), intrinsics.height()) label_image = ImageLabel16I(intrinsics.width(), intrinsics.height()) color_only = ColorOnlyEngine() color_only.RenderColorImage(color_cam, color_image) with self.assertRaisesRegex(RuntimeError, ".+pure virtual function.+"): color_only.RenderDepthImage(depth_cam, depth_image) with self.assertRaisesRegex(RuntimeError, ".+pure virtual function.+"): color_only.RenderLabelImage(color_cam, label_image) depth_only = DepthOnlyEngine() with self.assertRaisesRegex(RuntimeError, ".+pure virtual function.+"): depth_only.RenderColorImage(color_cam, color_image) depth_only.RenderDepthImage(depth_cam, depth_image) with self.assertRaisesRegex(RuntimeError, ".+pure virtual function.+"): depth_only.RenderLabelImage(color_cam, label_image) label_only = LabelOnlyEngine() with self.assertRaisesRegex(RuntimeError, ".+pure virtual function.+"): label_only.RenderColorImage(color_cam, color_image) with self.assertRaisesRegex(RuntimeError, ".+pure virtual function.+"): label_only.RenderDepthImage(depth_cam, depth_image) label_only.RenderLabelImage(color_cam, label_image)
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/frame_id_test.py
import pydrake.geometry as mut import unittest class TestFrameId(unittest.TestCase): """Checks that FrameId values are globally unique. This test case must be isolated as its own test program (not mixed with the other FrameId unit tests) because it relies on global state (the ID counter). """ def test_id_uniqueness(self): """Every FrameId must be unique.""" scene_graph = mut.SceneGraph() f = mut.FrameId.get_new_id().get_value() g = mut.GeometryFrame("geometry").id().get_value() w = scene_graph.world_frame_id().get_value() self.assertNotEqual(f, g) self.assertNotEqual(w, f) self.assertNotEqual(w, g)
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/hydro_test.py
import pydrake.geometry as mut import pydrake.geometry._testing as mut_testing import copy import unittest import numpy as np from pydrake.common import FindResourceOrThrow class TestGeometryHydro(unittest.TestCase): def test_hydro_proximity_properties(self): """ Tests the utility functions (related to hydroelastic contact) for setting values in ProximityProperties (as defined in proximity_properties.h). """ props = mut.ProximityProperties() res_hint = 0.175 E = 1e8 mut.AddRigidHydroelasticProperties( resolution_hint=res_hint, properties=props) self.assertTrue(props.HasProperty("hydroelastic", "compliance_type")) self.assertFalse(mut_testing.PropertiesIndicateCompliantHydro(props)) self.assertTrue(props.HasProperty("hydroelastic", "resolution_hint")) self.assertEqual(props.GetProperty("hydroelastic", "resolution_hint"), res_hint) props = mut.ProximityProperties() mut.AddRigidHydroelasticProperties(properties=props) self.assertTrue(props.HasProperty("hydroelastic", "compliance_type")) self.assertFalse(mut_testing.PropertiesIndicateCompliantHydro(props)) self.assertFalse(props.HasProperty("hydroelastic", "resolution_hint")) props = mut.ProximityProperties() res_hint = 0.275 mut.AddCompliantHydroelasticProperties( resolution_hint=res_hint, hydroelastic_modulus=E, properties=props) self.assertTrue(props.HasProperty("hydroelastic", "compliance_type")) self.assertTrue(mut_testing.PropertiesIndicateCompliantHydro(props)) self.assertTrue(props.HasProperty("hydroelastic", "resolution_hint")) self.assertEqual(props.GetProperty("hydroelastic", "resolution_hint"), res_hint) self.assertTrue(props.HasProperty("hydroelastic", "hydroelastic_modulus")) self.assertEqual(props.GetProperty("hydroelastic", "hydroelastic_modulus"), E) props = mut.ProximityProperties() slab_thickness = 0.275 mut.AddCompliantHydroelasticPropertiesForHalfSpace( slab_thickness=slab_thickness, hydroelastic_modulus=E, properties=props) self.assertTrue(props.HasProperty("hydroelastic", "compliance_type")) self.assertTrue(mut_testing.PropertiesIndicateCompliantHydro(props)) self.assertTrue(props.HasProperty("hydroelastic", "slab_thickness")) self.assertEqual(props.GetProperty("hydroelastic", "slab_thickness"), slab_thickness) self.assertTrue(props.HasProperty("hydroelastic", "hydroelastic_modulus")) self.assertEqual(props.GetProperty("hydroelastic", "hydroelastic_modulus"), E) def test_make_convex_hull(self): mesh_path = FindResourceOrThrow("drake/geometry/test/quad_cube.obj") hull = mut._MakeConvexHull(mut.Convex(mesh_path)) self.assertIsInstance(hull, mut.PolygonSurfaceMesh)
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/optimization_test.py
import pydrake.geometry.optimization as mut import os.path import unittest import copy import numpy as np from pydrake.common import RandomGenerator, temp_directory from pydrake.common.test_utilities.deprecation import catch_drake_warnings from pydrake.common.test_utilities.pickle_compare import assert_pickle from pydrake.geometry import ( Box, Capsule, Cylinder, Convex, Ellipsoid, FramePoseVector, GeometryFrame, GeometryInstance, ProximityProperties, SceneGraph, Sphere, GeometryId ) from pydrake.math import RigidTransform from pydrake.multibody.inverse_kinematics import InverseKinematics from pydrake.multibody.parsing import Parser from pydrake.multibody.plant import AddMultibodyPlantSceneGraph from pydrake.multibody.tree import BodyIndex from pydrake.systems.framework import DiagramBuilder from pydrake.solvers import ( Binding, ClpSolver, Constraint, Cost, MathematicalProgram, MathematicalProgramResult, SolverOptions, CommonSolverOption, ScsSolver, MosekSolver ) from pydrake.symbolic import Variable, Polynomial class TestGeometryOptimization(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.A = np.eye(3) self.b = np.array([1.0, 1.0, 1.0]) self.prog = MathematicalProgram() self.x = self.prog.NewContinuousVariables(3, "x") self.t = self.prog.NewContinuousVariables(1, "t")[0] self.Ay = np.array([[1., 0.], [0., 1.], [1., 0.]]) self.by = np.ones(3) self.cz = np.ones(2) self.dz = 1. self.y = self.prog.NewContinuousVariables(2, "y") self.z = self.prog.NewContinuousVariables(2, "z") def test_point_convex_set(self): mut.Point() p = np.array([11.1, 12.2, 13.3]) point = mut.Point(p) self.assertFalse(point.IsEmpty()) self.assertEqual(point.ambient_dimension(), 3) np.testing.assert_array_equal(point.x(), p) np.testing.assert_array_equal(point.MaybeGetPoint(), p) np.testing.assert_array_equal(point.MaybeGetFeasiblePoint(), p) point.set_x(x=2*p) np.testing.assert_array_equal(point.x(), 2*p) point.set_x(x=p) assert_pickle(self, point, lambda S: S.x()) # TODO(SeanCurtis-TRI): This doesn't test the constructor that # builds from shape. def test_affine_ball(self): dut = mut.AffineBall() self.assertEqual(dut.B().shape[0], 0) self.assertEqual(dut.B().shape[1], 0) self.assertEqual(dut.center().shape[0], 0) self.assertEqual(dut.ambient_dimension(), 0) self.assertFalse(dut.IsEmpty()) self.assertTrue(dut.IsBounded()) self.assertTrue(dut.PointInSet(dut.MaybeGetFeasiblePoint())) self.assertTrue(dut.IntersectsWith(dut)) B = np.eye(2) center = np.zeros(2) E = mut.AffineBall(B=B, center=center) self.assertEqual(E.B().shape[0], 2) self.assertEqual(E.B().shape[1], 2) self.assertEqual(E.center().shape[0], 2) self.assertEqual(E.ambient_dimension(), 2) self.assertEqual(E.CalcVolume(), np.pi) self.assertFalse(E.IsEmpty()) self.assertTrue(E.IsBounded()) self.assertTrue(E.PointInSet(E.MaybeGetFeasiblePoint())) self.assertTrue(E.IntersectsWith(E)) mut.AffineBall.MakeAxisAligned( radius=np.ones(3), center=np.zeros(3)) mut.AffineBall.MakeHypersphere(radius=2, center=np.zeros(3)) mut.AffineBall.MakeUnitBall(dim=2) mut.AffineBall(ellipsoid=mut.Hyperellipsoid.MakeUnitBall(dim=1)) points = np.array([[1, 0], [-1, 0], [0, 2], [0, -2]]).T e_lowner_john = mut.AffineBall.MinimumVolumeCircumscribedEllipsoid( points=points, rank_tol=1e-2) e_lowner_john = mut.AffineBall.MinimumVolumeCircumscribedEllipsoid( points=points) def test_affine_subspace(self): dut = mut.AffineSubspace() self.assertEqual(dut.basis().shape[0], 0) self.assertEqual(dut.basis().shape[1], 0) self.assertEqual(dut.translation().shape[0], 0) self.assertEqual(dut.ambient_dimension(), 0) self.assertFalse(dut.IsEmpty()) self.assertTrue(dut.IsBounded()) self.assertTrue(dut.PointInSet(dut.MaybeGetFeasiblePoint())) self.assertTrue(dut.IntersectsWith(dut)) with catch_drake_warnings(expected_count=1): self.assertTrue(dut.PointInSet(dut.Project([]))) self.assertEqual(dut.AffineDimension(), 0) self.assertTrue(dut.ContainedIn(mut.AffineSubspace())) self.assertTrue(dut.IsNearlyEqualTo(mut.AffineSubspace())) basis = np.array([[1, 0, 0], [0, 1, 0]]).T translation = np.array([0, 0, 1]) dut = mut.AffineSubspace(basis=basis, translation=translation) self.assertEqual(dut.basis().shape[0], 3) self.assertEqual(dut.basis().shape[1], 2) self.assertEqual(dut.translation().shape[0], 3) self.assertEqual(dut.ambient_dimension(), 3) self.assertFalse(dut.IsEmpty()) self.assertFalse(dut.IsBounded()) self.assertTrue(dut.PointInSet(dut.MaybeGetFeasiblePoint())) self.assertTrue(dut.IntersectsWith(dut)) self.assertEqual(dut.AffineDimension(), 2) complement_basis = dut.OrthogonalComplementBasis() self.assertEqual(complement_basis.shape, (3, 1)) test_point = np.array([43, 43, 0]) self.assertFalse(dut.PointInSet(test_point)) with catch_drake_warnings(expected_count=1): self.assertTrue(dut.PointInSet(dut.Project(test_point))) with catch_drake_warnings(expected_count=1) as w: np.testing.assert_array_equal(dut.ToGlobalCoordinates( dut.ToLocalCoordinates(test_point)), dut.Project(test_point)) local_coords = np.array([1, -1]) np.testing.assert_array_equal(dut.ToLocalCoordinates( dut.ToGlobalCoordinates(local_coords)), local_coords.reshape(-1, 1)) np.testing.assert_array_equal(dut.ToLocalCoordinates( dut.ToGlobalCoordinates(local_coords.reshape(-1, 1))), local_coords.reshape(-1, 1)) test_point_batch = np.zeros((3, 5)) self.assertEqual(dut.ToLocalCoordinates(x=test_point_batch).shape, (2, 5)) with catch_drake_warnings(expected_count=1) as w: self.assertEqual(dut.Project(x=test_point_batch).shape, (3, 5)) local_coords_batch = np.zeros((2, 5)) self.assertEqual(dut.ToGlobalCoordinates(y=local_coords_batch).shape, (3, 5)) self.assertTrue(dut.ContainedIn(other=mut.AffineSubspace( basis, translation), tol=0)) self.assertTrue(dut.IsNearlyEqualTo(other=mut.AffineSubspace( basis, translation), tol=0)) self.assertFalse(dut.ContainedIn(other=mut.AffineSubspace(), tol=0)) self.assertFalse(mut.AffineSubspace().ContainedIn(other=dut, tol=0)) self.assertFalse(dut.IsNearlyEqualTo(other=mut.AffineSubspace(), tol=0)) self.assertIsNot(dut.Clone(), dut) self.assertIsNot(copy.deepcopy(dut), dut) p = np.array([11.1, 12.2, 13.3]) point = mut.Point(p) aff = mut.AffineSubspace(set=point, tol=1e-12) def test_h_polyhedron(self): mut.HPolyhedron() hpoly = mut.HPolyhedron(A=self.A, b=self.b) self.assertEqual(hpoly.ambient_dimension(), 3) np.testing.assert_array_equal(hpoly.A(), self.A) np.testing.assert_array_equal(hpoly.b(), self.b) self.assertTrue(hpoly.PointInSet(x=[0, 0, 0], tol=0.0)) self.assertFalse(hpoly.IsEmpty()) self.assertFalse(hpoly.MaybeGetFeasiblePoint() is None) self.assertTrue(hpoly.PointInSet(hpoly.MaybeGetFeasiblePoint())) self.assertFalse(hpoly.IsBounded()) new_vars, new_constraints = hpoly.AddPointInSetConstraints( self.prog, self.x) self.assertEqual(new_vars.size, 0) constraints = hpoly.AddPointInNonnegativeScalingConstraints( prog=self.prog, x=self.x, t=self.t) self.assertGreaterEqual(len(constraints), 2) self.assertIsInstance(constraints[0], Binding[Constraint]) constraints = hpoly.AddPointInNonnegativeScalingConstraints( prog=self.prog, A=self.Ay, b=self.by, c=self.cz, d=self.dz, x=self.y, t=self.z) self.assertGreaterEqual(len(constraints), 2) self.assertIsInstance(constraints[0], Binding[Constraint]) with self.assertRaisesRegex( RuntimeError, ".*not implemented yet for HPolyhedron.*"): hpoly.ToShapeWithPose() assert_pickle(self, hpoly, lambda S: np.vstack((S.A(), S.b()))) h_box = mut.HPolyhedron.MakeBox( lb=[-1, -1, -1], ub=[1, 1, 1]) self.assertTrue(h_box.IntersectsWith(hpoly)) h_unit_box = mut.HPolyhedron.MakeUnitBox(dim=3) np.testing.assert_array_equal(h_box.A(), h_unit_box.A()) np.testing.assert_array_equal(h_box.b(), h_unit_box.b()) A_l1 = np.array([[1, 1, 1], [-1, 1, 1], [1, -1, 1], [-1, -1, 1], [1, 1, -1], [-1, 1, -1], [1, -1, -1], [-1, -1, -1]]) b_l1 = np.ones(8) h_l1_ball = mut.HPolyhedron.MakeL1Ball(dim=3) np.testing.assert_array_equal(A_l1, h_l1_ball.A()) np.testing.assert_array_equal(b_l1, h_l1_ball.b()) self.assertIsInstance( h_box.MaximumVolumeInscribedEllipsoid(), mut.Hyperellipsoid) np.testing.assert_array_almost_equal( h_box.ChebyshevCenter(), [0, 0, 0]) h_scaled = h_box.Scale(scale=2.0, center=[1, 2, 3]) self.assertIsInstance(h_scaled, mut.HPolyhedron) h_scaled = h_box.Scale(scale=2.0) self.assertIsInstance(h_scaled, mut.HPolyhedron) h2 = h_box.CartesianProduct(other=h_unit_box) self.assertIsInstance(h2, mut.HPolyhedron) self.assertEqual(h2.ambient_dimension(), 6) h3 = h_box.CartesianPower(n=3) self.assertIsInstance(h3, mut.HPolyhedron) self.assertEqual(h3.ambient_dimension(), 9) h4 = h_box.Intersection(other=h_unit_box) self.assertIsInstance(h4, mut.HPolyhedron) self.assertEqual(h4.ambient_dimension(), 3) h5 = h_box.PontryaginDifference(other=h_unit_box) self.assertIsInstance(h5, mut.HPolyhedron) np.testing.assert_array_equal(h5.A(), h_box.A()) np.testing.assert_array_equal(h5.b(), np.zeros(6)) generator = RandomGenerator() sample = h_box.UniformSample(generator=generator) self.assertEqual(sample.shape, (3,)) self.assertEqual( h_box.UniformSample(generator=generator, previous_sample=sample, mixing_steps=7).shape, (3, )) h_box.UniformSample(generator=generator, mixing_steps=7) h_half_box = mut.HPolyhedron.MakeBox( lb=[-0.5, -0.5, -0.5], ub=[0.5, 0.5, 0.5]) self.assertTrue(h_half_box.ContainedIn (other=h_unit_box, tol=1E-9)) h_half_box2 = h_half_box.Intersection( other=h_unit_box, check_for_redundancy=True, tol=1E-9) self.assertIsInstance(h_half_box2, mut.HPolyhedron) self.assertEqual(h_half_box2.ambient_dimension(), 3) np.testing.assert_array_almost_equal( h_half_box2.A(), h_half_box.A()) np.testing.assert_array_almost_equal( h_half_box2.b(), h_half_box.b()) # Intersection of 1/2*unit_box and unit_box and reducing the redundant # inequalities should result in the 1/2*unit_box. h_half_box_intersect_unit_box = h_half_box.Intersection( other=h_unit_box, check_for_redundancy=False) # Check that the ReduceInequalities binding works. redundant_indices = h_half_box_intersect_unit_box.FindRedundant( tol=1E-9) # Check FindRedundant with default tol. h_half_box_intersect_unit_box.FindRedundant() h_half_box3 = h_half_box_intersect_unit_box.ReduceInequalities( tol=1E-9) # Check SimplifyByIncrementalFaceTranslation binding with # default input parameters. h6 = h_box.SimplifyByIncrementalFaceTranslation( min_volume_ratio=0.1, do_affine_transformation=True, max_iterations=10, points_to_contain=np.empty((3, 0)), intersecting_polytopes=[], keep_whole_intersection=False, intersection_padding=0.1, random_seed=0) self.assertIsInstance(h6, mut.HPolyhedron) self.assertEqual(h6.ambient_dimension(), 3) # Check Simplify MaximumVolumeInscribedAffineTransformation binding # with default input parameters. h7 = h6.MaximumVolumeInscribedAffineTransformation( circumbody=h_box) self.assertIsInstance(h7, mut.HPolyhedron) self.assertEqual(h7.ambient_dimension(), 3) # This polyhedron is intentionally constructed to be an empty set. A_empty = np.vstack([np.eye(3), -np.eye(3)]) b_empty = -np.ones(6) h_empty = mut.HPolyhedron(A_empty, b_empty) self.assertTrue(h_empty.IsEmpty()) self.assertFalse(h_l1_ball.IsEmpty()) vpoly = mut.VPolytope(np.array( [[0., 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])) hpoly = mut.HPolyhedron(vpoly=vpoly) hpoly = mut.HPolyhedron(vpoly=vpoly, tol=1E-9) self.assertEqual(hpoly.ambient_dimension(), 3) self.assertEqual(hpoly.A().shape, (4, 3)) prog = MathematicalProgram() x = prog.NewContinuousVariables(1) prog.AddLinearConstraint(x[0] >= 0) hpoly = mut.HPolyhedron(prog=prog) self.assertEqual(hpoly.ambient_dimension(), 1) self.assertEqual(hpoly.A().shape, (1, 1)) def test_hyper_ellipsoid(self): mut.Hyperellipsoid() ellipsoid = mut.Hyperellipsoid(A=self.A, center=self.b) self.assertEqual(ellipsoid.ambient_dimension(), 3) self.assertFalse(ellipsoid.IsEmpty()) self.assertFalse(ellipsoid.MaybeGetFeasiblePoint() is None) self.assertTrue(ellipsoid.PointInSet( ellipsoid.MaybeGetFeasiblePoint())) np.testing.assert_array_equal(ellipsoid.A(), self.A) np.testing.assert_array_equal(ellipsoid.center(), self.b) self.assertTrue(ellipsoid.PointInSet(x=self.b, tol=0.0)) new_vars, new_constraints = ellipsoid.AddPointInSetConstraints( self.prog, self.x) self.assertEqual(new_vars.size, 0) self.assertGreater(len(new_constraints), 0) constraints = ellipsoid.AddPointInNonnegativeScalingConstraints( prog=self.prog, x=self.x, t=self.t) self.assertGreaterEqual(len(constraints), 2) self.assertIsInstance(constraints[0], Binding[Constraint]) constraints = ellipsoid.AddPointInNonnegativeScalingConstraints( prog=self.prog, A=self.Ay, b=self.by, c=self.cz, d=self.dz, x=self.y, t=self.z) self.assertGreaterEqual(len(constraints), 2) self.assertIsInstance(constraints[0], Binding[Constraint]) shape, pose = ellipsoid.ToShapeWithPose() self.assertIsInstance(shape, Ellipsoid) self.assertIsInstance(pose, RigidTransform) p = np.array([11.1, 12.2, 13.3]) point = mut.Point(p) scale, witness = ellipsoid.MinimumUniformScalingToTouch(point) self.assertTrue(scale > 0.0) np.testing.assert_array_almost_equal(witness, p) assert_pickle(self, ellipsoid, lambda S: np.vstack((S.A(), S.center()))) e_ball = mut.Hyperellipsoid.MakeAxisAligned( radius=[1, 1, 1], center=self.b) np.testing.assert_array_equal(e_ball.A(), self.A) np.testing.assert_array_equal(e_ball.center(), self.b) e_ball2 = mut.Hyperellipsoid.MakeHypersphere( radius=1, center=self.b) np.testing.assert_array_equal(e_ball2.A(), self.A) np.testing.assert_array_equal(e_ball2.center(), self.b) e_ball3 = mut.Hyperellipsoid.MakeUnitBall(dim=3) np.testing.assert_array_equal(e_ball3.A(), self.A) np.testing.assert_array_equal(e_ball3.center(), [0, 0, 0]) points = np.array([[1, 0], [-1, 0], [0, 2], [0, -2]]).T e_lowner_john = mut.Hyperellipsoid.MinimumVolumeCircumscribedEllipsoid( points=points, rank_tol=1e-2) e_lowner_john = mut.Hyperellipsoid.MinimumVolumeCircumscribedEllipsoid( points=points) mut.Hyperellipsoid(ellipsoid=mut.AffineBall.MakeUnitBall(dim=1)) def test_hyperrectangle(self): mut.Hyperrectangle() rect = mut.Hyperrectangle(lb=-self.b, ub=self.b) # Used for testing methods that require randomness. generator = RandomGenerator() # Methods inherited from ConvexSet self.assertEqual(rect.ambient_dimension(), self.b.shape[0]) self.assertTrue(rect.IntersectsWith(rect)) self.assertTrue(rect.IsBounded()) self.assertFalse(rect.IsEmpty()) self.assertTrue(rect.MaybeGetPoint() is None) point = rect.MaybeGetFeasiblePoint() self.assertTrue(point is not None) self.assertTrue(rect.PointInSet(x=point, tol=0.0)) new_vars, new_constraints = rect.AddPointInSetConstraints( self.prog, self.x) self.assertEqual(new_vars.size, 0) self.assertGreater(len(new_constraints), 0) constraints = rect.AddPointInNonnegativeScalingConstraints( prog=self.prog, x=self.x, t=self.t) self.assertGreaterEqual(len(constraints), 2) self.assertIsInstance(constraints[0], Binding[Constraint]) constraints = rect.AddPointInNonnegativeScalingConstraints( prog=self.prog, A=self.Ay, b=self.by, c=self.cz, d=self.dz, x=self.y, t=self.z) self.assertGreaterEqual(len(constraints), 2) self.assertIsInstance(constraints[0], Binding[Constraint]) shape, pose = rect.ToShapeWithPose() self.assertTrue(isinstance(shape, Box)) np.testing.assert_array_equal(pose.translation(), np.zeros_like(self.b)) test_point = np.ones_like(self.b) distance, projection = rect.Projection(points=test_point) self.assertEqual(distance[0], 0.0) np.testing.assert_array_equal(projection[:, 0], test_point) # Methods specific to Hyperrectangle np.testing.assert_array_equal(rect.lb(), -self.b) np.testing.assert_array_equal(rect.ub(), self.b) np.testing.assert_array_equal(rect.Center(), np.zeros_like(self.b)) sample = rect.UniformSample(generator=generator) self.assertEqual(sample.shape, (self.b.shape[0],)) hpoly = rect.MakeHPolyhedron() box = mut.HPolyhedron.MakeBox(rect.lb(), rect.ub()) np.testing.assert_array_equal(hpoly.A(), box.A()) np.testing.assert_array_equal(hpoly.b(), box.b()) assert_pickle(self, rect, lambda S: np.vstack((S.lb(), S.ub()))) rect2 = mut.Hyperrectangle(lb=-2*self.b, ub=0.5*self.b) intersection = rect.MaybeGetIntersection(rect2) np.testing.assert_array_equal(intersection.lb(), -self.b) np.testing.assert_array_equal(intersection.ub(), 0.5*self.b) other = mut.VPolytope(np.eye(2)) bbox = mut.Hyperrectangle.MaybeCalcAxisAlignedBoundingBox(set=other) self.assertIsInstance(bbox, mut.Hyperrectangle) def test_calc_volume_via_sampling(self): rect = mut.Hyperrectangle(lb=-self.b, ub=self.b) generator = RandomGenerator() desired_rel_accuracy = 1e-2 max_num_samples = 100 sampled_volume = rect.CalcVolumeViaSampling( generator=generator, desired_rel_accuracy=desired_rel_accuracy, max_num_samples=max_num_samples ) self.assertAlmostEqual(rect.CalcVolume(), sampled_volume.volume) self.assertGreaterEqual(sampled_volume.rel_accuracy, desired_rel_accuracy) self.assertEqual(sampled_volume.num_samples, max_num_samples) def test_minkowski_sum(self): mut.MinkowskiSum() point = mut.Point(np.array([11.1, 12.2, 13.3])) hpoly = mut.HPolyhedron(A=self.A, b=self.b) sum = mut.MinkowskiSum(setA=point, setB=hpoly) self.assertEqual(sum.ambient_dimension(), 3) self.assertEqual(sum.num_terms(), 2) sum2 = mut.MinkowskiSum(sets=[point, hpoly]) self.assertEqual(sum2.ambient_dimension(), 3) self.assertEqual(sum2.num_terms(), 2) self.assertIsInstance(sum2.term(0), mut.Point) self.assertFalse(sum.IsEmpty()) self.assertFalse(sum.MaybeGetFeasiblePoint() is None) self.assertTrue(sum.PointInSet(sum.MaybeGetFeasiblePoint())) def test_spectrahedron(self): s = mut.Spectrahedron() prog = MathematicalProgram() X = prog.NewSymmetricContinuousVariables(3) prog.AddPositiveSemidefiniteConstraint(X) prog.AddLinearEqualityConstraint(X[0, 0] + X[1, 1] + X[2, 2], 1) s = mut.Spectrahedron(prog=prog) self.assertEqual(s.ambient_dimension(), 6) self.assertFalse(s.IsEmpty()) self.assertFalse(s.MaybeGetFeasiblePoint() is None) self.assertTrue(s.PointInSet(s.MaybeGetFeasiblePoint())) def test_v_polytope(self): mut.VPolytope() vertices = np.array([[0.0, 1.0, 2.0], [3.0, 7.0, 5.0]]) vpoly = mut.VPolytope(vertices=vertices) self.assertFalse(vpoly.IsEmpty()) self.assertFalse(vpoly.MaybeGetFeasiblePoint() is None) self.assertTrue(vpoly.PointInSet(vpoly.MaybeGetFeasiblePoint())) self.assertEqual(vpoly.ambient_dimension(), 2) np.testing.assert_array_equal(vpoly.vertices(), vertices) self.assertTrue(vpoly.PointInSet(x=[1.0, 5.0], tol=1e-8)) new_vars, new_constraints = vpoly.AddPointInSetConstraints( self.prog, self.x[0:2]) self.assertEqual(new_vars.size, vertices.shape[1]) constraints = vpoly.AddPointInNonnegativeScalingConstraints( prog=self.prog, x=self.x[:2], t=self.t) self.assertGreaterEqual(len(constraints), 2) self.assertIsInstance(constraints[0], Binding[Constraint]) constraints = vpoly.AddPointInNonnegativeScalingConstraints( prog=self.prog, A=self.Ay[:2], b=self.by[:2], c=self.cz, d=self.dz, x=self.y, t=self.z) self.assertGreaterEqual(len(constraints), 2) self.assertIsInstance(constraints[0], Binding[Constraint]) assert_pickle(self, vpoly, lambda S: S.vertices()) v_box = mut.VPolytope.MakeBox( lb=[-1, -1, -1], ub=[1, 1, 1]) self.assertTrue(v_box.PointInSet([0, 0, 0])) self.assertAlmostEqual(v_box.CalcVolume(), 8, 1E-10) v_unit_box = mut.VPolytope.MakeUnitBox(dim=3) self.assertTrue(v_unit_box.PointInSet([0, 0, 0])) v_from_h = mut.VPolytope(H=mut.HPolyhedron.MakeUnitBox(dim=3)) self.assertTrue(v_from_h.PointInSet([0, 0, 0])) # Test creating a vpolytope from a non-minimal set of vertices # 2D: Random points inside a circle r = 2.0 n = 400 vertices = np.zeros((2, n + 4)) theta = np.linspace(0, 2 * np.pi, n, endpoint=False) vertices[0, 0:n] = r * np.cos(theta) vertices[1, 0:n] = r * np.sin(theta) vertices[:, n:] = np.array([ [r/2, r/3, r/4, r/5], [r/2, r/3, r/4, r/5] ]) vpoly = mut.VPolytope(vertices=vertices).GetMinimalRepresentation() self.assertAlmostEqual(vpoly.CalcVolume(), np.pi * r * r, delta=1e-3) self.assertEqual(vpoly.vertices().shape[1], n) # Calculate the length of the path that visits all the vertices # sequentially. # If the vertices are in clockwise/counter-clockwise order, # the length of the path will coincide with the perimeter of a # circle. self.assertAlmostEqual(self._calculate_path_length(vpoly.vertices()), 2 * np.pi * r, delta=1e-3) # 3D: Random points inside a box a = 2.0 vertices = np.array([ [0, a, 0, a, 0, a, 0, a, a/2, a/3, a/4, a/5], [0, 0, a, a, 0, 0, a, a, a/2, a/3, a/4, a/5], [0, 0, 0, 0, a, a, a, a, a/2, a/3, a/4, a/5] ]) vpoly = mut.VPolytope(vertices=vertices).GetMinimalRepresentation() self.assertAlmostEqual(vpoly.CalcVolume(), a * a * a) self.assertEqual(vpoly.vertices().shape[1], 8) temp_file_name = f"{temp_directory()}/vpoly.obj" vpoly.WriteObj(filename=temp_file_name) self.assertTrue(os.path.isfile(temp_file_name)) def _calculate_path_length(self, vertices): n = vertices.shape[1] length = 0 for i in range(n): j = (i + 1) % n diff = vertices[:, i] - vertices[:, j] length += np.sqrt(np.dot(diff, diff)) return length def test_cartesian_product(self): mut.CartesianProduct() point = mut.Point(np.array([11.1, 12.2, 13.3])) h_box = mut.HPolyhedron.MakeBox( lb=[-1, -1, -1], ub=[1, 1, 1]) sum = mut.CartesianProduct(setA=point, setB=h_box) self.assertFalse(sum.IsEmpty()) self.assertFalse(sum.MaybeGetFeasiblePoint() is None) self.assertTrue(sum.PointInSet(sum.MaybeGetFeasiblePoint())) self.assertEqual(sum.ambient_dimension(), 6) self.assertEqual(sum.num_factors(), 2) sum2 = mut.CartesianProduct(sets=[point, h_box]) self.assertEqual(sum2.ambient_dimension(), 6) self.assertEqual(sum2.num_factors(), 2) self.assertIsInstance(sum2.factor(0), mut.Point) sum2 = mut.CartesianProduct( sets=[point, h_box], A=np.eye(6, 3), b=[0, 1, 2, 3, 4, 5]) self.assertEqual(sum2.ambient_dimension(), 3) self.assertEqual(sum2.num_factors(), 2) self.assertIsInstance(sum2.factor(1), mut.HPolyhedron) def test_intersection(self): mut.Intersection() point = mut.Point(np.array([0.1, 0.2, 0.3])) h_box = mut.HPolyhedron.MakeBox( lb=[-1, -1, -1], ub=[1, 1, 1]) intersect = mut.Intersection(setA=point, setB=h_box) self.assertFalse(intersect.IsEmpty()) self.assertFalse(intersect.MaybeGetFeasiblePoint() is None) self.assertTrue(intersect.PointInSet( intersect.MaybeGetFeasiblePoint())) self.assertEqual(intersect.ambient_dimension(), 3) self.assertEqual(intersect.num_elements(), 2) intersect2 = mut.Intersection(sets=[point, h_box]) self.assertEqual(intersect2.ambient_dimension(), 3) self.assertEqual(intersect2.num_elements(), 2) self.assertIsInstance(intersect2.element(0), mut.Point) def test_make_from_scene_graph_and_iris(self): """ Tests the make from scene graph and iris functionality together as the Iris code makes obstacles from geometries registered in SceneGraph. """ scene_graph = SceneGraph() source_id = scene_graph.RegisterSource("source") frame_id = scene_graph.RegisterFrame( source_id=source_id, frame=GeometryFrame("frame")) box_geometry_id = scene_graph.RegisterGeometry( source_id=source_id, frame_id=frame_id, geometry=GeometryInstance(X_PG=RigidTransform(), shape=Box(1., 1., 1.), name="box")) cylinder_geometry_id = scene_graph.RegisterGeometry( source_id=source_id, frame_id=frame_id, geometry=GeometryInstance(X_PG=RigidTransform(), shape=Cylinder(1., 1.), name="cylinder")) sphere_geometry_id = scene_graph.RegisterGeometry( source_id=source_id, frame_id=frame_id, geometry=GeometryInstance(X_PG=RigidTransform(), shape=Sphere(1.), name="sphere")) capsule_geometry_id = scene_graph.RegisterGeometry( source_id=source_id, frame_id=frame_id, geometry=GeometryInstance(X_PG=RigidTransform(), shape=Capsule(1., 1.0), name="capsule")) for geometry_id in [box_geometry_id, cylinder_geometry_id, sphere_geometry_id, capsule_geometry_id]: scene_graph.AssignRole(source_id, geometry_id, properties=ProximityProperties()) context = scene_graph.CreateDefaultContext() pose_vector = FramePoseVector() pose_vector.set_value(frame_id, RigidTransform()) scene_graph.get_source_pose_port(source_id).FixValue( context, pose_vector) query_object = scene_graph.get_query_output_port().Eval(context) H = mut.HPolyhedron( query_object=query_object, geometry_id=box_geometry_id, reference_frame=scene_graph.world_frame_id()) self.assertEqual(H.ambient_dimension(), 3) C = mut.CartesianProduct( query_object=query_object, geometry_id=cylinder_geometry_id, reference_frame=scene_graph.world_frame_id()) self.assertEqual(C.ambient_dimension(), 3) E = mut.Hyperellipsoid( query_object=query_object, geometry_id=sphere_geometry_id, reference_frame=scene_graph.world_frame_id()) self.assertEqual(E.ambient_dimension(), 3) S = mut.MinkowskiSum( query_object=query_object, geometry_id=capsule_geometry_id, reference_frame=scene_graph.world_frame_id()) self.assertEqual(S.ambient_dimension(), 3) P = mut.Point( query_object=query_object, geometry_id=sphere_geometry_id, reference_frame=scene_graph.world_frame_id(), maximum_allowable_radius=1.5) self.assertEqual(P.ambient_dimension(), 3) V = mut.VPolytope( query_object=query_object, geometry_id=box_geometry_id, reference_frame=scene_graph.world_frame_id()) self.assertEqual(V.ambient_dimension(), 3) obstacles = mut.MakeIrisObstacles( query_object=query_object, reference_frame=scene_graph.world_frame_id()) self.assertGreater(len(obstacles), 0) for obstacle in obstacles: self.assertIsInstance(obstacle, mut.ConvexSet) options = mut.IrisOptions() options.require_sample_point_is_contained = True options.iteration_limit = 1 options.termination_threshold = 0.1 options.relative_termination_threshold = 0.01 options.random_seed = 1314 options.mixing_steps = 20 options.starting_ellipse = mut.Hyperellipsoid.MakeUnitBall(3) options.bounding_region = mut.HPolyhedron.MakeBox( lb=[-6, -6, -6], ub=[6, 6, 6]) options.solver_options = SolverOptions() self.assertNotIn("object at 0x", repr(options)) region = mut.Iris( obstacles=obstacles, sample=[2, 3.4, 5], domain=mut.HPolyhedron.MakeBox( lb=[-5, -5, -5], ub=[5, 5, 5]), options=options) self.assertIsInstance(region, mut.HPolyhedron) obstacles = [ mut.HPolyhedron.MakeUnitBox(3), mut.Hyperellipsoid.MakeUnitBall(3), mut.Point([0, 0, 0]), mut.VPolytope.MakeUnitBox(3)] region = mut.Iris( obstacles=obstacles, sample=[2, 3.4, 5], domain=mut.HPolyhedron.MakeBox( lb=[-5, -5, -5], ub=[5, 5, 5]), options=options) self.assertIsInstance(region, mut.HPolyhedron) def test_iris_cspace(self): limits_urdf = """ <robot name="limits"> <link name="movable"> <collision> <geometry><box size="1 1 1"/></geometry> </collision> </link> <joint name="movable" type="prismatic"> <axis xyz="1 0 0"/> <limit lower="-2" upper="2"/> <parent link="world"/> <child link="movable"/> </joint> </robot>""" builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0) Parser(plant).AddModelsFromString(limits_urdf, "urdf") plant.Finalize() diagram = builder.Build() context = diagram.CreateDefaultContext() options = mut.IrisOptions() options.num_collision_infeasible_samples = 3 ik = InverseKinematics(plant) options.prog_with_additional_constraints = ik.prog() options.num_additional_constraint_infeasible_samples = 2 plant.SetPositions(plant.GetMyMutableContextFromRoot(context), [0]) region = mut.IrisInConfigurationSpace( plant=plant, context=plant.GetMyContextFromRoot(context), options=options) self.assertIsInstance(region, mut.ConvexSet) self.assertEqual(region.ambient_dimension(), 1) self.assertTrue(region.PointInSet([1.0])) self.assertFalse(region.PointInSet([3.0])) options.configuration_obstacles = [mut.Point([-0.5])] point, = options.configuration_obstacles self.assertEqual(point.x(), [-0.5]) point2, = options.configuration_obstacles self.assertIs(point2, point) region = mut.IrisInConfigurationSpace( plant=plant, context=plant.GetMyContextFromRoot(context), options=options) self.assertIsInstance(region, mut.ConvexSet) self.assertEqual(region.ambient_dimension(), 1) self.assertTrue(region.PointInSet([1.0])) self.assertFalse(region.PointInSet([-1.0])) def test_serialize_iris_regions(self): iris_regions = { "box1": mut.HPolyhedron.MakeBox(lb=[-1, -2, -3], ub=[1, 2, 3]), "box2": mut.HPolyhedron.MakeBox(lb=[-4.1, -5.2, -6.3], ub=[4.1, 4.2, 6.3]) } temp_file_name = f"{temp_directory()}/iris.yaml" mut.SaveIrisRegionsYamlFile(filename=temp_file_name, regions=iris_regions, child_name="test") loaded_regions = mut.LoadIrisRegionsYamlFile(filename=temp_file_name, child_name="test") self.assertEqual(iris_regions.keys(), loaded_regions.keys()) for k in iris_regions.keys(): np.testing.assert_array_equal(iris_regions[k].A(), loaded_regions[k].A()) np.testing.assert_array_equal(iris_regions[k].b(), loaded_regions[k].b()) def test_graph_of_convex_sets(self): options = mut.GraphOfConvexSetsOptions() kMIP = mut.GraphOfConvexSets.Transcription.kMIP kRelaxation = mut.GraphOfConvexSets.Transcription.kRelaxation kRestriction = mut.GraphOfConvexSets.Transcription.kRestriction self.assertIsNone(options.convex_relaxation) self.assertIsNone(options.preprocessing) self.assertIsNone(options.max_rounded_paths) options.convex_relaxation = True options.preprocessing = False options.max_rounded_paths = 0 options.max_rounding_trials = 5 options.flow_tolerance = 1e-6 options.rounding_seed = 1 options.solver = ClpSolver() options.restriction_solver = ClpSolver() options.solver_options = SolverOptions() options.solver_options.SetOption(ClpSolver.id(), "scaling", 2) options.restriction_solver_options = SolverOptions() options.restriction_solver_options.SetOption(ClpSolver.id(), "dual", 0) self.assertIn("scaling", options.solver_options.GetOptions(ClpSolver.id())) self.assertIn("dual", options.restriction_solver_options.GetOptions( ClpSolver.id())) self.assertIn("convex_relaxation", repr(options)) spp = mut.GraphOfConvexSets() source = spp.AddVertex(set=mut.Point([0.1]), name="source") target = spp.AddVertex(set=mut.Point([0.2]), name="target") edge0 = spp.AddEdge(u=source, v=target, name="edge0") edge1 = spp.AddEdge(u=source, v=target, name="edge1") self.assertEqual(len(spp.Vertices()), 2) self.assertEqual(len(spp.Edges()), 2) result = spp.SolveShortestPath( source=source, target=target, options=options) self.assertIsInstance(result, MathematicalProgramResult) self.assertIsInstance(spp.SolveShortestPath( source=source, target=target, options=options), MathematicalProgramResult) self.assertIsInstance( spp.SolveConvexRestriction(active_edges=[edge0, edge1], options=options), MathematicalProgramResult) self.assertEqual( len( spp.GetSolutionPath(source=source, target=target, result=result, tolerance=0.1)), 1) self.assertIn("source", spp.GetGraphvizString( result=result, show_slacks=True, precision=2, scientific=False)) # Vertex self.assertAlmostEqual( source.GetSolutionCost(result=result), 0.0, 1e-6) np.testing.assert_array_almost_equal( source.GetSolution(result), [0.1], 1e-6) self.assertIsInstance(source.id(), mut.GraphOfConvexSets.VertexId) self.assertEqual(source.ambient_dimension(), 1) self.assertEqual(source.name(), "source") self.assertIsInstance(source.x()[0], Variable) self.assertIsInstance(source.set(), mut.Point) var, binding = source.AddCost(e=1.0+source.x()[0]) self.assertIsInstance(var, Variable) self.assertIsInstance(binding, Binding[Cost]) var, binding = source.AddCost(binding=binding) self.assertIsInstance(var, Variable) self.assertIsInstance(binding, Binding[Cost]) self.assertEqual(len(source.GetCosts()), 2) binding = source.AddConstraint(f=(source.x()[0] <= 1.0)) self.assertIsInstance(binding, Binding[Constraint]) binding = source.AddConstraint( binding=binding, use_in_transcription={kMIP, kRelaxation, kRestriction}) self.assertIsInstance(binding, Binding[Constraint]) binding = source.AddConstraint( f=(source.x()[0] <= 1.0), use_in_transcription={kMIP}) self.assertIsInstance(binding, Binding[Constraint]) binding = source.AddConstraint( binding=binding, use_in_transcription={kMIP}) self.assertIsInstance(binding, Binding[Constraint]) binding = source.AddConstraint( f=(source.x()[0] <= 1.0), use_in_transcription={kRelaxation}) self.assertIsInstance(binding, Binding[Constraint]) binding = source.AddConstraint( binding=binding, use_in_transcription={kRelaxation}) self.assertIsInstance(binding, Binding[Constraint]) binding = source.AddConstraint( f=(source.x()[0] <= 1.0), use_in_transcription={kRestriction}) self.assertIsInstance(binding, Binding[Constraint]) binding = source.AddConstraint( binding=binding, use_in_transcription={kRestriction}) self.assertIsInstance(binding, Binding[Constraint]) self.assertEqual( len(source.GetConstraints(used_in_transcription={kMIP})), len(source.GetConstraints(used_in_transcription={kRelaxation})) ) self.assertEqual( len(source.GetConstraints(used_in_transcription={kRelaxation})), len(source.GetConstraints(used_in_transcription={kRestriction})) ) self.assertNotEqual( len(source.GetConstraints(used_in_transcription={kRestriction})), len(source.GetConstraints()) ) self.assertEqual(len(source.incoming_edges()), 0) self.assertEqual(len(source.outgoing_edges()), 2) self.assertEqual(len(target.incoming_edges()), 2) self.assertEqual(len(target.outgoing_edges()), 0) # Edge self.assertAlmostEqual(edge0.GetSolutionCost(result=result), 0.0, 1e-6) np.testing.assert_array_almost_equal( edge0.GetSolutionPhiXu(result=result), [0.1], 1e-6) np.testing.assert_array_almost_equal( edge0.GetSolutionPhiXv(result=result), [0.2], 1e-6) self.assertIsInstance(edge0.id(), mut.GraphOfConvexSets.EdgeId) self.assertEqual(edge0.name(), "edge0") self.assertEqual(edge0.u(), source) self.assertEqual(edge0.v(), target) self.assertIsInstance(edge0.phi(), Variable) self.assertIsInstance(edge0.xu()[0], Variable) self.assertIsInstance(edge0.xv()[0], Variable) var, binding = edge0.AddCost(e=1.0+edge0.xu()[0]) self.assertIsInstance(var, Variable) self.assertIsInstance(binding, Binding[Cost]) var, binding = edge0.AddCost(binding=binding) self.assertIsInstance(var, Variable) self.assertIsInstance(binding, Binding[Cost]) self.assertEqual(len(edge0.GetCosts()), 2) binding = edge0.AddConstraint(f=(edge0.xu()[0] == edge0.xv()[0])) self.assertIsInstance(binding, Binding[Constraint]) binding = edge0.AddConstraint( binding=binding, use_in_transcription={kMIP, kRelaxation, kRestriction}) self.assertIsInstance(binding, Binding[Constraint]) binding = edge0.AddConstraint( f=(edge0.xu()[0] == edge0.xv()[0]), use_in_transcription={kMIP}) self.assertIsInstance(binding, Binding[Constraint]) binding = edge0.AddConstraint( binding=binding, use_in_transcription={kMIP}) self.assertIsInstance(binding, Binding[Constraint]) binding = edge0.AddConstraint( f=(edge0.xu()[0] == edge0.xv()[0]), use_in_transcription={kRelaxation}) self.assertIsInstance(binding, Binding[Constraint]) binding = edge0.AddConstraint( binding=binding, use_in_transcription={kRelaxation}) self.assertIsInstance(binding, Binding[Constraint]) binding = edge0.AddConstraint( f=(edge0.xu()[0] == edge0.xv()[0]), use_in_transcription={kRestriction}) self.assertIsInstance(binding, Binding[Constraint]) binding = edge0.AddConstraint( binding=binding, use_in_transcription={kRestriction}) self.assertIsInstance(binding, Binding[Constraint]) self.assertEqual( len(edge0.GetConstraints(used_in_transcription={kMIP})), len(edge0.GetConstraints(used_in_transcription={kRelaxation})) ) self.assertEqual( len(edge0.GetConstraints(used_in_transcription={kRelaxation})), len(edge0.GetConstraints(used_in_transcription={kRestriction})) ) self.assertNotEqual( len(edge0.GetConstraints(used_in_transcription={kRestriction})), len(edge0.GetConstraints()) ) edge0.AddPhiConstraint(phi_value=False) edge0.ClearPhiConstraints() edge1.AddPhiConstraint(phi_value=True) spp.ClearAllPhiConstraints() # Remove Edges self.assertEqual(len(spp.Edges()), 2) spp.RemoveEdge(edge0) self.assertEqual(len(spp.Edges()), 1) spp.RemoveEdge(edge1) self.assertEqual(len(spp.Edges()), 0) # Remove Vertices self.assertEqual(len(spp.Vertices()), 2) spp.RemoveVertex(source) self.assertEqual(len(spp.Vertices()), 1) spp.RemoveVertex(target) self.assertEqual(len(spp.Vertices()), 0) class TestCspaceFreePolytope(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) limits_urdf = """ <robot name="limits"> <link name="movable"> <collision> <geometry><box size="0.1 0.1 0.1"/></geometry> </collision> </link> <link name="unmovable"> <collision> <geometry><box size="1 1 1"/></geometry> </collision> </link> <joint name="movable" type="prismatic"> <axis xyz="1 0 0"/> <limit lower="-2" upper="2"/> <parent link="world"/> <child link="movable"/> </joint> <joint name="unmovable" type = "fixed"> <parent link="world"/> <child link="unmovable"/> <origin xyz="1 0 0"/> </joint> </robot>""" builder = DiagramBuilder() self.plant, self.scene_graph = AddMultibodyPlantSceneGraph( builder, 0.01) Parser(self.plant).AddModelsFromString(limits_urdf, "urdf") self.plant.Finalize() diagram = builder.Build() # Tests the constructor options = mut.CspaceFreePolytope.Options() options.with_cross_y = False self.cspace_free_polytope = mut.CspaceFreePolytope( plant=self.plant, scene_graph=self.scene_graph, plane_order=mut.SeparatingPlaneOrder.kAffine, q_star=np.zeros(self.plant.num_positions()), options=options) def test_CspaceFreePolytope_SeparatingPlaneOrder(self): # Access the separating plane orders. possible_orders = [mut.SeparatingPlaneOrder.kAffine] self.assertEqual(len(possible_orders), 1) def test_CspaceFreePolytope_Options(self): dut = mut.CspaceFreePolytope solver_options = SolverOptions() solver_options.SetOption(CommonSolverOption.kPrintToConsole, 1) # FindSeparationCertificateOptions find_separation_options = mut.FindSeparationCertificateOptions() find_separation_options.parallelism = False find_separation_options.verbose = True find_separation_options.solver_id = ScsSolver.id() find_separation_options.terminate_at_failure = False find_separation_options.solver_options = solver_options self.assertEqual(find_separation_options.parallelism.num_threads(), 1) self.assertTrue(find_separation_options.verbose) self.assertEqual(find_separation_options.solver_id, ScsSolver.id()) self.assertFalse(find_separation_options.terminate_at_failure) self.assertEqual( find_separation_options.solver_options.common_solver_options()[ CommonSolverOption.kPrintToConsole], 1) # FindSeparationCertificateGivenPolytopeOptions lagrangian_options = \ dut.FindSeparationCertificateGivenPolytopeOptions() self.assertIsInstance( lagrangian_options.parallelism.num_threads(), int) self.assertFalse( lagrangian_options.verbose) self.assertEqual( lagrangian_options.solver_id, MosekSolver.id()) self.assertTrue( lagrangian_options.terminate_at_failure) self.assertIsNone( lagrangian_options.solver_options) self.assertFalse( lagrangian_options.ignore_redundant_C) lagrangian_options.parallelism = False lagrangian_options.verbose = True lagrangian_options.solver_id = ScsSolver.id() lagrangian_options.terminate_at_failure = False lagrangian_options.solver_options = solver_options lagrangian_options.ignore_redundant_C = True self.assertEqual(lagrangian_options.parallelism.num_threads(), 1) self.assertTrue( lagrangian_options.verbose) self.assertEqual( lagrangian_options.solver_id, ScsSolver.id()) self.assertFalse( lagrangian_options.terminate_at_failure) self.assertEqual( lagrangian_options.solver_options.common_solver_options()[ CommonSolverOption.kPrintToConsole], 1) self.assertTrue( lagrangian_options.ignore_redundant_C) # EllipsoidMarginCost margin_cost = [dut.EllipsoidMarginCost.kGeometricMean, dut.EllipsoidMarginCost.kSum] # FindPolytopeGivenLagrangianOptions polytope_options = dut.FindPolytopeGivenLagrangianOptions() self.assertIsNone(polytope_options.backoff_scale) self.assertEqual( polytope_options.ellipsoid_margin_epsilon, 1e-5) self.assertEqual( polytope_options.solver_id, MosekSolver.id()) self.assertIsNone(polytope_options.solver_options) self.assertIsNone(polytope_options.s_inner_pts) self.assertTrue( polytope_options.search_s_bounds_lagrangians) self.assertEqual( polytope_options.ellipsoid_margin_cost, dut.EllipsoidMarginCost.kGeometricMean) polytope_options.backoff_scale = 1e-3 polytope_options.ellipsoid_margin_epsilon = 1e-6 polytope_options.solver_id = ScsSolver.id() polytope_options.solver_options = solver_options polytope_options.s_inner_pts = np.zeros((2, 1)) polytope_options.search_s_bounds_lagrangians = False polytope_options.ellipsoid_margin_cost = dut.EllipsoidMarginCost.kSum self.assertEqual( polytope_options.backoff_scale, 1e-3) self.assertEqual( polytope_options.ellipsoid_margin_epsilon, 1e-6) self.assertEqual( polytope_options.solver_id, ScsSolver.id()) self.assertEqual( polytope_options.solver_options.common_solver_options()[ CommonSolverOption.kPrintToConsole], 1) np.testing.assert_array_almost_equal( polytope_options.s_inner_pts, np.zeros( (2, 1)), 1e-5) self.assertFalse( polytope_options.search_s_bounds_lagrangians) self.assertEqual( polytope_options.ellipsoid_margin_cost, dut.EllipsoidMarginCost.kSum) # BilinearAlternationOptions bilinear_alternation_options = dut.BilinearAlternationOptions() self.assertEqual(bilinear_alternation_options.max_iter, 10) self.assertAlmostEqual(bilinear_alternation_options.convergence_tol, 1e-3) self.assertAlmostEqual(bilinear_alternation_options.ellipsoid_scaling, 0.99) self.assertTrue(bilinear_alternation_options. find_polytope_options.search_s_bounds_lagrangians) self.assertFalse( bilinear_alternation_options.find_lagrangian_options.verbose) bilinear_alternation_options.max_iter = 4 bilinear_alternation_options.convergence_tol = 1e-2 bilinear_alternation_options.find_polytope_options = polytope_options bilinear_alternation_options.find_lagrangian_options.verbose = \ True bilinear_alternation_options.ellipsoid_scaling = 0.5 self.assertEqual(bilinear_alternation_options.max_iter, 4) self.assertAlmostEqual(bilinear_alternation_options.convergence_tol, 1e-2) self.assertAlmostEqual(bilinear_alternation_options.ellipsoid_scaling, 0.5) self.assertFalse(bilinear_alternation_options. find_polytope_options.search_s_bounds_lagrangians) self.assertTrue(bilinear_alternation_options. find_lagrangian_options.verbose) # BinarySearchOptions binary_search_options = dut.BinarySearchOptions() self.assertAlmostEqual(binary_search_options.scale_max, 1) self.assertAlmostEqual(binary_search_options.scale_min, 0.01) self.assertEqual(binary_search_options.max_iter, 10) self.assertAlmostEqual( binary_search_options.convergence_tol, 1e-3) self.assertFalse( binary_search_options.find_lagrangian_options.verbose) binary_search_options.scale_max = 2 binary_search_options.scale_min = 1 binary_search_options.max_iter = 2 binary_search_options.convergence_tol = 1e-5 binary_search_options.find_lagrangian_options.verbose = True self.assertAlmostEqual(binary_search_options.scale_max, 2) self.assertAlmostEqual(binary_search_options.scale_min, 1) self.assertEqual(binary_search_options.max_iter, 2) self.assertAlmostEqual( binary_search_options.convergence_tol, 1e-5) self.assertTrue( binary_search_options.find_lagrangian_options.verbose) options = dut.Options() self.assertFalse(options.with_cross_y) options.with_cross_y = True self.assertTrue(options.with_cross_y) self.assertIn("with_cross_y", repr(options)) self.assertNotIn("object at 0x", repr(options)) def test_CspaceFreePolytope_getters_and_auxillary_structs(self): dut = self.cspace_free_polytope # TODO(Alexandre.Amice): Insert the suggested test from #20025 once the # issue is resolved. self.assertGreaterEqual( len(dut.map_geometries_to_separating_planes().keys()), 1) self.assertGreaterEqual( len(dut.separating_planes()), 1) self.assertEqual(len(dut.y_slack()), 3) # Test all bindings of objects in c_iris_collision_geometry.h/cc, # cspace_separating_plane.h/cc, cspace_free_structs.h/cc. # Many of these objects require an instantiation of # CspaceFreePolytopeBase (either CspaceFreePolytope or CspaceFreeBox) # to access which is why they are tested here. # Test CSpaceSeparatingPlane and CIrisCollisionGeometry geom_type_possible_values = [ mut.CIrisGeometryType.kPolytope, mut.CIrisGeometryType.kSphere, mut.CIrisGeometryType.kCylinder, mut.CIrisGeometryType.kCapsule] geom_shape_possible_values = [ Capsule, Sphere, Cylinder, Box, Convex ] for plane_idx in dut.map_geometries_to_separating_planes().values(): plane = dut.separating_planes()[plane_idx] self.assertIsInstance(plane.a[0], Polynomial) self.assertIsInstance(plane.b, Polynomial) self.assertIsInstance(plane.expressed_body, BodyIndex) self.assertEqual(plane.plane_degree, 1) self.assertIsInstance(plane.decision_variables[0], Variable) for geom in [plane.positive_side_geometry, plane.negative_side_geometry]: self.assertIn(geom.type(), geom_type_possible_values) self.assertIn( type( geom.geometry()), geom_shape_possible_values) self.assertIsInstance(geom.body_index(), BodyIndex) self.assertGreater(geom.num_rationals(), 0) self.assertIsInstance(geom.X_BG(), RigidTransform) self.assertIsInstance(geom.id(), GeometryId) # SeparationCertificateProgramBase, SeparationCertificateResultBase are # not tested as they cannot be instantiated. They are bound only to # provide subclassing to other bindings. The class # FindSeparationCertificateOptions is tested in # test_CspaceFreePolytope_Options along with all the other options. @unittest.skipUnless(MosekSolver().available(), "Requires Mosek") def test_CspaceFreePolytopeMethods(self): # These tests take very long using any solver besides Mosek so only run # them if Mosek is available. mosek_solver = MosekSolver() C_init = np.vstack([np.atleast_2d(np.eye(self.plant.num_positions( ))), -np.atleast_2d(np.eye(self.plant.num_positions()))]) d_init = 1e-3 * np.ones((C_init.shape[0], 1)) lagrangian_options = \ mut.CspaceFreePolytope.\ FindSeparationCertificateGivenPolytopeOptions() binary_search_options = \ mut.CspaceFreePolytope.BinarySearchOptions() binary_search_options.scale_min = 1e-2 binary_search_options.scale_max = 1e7 binary_search_options.max_iter = 2 bilinear_alternation_options = \ mut.CspaceFreePolytope.BilinearAlternationOptions() bilinear_alternation_options.max_iter = 2 (success, certificates) = self.cspace_free_polytope.\ FindSeparationCertificateGivenPolytope( C=C_init, d=d_init, ignored_collision_pairs=set(), options=lagrangian_options) self.assertTrue(success) geom_pair = list(self.cspace_free_polytope. map_geometries_to_separating_planes().keys())[0] self.assertIn(geom_pair, certificates.keys()) self.assertIsInstance( certificates[geom_pair], mut.CspaceFreePolytope.SeparationCertificateResult) result = self.cspace_free_polytope.BinarySearch( ignored_collision_pairs=set(), C=C_init, d=d_init, s_center=np.zeros(self.plant.num_positions()), options=binary_search_options ) # Accesses all members of SearchResult. self.assertGreaterEqual(result.num_iter(), 1) self.assertGreaterEqual(len(result.C()), 1) self.assertGreaterEqual(len(result.d()), 1) self.assertIsInstance(result.certified_polytope(), mut.HPolyhedron) self.assertEqual(len(result.a()), 1) self.assertEqual(len(result.b()), 1) self.assertIsInstance(result.a()[0][0], Polynomial) result = self.cspace_free_polytope.SearchWithBilinearAlternation( ignored_collision_pairs=set(), C_init=C_init, d_init=d_init, options=bilinear_alternation_options) self.assertIsNotNone(result) self.assertGreaterEqual(len(result), 1) self.assertIsInstance(result[0], mut.CspaceFreePolytope.SearchResult) # Make and Solve GeometrySeparableProgram. pair = list(self.cspace_free_polytope. map_geometries_to_separating_planes().keys())[0] cert_prog = \ self.cspace_free_polytope.MakeIsGeometrySeparableProgram( geometry_pair=pair, C=C_init, d=d_init) # Call all CspaceFreePolytope.SeparationCertificateProgram methods. certificates = cert_prog.certificate self.assertIsInstance(certificates, mut.CspaceFreePolytope.SeparationCertificate) self.assertIsInstance(cert_prog.prog(), MathematicalProgram) self.assertGreaterEqual(cert_prog.plane_index, 0) self.assertIsInstance( certificates.positive_side_rational_lagrangians[0], mut.CspaceFreePolytope.SeparatingPlaneLagrangians) self.assertIsInstance( certificates.negative_side_rational_lagrangians[0], mut.CspaceFreePolytope.SeparatingPlaneLagrangians) cert_prog_sol = \ self.cspace_free_polytope.SolveSeparationCertificateProgram( certificate_program=cert_prog, options=lagrangian_options) # Call all CspaceFreePolytope.SeparationCertificateResult # methods. self.assertEqual(cert_prog_sol.a.shape, (3,)) self.assertIsInstance(cert_prog_sol.a[0], Polynomial) self.assertIsInstance(cert_prog_sol.b, Polynomial) self.assertIsInstance( cert_prog_sol.plane_decision_var_vals[0], float) self.assertIsInstance( cert_prog_sol.result, MathematicalProgramResult) # Bindings for SeparatingPlaneLagrangians. positive_side_lagrangians = \ cert_prog_sol.positive_side_rational_lagrangians positive_test_lagrangian = positive_side_lagrangians[0] negative_side_lagrangians = \ cert_prog_sol.negative_side_rational_lagrangians negative_test_lagrangian = negative_side_lagrangians[0] positive_test_lagrangian.GetSolution(cert_prog_sol.result) negative_test_lagrangian.GetSolution(cert_prog_sol.result) self.assertEqual(len(positive_test_lagrangian.polytope()), C_init.shape[0]) self.assertEqual(len(positive_test_lagrangian.s_lower()), 1) self.assertEqual(len(positive_test_lagrangian.s_upper()), 1) self.assertEqual(len(negative_test_lagrangian.polytope()), C_init.shape[0]) self.assertEqual(len(negative_test_lagrangian.s_lower()), 1) self.assertEqual(len(negative_test_lagrangian.s_upper()), 1) def test_partition_convex_set(self): big_convex_set = mut.VPolytope(np.array([[0, 4]])) out = mut.PartitionConvexSet(big_convex_set, [0]) self.assertEqual(len(out), 2) self.assertTrue(isinstance(out[0], mut.ConvexSet)) mut.PartitionConvexSet(big_convex_set, [0], 1e-5) mut.PartitionConvexSet(convex_set=big_convex_set, continuous_revolute_joints=[0], epsilon=1e-5) mut.PartitionConvexSet([big_convex_set], [0]) mut.PartitionConvexSet([big_convex_set], [0], 1e-5) mut.PartitionConvexSet(convex_sets=[big_convex_set], continuous_revolute_joints=[0], epsilon=1e-5) mut.CheckIfSatisfiesConvexityRadius(convex_set=big_convex_set, continuous_revolute_joints=[0]) def test_calc_pairwise_intersections(self): sets_A = [mut.VPolytope(np.array([[0, 4]])), mut.VPolytope(np.array([[2, 6]]))] sets_B = [mut.VPolytope(np.array([[1, 5]]) - (2 * np.pi))] out = mut.CalcPairwiseIntersections(convex_sets_A=sets_A, convex_sets_B=sets_B, continuous_revolute_joints=[0]) self.assertIsInstance(out, list) self.assertEqual(len(out), 2) self.assertIsInstance(out[0], tuple) out2 = mut.CalcPairwiseIntersections(convex_sets=sets_A, continuous_revolute_joints=[0]) self.assertIsInstance(out, list) self.assertEqual(len(out), 2) self.assertIsInstance(out[0], tuple)
0
/home/johnshepherd/drake/bindings/pydrake/geometry
/home/johnshepherd/drake/bindings/pydrake/geometry/test/render_engine_gl_test.py
import pydrake.geometry as mut import sys import unittest from pydrake.common.test_utilities import numpy_compare class TestGeometry(unittest.TestCase): @numpy_compare.check_nonsymbolic_types def test_render_engine_gl_api(self, T): SceneGraph = mut.SceneGraph_[T] scene_graph = SceneGraph() params = mut.RenderEngineGlParams() if 'darwin' in sys.platform: # OpenGL is not supported on macOS. self.assertRaises(RuntimeError, mut.MakeRenderEngineGl) else: scene_graph.AddRenderer("gl_renderer", mut.MakeRenderEngineGl(params=params)) self.assertTrue(scene_graph.HasRenderer("gl_renderer")) self.assertEqual(scene_graph.RendererCount(), 1)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/math/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_library", ) load( "//tools/skylark:drake_py.bzl", "drake_py_binary", "drake_py_library", "drake_py_unittest", ) load( "//tools/skylark:pybind.bzl", "EXTRA_PYBIND_COPTS", "get_pybind_package_info", ) package(default_visibility = ["//visibility:private"]) # This determines how `PYTHONPATH` is configured, and how to install the # bindings. PACKAGE_INFO = get_pybind_package_info("//bindings") # N.B. The `pydrake.math` module is part of the root module dependency cycle. # Refer to bindings/pydrake/common/module_cycle.md for details. drake_cc_library( name = "math_py", srcs = [ "math_py_matmul.cc", "math_py_operators.cc", # TODO(jwnimmer-tri) Split the monolith into pieces. "math_py_monolith.cc", ], hdrs = [ "math_py.h", ], copts = EXTRA_PYBIND_COPTS, declare_installed_headers = False, visibility = [ "//bindings/pydrake/common:__pkg__", ], deps = [ "//bindings/pydrake:autodiff_types_pybind", "//bindings/pydrake:documentation_pybind", "//bindings/pydrake:math_operators_pybind", "//bindings/pydrake:symbolic_types_pybind", "//bindings/pydrake/common:cpp_template_pybind", "//bindings/pydrake/common:default_scalars_pybind", "//bindings/pydrake/common:eigen_pybind", "//bindings/pydrake/common:type_pack", "//bindings/pydrake/common:value_pybind", ], ) drake_py_library( name = "math_extra", srcs = ["_math_extra.py"], visibility = [ "//bindings/pydrake/common:__pkg__", ], ) install( name = "install", targets = [":math_extra"], py_dest = PACKAGE_INFO.py_dest, visibility = ["//bindings/pydrake:__pkg__"], ) drake_py_binary( name = "math_example", srcs = ["math_example.py"], add_test_rule = True, isolate = True, deps = [ "//bindings/pydrake:module_py", ], ) drake_py_unittest( name = "math_test", deps = [ "//bindings/pydrake:module_py", "//bindings/pydrake/common/test_utilities", ], ) drake_py_unittest( name = "math_overloads_test", deps = [ "//bindings/pydrake:module_py", ], ) drake_py_unittest( name = "math_overloads_matrix_test", deps = [ "//bindings/pydrake:module_py", "//bindings/pydrake/common/test_utilities:meta_py", "//bindings/pydrake/common/test_utilities:numpy_compare_py", ], ) add_lint_tests_pydrake()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/math/math_py.h
#pragma once /* This file declares the functions that bind the drake::math namespace. These functions form a complete partition of the drake::math bindings. The implementations of these functions are parceled out into various *.cc files as indicated in each function's documentation. TODO(jwnimmer-tri) At the moment there is no parceling, just one obnoxiously large file. We should work to split it up. */ #include "drake/bindings/pydrake/pydrake_pybind.h" namespace drake { namespace pydrake { namespace internal { /* Binds a native C++ matmul(A, B) for wide variety of scalar types. This is important for performance until numpy allows us to define dtype-specific implementations. Doing a matmul elementwise with a C++ <=> Python call for every flop is extraordinarily slow. */ void DefineMathMatmul(py::module m); /* Defines bindings per math_py_monolith.cc. */ void DefineMathMonolith(py::module m); /* Defines bindings per math_py_operators.cc. */ void DefineMathOperators(py::module m); } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/math/math_py_operators.cc
#include "drake/bindings/pydrake/autodiff_types_pybind.h" #include "drake/bindings/pydrake/math_operators_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/bindings/pydrake/symbolic_types_pybind.h" namespace drake { namespace pydrake { namespace internal { void DefineMathOperators(py::module m) { // Define math operations for all three scalar types. pydrake::internal::BindMathOperators<double>(&m); pydrake::internal::BindMathOperators<AutoDiffXd>(&m); pydrake::internal::BindMathOperators<symbolic::Expression>(&m); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/math/math_py_monolith.cc
#include <cmath> #include "drake/bindings/pydrake/autodiff_types_pybind.h" #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/documentation_pybind.h" #include "drake/bindings/pydrake/math/math_py.h" #include "drake/bindings/pydrake/math_operators_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/bindings/pydrake/symbolic_types_pybind.h" #include "drake/common/fmt_ostream.h" #include "drake/math/barycentric.h" #include "drake/math/bspline_basis.h" #include "drake/math/compute_numerical_gradient.h" #include "drake/math/continuous_algebraic_riccati_equation.h" #include "drake/math/continuous_lyapunov_equation.h" #include "drake/math/cross_product.h" #include "drake/math/discrete_algebraic_riccati_equation.h" #include "drake/math/discrete_lyapunov_equation.h" #include "drake/math/matrix_util.h" #include "drake/math/quadratic_form.h" #include "drake/math/quaternion.h" #include "drake/math/random_rotation.h" #include "drake/math/rigid_transform.h" #include "drake/math/roll_pitch_yaw.h" #include "drake/math/rotation_matrix.h" #include "drake/math/soft_min_max.h" #include "drake/math/wrap_to.h" namespace drake { namespace pydrake { namespace internal { using symbolic::Expression; using symbolic::Monomial; using symbolic::Variable; namespace { template <typename T> void DoScalarDependentDefinitions(py::module m, T) { py::tuple param = GetPyParam<T>(); // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::math; constexpr auto& doc = pydrake_doc.drake.math; // N.B. Some classes define `__repr__` in `_math_extra.py`. { using Class = RigidTransform<T>; constexpr auto& cls_doc = doc.RigidTransform; auto cls = DefineTemplateClassWithDefault<Class>( m, "RigidTransform", param, 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 RotationMatrix<T>&, const Vector3<T>&>(), py::arg("R"), py::arg("p"), cls_doc.ctor.doc_2args_R_p) .def(py::init<const RollPitchYaw<T>&, const Vector3<T>&>(), py::arg("rpy"), py::arg("p"), cls_doc.ctor.doc_2args_rpy_p) .def(py::init<const Eigen::Quaternion<T>&, const Vector3<T>&>(), py::arg("quaternion"), py::arg("p"), cls_doc.ctor.doc_2args_quaternion_p) .def(py::init<const Eigen::AngleAxis<T>&, const Vector3<T>&>(), py::arg("theta_lambda"), py::arg("p"), cls_doc.ctor.doc_2args_theta_lambda_p) .def(py::init<const RotationMatrix<T>&>(), py::arg("R"), cls_doc.ctor.doc_1args_R) .def(py::init<const Vector3<T>&>(), py::arg("p"), cls_doc.ctor.doc_1args_p) .def(py::init<const Isometry3<T>&>(), py::arg("pose"), cls_doc.ctor.doc_1args_pose) .def(py::init<const MatrixX<T>&>(), py::arg("pose"), cls_doc.ctor.doc_1args_constEigenMatrixBase) .def_static("MakeUnchecked", &Class::MakeUnchecked, py::arg("pose"), cls_doc.MakeUnchecked.doc) .def("set", &Class::set, py::arg("R"), py::arg("p"), cls_doc.set.doc) .def("SetFromIsometry3", &Class::SetFromIsometry3, py::arg("pose"), cls_doc.SetFromIsometry3.doc) .def_static("Identity", &Class::Identity, cls_doc.Identity.doc) .def("rotation", &Class::rotation, py_rvp::reference_internal, cls_doc.rotation.doc) .def("set_rotation", py::overload_cast<const RotationMatrix<T>&>(&Class::set_rotation), py::arg("R"), cls_doc.set_rotation.doc_1args_R) .def("set_rotation", py::overload_cast<const RollPitchYaw<T>&>(&Class::set_rotation), py::arg("rpy"), cls_doc.set_rotation.doc_1args_rpy) .def("set_rotation", py::overload_cast<const Eigen::Quaternion<T>&>( &Class::set_rotation), py::arg("quaternion"), cls_doc.set_rotation.doc_1args_quaternion) .def("set_rotation", py::overload_cast<const Eigen::AngleAxis<T>&>(&Class::set_rotation), py::arg("theta_lambda"), cls_doc.set_rotation.doc_1args_theta_lambda) .def("translation", &Class::translation, return_value_policy_for_scalar_type<T>(), cls_doc.translation.doc) .def("set_translation", &Class::set_translation, py::arg("p"), cls_doc.set_translation.doc) .def("GetAsMatrix4", &Class::GetAsMatrix4, cls_doc.GetAsMatrix4.doc) .def("GetAsMatrix34", &Class::GetAsMatrix34, cls_doc.GetAsMatrix34.doc) .def("GetAsIsometry3", &Class::GetAsIsometry3, cls_doc.GetAsIsometry3.doc) .def("SetIdentity", &Class::SetIdentity, cls_doc.SetIdentity.doc) .def("IsExactlyIdentity", &Class::IsExactlyIdentity, cls_doc.IsExactlyIdentity.doc) .def("IsNearlyIdentity", &Class::IsNearlyIdentity, py::arg("translation_tolerance"), cls_doc.IsNearlyIdentity.doc) .def("IsExactlyEqualTo", &Class::IsExactlyEqualTo, py::arg("other"), cls_doc.IsExactlyEqualTo.doc) .def("IsNearlyEqualTo", &Class::IsNearlyEqualTo, py::arg("other"), py::arg("tolerance"), cls_doc.IsNearlyEqualTo.doc) .def("inverse", &Class::inverse, cls_doc.inverse.doc) .def("InvertAndCompose", &Class::InvertAndCompose, py::arg("other"), cls_doc.InvertAndCompose.doc) .def("GetMaximumAbsoluteDifference", &Class::GetMaximumAbsoluteDifference, py::arg("other"), cls_doc.GetMaximumAbsoluteDifference.doc) .def("GetMaximumAbsoluteTranslationDifference", &Class::GetMaximumAbsoluteTranslationDifference, py::arg("other"), cls_doc.GetMaximumAbsoluteTranslationDifference.doc) .def( "multiply", [](const Class* self, const Class& other) { return *self * other; }, py::arg("other"), cls_doc.operator_mul.doc_1args_other) .def( "multiply", [](const Class* self, const Vector3<T>& p_BoQ_B) { return *self * p_BoQ_B; }, py::arg("p_BoQ_B"), cls_doc.operator_mul.doc_1args_p_BoQ_B) .def( "multiply", [](const Class* self, const Vector4<T>& vec_B) { return *self * vec_B; }, py::arg("vec_B"), cls_doc.operator_mul.doc_1args_vec_B) .def( "multiply", [](const Class* self, const Matrix3X<T>& p_BoQ_B) { return *self * p_BoQ_B; }, py::arg("p_BoQ_B"), cls_doc.operator_mul.doc_1args_constEigenMatrixBase) .def(py::pickle([](const Class& self) { return self.GetAsMatrix34(); }, [](const Eigen::Matrix<T, 3, 4>& matrix) { return Class::MakeUnchecked(matrix); })); cls.attr("multiply") = WrapToMatchInputShape(cls.attr("multiply")); cls.attr("__matmul__") = cls.attr("multiply"); DefCopyAndDeepCopy(&cls); DefCast<T>(&cls, cls_doc.cast.doc); AddValueInstantiation<Class>(m); // Some ports need `Value<std::vector<Class>>`. AddValueInstantiation<std::vector<Class>>(m); } { using Class = RotationMatrix<T>; constexpr auto& cls_doc = doc.RotationMatrix; auto cls = DefineTemplateClassWithDefault<Class>( m, "RotationMatrix", param, 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 Matrix3<T>&>(), py::arg("R"), cls_doc.ctor.doc_1args_R) .def(py::init<Eigen::Quaternion<T>>(), py::arg("quaternion"), cls_doc.ctor.doc_1args_quaternion) .def(py::init<const Eigen::AngleAxis<T>&>(), py::arg("theta_lambda"), cls_doc.ctor.doc_1args_theta_lambda) .def(py::init<const RollPitchYaw<T>&>(), py::arg("rpy"), cls_doc.ctor.doc_1args_rpy) .def_static("MakeUnchecked", &Class::MakeUnchecked, py::arg("R"), cls_doc.MakeUnchecked.doc) .def_static("MakeXRotation", &Class::MakeXRotation, py::arg("theta"), cls_doc.MakeXRotation.doc) .def_static("MakeYRotation", &Class::MakeYRotation, py::arg("theta"), cls_doc.MakeYRotation.doc) .def_static("MakeZRotation", &Class::MakeZRotation, py::arg("theta"), cls_doc.MakeZRotation.doc) .def_static("MakeFromOneVector", &Class::MakeFromOneVector, py::arg("b_A"), py::arg("axis_index"), cls_doc.MakeFromOneVector.doc) .def_static("Identity", &Class::Identity, cls_doc.Identity.doc) .def("set", &Class::set, py::arg("R"), cls_doc.set.doc) .def("inverse", &Class::inverse, cls_doc.inverse.doc) .def("InvertAndCompose", &Class::InvertAndCompose, py::arg("other"), cls_doc.InvertAndCompose.doc) .def("transpose", &Class::transpose, cls_doc.transpose.doc) .def("matrix", &Class::matrix, cls_doc.matrix.doc) .def("row", &Class::row, py::arg("index"), cls_doc.row.doc) .def("col", &Class::col, py::arg("index"), cls_doc.col.doc) .def( "multiply", [](const Class& self, const Class& other) { return self * other; }, py::arg("other"), cls_doc.operator_mul.doc_1args_other) .def( "multiply", [](const Class& self, const Vector3<T>& v_B) { return self * v_B; }, py::arg("v_B"), cls_doc.operator_mul.doc_1args_v_B) .def( "multiply", [](const Class& self, const Matrix3X<T>& v_B) { return self * v_B; }, py::arg("v_B"), cls_doc.operator_mul.doc_1args_constEigenMatrixBase) .def("IsValid", overload_cast_explicit<boolean<T>>(&Class::IsValid), cls_doc.IsValid.doc_0args) .def("IsExactlyIdentity", &Class::IsExactlyIdentity, cls_doc.IsExactlyIdentity.doc) .def("IsNearlyIdentity", &Class::IsNearlyIdentity, py::arg("tolerance") = Class::get_internal_tolerance_for_orthonormality(), cls_doc.IsNearlyIdentity.doc) // Does not return the quality_factor .def_static( "ProjectToRotationMatrix", [](const Matrix3<T>& M) { return RotationMatrix<T>::ProjectToRotationMatrix(M); }, py::arg("M"), cls_doc.ProjectToRotationMatrix.doc) .def("ToRollPitchYaw", &Class::ToRollPitchYaw, cls_doc.ToRollPitchYaw.doc) .def("ToQuaternion", overload_cast_explicit<Eigen::Quaternion<T>>(&Class::ToQuaternion), cls_doc.ToQuaternion.doc_0args) .def("ToAngleAxis", &Class::ToAngleAxis, cls_doc.ToAngleAxis.doc) .def(py::pickle([](const Class& self) { return self.matrix(); }, [](const Matrix3<T>& matrix) { return Class::MakeUnchecked(matrix); })); cls.attr("multiply") = WrapToMatchInputShape(cls.attr("multiply")); cls.attr("__matmul__") = cls.attr("multiply"); DefCopyAndDeepCopy(&cls); DefCast<T>(&cls, cls_doc.cast.doc); AddValueInstantiation<Class>(m); // Some ports need `Value<std::vector<Class>>`. AddValueInstantiation<std::vector<Class>>(m); } { using Class = RollPitchYaw<T>; constexpr auto& cls_doc = doc.RollPitchYaw; auto cls = DefineTemplateClassWithDefault<Class>( m, "RollPitchYaw", param, cls_doc.doc); cls // BR .def(py::init<const Class&>(), py::arg("other")) .def(py::init<const Vector3<T>>(), py::arg("rpy"), cls_doc.ctor.doc_1args_rpy) .def(py::init<const T&, const T&, const T&>(), py::arg("roll"), py::arg("pitch"), py::arg("yaw"), cls_doc.ctor.doc_3args_roll_pitch_yaw) .def(py::init<const RotationMatrix<T>&>(), py::arg("R"), cls_doc.ctor.doc_1args_R) .def(py::init<const Eigen::Quaternion<T>&>(), py::arg("quaternion"), cls_doc.ctor.doc_1args_quaternion) .def(py::init([](const Matrix3<T>& matrix) { return Class(RotationMatrix<T>(matrix)); }), py::arg("matrix"), "Construct from raw rotation matrix. See RotationMatrix overload " "for more information.") .def("vector", &Class::vector, cls_doc.vector.doc) .def("roll_angle", &Class::roll_angle, cls_doc.roll_angle.doc) .def("pitch_angle", &Class::pitch_angle, cls_doc.pitch_angle.doc) .def("yaw_angle", &Class::yaw_angle, cls_doc.yaw_angle.doc) .def("ToQuaternion", &Class::ToQuaternion, cls_doc.ToQuaternion.doc) .def("ToRotationMatrix", &Class::ToRotationMatrix, cls_doc.ToRotationMatrix.doc) .def("CalcRotationMatrixDt", &Class::CalcRotationMatrixDt, py::arg("rpyDt"), cls_doc.CalcRotationMatrixDt.doc) .def("CalcAngularVelocityInParentFromRpyDt", &Class::CalcAngularVelocityInParentFromRpyDt, py::arg("rpyDt"), cls_doc.CalcAngularVelocityInParentFromRpyDt.doc) .def("CalcAngularVelocityInChildFromRpyDt", &Class::CalcAngularVelocityInChildFromRpyDt, py::arg("rpyDt"), cls_doc.CalcAngularVelocityInChildFromRpyDt.doc) .def("CalcRpyDtFromAngularVelocityInParent", &Class::CalcRpyDtFromAngularVelocityInParent, py::arg("w_AD_A"), cls_doc.CalcRpyDtFromAngularVelocityInParent.doc) .def("CalcRpyDtFromAngularVelocityInChild", &Class::CalcRpyDtFromAngularVelocityInChild, py::arg("w_AD_D"), cls_doc.CalcRpyDtFromAngularVelocityInChild.doc) .def("CalcRpyDDtFromRpyDtAndAngularAccelInParent", &Class::CalcRpyDDtFromRpyDtAndAngularAccelInParent, py::arg("rpyDt"), py::arg("alpha_AD_A"), cls_doc.CalcRpyDDtFromRpyDtAndAngularAccelInParent.doc) .def("CalcRpyDDtFromAngularAccelInChild", &Class::CalcRpyDDtFromAngularAccelInChild, py::arg("rpyDt"), py::arg("alpha_AD_D"), cls_doc.CalcRpyDDtFromAngularAccelInChild.doc) .def(py::pickle([](const Class& self) { return self.vector(); }, [](const Vector3<T>& rpy) { return Class(rpy); })); DefCopyAndDeepCopy(&cls); // N.B. `RollPitchYaw::cast` is not defined in C++. } { using Class = BsplineBasis<T>; constexpr auto& cls_doc = doc.BsplineBasis; auto cls = DefineTemplateClassWithDefault<Class>( m, "BsplineBasis", param, cls_doc.doc); cls // BR .def(py::init()) .def(py::init<int, std::vector<T>>(), py::arg("order"), py::arg("knots"), cls_doc.ctor.doc_2args) .def(py::init<int, int, KnotVectorType, const T&, const T&>(), py::arg("order"), py::arg("num_basis_functions"), py::arg("type") = KnotVectorType::kClampedUniform, py::arg("initial_parameter_value") = 0.0, py::arg("final_parameter_value") = 1.0, cls_doc.ctor.doc_5args) .def(py::init<const Class&>(), py::arg("other")) .def("order", &Class::order, cls_doc.order.doc) .def("degree", &Class::degree, cls_doc.degree.doc) .def("num_basis_functions", &Class::num_basis_functions, cls_doc.num_basis_functions.doc) .def("knots", &Class::knots, cls_doc.knots.doc) .def("initial_parameter_value", &Class::initial_parameter_value, cls_doc.initial_parameter_value.doc) .def("final_parameter_value", &Class::final_parameter_value, cls_doc.final_parameter_value.doc) .def("FindContainingInterval", &Class::FindContainingInterval, py::arg("parameter_value"), cls_doc.FindContainingInterval.doc) .def("ComputeActiveBasisFunctionIndices", overload_cast_explicit<std::vector<int>, const std::array<T, 2>&>( &Class::ComputeActiveBasisFunctionIndices), py::arg("parameter_interval"), cls_doc.ComputeActiveBasisFunctionIndices .doc_1args_parameter_interval) .def("ComputeActiveBasisFunctionIndices", overload_cast_explicit<std::vector<int>, const T&>( &Class::ComputeActiveBasisFunctionIndices), py::arg("parameter_value"), cls_doc.ComputeActiveBasisFunctionIndices.doc_1args_parameter_value) .def( "EvaluateCurve", [](Class* self, const std::vector<VectorX<T>>& control_points, const T& parameter_value) { return self->EvaluateCurve(control_points, parameter_value); }, py::arg("control_points"), py::arg("parameter_value"), cls_doc.EvaluateCurve.doc) .def("EvaluateBasisFunctionI", &Class::EvaluateBasisFunctionI, py::arg("i"), py::arg("parameter_value"), cls_doc.EvaluateBasisFunctionI.doc) .def(py::pickle( [](const Class& self) { return std::make_pair(self.order(), self.knots()); }, [](std::pair<int, std::vector<T>> args) { return Class(std::get<0>(args), std::get<1>(args)); })); } m.def("wrap_to", &wrap_to<T, T>, py::arg("value"), py::arg("low"), py::arg("high"), doc.wrap_to.doc); // Cross product m.def( "VectorToSkewSymmetric", [](const Eigen::Ref<const Vector3<T>>& p) { return VectorToSkewSymmetric(p); }, py::arg("p"), doc.VectorToSkewSymmetric.doc); // Quaternion. m // BR .def("ClosestQuaternion", &ClosestQuaternion<T>, py::arg("quat1"), py::arg("quat2"), doc.ClosestQuaternion.doc) // TODO(russt): Bind quatConjugate, quatProduct, quatRotateVec, quatDiff, // quatDiffAxisInvar once they've been switched to Eigen::Quaternion<T>. .def("is_quaternion_in_canonical_form", &is_quaternion_in_canonical_form<T>, py::arg("quat"), doc.is_quaternion_in_canonical_form.doc) .def("QuaternionToCanonicalForm", &QuaternionToCanonicalForm<T>, py::arg("quat"), doc.QuaternionToCanonicalForm.doc) .def("AreQuaternionsEqualForOrientation", &AreQuaternionsEqualForOrientation<T>, py::arg("quat1"), py::arg("quat2"), py::arg("tolerance"), doc.AreQuaternionsEqualForOrientation.doc) .def("CalculateQuaternionDtFromAngularVelocityExpressedInB", &CalculateQuaternionDtFromAngularVelocityExpressedInB<T>, py::arg("quat_AB"), py::arg("w_AB_B"), doc.CalculateQuaternionDtFromAngularVelocityExpressedInB.doc) .def("CalculateAngularVelocityExpressedInBFromQuaternionDt", &CalculateAngularVelocityExpressedInBFromQuaternionDt<T>, py::arg("quat_AB"), py::arg("quatDt"), doc.CalculateAngularVelocityExpressedInBFromQuaternionDt.doc) .def("CalculateQuaternionDtConstraintViolation", &CalculateQuaternionDtConstraintViolation<T>, py::arg("quat"), py::arg("quatDt"), doc.CalculateQuaternionDtConstraintViolation.doc) .def("IsQuaternionValid", &IsQuaternionValid<T>, py::arg("quat"), py::arg("tolerance"), doc.IsQuaternionValid.doc) .def("IsBothQuaternionAndQuaternionDtOK", &IsBothQuaternionAndQuaternionDtOK<T>, py::arg("quat"), py::arg("quatDt"), py::arg("tolerance"), doc.IsBothQuaternionAndQuaternionDtOK.doc); // TODO(russt): Bind // IsQuaternionAndQuaternionDtEqualAngularVelocityExpressedInB, but this // requires additional support for T=Expression (e.g. if_then_else(Formula, // Formula, Formula)) or an exclusion. } void DoScalarIndependentDefinitions(py::module m) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::math; constexpr auto& doc = pydrake_doc.drake.math; // TODO(eric.cousineau): Bind remaining classes for all available scalar // types. using T = double; py::class_<BarycentricMesh<T>>(m, "BarycentricMesh", doc.BarycentricMesh.doc) .def(py::init<BarycentricMesh<T>::MeshGrid>(), doc.BarycentricMesh.ctor.doc) .def("get_input_grid", &BarycentricMesh<T>::get_input_grid, doc.BarycentricMesh.get_input_grid.doc) .def("get_input_size", &BarycentricMesh<T>::get_input_size, doc.BarycentricMesh.get_input_size.doc) .def("get_num_mesh_points", &BarycentricMesh<T>::get_num_mesh_points, doc.BarycentricMesh.get_num_mesh_points.doc) .def("get_num_interpolants", &BarycentricMesh<T>::get_num_interpolants, doc.BarycentricMesh.get_num_interpolants.doc) .def("get_mesh_point", overload_cast_explicit<VectorX<T>, int>( &BarycentricMesh<T>::get_mesh_point), doc.BarycentricMesh.get_mesh_point.doc_1args) .def("get_all_mesh_points", &BarycentricMesh<T>::get_all_mesh_points, doc.BarycentricMesh.get_all_mesh_points.doc) .def( "EvalBarycentricWeights", [](const BarycentricMesh<T>* self, const Eigen::Ref<const VectorX<T>>& input) { const int n = self->get_num_interpolants(); Eigen::VectorXi indices(n); VectorX<T> weights(n); self->EvalBarycentricWeights(input, &indices, &weights); return std::make_pair(indices, weights); }, doc.BarycentricMesh.EvalBarycentricWeights.doc) .def("Eval", overload_cast_explicit<VectorX<T>, const Eigen::Ref<const MatrixX<T>>&, const Eigen::Ref<const VectorX<T>>&>(&BarycentricMesh<T>::Eval), doc.BarycentricMesh.Eval.doc_2args) .def("MeshValuesFrom", &BarycentricMesh<T>::MeshValuesFrom, doc.BarycentricMesh.MeshValuesFrom.doc); { using Class = KnotVectorType; constexpr auto& cls_doc = doc.KnotVectorType; py::enum_<Class>(m, "KnotVectorType", py::arithmetic(), cls_doc.doc) .value("kUniform", Class::kUniform, cls_doc.kUniform.doc) .value("kClampedUniform", Class::kClampedUniform, cls_doc.kClampedUniform.doc); } // Random Rotations m // BR .def("UniformlyRandomQuaternion", overload_cast_explicit<Eigen::Quaternion<T>, RandomGenerator*>( &UniformlyRandomQuaternion), py::arg("generator"), doc.UniformlyRandomQuaternion.doc) .def("UniformlyRandomAngleAxis", overload_cast_explicit<Eigen::AngleAxis<T>, RandomGenerator*>( &UniformlyRandomAngleAxis), py::arg("generator"), doc.UniformlyRandomAngleAxis.doc) .def("UniformlyRandomRotationMatrix", overload_cast_explicit<RotationMatrix<T>, RandomGenerator*>( &UniformlyRandomRotationMatrix), py::arg("generator"), doc.UniformlyRandomRotationMatrix.doc) .def("UniformlyRandomRPY", overload_cast_explicit<Vector3<T>, RandomGenerator*>( &UniformlyRandomRPY), py::arg("generator"), doc.UniformlyRandomRPY.doc); // Matrix Util. m // BR .def( "IsSymmetric", [](const Eigen::Ref<const MatrixX<T>>& matrix) { return IsSymmetric(matrix); }, py::arg("matrix"), doc.IsSymmetric.doc_1args) .def( "IsSymmetric", [](const Eigen::Ref<const MatrixX<T>>& matrix, const T& precision) { return IsSymmetric(matrix, precision); }, py::arg("matrix"), py::arg("precision"), doc.IsSymmetric.doc_2args) .def( "IsPositiveDefinite", [](const Eigen::Ref<const Eigen::MatrixXd>& matrix, double tolerance) { return IsPositiveDefinite(matrix, tolerance); }, py::arg("matrix"), py::arg("tolerance") = 0.0, doc.IsPositiveDefinite.doc) .def( "ToSymmetricMatrixFromLowerTriangularColumns", [](const Eigen::Ref<const Eigen::VectorXd>& lower_triangular_columns) { return ToSymmetricMatrixFromLowerTriangularColumns( lower_triangular_columns); }, py::arg("lower_triangular_columns"), doc.ToSymmetricMatrixFromLowerTriangularColumns.doc_dynamic_size) .def( "ToLowerTriangularColumnsFromMatrix", [](const Eigen::Ref<const MatrixX<T>>& matrix) { return ToLowerTriangularColumnsFromMatrix(matrix); }, py::arg("matrix"), doc.ToLowerTriangularColumnsFromMatrix.doc) .def( "ExtractPrincipalSubmatrix", [](const Eigen::Ref<const MatrixX<T>>& matrix, const std::set<int>& indices) { return ExtractPrincipalSubmatrix(matrix, indices); }, py::arg("matrix"), py::arg("indices"), doc.ExtractPrincipalSubmatrix.doc); // Quadratic Form. m // BR .def("DecomposePSDmatrixIntoXtransposeTimesX", &DecomposePSDmatrixIntoXtransposeTimesX, py::arg("Y"), py::arg("zero_tol"), py::arg("return_empty_if_not_psd") = false, doc.DecomposePSDmatrixIntoXtransposeTimesX.doc) .def("DecomposePositiveQuadraticForm", &DecomposePositiveQuadraticForm, py::arg("Q"), py::arg("b"), py::arg("c"), py::arg("tol") = 0, doc.DecomposePositiveQuadraticForm.doc) .def("BalanceQuadraticForms", &BalanceQuadraticForms, py::arg("S"), py::arg("P"), doc.BalanceQuadraticForms.doc); // Riccati and Lyapunov Equations. m // BR .def("ContinuousAlgebraicRiccatiEquation", py::overload_cast<const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&>( &ContinuousAlgebraicRiccatiEquation), py::arg("A"), py::arg("B"), py::arg("Q"), py::arg("R"), doc.ContinuousAlgebraicRiccatiEquation.doc_4args_A_B_Q_R) .def("RealContinuousLyapunovEquation", &RealContinuousLyapunovEquation, py::arg("A"), py::arg("Q"), doc.RealContinuousLyapunovEquation.doc) .def("DiscreteAlgebraicRiccatiEquation", py::overload_cast<const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&>( &DiscreteAlgebraicRiccatiEquation), py::arg("A"), py::arg("B"), py::arg("Q"), py::arg("R"), doc.DiscreteAlgebraicRiccatiEquation.doc_4args) .def("DiscreteAlgebraicRiccatiEquation", py::overload_cast<const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&, const Eigen::Ref<const Eigen::MatrixXd>&>( &DiscreteAlgebraicRiccatiEquation), py::arg("A"), py::arg("B"), py::arg("Q"), py::arg("R"), py::arg("N"), doc.DiscreteAlgebraicRiccatiEquation.doc_5args) .def("RealDiscreteLyapunovEquation", &RealDiscreteLyapunovEquation, py::arg("A"), py::arg("Q"), doc.RealDiscreteLyapunovEquation.doc); { using Class = NumericalGradientMethod; constexpr auto& cls_doc = doc.NumericalGradientMethod; py::enum_<Class>(m, "NumericalGradientMethod", cls_doc.doc) .value("kForward", Class::kForward, cls_doc.kForward.doc) .value("kBackward", Class::kBackward, cls_doc.kBackward.doc) .value("kCentral", Class::kCentral, cls_doc.kCentral.doc); } { using Class = NumericalGradientOption; constexpr auto& cls_doc = doc.NumericalGradientOption; py::class_<Class>(m, "NumericalGradientOption", cls_doc.doc) .def(py::init<NumericalGradientMethod, double>(), py::arg("method"), py::arg("function_accuracy") = 1E-15, cls_doc.ctor.doc) .def("NumericalGradientMethod", &Class::method, cls_doc.method.doc) .def("perturbation_size", &Class::perturbation_size, cls_doc.perturbation_size.doc) .def( "__repr__", [](const NumericalGradientOption& self) -> std::string { py::object method = py::cast(self.method()); // This is a minimal implementation that serves to avoid // displaying memory addresses in pydrake docs and help strings. // In the future, we should enhance this to display all of the // information. return fmt::format("<NumericalGradientOption({})>", fmt_streamed(py::repr(method))); }); } m.def( "ComputeNumericalGradient", [](std::function<Eigen::VectorXd(const Eigen::VectorXd&)> calc_func, const Eigen::VectorXd& x, const NumericalGradientOption& option) { std::function<void(const Eigen::VectorXd&, Eigen::VectorXd*)> calc_func_no_return = [&calc_func](const Eigen::VectorXd& x_val, Eigen::VectorXd* y) { *y = calc_func(x_val); }; return ComputeNumericalGradient(calc_func_no_return, x, option); }, py::arg("calc_func"), py::arg("x"), py::arg("option") = NumericalGradientOption(NumericalGradientMethod::kForward), doc.ComputeNumericalGradient.doc); } template <typename T> void DoNonsymbolicScalarDefinitions(py::module m, T) { // NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace. using namespace drake::math; constexpr auto& doc = pydrake_doc.drake.math; // Soft min and max m.def("SoftOverMax", &SoftOverMax<T>, py::arg("x"), py::arg("alpha") = 1.0, doc.SoftOverMax.doc) .def("SoftUnderMax", &SoftUnderMax<T>, py::arg("x"), py::arg("alpha") = 1.0, doc.SoftUnderMax.doc) .def("SoftOverMin", &SoftOverMin<T>, py::arg("x"), py::arg("alpha") = 1.0, doc.SoftOverMin.doc) .def("SoftUnderMin", &SoftUnderMin<T>, py::arg("x"), py::arg("alpha") = 1.0, doc.SoftUnderMin.doc); } } // namespace void DefineMathMonolith(py::module m) { DoScalarIndependentDefinitions(m); type_visit([m](auto dummy) { DoScalarDependentDefinitions(m, dummy); }, CommonScalarPack{}); type_visit([m](auto dummy) { DoNonsymbolicScalarDefinitions(m, dummy); }, NonSymbolicScalarPack{}); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/math/math_example.py
"""Shows examples using math utilities. To see this interactively: bazel run //bindings/pydrake:py/math_example """ # To be a meaningful unit test, we must render the figure somehow. # The Agg backend (creating a PNG image) is suitably cross-platform. # Users should feel free to use a different back-end in their own code. import os os.environ['MPLBACKEND'] = 'Agg' # noqa # Now that the environment is set up, it's safe to import matplotlib, etc. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import webbrowser from pydrake.math import BarycentricMesh # If running under `bazel run`, output to cwd so the user can find it. # If running under `bazel test`, avoid polluting the test's cwd. for env_name in ['BUILD_WORKING_DIRECTORY', 'TEST_TMPDIR']: if env_name in os.environ: os.chdir(os.environ[env_name]) # Plot a surface using BarycentricMesh. mesh = BarycentricMesh([{0, 1}, {0, 1}]) values = np.array([[0, 1, 2, 3]]) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y = np.meshgrid(list(mesh.get_input_grid()[0]), list(mesh.get_input_grid()[1])) Z = np.reshape(values, X.shape) ax.plot_surface(X, Y, Z) ax.set_xlabel('x') ax.set_ylabel('y') plt.savefig('math_example.png') assert os.path.exists('math_example.png') # Show the figure (but not when testing). if 'TEST_TMPDIR' not in os.environ: webbrowser.open_new_tab(url='math_example.png')
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/math/math_py_matmul.cc
#include "drake/bindings/pydrake/autodiff_types_pybind.h" #include "drake/bindings/pydrake/common/eigen_pybind.h" #include "drake/bindings/pydrake/pydrake_pybind.h" #include "drake/bindings/pydrake/symbolic_types_pybind.h" namespace drake { namespace pydrake { namespace internal { namespace { using symbolic::Expression; using symbolic::Monomial; using symbolic::Variable; template <typename T> std::string_view GetDtypeName() { if constexpr (std::is_same_v<T, double>) { return "float"; } if constexpr (std::is_same_v<T, AutoDiffXd>) { return "AutoDiffXd"; } if constexpr (std::is_same_v<T, Variable>) { return "Variable"; } if constexpr (std::is_same_v<T, Expression>) { return "Expression"; } if constexpr (std::is_same_v<T, symbolic::Polynomial>) { return "Polynomial"; } if constexpr (std::is_same_v<T, Monomial>) { return "Monomial"; } } } // namespace void DefineMathMatmul(py::module m) { const auto bind = [&m]<typename T1, typename T2>() { using T3 = typename decltype(std::declval<MatrixX<T1>>() * std::declval<MatrixX<T2>>())::Scalar; // To avoid too much doc spam, we'll use a more descriptive docstring for // the first overload only. const std::string_view extra_doc = (std::is_same_v<T1, double> && std::is_same_v<T2, double>) ? " The numpy matmul ``A @ B`` is typically slow when multiplying " "user-defined dtypes such as AutoDiffXd or Expression. Use this " "function for better performance, e.g., ``matmul(A, B)``. For a " "dtype=float @ dtype=float, this might be a little slower than " "numpy, but is provided here for convenience so that the user " "doesn't need to be overly careful about the dtype of arguments." : ""; const std::string doc = fmt::format( "Matrix product for dtype={} @ dtype={} -> dtype={}.{}", GetDtypeName<T1>(), GetDtypeName<T2>(), GetDtypeName<T3>(), extra_doc); m.def( "matmul", [](const Eigen::Ref<const MatrixX<T1>, 0, StrideX>& A, const Eigen::Ref<const MatrixX<T2>, 0, StrideX>& B) -> MatrixX<T3> { if constexpr (std::is_same_v<T3, AutoDiffXd>) { return A.template cast<AutoDiffXd>() * B.template cast<AutoDiffXd>(); } else { return A * B; } }, doc.c_str()); }; // NOLINT(readability/braces) // The ordering of the calls to `bind` here are sorted fastest-to-slowest to // ensure that overload resolution chooses the fastest one. // Bind a double-only overload for convenience. bind.operator()<double, double>(); // Bind the AutoDiff-related overloads. bind.operator()<double, AutoDiffXd>(); bind.operator()<AutoDiffXd, double>(); bind.operator()<AutoDiffXd, AutoDiffXd>(); // Bind the symbolic expression family of overloads. // // The order here is important for choosing the most specific types (e.g., so // that a Polynomial stays as a Polynomial instead of lapsing back into an // Expression). The order should go start from the narrowest type and work up // to the broadest type. // // - One operand is a double. bind.operator()<double, Variable>(); bind.operator()<Variable, double>(); bind.operator()<double, Monomial>(); bind.operator()<Monomial, double>(); bind.operator()<double, symbolic::Polynomial>(); bind.operator()<symbolic::Polynomial, double>(); bind.operator()<double, Expression>(); bind.operator()<Expression, double>(); // - One operand is a Variable. bind.operator()<Variable, Variable>(); bind.operator()<Variable, Monomial>(); bind.operator()<Monomial, Variable>(); bind.operator()<Variable, symbolic::Polynomial>(); bind.operator()<symbolic::Polynomial, Variable>(); bind.operator()<Variable, Expression>(); bind.operator()<Expression, Variable>(); // - One operand is a Monomial. bind.operator()<Monomial, Monomial>(); bind.operator()<Monomial, symbolic::Polynomial>(); bind.operator()<symbolic::Polynomial, Monomial>(); bind.operator()<Monomial, Expression>(); bind.operator()<Expression, Monomial>(); // - One operand is a Polynomial. bind.operator()<symbolic::Polynomial, symbolic::Polynomial>(); bind.operator()<symbolic::Polynomial, Expression>(); bind.operator()<Expression, symbolic::Polynomial>(); // - Both operands are Expression. bind.operator()<Expression, Expression>(); } } // namespace internal } // namespace pydrake } // namespace drake
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/math/_math_extra.py
""" Bindings for ``math``, including overloads for scalar types and basic SE(3) representations. Note that arrays of symbolic scalar types, such as ``Variable`` and ``Expression``, are exposed using ``ndarray[object]``, and as such logical operations are constrained to return boolean values given NumPy's implementation; this is not desirable, as one should really get a ``Formula`` object. As a workaround, this module provides the following vectorized operators, following suit with the ``operator`` builtin module: ``lt``, ``le``, ``eq``, ``ne``, ``ge``, and ``gt``. As an example:: >>> x = np.array([Variable("x0"), Variable("x1")]) >>> y = np.array([Variable("y0"), Variable("y1")]) >>> x >= y # This should throw a RuntimeError >>> ge(x, y) array([<Formula "(x0 >= y0)">, <Formula "(x1 >= y1)">], dtype=object) """ # See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and # rationale. import functools import operator import numpy as np from pydrake.autodiffutils import AutoDiffXd as _AutoDiffXd from pydrake.common import ( _MangledName, pretty_class_name as _pretty_class_name, ) import pydrake.symbolic as _sym _sym_cls_list = ( _sym.Expression, _sym.Variable, ) def _is_elementwise_comparison_error(e): return ( # Newer error message (numpy >= 1.16.0). "elementwise comparison failed" in str(e) # Older error messages. or "elementwise == comparison failed" in str(e) or "elementwise != comparison failed" in str(e) ) def _best_effort_rich_compare(a, b, *, oper): try: return oper(a, b) except RuntimeError as e: if "not call `__bool__` / `__nonzero__` on `Formula`" in str(e): if isinstance(a, _sym_cls_list): return oper(a, _sym.Expression(b)) elif isinstance(b, _sym_cls_list): return oper(_sym.Expression(a), b) raise except DeprecationWarning as e: # N.B. This is only appears to be triggered for symbolic types. if _is_elementwise_comparison_error(e): if isinstance(a, np.generic): a = float(a) elif isinstance(b, np.generic): b = float(b) else: raise RuntimeError("Unexpected condition") return oper(a, b) raise def _drake_vectorize(oper, *, doc): wrapped = functools.partial(_best_effort_rich_compare, oper=oper) return np.vectorize(wrapped, doc=doc) # As mentioned in top-level, add generic logical operators as ufuncs so that we # may do comparisons on arrays of any scalar type, without restriction on the # output type. These are added solely to work around #8315, where arrays of # Expression can't use direct logical operators (e.g. `<=`) since the output # type is not bool. # N.B. Defined in order listed in Python documentation: # https://docs.python.org/3.6/library/operator.html lt = _drake_vectorize(operator.lt, doc="Drake's vectorized `lt`") le = _drake_vectorize(operator.le, doc="Drake's vectorized `le`") eq = _drake_vectorize(operator.eq, doc="Drake's vectorized `eq`") ne = _drake_vectorize(operator.ne, doc="Drake's vectorized `ne`") ge = _drake_vectorize(operator.ge, doc="Drake's vectorized `ge`") gt = _drake_vectorize(operator.gt, doc="Drake's vectorized `gt`") # The following values are defined for testing. _OPERATORS = (lt, le, eq, ne, ge, gt) # - Equivalent expression when operands are reversed. _OPERATORS_REVERSE = { lt: gt, le: ge, eq: eq, ne: ne, ge: le, gt: lt, } def _indented_repr(o): """Returns repr(o), with any lines beyond the first one indented +2.""" return repr(o).replace("\n", "\n ") def _roll_pitch_yaw_repr(rpy): return ( f"{_pretty_class_name(type(rpy))}(" f"roll={repr(rpy.roll_angle())}, " f"pitch={repr(rpy.pitch_angle())}, " f"yaw={repr(rpy.yaw_angle())})") def _rotation_matrix_repr(R): M = R.matrix().tolist() return ( f"{_pretty_class_name(type(R))}([\n" f" {_indented_repr(M[0])},\n" f" {_indented_repr(M[1])},\n" f" {_indented_repr(M[2])},\n" f"])") def _rigid_transform_repr(X): return ( f"{_pretty_class_name(type(X))}(\n" f" R={_indented_repr(X.rotation())},\n" f" p={_indented_repr(X.translation().tolist())},\n" f")") def _add_repr_functions(): for T in [float, _AutoDiffXd, _sym.Expression]: RollPitchYaw_[T].__repr__ = _roll_pitch_yaw_repr RotationMatrix_[T].__repr__ = _rotation_matrix_repr RigidTransform_[T].__repr__ = _rigid_transform_repr _add_repr_functions() 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/math
/home/johnshepherd/drake/bindings/pydrake/math/test/math_overloads_matrix_test.py
import pydrake.math as mut import itertools import unittest import numpy as np from pydrake.autodiffutils import AutoDiffXd from pydrake.common.test_utilities import meta, numpy_compare from pydrake.symbolic import ( Expression, MakeMatrixContinuousVariable, Monomial, Polynomial, Variable, ) def _matmul_dtype_pairs(): """Returns the list of type pairs (T1, T2) to use for testing functions that operate on a pair of matrix inputs. We'll test all pairs *except* we won't mix autodiff with symbolic. """ types = (float, AutoDiffXd, Variable, Expression, Monomial, Polynomial) for T1, T2 in itertools.product(types, types): any_autodiff = any([T in (AutoDiffXd,) for T in (T1, T2)]) all_nonsymbolic = all([T in (float, AutoDiffXd) for T in (T1, T2)]) if any_autodiff and not all_nonsymbolic: continue yield dict(T1=T1, T2=T2) class MathOverloadsMatrixTest(unittest.TestCase, metaclass=meta.ValueParameterizedTest): def _astype(self, M, dtype, name): """Returns matrix like M but with a new dtype.""" assert M.dtype == np.float64, M.dtype if dtype is float: return M if dtype is AutoDiffXd: # Return a copy with a non-zero gradient. result = M.astype(dtype=AutoDiffXd) result[0, 0] = AutoDiffXd(M[0, 0], np.array([1.0])) return result if dtype is Variable: # Return a like-sized matrix of variables. return MakeMatrixContinuousVariable(*M.shape, name) if dtype in (Expression, Polynomial, Monomial): # Return a like-sized matrix of variables promoted to the dtype. return self._astype(M, Variable, name).astype(dtype=dtype) assert False @meta.run_with_multiple_values(_matmul_dtype_pairs()) def test_matmul(self, *, T1, T2): # Create some sample data for A @ B == [[11.0]]. A = np.array([[1.0, 2.0]]) B = np.array([[3.0, 4.0]]).T # Convert the dtypes. A_T1 = self._astype(A, T1, "A") B_T2 = self._astype(B, T2, "B") # Compare the fast overload the slow fallback. actual = mut.matmul(A_T1, B_T2) expected = A_T1 @ B_T2 self.assertEqual(actual.dtype, expected.dtype) numpy_compare.assert_equal(actual, expected)
0
/home/johnshepherd/drake/bindings/pydrake/math
/home/johnshepherd/drake/bindings/pydrake/math/test/math_test.py
import pydrake.math as mut from pydrake.math import (BarycentricMesh, wrap_to) from pydrake.common import RandomGenerator from pydrake.common.cpp_param import List from pydrake.common.eigen_geometry import Isometry3_, Quaternion_, AngleAxis_ from pydrake.common.value import Value from pydrake.autodiffutils import AutoDiffXd from pydrake.symbolic import Expression import pydrake.common.test_utilities.numpy_compare as numpy_compare from pydrake.common.test_utilities.pickle_compare import assert_pickle import copy import math import pickle import textwrap import unittest import numpy as np class TestBarycentricMesh(unittest.TestCase): def test_spelling(self): mesh = BarycentricMesh([{0, 1}, {0, 1}]) values = np.array([[0, 1, 2, 3]]) grid = mesh.get_input_grid() self.assertIsInstance(grid, list) self.assertEqual(len(grid), 2) self.assertIsInstance(grid[0], set) self.assertEqual(len(grid[0]), 2) self.assertEqual(mesh.get_input_size(), 2) self.assertEqual(mesh.get_num_mesh_points(), 4) self.assertEqual(mesh.get_num_interpolants(), 3) self.assertTrue((mesh.get_mesh_point(0) == [0., 0.]).all()) points = mesh.get_all_mesh_points() self.assertEqual(points.shape, (2, 4)) self.assertTrue((points[:, 3] == [1., 1.]).all()) self.assertEqual(mesh.Eval(values, (0, 0))[0], 0) self.assertEqual(mesh.Eval(values, (1, 0))[0], 1) self.assertEqual(mesh.Eval(values, (0, 1))[0], 2) self.assertEqual(mesh.Eval(values, (1, 1))[0], 3) def test_weight(self): mesh = BarycentricMesh([{0, 1}, {0, 1}]) (Ti, T) = mesh.EvalBarycentricWeights((0., 1.)) np.testing.assert_equal(Ti, [2, 2, 0]) np.testing.assert_almost_equal(T, (1., 0., 0.)) def test_mesh_values_from(self): mesh = BarycentricMesh([{0, 1}, {0, 1}]) def mynorm(x): return [x.dot(x)] values = mesh.MeshValuesFrom(mynorm) self.assertEqual(values.size, 4) # TODO(eric.cousineau): Test wrappings against non-identity transforms. class TestMath(unittest.TestCase): def test_math(self): # Compare against `math` functions. # TODO(eric.cousineau): Consider removing this and only rely on # `math_overloads_test`, which already tests this. unary = [ (mut.log, math.log), (mut.abs, math.fabs), (mut.exp, math.exp), (mut.sqrt, math.sqrt), (mut.sin, math.sin), (mut.cos, math.cos), (mut.tan, math.tan), (mut.asin, math.asin), (mut.acos, math.acos), (mut.atan, math.atan), (mut.sinh, math.sinh), (mut.cosh, math.cosh), (mut.tanh, math.tanh), (mut.ceil, math.ceil), (mut.floor, math.floor), (mut.isnan, math.isnan), ] binary = [ (mut.min, min), (mut.max, max), (mut.pow, math.pow), (mut.atan2, math.atan2), ] a = 0.1 b = 0.2 for f_core, f_cpp in unary: self.assertEqual(f_core(a), f_cpp(a), (f_core, f_cpp)) for f_core, f_cpp in binary: self.assertEqual(f_core(a, b), f_cpp(a, b)) def check_cast(self, template, T): value = template[T]() # Refer to docstrings for `CastUPack` in `default_scalars_pybind.h`. if T == float: U_list = [float, AutoDiffXd, Expression] else: U_list = [T] for U in U_list: self.assertIsInstance(value.cast[U](), template[U], U) @numpy_compare.check_all_types def test_rigid_transform(self, T): RigidTransform = mut.RigidTransform_[T] RotationMatrix = mut.RotationMatrix_[T] RollPitchYaw = mut.RollPitchYaw_[T] Isometry3 = Isometry3_[T] Quaternion = Quaternion_[T] AngleAxis = AngleAxis_[T] def check_equality(X_actual, X_expected_matrix): self.assertIsInstance(X_actual, RigidTransform) numpy_compare.assert_float_equal( X_actual.GetAsMatrix4(), X_expected_matrix) # - Constructors. X_I_np = np.eye(4) check_equality(RigidTransform(), X_I_np) check_equality(RigidTransform(other=RigidTransform()), X_I_np) check_equality(copy.copy(RigidTransform()), X_I_np) R_I = RotationMatrix() p_I = np.zeros(3) rpy_I = RollPitchYaw(0, 0, 0) quaternion_I = Quaternion.Identity() angle = np.pi * 0 axis = [0, 0, 1] angle_axis = AngleAxis(angle=angle, axis=axis) check_equality(RigidTransform(R=R_I, p=p_I), X_I_np) check_equality(RigidTransform(rpy=rpy_I, p=p_I), X_I_np) check_equality(RigidTransform(quaternion=quaternion_I, p=p_I), X_I_np) check_equality(RigidTransform(theta_lambda=angle_axis, p=p_I), X_I_np) check_equality(RigidTransform(R=R_I), X_I_np) check_equality(RigidTransform(p=p_I), X_I_np) check_equality(RigidTransform(pose=p_I), X_I_np) check_equality(RigidTransform(pose=X_I_np), X_I_np) check_equality(RigidTransform(pose=X_I_np[:3]), X_I_np) check_equality(RigidTransform.MakeUnchecked(pose=X_I_np[:3]), X_I_np) # - Cast. self.check_cast(mut.RigidTransform_, T) # - Accessors, mutators, and general methods. X = RigidTransform() X.set(R=R_I, p=p_I) X.SetFromIsometry3(pose=Isometry3.Identity()) check_equality(RigidTransform.Identity(), X_I_np) self.assertIsInstance(X.rotation(), RotationMatrix) X.set_rotation(R=R_I) X.set_rotation(rpy=rpy_I) X.set_rotation(quaternion=quaternion_I) X.set_rotation(theta_lambda=angle_axis) self.assertIsInstance(X.translation(), np.ndarray) X.set_translation(p=np.zeros(3)) numpy_compare.assert_float_equal(X.GetAsMatrix4(), X_I_np) numpy_compare.assert_float_equal(X.GetAsMatrix34(), X_I_np[:3]) self.assertIsInstance(X.GetAsIsometry3(), Isometry3) check_equality(X.inverse(), X_I_np) self.assertIsInstance( X.multiply(other=RigidTransform()), RigidTransform) self.assertIsInstance( X.InvertAndCompose(other=RigidTransform()), RigidTransform) self.assertIsInstance( X.GetMaximumAbsoluteDifference(other=RigidTransform()), T) self.assertIsInstance( X.GetMaximumAbsoluteTranslationDifference( other=RigidTransform()), T) self.assertIsInstance(X @ RigidTransform(), RigidTransform) self.assertIsInstance(X @ [0, 0, 0], np.ndarray) if T != Expression: self.assertTrue(X.IsExactlyIdentity()) self.assertTrue(X.IsNearlyIdentity(translation_tolerance=0)) self.assertTrue(X.IsNearlyEqualTo(other=X, tolerance=0)) self.assertTrue(X.IsExactlyEqualTo(other=X)) # - Test shaping (#13885). v = np.array([0., 0., 0.]) vs = np.array([[1., 2., 3.], [4., 5., 6.]]).T self.assertEqual((X @ v).shape, (3,)) self.assertEqual((X @ v.reshape((3, 1))).shape, (3, 1)) self.assertEqual((X @ vs).shape, (3, 2)) # - Test 3-element vector multiplication. R_AB = RotationMatrix([ [0., 1, 0], [-1, 0, 0], [0, 0, 1]]) p_AB = np.array([1., 2, 3]) X_AB = RigidTransform(R=R_AB, p=p_AB) p_BQ = [10, 20, 30] p_AQ = [21., -8, 33] numpy_compare.assert_float_equal(X_AB.multiply(p_BoQ_B=p_BQ), p_AQ) # - Test 4-element vector multiplication. p_BQ_vec4 = np.array([10, 20, 30, 1]) p_AQ_vec4 = np.array([21., -8, 33, 1]) numpy_compare.assert_float_equal( X_AB.multiply(vec_B=p_BQ_vec4), p_AQ_vec4) # N.B. Remember that this takes ndarray[3, n], NOT ndarray[n, 3]! p_BQlist = np.array([p_BQ, p_BQ]).T p_AQlist = np.array([p_AQ, p_AQ]).T numpy_compare.assert_float_equal( X_AB.multiply(p_BoQ_B=p_BQlist), p_AQlist) # - Repr. z = repr(T(0.0)) i = repr(T(1.0)) type_suffix = { float: "", AutoDiffXd: "_[AutoDiffXd]", Expression: "_[Expression]", }[T] self.assertEqual(repr(RigidTransform()), textwrap.dedent(f"""\ RigidTransform{type_suffix}( R=RotationMatrix{type_suffix}([ [{i}, {z}, {z}], [{z}, {i}, {z}], [{z}, {z}, {i}], ]), p=[{z}, {z}, {z}], )""")) if T == float: # TODO(jwnimmer-tri) Once AutoDiffXd and Expression implement an # eval-able repr, then we can test more than just T=float here. roundtrip = eval(repr(RigidTransform())) # TODO(jwnimmer-tri) Once IsExactlyEqualTo is bound, we can easily # check the contents of the roundtrip object here. self.assertIsInstance(roundtrip, RigidTransform) # Test pickling. assert_pickle(self, X_AB, RigidTransform.GetAsMatrix4, T=T) X_AB = RigidTransform.MakeUnchecked(np.full((3, 4), math.inf)) assert_pickle(self, X_AB, RigidTransform.GetAsMatrix4, T=T) def test_legacy_unpickle(self): """Checks that data pickled as RotationMatrix_[float] in Drake v1.12.0 can be unpickled as RotationMatrix_𝓣float𝓤 in newer versions of Drake. Since the unpickling shim lives at the module level, testing one class is sufficient even though our module has several pickle-able classes. """ legacy_data = b"\x80\x04\x95\x18\x01\x00\x00\x00\x00\x00\x00\x8c\x0cpydrake.math\x94\x8c\x16RigidTransform_[float]\x94\x93\x94)\x81\x94\x8c\x15numpy.core.multiarray\x94\x8c\x0c_reconstruct\x94\x93\x94\x8c\x05numpy\x94\x8c\x07ndarray\x94\x93\x94K\x00\x85\x94C\x01b\x94\x87\x94R\x94(K\x01K\x03K\x04\x86\x94h\x07\x8c\x05dtype\x94\x93\x94\x8c\x02f8\x94\x89\x88\x87\x94R\x94(K\x03\x8c\x01<\x94NNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00t\x94b\x88C`\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0\xbf\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@\x94t\x94bb." # noqa obj = pickle.loads(legacy_data) self.assertIsInstance(obj, mut.RigidTransform_[float]) expected = np.array([ [0.0, 1.0, 0.0, 1.0], [-1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 1.0, 3.0], ]) numpy_compare.assert_float_equal(obj.GetAsMatrix34(), expected) @numpy_compare.check_all_types def test_rotation_matrix(self, T): # - Constructors. RotationMatrix = mut.RotationMatrix_[T] AngleAxis = AngleAxis_[T] Quaternion = Quaternion_[T] RollPitchYaw = mut.RollPitchYaw_[T] R = RotationMatrix() numpy_compare.assert_float_equal( RotationMatrix(other=R).matrix(), np.eye(3)) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) numpy_compare.assert_float_equal(copy.copy(R).matrix(), np.eye(3)) numpy_compare.assert_float_equal( RotationMatrix.Identity().matrix(), np.eye(3)) R = RotationMatrix(R=np.eye(3)) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) R = RotationMatrix.MakeUnchecked(R=np.eye(3)) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) R = RotationMatrix(quaternion=Quaternion.Identity()) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) R = RotationMatrix(theta_lambda=AngleAxis(angle=0, axis=[0, 0, 1])) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) R = RotationMatrix(rpy=RollPitchYaw(rpy=[0, 0, 0])) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) # One axis RotationMatrices R = RotationMatrix.MakeXRotation(theta=0) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) R = RotationMatrix.MakeYRotation(theta=0) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) R = RotationMatrix.MakeZRotation(theta=0) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) # TODO(eric.cousineau): #11575, remove the conditional. if T == float: numpy_compare.assert_float_equal(R.row(index=0), [1., 0., 0.]) numpy_compare.assert_float_equal(R.col(index=0), [1., 0., 0.]) R = RotationMatrix.MakeFromOneVector(b_A=[1, 0, 0], axis_index=0) numpy_compare.assert_equal(R.IsValid(), True) R.set(R=np.eye(3)) numpy_compare.assert_float_equal(R.matrix(), np.eye(3)) # - Cast. self.check_cast(mut.RotationMatrix_, T) # - Conversion to RollPitchYaw roll_pitch_yaw = R.ToRollPitchYaw() self.assertIsInstance(roll_pitch_yaw, RollPitchYaw) # - Nontrivial quaternion. q = Quaternion(wxyz=[0.5, 0.5, 0.5, 0.5]) R = RotationMatrix(quaternion=q) q_R = R.ToQuaternion() numpy_compare.assert_float_equal( q.wxyz(), numpy_compare.to_float(q_R.wxyz())) # - Conversion to AngleAxis angle_axis = R.ToAngleAxis() self.assertIsInstance(angle_axis, AngleAxis) R_AngleAxis = RotationMatrix(angle_axis) R_I = R.inverse().multiply(R_AngleAxis) numpy_compare.assert_equal(R_I.IsNearlyIdentity(), True) numpy_compare.assert_equal(R_I.IsNearlyIdentity(2E-15), True) R_I = R.InvertAndCompose(other=R_AngleAxis) numpy_compare.assert_equal(R_I.IsNearlyIdentity(2E-15), True) # - Inverse, transpose, projection R_I = R.inverse().multiply(R) numpy_compare.assert_float_equal(R_I.matrix(), np.eye(3)) numpy_compare.assert_float_equal((R.inverse() @ R).matrix(), np.eye(3)) R_T = R.transpose().multiply(R) numpy_compare.assert_float_equal(R_T.matrix(), np.eye(3)) R_P = RotationMatrix.ProjectToRotationMatrix(M=2*np.eye(3)) numpy_compare.assert_float_equal(R_P.matrix(), np.eye(3)) # - Multiplication. R_AB = RotationMatrix([ [0., 1, 0], [-1, 0, 0], [0, 0, 1]]) v_B = [10, 20, 30] v_A = [20., -10., 30] numpy_compare.assert_float_equal(R_AB.multiply(v_B=v_B), v_A) # N.B. Remember that this takes ndarray[3, n], NOT ndarray[n, 3]! vlist_B = np.array([v_B, v_B]).T vlist_A = np.array([v_A, v_A]).T numpy_compare.assert_float_equal(R_AB.multiply(v_B=vlist_B), vlist_A) # - Test shaping (#13885). v = np.array([0., 0., 0.]) vs = np.array([[1., 2., 3.], [4., 5., 6.]]).T self.assertEqual((R_AB @ v).shape, (3,)) self.assertEqual((R_AB @ v.reshape((3, 1))).shape, (3, 1)) self.assertEqual((R_AB @ vs).shape, (3, 2)) # Matrix checks numpy_compare.assert_equal(R.IsValid(), True) R = RotationMatrix() numpy_compare.assert_equal(R.IsExactlyIdentity(), True) numpy_compare.assert_equal(R.IsNearlyIdentity(0.0), True) numpy_compare.assert_equal(R.IsNearlyIdentity(tolerance=1E-15), True) # - Repr. z = repr(T(0.0)) # "z" for zero i = repr(T(1.0)) # "i" for identity (one) t = repr(T(2.0)) # "t" for two type_suffix = { float: "", AutoDiffXd: "_[AutoDiffXd]", Expression: "_[Expression]", }[T] self.assertEqual(repr(RotationMatrix()), textwrap.dedent(f"""\ RotationMatrix{type_suffix}([ [{i}, {z}, {z}], [{z}, {i}, {z}], [{z}, {z}, {i}], ])""")) self.assertEqual(repr(RollPitchYaw(rpy=[2, 1, 0])), f"RollPitchYaw{type_suffix}(" f"roll={t}, pitch={i}, yaw={z})") if T == float: # TODO(jwnimmer-tri) Once AutoDiffXd and Expression implement an # eval-able repr, then we can test more than just T=float here. roundtrip = eval(repr(RotationMatrix())) self.assertTrue(roundtrip.IsExactlyIdentity()) roundtrip = eval(repr(RollPitchYaw(rpy=[2, 1, 0]))) self.assertAlmostEqual(roundtrip.roll_angle(), 2) self.assertAlmostEqual(roundtrip.pitch_angle(), 1) self.assertAlmostEqual(roundtrip.yaw_angle(), 0) # Test pickling. assert_pickle(self, R_AB, RotationMatrix.matrix, T=T) R_AB = RotationMatrix.MakeUnchecked(np.full((3, 3), math.inf)) assert_pickle(self, R_AB, RotationMatrix.matrix, T=T) @numpy_compare.check_all_types def test_roll_pitch_yaw(self, T): # - Constructors. RollPitchYaw = mut.RollPitchYaw_[T] RotationMatrix = mut.RotationMatrix_[T] Quaternion = Quaternion_[T] rpy = RollPitchYaw(rpy=[0, 0, 0]) numpy_compare.assert_float_equal( RollPitchYaw(other=rpy).vector(), [0., 0., 0.]) numpy_compare.assert_float_equal(rpy.vector(), [0., 0., 0.]) rpy = RollPitchYaw(roll=0, pitch=0, yaw=0) numpy_compare.assert_float_equal([ rpy.roll_angle(), rpy.pitch_angle(), rpy.yaw_angle()], [0., 0., 0.]) rpy = RollPitchYaw(R=RotationMatrix()) numpy_compare.assert_float_equal(rpy.vector(), [0., 0., 0.]) rpy = RollPitchYaw(matrix=np.eye(3)) numpy_compare.assert_float_equal(rpy.vector(), [0., 0., 0.]) q_I = Quaternion() rpy_q_I = RollPitchYaw(quaternion=q_I) numpy_compare.assert_float_equal(rpy_q_I.vector(), [0., 0., 0.]) # - Additional properties. numpy_compare.assert_float_equal( rpy.ToQuaternion().wxyz(), numpy_compare.to_float(q_I.wxyz())) R = rpy.ToRotationMatrix().matrix() numpy_compare.assert_float_equal(R, np.eye(3)) # - Converting changes in orientation numpy_compare.assert_float_equal(rpy.CalcRotationMatrixDt( rpyDt=[0, 0, 0]), np.zeros((3, 3))) numpy_compare.assert_float_equal( rpy.CalcAngularVelocityInParentFromRpyDt(rpyDt=[0, 0, 0]), [0., 0., 0.]) numpy_compare.assert_float_equal( rpy.CalcAngularVelocityInChildFromRpyDt(rpyDt=[0, 0, 0]), [0., 0., 0.]) numpy_compare.assert_float_equal( rpy.CalcRpyDtFromAngularVelocityInParent(w_AD_A=[0, 0, 0]), [0., 0., 0.]) numpy_compare.assert_float_equal( rpy.CalcRpyDtFromAngularVelocityInChild(w_AD_D=[0, 0, 0]), [0., 0., 0.]) numpy_compare.assert_float_equal( rpy.CalcRpyDDtFromRpyDtAndAngularAccelInParent( rpyDt=[0, 0, 0], alpha_AD_A=[0, 0, 0]), [0., 0., 0.]) numpy_compare.assert_float_equal(rpy.CalcRpyDDtFromAngularAccelInChild( rpyDt=[0, 0, 0], alpha_AD_D=[0, 0, 0]), [0., 0., 0.]) # Test pickling. assert_pickle(self, rpy, RollPitchYaw.vector, T=T) @numpy_compare.check_all_types def test_bspline_basis(self, T): BsplineBasis = mut.BsplineBasis_[T] bspline = BsplineBasis() self.assertEqual(bspline.order(), 0) self.assertEqual(BsplineBasis(other=bspline).order(), 0) bspline = BsplineBasis(order=2, knots=[0, 1, 3, 5]) self.assertEqual(bspline.order(), 2) bspline = BsplineBasis(order=2, num_basis_functions=3, type=mut.KnotVectorType.kUniform, initial_parameter_value=5., final_parameter_value=6.) self.assertEqual(bspline.order(), 2) self.assertEqual(bspline.degree(), 1) self.assertEqual(bspline.num_basis_functions(), 3) numpy_compare.assert_float_equal(bspline.knots(), [4.5, 5.0, 5.5, 6.0, 6.5]) numpy_compare.assert_float_equal(bspline.initial_parameter_value(), 5.) numpy_compare.assert_float_equal(bspline.final_parameter_value(), 6.) self.assertEqual( bspline.FindContainingInterval(parameter_value=5.2), 1) self.assertEqual( bspline.ComputeActiveBasisFunctionIndices( parameter_interval=[5.2, 5.7]), [0, 1, 2]) self.assertEqual( bspline.ComputeActiveBasisFunctionIndices(parameter_value=5.4), [0, 1]) val = bspline.EvaluateCurve(control_points=[[1, 2], [2, 3], [3, 4]], parameter_value=5.7) self.assertEqual(val.shape, (2,)) numpy_compare.assert_float_equal( bspline.EvaluateBasisFunctionI(i=0, parameter_value=5.7), 0.) assert_pickle(self, bspline, BsplineBasis.knots, T=T) @numpy_compare.check_all_types def test_wrap_to(self, T): value = wrap_to(T(1.5), T(0.), T(1.)) if T != Expression: self.assertEqual(value, T(.5)) @numpy_compare.check_nonsymbolic_types def test_soft_min_max(self, T): x = [T(1), T(2), T(3)] self.assertLess(mut.SoftUnderMax(x=x, alpha=1), T(3)) self.assertGreater(mut.SoftOverMax(x=x, alpha=1), T(3)) self.assertLess(mut.SoftUnderMin(x=x, alpha=1), T(1)) self.assertGreater(mut.SoftOverMin(x=x, alpha=1), T(1)) @numpy_compare.check_all_types def test_cross_product(self, T): p = np.array([T(1), T(2), T(3)]) p_cross = mut.VectorToSkewSymmetric(p) self.assertEqual(p_cross.shape, (3, 3)) @numpy_compare.check_all_types def test_quaternion(self, T): q1 = Quaternion_[T]() q2 = Quaternion_[T]() w = np.zeros(3) tolerance = 1e-4 quat = mut.ClosestQuaternion(quat1=q1, quat2=q2) self.assertIsInstance(quat, Quaternion_[T]) b = mut.is_quaternion_in_canonical_form(quat=q1) numpy_compare.assert_equal(b, True) quat = mut.QuaternionToCanonicalForm(quat=q1) self.assertIsInstance(quat, Quaternion_[T]) b = mut.AreQuaternionsEqualForOrientation(quat1=q1, quat2=q2, tolerance=tolerance) numpy_compare.assert_equal(b, True) quatDt = mut.CalculateQuaternionDtFromAngularVelocityExpressedInB( quat_AB=q1, w_AB_B=w) numpy_compare.assert_float_equal(quatDt, np.zeros(4)) w2 = mut.CalculateAngularVelocityExpressedInBFromQuaternionDt( quat_AB=q1, quatDt=quatDt) self.assertEqual(len(w2), 3) v = mut.CalculateQuaternionDtConstraintViolation(quat=q1, quatDt=quatDt) self.assertIsInstance(v, T) b = mut.IsQuaternionValid(quat=q1, tolerance=tolerance) numpy_compare.assert_equal(b, True) b = mut.IsBothQuaternionAndQuaternionDtOK(quat=q1, quatDt=quatDt, tolerance=tolerance) numpy_compare.assert_equal(b, True) def test_random_rotations(self): g = RandomGenerator() quat = mut.UniformlyRandomQuaternion(g) self.assertIsInstance(quat, Quaternion_[float]) angle_axis = mut.UniformlyRandomAngleAxis(g) self.assertIsInstance(angle_axis, AngleAxis_[float]) rot_mat = mut.UniformlyRandomRotationMatrix(g) self.assertIsInstance(rot_mat, mut.RotationMatrix) rpy = mut.UniformlyRandomRPY(g) self.assertIsInstance(rpy, np.ndarray) self.assertEqual(len(rpy), 3) def test_matrix_util(self): A = np.array([[1, 2], [3, 4]]) self.assertFalse(mut.IsSymmetric(matrix=A)) self.assertFalse(mut.IsSymmetric(matrix=A, precision=0)) self.assertTrue(mut.IsSymmetric(np.eye(3), 0.)) self.assertFalse(mut.IsPositiveDefinite(matrix=A, tolerance=0)) self.assertTrue(mut.IsPositiveDefinite(A.dot(A.T))) lower_triangular = np.array([1, 2, 3, 4, 5, 6.]) symmetric_mat = mut.ToSymmetricMatrixFromLowerTriangularColumns( lower_triangular_columns=lower_triangular) np.testing.assert_array_equal( symmetric_mat, np.array([[1, 2, 3], [2, 4, 5], [3, 5, 6]])) lower_triangular2 = mut.ToLowerTriangularColumnsFromMatrix( matrix=symmetric_mat) np.testing.assert_array_equal(lower_triangular, lower_triangular2) minor_indices = {0, 2} minor = mut.ExtractPrincipalSubmatrix(matrix=symmetric_mat, indices=minor_indices) np.testing.assert_array_equal( minor, symmetric_mat[np.ix_(list(minor_indices), list(minor_indices))]) def test_quadratic_form(self): Q = np.diag([1., 2., 3.]) X = mut.DecomposePSDmatrixIntoXtransposeTimesX( Y=Q, zero_tol=1e-8, return_empty_if_not_psd=False) np.testing.assert_array_almost_equal(X, np.sqrt(Q)) b = np.zeros(3) c = 4. R, d = mut.DecomposePositiveQuadraticForm(Q, b, c) self.assertEqual(np.size(R, 0), 4) self.assertEqual(np.size(R, 1), 3) self.assertEqual(len(d), 4) T = mut.BalanceQuadraticForms(S=np.eye(3), P=np.eye(3)) np.testing.assert_array_almost_equal(T, np.eye(3)) def test_riccati_lyapunov(self): A = 0.1*np.eye(2) B = np.eye(2) Q = np.eye(2) R = np.eye(2) mut.ContinuousAlgebraicRiccatiEquation(A=A, B=B, Q=Q, R=R) mut.RealContinuousLyapunovEquation(A=A, Q=Q) mut.RealDiscreteLyapunovEquation(A=A, Q=Q) A = np.array([[1, 1], [0, 1]]) B = np.array([[0], [1]]) Q = np.array([[1, 0], [0, 0]]) R = [0.3] mut.DiscreteAlgebraicRiccatiEquation(A=A, B=B, Q=Q, R=R) def test_compute_numerical_gradient(self): option = mut.NumericalGradientOption( method=mut.NumericalGradientMethod.kCentral, function_accuracy=1E-15) self.assertIn("kCentral", repr(option)) def foo(x): return np.array([x[0] ** 2, x[0] * x[1]]) grad = mut.ComputeNumericalGradient( calc_func=foo, x=np.array([1., 2.]), option=option) np.testing.assert_allclose( grad, np.array([[2., 0.], [2., 1.]]), atol=1E-5) @numpy_compare.check_all_types def test_value_instantiations(self, T): # Existence checks. Value[mut.RigidTransform_[T]] Value[List[mut.RigidTransform_[T]]] Value[mut.RotationMatrix_[T]] Value[List[mut.RotationMatrix_[T]]]
0
/home/johnshepherd/drake/bindings/pydrake/math
/home/johnshepherd/drake/bindings/pydrake/math/test/math_overloads_test.py
""" Test math overloads. """ import math import unittest import numpy as np # Change this to inspect output. VERBOSE = False def debug_print(*args): # Prints only if `VERBOSE` is true. if VERBOSE: print(*args) def qualname(obj): return "{}.{}".format(obj.__module__, obj.__name__) class Overloads: # Provides interface for testing function overloads for a given type, `T`. def supports(self, func): # Determines if `func` is supported by this overload. raise NotImplemented def to_float(self, y_T): # Converts `y_T` (a value of type `T`) to a float. raise NotImplemented def to_type(self, y_float): # Converts `y_float` (a float value) to a value of type `T`. raise NotImplemented class FloatOverloads(Overloads): # Imports `math` and provides support for testing `float` overloads. def __init__(self): import pydrake.math as m self.m = m self.T = float self.T_logical = bool def supports(self, func): return True def to_float(self, y_T): return y_T def to_type(self, y_float): return y_float class AutoDiffOverloads(Overloads): # Imports `pydrake.autodiffutils` and provides support for testing its # overloads. def __init__(self): import pydrake.autodiffutils as m self.m = m self.T = m.AutoDiffXd self.T_logical = bool def supports(self, func): backwards_compat = [ "cos", "sin", ] supported = backwards_compat + [ "log", "tan", "asin", "acos", "atan2", "sinh", "cosh", "tanh", "inv", ] if func.__name__ in backwards_compat: # Check backwards compatibility. assert hasattr(self.T, func.__name__) return func.__name__ in supported def to_float(self, y_T): return y_T.value() def to_type(self, y_float): return self.T(y_float, []) class SymbolicOverloads(Overloads): # Imports `pydrake.symbolic` and provides support for testing its # overloads. def __init__(self): import pydrake.symbolic as m self.m = m self.T = m.Expression self.T_logical = bool def supports(self, func): backwards_compat = [ "log", "abs", "exp", "sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "sinh", "cosh", "tanh", "ceil", "floor", "min", "max", "pow", "atan2", "inv", ] supported = backwards_compat if func.__name__ in backwards_compat: # Check backwards compatibility. assert hasattr(self.m, func.__name__), self.m.__name__ return func.__name__ in supported def to_float(self, y_T): return y_T.Evaluate() def to_type(self, y_float): return self.T(y_float) class MathOverloadsTest(unittest.TestCase): """Tests overloads of math functions.""" def test_overloads(self): self.check_overload(FloatOverloads()) self.check_overload(SymbolicOverloads()) self.check_overload(AutoDiffOverloads()) def check_overload(self, overload): # TODO(eric.cousineau): Consider comparing against `numpy` ufunc # methods. import pydrake.math as drake_math unary = [ (drake_math.log, math.log), (drake_math.abs, math.fabs), (drake_math.exp, math.exp), (drake_math.sqrt, math.sqrt), (drake_math.sin, math.sin), (drake_math.cos, math.cos), (drake_math.tan, math.tan), (drake_math.asin, math.asin), (drake_math.acos, math.acos), (drake_math.atan, math.atan), (drake_math.sinh, math.sinh), (drake_math.cosh, math.cosh), (drake_math.tanh, math.tanh), (drake_math.ceil, math.ceil), (drake_math.floor, math.floor), ] unary_logical = [ (drake_math.isnan, math.isnan), ] binary = [ (drake_math.min, min), (drake_math.max, max), (drake_math.pow, pow), (drake_math.atan2, math.atan2), ] # Arbitrary values to test overloads with. args_float_all = [0.1, 0.2] def check_eval(functions, nargs, *, logical=False): # Generate arguments. args_float = args_float_all[:nargs] args_T = list(map(overload.to_type, args_float)) # Check each supported function. for f_drake, f_builtin in functions: with self.subTest(function=f_drake.__name__, nargs=nargs): if not overload.supports(f_drake): continue debug_print( "- Functions: ", qualname(f_drake), qualname(f_builtin), ) y_builtin = f_builtin(*args_float) y_float = f_drake(*args_float) debug_print( " - - Float Eval:", repr(y_builtin), repr(y_float), ) self.assertEqual(y_float, y_builtin) if logical: self.assertIsInstance(y_float, bool) else: self.assertIsInstance(y_float, float) # Test method current overload, and ensure value is # accurate. y_T = f_drake(*args_T) y_T_float = overload.to_float(y_T) debug_print( " - - Overload Eval:", repr(y_T), repr(y_T_float), ) if logical: self.assertIsInstance(y_T, overload.T_logical) else: self.assertIsInstance(y_T, overload.T) # - Ensure the translated value is accurate. self.assertEqual(y_T_float, y_float) debug_print("\n\nOverload: ", qualname(type(overload))) float_overload = FloatOverloads() # Check each number of arguments. debug_print("Unary:") check_eval(unary, 1) debug_print("Unary Logical:") check_eval(unary_logical, 1, logical=True) debug_print("Binary:") check_eval(binary, 2) # Check specialized linear / array algebra. if overload.supports(drake_math.inv): f_drake, f_builtin = drake_math.inv, np.linalg.inv X_float = np.eye(2) Y_builtin = f_builtin(X_float) Y_float = f_drake(X_float) self.assertIsInstance(Y_float[0, 0].item(), float) np.testing.assert_equal(Y_builtin, Y_float) to_type_array = np.vectorize(overload.to_type) to_float_array = np.vectorize(overload.to_float) X_T = to_type_array(X_float) Y_T = drake_math.inv(X_T) self.assertIsInstance(Y_T[0, 0], overload.T) np.testing.assert_equal(to_float_array(Y_T), Y_float)
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/gym/_drake_gym_env.py
from typing import Callable, Optional, Union import warnings import gymnasium as gym import numpy as np from pydrake.common import RandomGenerator from pydrake.systems.analysis import Simulator, SimulatorStatus from pydrake.systems.framework import ( Context, InputPort, InputPortIndex, OutputPortIndex, PortDataType, System, ) from pydrake.systems.sensors import ImageRgba8U class DrakeGymEnv(gym.Env): """ DrakeGymEnv provides a gym.Env interface for a Drake System (often a Diagram) using a Simulator. """ def __init__(self, simulator: Union[Simulator, Callable[[RandomGenerator], Simulator]], time_step: float, action_space: gym.spaces.Space, observation_space: gym.spaces.Space, reward: Union[Callable[[System, Context], float], OutputPortIndex, str], action_port_id: Union[InputPort, InputPortIndex, str] = None, observation_port_id: Union[OutputPortIndex, str] = None, render_rgb_port_id: Union[OutputPortIndex, str] = None, render_mode: str = 'human', reset_handler: Callable[[Simulator, Context], None] = None, hardware: bool = False): """ Args: simulator: Either a ``drake.systems.analysis.Simulator``, or a function that produces a (randomized) Simulator. time_step: Each call to ``step()`` will advance the simulator by ``time_step`` seconds. action_space: Defines the ``gym.spaces.Space`` for the actions. If the action port is vector-valued, then passing ``None`` defaults to a ``gym.spaces.Box`` of the correct dimension with bounds at negative and positive infinity. Note: Stable Baselines 3 strongly encourages normalizing the ``action_space`` to [-1, 1]. observation_space: Defines the ``gym.spaces.Space`` for the observations. If the observation port is vector-valued, then passing ``None`` defaults to a ``gym.spaces.Box`` of the correct dimension with bounds at negative and positive infinity. reward: The reward can be specified in one of two ways: (1) by passing a callable with the signature ``value = reward(system, context)`` or (2) by passing a scalar vector-valued output port of ``simulator``'s system. action_port_id: The ID of an input port of ``simulator``'s system compatible with the ``action_space``. Each Env *must* have an action port; passing ``None`` defaults to using the *first* input port (inspired by ``InputPortSelection.kUseFirstInputIfItExists``). observation_port_id: An output port of ``simulator``'s system compatible with the ``observation_space``. Each Env *must* have an observation port (it seems that gym doesn't support empty observation spaces / open-loop policies); passing ``None`` defaults to using the *first* input port (inspired by ``OutputPortSelection.kUseFirstOutputIfItExists``). render_rgb_port_id: An optional output port of ``simulator``'s system that returns an ``ImageRgba8U``; often the ``color_image`` port of a Drake ``RgbdSensor``. render_mode: The render mode of the environment determined at initialization. Defaults to ``human`` which uses visualizers inside the System (e.g. MeshcatVisualizer, PlanarSceneGraphVisualizer, etc.). ``render_mode`` equal to ``rgb_array`` evaluates the ``render_rgb_port`` and ``ansi`` calls ``__repr__`` on the system Context. reset_handler: A function that sets the home state (plant, and/or env.) at ``reset()``. The reset state can be specified in one of the two ways: (if ``reset_handler`` is None) setting random context using a Drake random_generator (e.g. ``joint.set_random_pose_distribution()`` using the ``reset()`` seed), (otherwise) using ``reset_handler()``. hardware: If True, it prevents from setting random context at ``reset()`` when using ``random_generator``, but it does execute ``reset_handler()`` if given. Notes (using ``env`` as an instance of this class): - You may set simulator/integrator preferences by using ``env.simulator`` directly. - The ``done`` condition returned by ``step()`` is always False by default. Use ``env.simulator.set_monitor()`` to use Drake's monitor functionality for specifying termination conditions. - You may additionally wish to directly set ``env.reward_range`` and/or ``env.spec``. See the docs for ``gym.Env`` for more details. """ super().__init__() if isinstance(simulator, Simulator): self.simulator = simulator self.make_simulator = None elif callable(simulator): self.simulator = None self.make_simulator = simulator else: raise ValueError("Invalid simulator argument") assert time_step > 0 self.time_step = time_step assert isinstance(action_space, gym.spaces.Space) self.action_space = action_space assert isinstance(observation_space, gym.spaces.Space) self.observation_space = observation_space if isinstance(reward, (OutputPortIndex, str)): self.reward_port_id = reward self.reward = None elif callable(reward): self.reward_port_id = None self.reward = reward else: raise ValueError("Invalid reward argument") if action_port_id: assert isinstance(action_port_id, (InputPortIndex, str)) self.action_port_id = action_port_id else: self.action_port_id = InputPortIndex(0) if observation_port_id: assert isinstance(observation_port_id, (OutputPortIndex, str)) self.observation_port_id = observation_port_id else: self.observation_port_id = OutputPortIndex(0) self.metadata['render_modes'] = ['human', 'ascii'] # Setup rendering. self.render_mode = render_mode if render_rgb_port_id: assert isinstance(render_rgb_port_id, (OutputPortIndex, str)) self.render_mode = 'rgb_array' self.metadata['render_modes'].append('rgb_array') self.render_rgb_port_id = render_rgb_port_id self.generator = RandomGenerator() if reset_handler is None or callable(reset_handler): self.reset_handler = reset_handler else: raise ValueError("reset_handler is not callable.") self.hardware = hardware if self.simulator: self._setup() def _setup(self): """Completes the setup once we have a self.simulator.""" system = self.simulator.get_system() # Setup action port if self.action_port_id: if isinstance(self.action_port_id, InputPortIndex): self.action_port = system.get_input_port(self.action_port_id) else: self.action_port = system.GetInputPort(self.action_port_id) if self.action_port.get_data_type() == PortDataType.kVectorValued: assert np.array_equal(self.action_space.shape, [self.action_port.size()]) def get_output_port(id): if isinstance(id, OutputPortIndex): return system.get_output_port(id) return system.GetOutputPort(id) # Setup observation port if self.observation_port_id: self.observation_port = get_output_port(self.observation_port_id) if self.observation_port.get_data_type() == PortDataType.kVectorValued: assert np.array_equal(self.observation_space.shape, [self.observation_port.size()]) # Note: We require that there is no direct feedthrough action_port to # observation_port. Unfortunately, HasDirectFeedthrough returns false # positives, and would produce noisy warnings. # Setup reward. if self.reward_port_id: reward_port = get_output_port(self.reward_port_id) self.reward = lambda system, context: reward_port.Eval(context)[0] # Setup rendering port. if self.render_rgb_port_id: self.render_rgb_port = get_output_port(self.render_rgb_port_id) assert self.render_rgb_port.get_data_type() == \ PortDataType.kAbstractValued assert isinstance(self.render_rgb_port.Allocate().get_value(), ImageRgba8U) def step(self, action): """ Implements ``gym.Env.step`` to advance the simulation forward by one ``self.time_step``. Args: action: an element from ``self.action_space``. """ assert self.simulator, "You must call reset() first" context = self.simulator.get_context() time = context.get_time() self.action_port.FixValue(context, action) truncated = False # Observation prior to advancing the simulation. prev_observation = self.observation_port.Eval(context) info = dict() try: status = self.simulator.AdvanceTo(time + self.time_step) except RuntimeError as e: # TODO(JoseBarreiros-TRI) We don't currently check for the # error coming from the solver failing to converge. warnings.warn("Calling Done after catching RuntimeError:") warnings.warn(e.args[0]) # Truncated is used when the solver failed to converge. # Note: this is different than the official use of truncated # in Gymnasium: # "Whether the truncation condition outside the scope of the MDP # is satisfied. Typically, this is a timelimit, but # could also be used to indicate an agent physically going out # of bounds." # We handle the solver failure to converge by returning # zero reward and the previous observation since the action # was not successfully applied. This comes at a cost of # an extra evaluation of the observation port. truncated = True terminated = False reward = 0 return prev_observation, reward, terminated, truncated, info observation = self.observation_port.Eval(context) reward = self.reward(self.simulator.get_system(), context) terminated = ( not truncated and (status.reason() == SimulatorStatus.ReturnReason.kReachedTerminationCondition)) return observation, reward, terminated, truncated, info def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): """ If a callable "simulator factory" was passed to the constructor, then a new simulator is created. Otherwise this method simply resets the ``simulator`` and its Context. """ super().reset(seed=seed) assert options is None or options == dict(), ( "Options are not supported in env.reset() method.") if (seed is not None): # TODO(ggould) This should not reset the generator if it was # already explicitly seeded (see API spec), but we have no way to # check that at the moment. self.generator = RandomGenerator(seed) if self.make_simulator: self.simulator = self.make_simulator(self.generator) self._setup() context = self.simulator.get_mutable_context() context.SetTime(0) self.simulator.Initialize() if self.reset_handler is not None: # The initial state is set by reset_handler(). self.simulator.get_system().SetDefaultContext(context) self.reset_handler(self.simulator, context, seed) else: if not self.hardware: self.simulator.get_system().SetRandomContext(context, self.generator) # Note: The output port will be evaluated without fixing the input # port. observations = self.observation_port.Eval(context) return observations, dict() def render(self): """ Rendering in ``human`` mode is accomplished by calling ForcedPublish on ``system``. This should cause visualizers inside the System (e.g. MeshcatVisualizer, PlanarSceneGraphVisualizer, etc.) to draw their outputs. To be fully compliant, those visualizers should set their default publishing period to ``np.inf`` (do not publish periodically). Rendering in ``ascii`` mode calls ``__repr__`` on the system Context. Rendering in ``rgb_array`` mode is enabled by passing a compatible ``render_rgb_port`` to the class constructor. """ assert self.simulator, "You must call reset() first" if self.render_mode == 'human': self.simulator.get_system().ForcedPublish( self.simulator.get_context()) return elif self.render_mode == 'ansi': return __repr__(self.simulator.get_context()) elif self.render_mode == 'rgb_array': assert self.render_rgb_port, \ "You must set render_rgb_port in the constructor" return self.render_rgb_port.Eval( self.simulator.get_context()).data[:, :, :3] else: super(DrakeGymEnv).render()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/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_library", "drake_py_unittest", ) 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 = "gym", srcs = [ "__init__.py", "_drake_gym_env.py", ], deps = [ "//bindings/pydrake/systems", "@gymnasium_py", ], ) drake_py_library( name = "mock_torch_py", testonly = True, srcs = [ "test/mock_torch/torch/__init__.py", "test/mock_torch/torch/distributions.py", "test/mock_torch/torch/nn.py", "test/mock_torch/torch/optim.py", ], imports = ["test/mock_torch"], ) # TODO(ggould-tri) This depends on things in `examples` in order to build a # working env in order to run Gym's validation functions. We rely on Bazel # to prevent this from being a circular dependency. drake_py_unittest( name = "drake_gym_test", # DrakeGym is only supported for Python >= 3.10. tags = ["manual"] if PYTHON_VERSION in [ "3.8", "3.9", ] else [], deps = [ ":gym", ":mock_torch_py", "//bindings/pydrake/examples/gym:cart_pole_py", "@stable_baselines3_internal//:stable_baselines3", ], ) PY_LIBRARIES = [ ":gym", ] install( name = "install", targets = PY_LIBRARIES, py_dest = PACKAGE_INFO.py_dest, ) add_lint_tests_pydrake()
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/gym/README.md
Drake Gym ========= Running the examples -------------------- An example of training to stabilize a cart-pole system is provided. It includes added noise in the observation, added random disturbances, randomized states (position, velocity), randomized mass, and a monitoring camera for rollout logging. Before trying the following examples, <strong>read the note on dependencies below</strong>. Training can be invoked it via: bazel run //bindings/pydrake/examples/gym:train_cart_pole Depending on your machine, you should see the reward (`ep_rew_mean`) increasing from 0 to ~120 in about 7 min. The learned model can be played with: bazel run //bindings/pydrake/examples/gym:play_cart_pole -- \ --model_path {path_to_zip_model_file} A random policy can be played with: bazel run //bindings/pydrake/examples/gym:play_cart_pole -- --test To visualize, open meshcat by following the link in the prompts. If this link fails, it is likely that your loopback device is broken. Try using http://127.0.0.1:7000 instead. A note on dependencies ---------------------- In order to use a Gym, code must implement a `gymnasium.Env` (in this case the actual `Simulator` wrapped via `DrakeGymEnv`) and must run the Gym within an RL engine of some sort (that's usually an algorithm chosen from [Stable Baselines 3](https://stable-baselines3.readthedocs.io/en/master/index.html) but could also be from `nevergrad` or some other source of gradient-free optimizers). Stable Baselines3 itself is too large and too heavy of a dependency tree for Drake to require itself; as such you will need to provide it yourself to use these examples. If you are going to train drake gym examples on your machine, you should install a few dependencies including `stable_baselines3` and `gymnasium` inside of a virtual environment. The training examples will not run without it, and drake does not come with it (Drake does include a subset of `stable_baselines3` for testing purposes, but not enough to perform training). Run the training example via: # Create an environment (or use an existing). python3 -m venv ~/tmp/drakegym --system-site-packages # Activate the environment. source ~/tmp/drakegym/bin/activate # Install dependencies. pip install gymnasium stable_baselines3 tensorboard moviepy # From the Drake source tree, run the training. cd {your_your_drake_directory}/drake export PYTHONPATH=~/tmp/drakegym/lib/python3.10/site-packages bazel run //bindings/pydrake/examples/gym:train_cart_pole Notes ----- * The overall concept of Drake Gym is discussed in [the course notes for Russ's Robot Manipulation course](https://manipulation.csail.mit.edu/rl.html#section1) * The code here is borrowed from [the repository backing the course notebooks](https://github.com/RussTedrake/manipulation/blob/f569cd653f35202416e865c42d6825eff9ef2691/manipulation/drake_gym.py) * Where possible this code has been borrowed verbatim; small changes (e.g. to bazel rules, namespaces, and so forth) have been required.
0
/home/johnshepherd/drake/bindings/pydrake
/home/johnshepherd/drake/bindings/pydrake/gym/__init__.py
""" Drake Gym ========= THIS FEATURE IS EXPERIMENTAL. As per our [guidelines](https://drake.mit.edu/stable.html) for experimental code, development is ongoing and no guarantees against deprecation are provided for any file under this directory. Drake Gym is an implementation of Farama's "Gymnasium" interface for reinforcement learning which uses a Drake `Simulator` as a backend. The Gym interface provided by [the python `gym` module](https://pypi.org/project/gymnasium/) simply models a time-stepped process with an action space, a reward function, and some form of state observation. Note that pydrake.gym is an optional component of pydrake, and will only work when the gymnasium package is also installed. As such, the DrakeGymEnv and related code is not available for import as part of `pydrake.all`. A note on dependencies ---------------------- In order to use a Gym, code must implement a `gymnasium.Env` (in this case the actual `Simulator` wrapped via `DrakeGymEnv`) and must run the Gym within an RL engine of some sort (that's usually an algorithm chosen from [Stable Baselines 3] (https://stable-baselines3.readthedocs.io/en/master/index.html) but could also be from `nevergrad` or some other source of gradient-free optimizers). Stable Baselines3 iteself is too large and too heavy of a dependency tree for Drake to require itself; as such you will need to provide it yourself to use these examples. If you are going to train drake gym examples on your machine, you should install Stable Baselines 3 (for instance, `pip install stable_baselines3` inside of a virtual environment). The training examples will not run without it, and drake does not come with it (Drake does include a subset of `stable_baselines3` for testing purposes, but not enough to perform training). """ from ._drake_gym_env import DrakeGymEnv __all__ = [x for x in globals() if not x.startswith("_")]
0