repo_id
stringclasses
205 values
file_path
stringlengths
33
141
content
stringlengths
1
307k
__index_level_0__
int64
0
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_binary", "drake_cc_googletest", "drake_cc_library", "drake_cc_package_library", ) load("//tools/skylark:drake_py.bzl", "drake_py_binary") package(default_visibility = ["//visibility:public"]) drake_cc_package_library( name = "util", visibility = ["//visibility:public"], deps = [ ":apply_driver_configs", ":make_arm_controller_model", ":move_ik_demo_base", ":moving_average_filter", ":robot_plan_interpolator", ":robot_plan_utils", ":zero_force_driver", ":zero_force_driver_functions", ], ) drake_cc_library( name = "move_ik_demo_base", srcs = [ "move_ik_demo_base.cc", ], hdrs = [ "move_ik_demo_base.h", ], deps = [ ":robot_plan_utils", "//lcmtypes:robot_plan", "//multibody/inverse_kinematics:constraint_relaxing_ik", "//multibody/parsing", "//multibody/plant", ], ) drake_cc_library( name = "robot_plan_utils", srcs = [ "robot_plan_utils.cc", ], hdrs = [ "robot_plan_utils.h", ], deps = [ "//common:default_scalars", "//lcmtypes:robot_plan", "//multibody/plant", ], ) # TODO(naveenoid) : Move the moving_average_filter to within drake/perception. drake_cc_library( name = "moving_average_filter", srcs = ["moving_average_filter.cc"], hdrs = ["moving_average_filter.h"], deps = ["//common:essential"], ) drake_cc_library( name = "apply_driver_configs", hdrs = ["apply_driver_configs.h"], ) drake_cc_library( name = "zero_force_driver", hdrs = ["zero_force_driver.h"], deps = [ "//common:name_value", ], ) drake_cc_library( name = "zero_force_driver_functions", srcs = ["zero_force_driver_functions.cc"], hdrs = ["zero_force_driver_functions.h"], interface_deps = [ ":zero_force_driver", "//multibody/parsing:model_instance_info", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/lcm:lcm_buses", ], deps = [ "//systems/primitives:constant_vector_source", ], ) drake_cc_library( name = "make_arm_controller_model", srcs = ["make_arm_controller_model.cc"], hdrs = ["make_arm_controller_model.h"], deps = [ "//math:geometric_transform", "//multibody/parsing", "//multibody/plant", ], ) drake_cc_library( name = "robot_plan_interpolator", srcs = ["robot_plan_interpolator.cc"], hdrs = ["robot_plan_interpolator.h"], deps = [ "//common/trajectories:piecewise_polynomial", "//lcmtypes:robot_plan", "//multibody/parsing", "//systems/framework:leaf_system", ], ) drake_py_binary( name = "show_model", srcs = ["show_model.py"], deps = ["//bindings/pydrake"], ) drake_py_binary( name = "meshlab_to_sdf", srcs = ["meshlab_to_sdf.py"], ) drake_cc_binary( name = "stl2obj", srcs = ["stl2obj.cc"], visibility = ["//:__subpackages__"], deps = [ "//common:add_text_logging_gflags", "//common:essential", "@gflags", "@vtk_internal//:vtkFiltersCore", "@vtk_internal//:vtkIOGeometry", ], ) # === test/ === drake_cc_googletest( name = "move_ik_demo_base_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":move_ik_demo_base", "//manipulation/kuka_iiwa:iiwa_constants", ], ) drake_cc_googletest( name = "robot_plan_utils_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":robot_plan_utils", "//multibody/parsing", ], ) drake_cc_googletest( name = "moving_average_filter_test", srcs = ["test/moving_average_filter_test.cc"], deps = [ ":moving_average_filter", "//common:essential", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", ], ) drake_cc_googletest( name = "zero_force_driver_functions_test", data = [ "@drake_models//:wsg_50_description", ], deps = [ ":zero_force_driver_functions", "//multibody/parsing", "//systems/analysis:simulator", ], ) filegroup( name = "panda_arm_and_hand_test_model", testonly = 1, srcs = [ ":test/panda_arm_and_hand.dmd.yaml", "@drake_models//:franka_description", ], visibility = ["//multibody/parsing:__pkg__"], ) drake_cc_googletest( name = "make_arm_controller_model_test", data = [ ":test/fake_camera.sdf", ":test/iiwa7_wsg.dmd.yaml", ":test/iiwa7_wsg_cameras.dmd.yaml", "@drake_models//:iiwa_description", "@drake_models//:wsg_50_description", ], deps = [ ":make_arm_controller_model", "//common:find_resource", "//common/test_utilities:eigen_matrix_compare", "//math:geometric_transform", "//multibody/parsing:parser", "//multibody/parsing:process_model_directives", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/primitives:shared_pointer_system", ], ) drake_cc_googletest( name = "robot_plan_interpolator_test", data = [ "//examples/kuka_iiwa_arm:models", "@drake_models//:iiwa_description", ], deps = [ ":robot_plan_interpolator", "//systems/framework", ], ) filegroup( name = "test_directives", testonly = True, srcs = [ ":test/iiwa7_wsg.dmd.yaml", ], ) filegroup( name = "test_models", testonly = True, srcs = [ ":test/simple_nested_model.sdf", ":test/simple_world_with_two_models.sdf", ], ) add_lint_tests()
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/robot_plan_interpolator.cc
#include "drake/manipulation/util/robot_plan_interpolator.h" #include <map> #include <memory> #include <set> #include <stdexcept> #include <string> #include <utility> #include <vector> #include "drake/common/fmt_eigen.h" #include "drake/common/text_logging.h" #include "drake/common/trajectories/piecewise_polynomial.h" #include "drake/lcmt_robot_plan.hpp" #include "drake/multibody/parsing/parser.h" namespace drake { namespace manipulation { namespace util { using multibody::BodyIndex; using multibody::JointIndex; using trajectories::PiecewisePolynomial; // TODO(sammy-tri) If we had version of Trajectory which supported // outputting the derivatives in value(), we could avoid keeping track // of multiple polynomials below. struct RobotPlanInterpolator::PlanData { PlanData() {} double start_time{0}; std::vector<char> encoded_msg; PiecewisePolynomial<double> pp; PiecewisePolynomial<double> pp_deriv; PiecewisePolynomial<double> pp_double_deriv; }; RobotPlanInterpolator::RobotPlanInterpolator(const std::string& model_path, const InterpolatorType interp_type, double update_interval) : plan_input_port_( this->DeclareAbstractInputPort("plan", Value<lcmt_robot_plan>()) .get_index()), interp_type_(interp_type) { multibody::Parser(&plant_).AddModels(model_path); // Search for any bodies with no parent. We'll weld those to the world. std::set<BodyIndex> parent_bodies; std::set<BodyIndex> child_bodies; for (JointIndex i : plant_.GetJointIndices()) { const multibody::Joint<double>& joint = plant_.get_joint(i); if (joint.parent_body().index() == plant_.world_body().index()) { // Nothing to weld, we're connected to the world. parent_bodies.clear(); break; } parent_bodies.insert(joint.parent_body().index()); child_bodies.insert(joint.child_body().index()); } if (!parent_bodies.empty()) { for (const BodyIndex& child : child_bodies) { if (parent_bodies.contains(child)) { parent_bodies.erase(child); } } // Weld all remaining parents to the world. This probably isn't going to // work for all model types. for (const BodyIndex& index : parent_bodies) { plant_.WeldFrames(plant_.world_frame(), plant_.get_body(index).body_frame()); } } plant_.Finalize(); // TODO(sammy-tri) This implementation doesn't know how to // calculate velocities/accelerations for differing numbers of // positions and velocities. DRAKE_DEMAND(plant_.IsVelocityEqualToQDot()); const int num_pv = plant_.num_positions() + plant_.num_velocities(); state_output_port_ = this->DeclareVectorOutputPort("state", num_pv, &RobotPlanInterpolator::OutputState) .get_index(); acceleration_output_port_ = this->DeclareVectorOutputPort("acceleration", plant_.num_velocities(), &RobotPlanInterpolator::OutputAccel) .get_index(); // This corresponds to the actual plan. plan_index_ = this->DeclareAbstractState(Value<PlanData>()); // Flag indicating whether RobotPlanInterpolator::Initialize has been called. init_flag_index_ = this->DeclareAbstractState(Value<bool>(false)); this->DeclarePeriodicUnrestrictedUpdateEvent( update_interval, 0, &RobotPlanInterpolator::UpdatePlanOnNewMessage); } RobotPlanInterpolator::~RobotPlanInterpolator() {} void RobotPlanInterpolator::OutputState( const systems::Context<double>& context, systems::BasicVector<double>* output) const { const PlanData& plan = context.get_abstract_state<PlanData>(plan_index_); const bool inited = context.get_abstract_state<bool>(init_flag_index_); DRAKE_DEMAND(inited); Eigen::VectorBlock<VectorX<double>> output_vec = output->get_mutable_value(); const double current_plan_time = context.get_time() - plan.start_time; output_vec.head(plant_.num_positions()) = plan.pp.value(current_plan_time); output_vec.tail(plant_.num_velocities()) = plan.pp_deriv.value(current_plan_time); } void RobotPlanInterpolator::OutputAccel( const systems::Context<double>& context, systems::BasicVector<double>* output) const { const PlanData& plan = context.get_abstract_state<PlanData>(plan_index_); const bool inited = context.get_abstract_state<bool>(init_flag_index_); DRAKE_DEMAND(inited); Eigen::VectorBlock<VectorX<double>> output_acceleration_vec = output->get_mutable_value(); const double current_plan_time = context.get_time() - plan.start_time; output_acceleration_vec = plan.pp_double_deriv.value(current_plan_time); // Stop outputting accelerations at the end of the plan. if (current_plan_time > plan.pp_double_deriv.end_time()) { output_acceleration_vec.fill(0); } } void RobotPlanInterpolator::MakeFixedPlan(double plan_start_time, const VectorX<double>& q0, systems::State<double>* state) const { DRAKE_DEMAND(state != nullptr); DRAKE_DEMAND(q0.size() == plant_.num_positions()); PlanData& plan = state->get_mutable_abstract_state<PlanData>(plan_index_); std::vector<Eigen::MatrixXd> knots(2, q0); std::vector<double> times{0., 1.}; plan.start_time = plan_start_time; plan.pp = PiecewisePolynomial<double>::ZeroOrderHold(times, knots); plan.pp_deriv = plan.pp.derivative(); plan.pp_double_deriv = plan.pp_deriv.derivative(); drake::log()->info("Generated fixed plan at {}", fmt_eigen(q0.transpose())); } void RobotPlanInterpolator::Initialize(double plan_start_time, const VectorX<double>& q0, systems::State<double>* state) const { DRAKE_DEMAND(state != nullptr); MakeFixedPlan(plan_start_time, q0, state); state->get_mutable_abstract_state<bool>(init_flag_index_) = true; } systems::EventStatus RobotPlanInterpolator::UpdatePlanOnNewMessage( const systems::Context<double>& context, systems::State<double>* state) const { PlanData& plan = state->get_mutable_abstract_state<PlanData>(plan_index_); const lcmt_robot_plan& plan_input = get_plan_input_port().Eval<lcmt_robot_plan>(context); // I (sammy-tri) wish I could think of a more effective way to // determine that a new message has arrived, but unfortunately // this is the best I've got. std::vector<char> encoded_msg(plan_input.getEncodedSize()); plan_input.encode(encoded_msg.data(), 0, encoded_msg.size()); if (encoded_msg == plan.encoded_msg) { return systems::EventStatus::DidNothing(); } plan.encoded_msg.swap(encoded_msg); if (plan_input.num_states == 0) { // The plan is empty. Encode a plan for the current planned position. const double current_plan_time = context.get_time() - plan.start_time; MakeFixedPlan(context.get_time(), plan.pp.value(current_plan_time), state); } else if (plan_input.num_states == 1) { drake::log()->info("Ignoring plan with only one knot point."); } else { plan.start_time = context.get_time(); std::vector<Eigen::MatrixXd> knots( plan_input.num_states, Eigen::MatrixXd::Zero(plant_.num_positions(), 1)); for (int i = 0; i < plan_input.num_states; ++i) { const auto& plan_state = plan_input.plan[i]; for (int j = 0; j < plan_state.num_joints; ++j) { if (!plant_.HasJointNamed(plan_state.joint_name[j])) { continue; } const auto joint_index = plant_.GetJointByName(plan_state.joint_name[j]).position_start(); knots[i](joint_index, 0) = plan_state.joint_position[j]; } } std::vector<double> input_time; for (int k = 0; k < static_cast<int>(plan_input.plan.size()); ++k) { input_time.push_back(plan_input.plan[k].utime / 1e6); } const Eigen::MatrixXd knot_dot = Eigen::MatrixXd::Zero(plant_.num_velocities(), 1); switch (interp_type_) { case InterpolatorType::ZeroOrderHold: plan.pp = PiecewisePolynomial<double>::ZeroOrderHold(input_time, knots); break; case InterpolatorType::FirstOrderHold: plan.pp = PiecewisePolynomial<double>::FirstOrderHold(input_time, knots); break; case InterpolatorType::Pchip: plan.pp = PiecewisePolynomial<double>::CubicShapePreserving( input_time, knots, true); break; case InterpolatorType::Cubic: plan.pp = PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives( input_time, knots, knot_dot, knot_dot); break; } plan.pp_deriv = plan.pp.derivative(); plan.pp_double_deriv = plan.pp_deriv.derivative(); } return systems::EventStatus::Succeeded(); } } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/move_ik_demo_base.h
#pragma once #include <memory> #include <optional> #include <string> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/lcmt_robot_plan.hpp" #include "drake/math/rigid_transform.h" #include "drake/multibody/inverse_kinematics/constraint_relaxing_ik.h" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace manipulation { namespace util { /// This class provides some common functionality for generating IK plans for /// robot arms, including things like creating a MultibodyPlant, setting joint /// velocity limits, implementing a robot status update handler suitable for /// invoking from an LCM callback, and generating plans to move a specified /// link to a goal configuration. /// /// This can be useful when building simple demonstration programs to move a /// robot arm, for example when testing new arms which haven't been previously /// used with Drake, or testing modifications to existing robot /// configurations. See the kuka_iiwa_arm and kinova_jaco_arm examples for /// existing uses. class MoveIkDemoBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MoveIkDemoBase); /// @param robot_description A description file to load of the robot to /// plan. /// /// @param base_link Name of the base link of the robot, will be welded to /// the world in the planning model. /// /// @param ik_link Name of the link to plan a pose for. /// /// @param print_interval Print an updated end effector position every N /// calls to HandleStatus. MoveIkDemoBase(std::string robot_description, std::string base_link, std::string ik_link, int print_interval); ~MoveIkDemoBase(); /// @return a reference to the internal plant. const multibody::MultibodyPlant<double>& plant() const { return plant_; } /// Set the joint velocity limits when building the plan. The default /// velocity limits from the robot description will be used if this isn't /// set. /// /// @pre The size of the input vector must be equal to the number of /// velocities in the MultibodyPlant (see plant()). void set_joint_velocity_limits(const Eigen::Ref<const Eigen::VectorXd>&); /// Update the current robot status. /// /// @param q must be equal to the number of positions in the MultibodyPlant /// (see plant()). void HandleStatus(const Eigen::Ref<const Eigen::VectorXd>& q); /// Attempt to generate a plan moving ik_link (specified at construction /// time) from the joint configuration specified in the last call to /// `HandleStatus` to a configuration with ik_link at @p goal_pose. Returns /// nullopt if planning failed. /// /// @throw If HandleStatus has not been invoked. std::optional<lcmt_robot_plan> Plan(const math::RigidTransformd& goal_pose); /// Returns a count of how many times `HandleStatus` has been called. int status_count() const { return status_count_; } private: std::string robot_description_; std::string ik_link_; int print_interval_{}; multibody::MultibodyPlant<double> plant_; std::unique_ptr<systems::Context<double>> context_; std::vector<std::string> joint_names_; Eigen::VectorXd joint_velocity_limits_; int status_count_{0}; multibody::ConstraintRelaxingIk constraint_relaxing_ik_; }; } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/make_arm_controller_model.h
#pragma once #include <memory> #include <optional> #include "drake/math/rotation_matrix.h" #include "drake/multibody/parsing/model_instance_info.h" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace manipulation { namespace internal { /* Constructs a separate plant (different from the simulated plant!) that can be used to instantiate a controller system such as `InverseDynamicsController`. The difference between this plant and @p simulation_plant is the dynamics modeling error. The returned plant will contain an arm model loaded from @p arm_info.model_path and welded to the world at @p arm_info.child_frame_name at the same pose as @p simulation_plant. All bodies welded directly to bodies of the arm will be replaced with lumped masses. If @p gripper_info is provided, this function will use @p simulation_plant to measure the gripper's inertia and attach a single non-articulated rigid body that matches the gripper's inertia, including any bodies welded to the gripper. Additionally, if `grasp_frame` is present in the gripper model and welded to @p gripper_info.child_frame_name, a `grasp_frame` Frame will be added at the same pose as @p simulation_plant. This function requires that (a) most intermediate frames / bodies can be recreated by loading the URDF / SDFormat file dictated by ModelInstanceInfo and (b) the heuristics in ProcessModelDirectives reflect the actual construction of this plant. @pre @p arm_info.child_frame_name is welded to the world frame. @pre If @p gripper_info is given and `grasp_frame` exists, then `grasp_frame` is welded to @p gripper_info.child_frame_name. */ // TODO(eric.cousineau): Replace this with more generic (and robust) multibody // plant subgraph (#7336). std::unique_ptr<multibody::MultibodyPlant<double>> MakeArmControllerModel( const multibody::MultibodyPlant<double>& simulation_plant, const multibody::parsing::ModelInstanceInfo& arm_info, const std::optional<multibody::parsing::ModelInstanceInfo>& gripper_info = {}); } // namespace internal } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/show_model.py
# Prints a deprecation notice and forwards to the equivalent pydrake script. # TODO(jwnimmer-tri) Remove this stub on or around 2025-01-01. from pydrake.visualization.model_visualizer import _main if __name__ == '__main__': print("** Note: This script is deprecated. **") print("Please switch to //tools:model_visualizer when convenient.") _main()
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/robot_plan_utils.cc
#include "drake/manipulation/util/robot_plan_utils.h" #include <map> #include "drake/common/default_scalars.h" #include "drake/common/drake_assert.h" namespace drake { namespace manipulation { namespace util { /// @return A vector of joint names corresponding to the positions in @plant /// in the order of the joint indices. template <typename T> std::vector<std::string> GetJointNames( const multibody::MultibodyPlant<T>& plant) { std::map<int, std::string> position_names; const int num_positions = plant.num_positions(); for (multibody::JointIndex i : plant.GetJointIndices()) { const multibody::Joint<T>& joint = plant.get_joint(i); if (joint.num_positions() == 0) { continue; } DRAKE_DEMAND(joint.num_positions() == 1); DRAKE_DEMAND(joint.position_start() < num_positions); position_names[joint.position_start()] = joint.name(); } DRAKE_DEMAND(static_cast<int>(position_names.size()) == num_positions); std::vector<std::string> joint_names; for (int i = 0; i < num_positions; ++i) { joint_names.push_back(position_names[i]); } return joint_names; } void ApplyJointVelocityLimits(const std::vector<Eigen::VectorXd>& keyframes, const Eigen::VectorXd& limits, std::vector<double>* times) { DRAKE_DEMAND(keyframes.size() == times->size()); DRAKE_DEMAND(times->front() == 0); const int num_time_steps = keyframes.size(); // Calculate a matrix of velocities between each time step. We'll // use this later to determine by how much the plan exceeds the // joint velocity limits. Eigen::MatrixXd velocities(limits.size(), num_time_steps - 1); for (int i = 0; i < velocities.rows(); i++) { for (int j = 0; j < velocities.cols(); j++) { DRAKE_ASSERT((*times)[j + 1] > (*times)[j]); velocities(i, j) = std::abs((keyframes[j + 1](i) - keyframes[j](i)) / ((*times)[j + 1] - (*times)[j])); } } Eigen::VectorXd velocity_ratios(velocities.rows()); for (int i = 0; i < velocities.rows(); i++) { const double max_plan_velocity = velocities.row(i).maxCoeff(); velocity_ratios(i) = max_plan_velocity / limits(i); } const double max_velocity_ratio = velocity_ratios.maxCoeff(); if (max_velocity_ratio > 1) { // The code below slows the entire plan such that the fastest step // meets the limits. If that step is much faster than the others, // the whole plan becomes very slow. drake::log()->debug("Slowing plan by {}", max_velocity_ratio); for (int j = 0; j < num_time_steps; j++) { (*times)[j] *= max_velocity_ratio; } } } lcmt_robot_plan EncodeKeyFrames(const std::vector<std::string>& joint_names, const std::vector<double>& times, const std::vector<Eigen::VectorXd>& keyframes) { DRAKE_DEMAND(keyframes.size() == times.size()); const int num_time_steps = keyframes.size(); lcmt_robot_plan plan{}; plan.utime = 0; // I (sam.creasey) don't think this is used? plan.num_states = num_time_steps; const lcmt_robot_state default_robot_state{}; plan.plan.resize(num_time_steps, default_robot_state); /// Encode the q_sol returned for each time step into the vector of /// robot states. for (int i = 0; i < num_time_steps; i++) { DRAKE_DEMAND(keyframes[i].size() == static_cast<int>(joint_names.size())); lcmt_robot_state& step = plan.plan[i]; step.utime = times[i] * 1e6; step.num_joints = keyframes[i].size(); for (int j = 0; j < step.num_joints; j++) { step.joint_name.push_back(joint_names[j]); step.joint_position.push_back(keyframes[i](j)); // step.joint_velocity.push_back(0); // step.joint_effort.push_back(0); } } return plan; } // clang-format off DRAKE_DEFINE_FUNCTION_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(( &GetJointNames<T> )) // clang-format on } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/meshlab_to_sdf.py
# Prints a message pointing the user to our replacement tool. # TODO(jwnimmer-tri) Remove this stub on or around 2025-01-01. import sys if __name__ == '__main__': print("** Error: This script has been removed. **") print("Instead, please use pydrake.multibody.mesh_to_model or pydrake.multibody.fix_inertia.") # noqa sys.exit(1)
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/make_arm_controller_model.cc
#include "drake/manipulation/util/make_arm_controller_model.h" #include <set> #include <string> #include <vector> #include "drake/math/rigid_transform.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/parsing/scoped_names.h" namespace drake { namespace manipulation { namespace internal { using math::RigidTransform; using multibody::BodyIndex; using multibody::Frame; using multibody::ModelInstanceIndex; using multibody::MultibodyPlant; using multibody::Parser; using multibody::RigidBody; using multibody::SpatialInertia; using multibody::parsing::ModelInstanceInfo; using systems::Context; namespace { template <typename Container, typename Item> bool Contains(const Container& haystack, const Item& needle) { return std::find(haystack.begin(), haystack.end(), needle) != haystack.end(); } bool AreFramesWelded(const MultibodyPlant<double>& plant, const Frame<double>& A, const Frame<double>& B) { if (&A.body() == &B.body()) { return true; } for (const auto* body : plant.GetBodiesWeldedTo(A.body())) { if (body == &B.body()) { return true; } } return false; } } // namespace std::unique_ptr<MultibodyPlant<double>> MakeArmControllerModel( const MultibodyPlant<double>& simulation_plant, const ModelInstanceInfo& arm_info, const std::optional<ModelInstanceInfo>& gripper_info) { log()->debug("MakeArmControllerModel:"); log()->debug(" arm:"); log()->debug(" model: {}", arm_info.model_path); log()->debug(" child_frame: {}", arm_info.child_frame_name); const ModelInstanceIndex sim_arm_model_index = simulation_plant.GetModelInstanceByName(arm_info.model_name); auto plant = std::make_unique<MultibodyPlant<double>>(0.0); plant->mutable_gravity_field().set_gravity_vector( simulation_plant.gravity_field().gravity_vector()); Parser parser(plant.get()); const auto models = parser.AddModels(arm_info.model_path); DRAKE_DEMAND(models.size() == 1); const ModelInstanceIndex arm_model_index = models[0]; // The arm must be anchored to the world. const Frame<double>& sim_arm_child_frame = simulation_plant.GetFrameByName( arm_info.child_frame_name, sim_arm_model_index); DRAKE_THROW_UNLESS(simulation_plant.IsAnchored(sim_arm_child_frame.body())); // Make sure that the arm is attached to the same location in the controller // plant as it is in the simulation plant. // TODO(siyuan): mbp should provide a way to query anchored frame kinematics // without a Context. std::unique_ptr<Context<double>> sim_context = simulation_plant.CreateDefaultContext(); const RigidTransform<double> arm_X_WC = simulation_plant.CalcRelativeTransform( *sim_context, simulation_plant.world_frame(), sim_arm_child_frame); plant->WeldFrames( plant->world_frame(), plant->GetFrameByName(arm_info.child_frame_name, arm_model_index), arm_X_WC); const std::vector<BodyIndex> sim_arm_body_indices = simulation_plant.GetBodyIndices(sim_arm_model_index); std::set<BodyIndex> sim_bodies_accounted_for(sim_arm_body_indices.begin(), sim_arm_body_indices.end()); // Get all models that are gripper-related. This includes all of the bodies // that are part of the gripper's model instance and anything welded to the // gripper (for example, the calibration checkerboard). if (gripper_info) { log()->debug(" gripper:"); log()->debug(" model: {}", gripper_info->model_path); log()->debug(" parent_frame: {}", gripper_info->parent_frame_name); log()->debug(" child_frame: {}", gripper_info->child_frame_name); DRAKE_DEMAND(gripper_info->model_instance != multibody::default_model_instance()); std::vector<BodyIndex> sim_gripper_body_indices = simulation_plant.GetBodyIndices(gripper_info->model_instance); const std::string gripper_body_name = gripper_info->child_frame_name; const Frame<double>& G = simulation_plant.GetFrameByName( gripper_body_name, gripper_info->model_instance); // TODO(sam-creasey) We actually want all kinematic children from the // gripper body, but there doesn't seem to be an existing way to do that // from MultibodyPlant. MultibodyTreeTopology/BodyTopology have the needed // information, but it doesn't seem to be accessible. std::vector<const RigidBody<double>*> sim_gripper_welded_bodies = simulation_plant.GetBodiesWeldedTo(G.body()); for (const RigidBody<double>* welded_body : sim_gripper_welded_bodies) { if ((welded_body->model_instance() != gripper_info->model_instance) && (welded_body->model_instance() != arm_info.model_instance)) { log()->debug("Adding BodyIndex of RigidBody {}", welded_body->name()); sim_gripper_body_indices.push_back(welded_body->index()); } } for (const BodyIndex& sim_body_index : sim_gripper_body_indices) { sim_bodies_accounted_for.insert(sim_body_index); } // `C` is the composite body for the gripper. const SpatialInertia<double> M_CGo_G = simulation_plant.CalcSpatialInertia( *sim_context, G, sim_gripper_body_indices); // Add surrogate composite body. const RigidBody<double>& C = plant->AddRigidBody(gripper_body_name, arm_model_index, M_CGo_G); // Make sure that the gripper is attached to the same location (and arm // frame) in the controller plant as it is in the simulation plant. const Frame<double>& sim_gripper_parent_frame = simulation_plant.GetFrameByName(gripper_info->parent_frame_name, arm_info.model_instance); // `Pp` is the "grand-parent" frame. const std::string gripper_grand_parent_frame_name = sim_gripper_parent_frame.body().body_frame().name(); const Frame<double>& gripper_grand_parent_frame = plant->GetFrameByName(gripper_grand_parent_frame_name, arm_model_index); log()->trace(" gripper_grand_parent_frame: {}", gripper_grand_parent_frame.scoped_name()); const RigidTransform<double> gripper_X_PpP = sim_gripper_parent_frame.GetFixedPoseInBodyFrame(); const RigidTransform<double> gripper_X_PpC = gripper_X_PpP * gripper_info->X_PC; plant->WeldFrames(gripper_grand_parent_frame, C.body_frame(), gripper_X_PpC); // Add the grasp frame, F, to the plant if present. if (simulation_plant.HasFrameNamed("grasp_frame", gripper_info->model_instance)) { const Frame<double>& frame_F = simulation_plant.GetFrameByName( "grasp_frame", gripper_info->model_instance); DRAKE_DEMAND(AreFramesWelded(simulation_plant, frame_F, G)); // Since F and G are rigidly attached, we can use the default context // to compute the offset. const RigidTransform<double> X_GF = frame_F.CalcPose(*sim_context, G); // Since the body frame of C in `plant` corresponds to frame G in // `simulation_plant`, the relative transform X_CF' (where F' is the grasp // frame in `plant`) should be equal to X_GF. plant->AddFrame(std::make_unique<multibody::FixedOffsetFrame<double>>( "grasp_frame", C.body_frame(), X_GF)); } } // For any body on the arm, account for attached mass that is not part of the // arm's model instance. // Note that the following bodies should already be accounted for: // - bodies on the arm itself // - bodies on and welded to the gripper, if gripper_info is supplied // TODO(eric.cousineau): Is it possible to iterate directly through welded // subgraphs? for (const BodyIndex& sim_body_index : sim_arm_body_indices) { const RigidBody<double>& sim_body = simulation_plant.get_body(sim_body_index); const std::vector<const RigidBody<double>*> sim_welded_bodies = simulation_plant.GetBodiesWeldedTo(sim_body); // Do not incorporate world-welded information. if (Contains(sim_welded_bodies, &simulation_plant.world_body())) { continue; } std::vector<BodyIndex> sim_to_calc_inertia; for (const RigidBody<double>* sim_welded_body : sim_welded_bodies) { if (sim_bodies_accounted_for.contains(sim_welded_body->index())) { continue; } sim_bodies_accounted_for.insert(sim_welded_body->index()); sim_to_calc_inertia.push_back(sim_welded_body->index()); } if (sim_to_calc_inertia.size() > 0) { const RigidBody<double>& body = plant->GetBodyByName(sim_body.name(), arm_model_index); // `C` is the new (composite) body. const SpatialInertia<double> M_CBo_B = simulation_plant.CalcSpatialInertia( *sim_context, sim_body.body_frame(), sim_to_calc_inertia); const std::string temp_body_name = fmt::format("_{}_attached_mass", body.name()); const RigidBody<double>& new_body = plant->AddRigidBody(temp_body_name, arm_model_index, M_CBo_B); plant->WeldFrames(body.body_frame(), new_body.body_frame()); } } plant->Finalize(); return plant; } } // namespace internal } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/stl2obj.cc
#include <gflags/gflags.h> // To ease build system upkeep, we annotate VTK includes with their deps. #include <vtkDecimatePro.h> // vtkFiltersCore #include <vtkOBJWriter.h> // vtkIOGeometry #include <vtkSTLReader.h> // vtkIOGeometry #include <vtkTriangleFilter.h> // vtkFiltersCore #include "drake/common/drake_throw.h" #include "drake/common/text_logging.h" DEFINE_string(input, "", "STL filename to read"); DEFINE_string(output, "", "OBJ filename to write"); DEFINE_double(reduction, 0.0, "Remove this fraction of the vertices (< 1.0)"); namespace drake { namespace { void main() { DRAKE_THROW_UNLESS(!FLAGS_input.empty()); DRAKE_THROW_UNLESS(!FLAGS_output.empty()); DRAKE_THROW_UNLESS(FLAGS_reduction >= 0.0); DRAKE_THROW_UNLESS(FLAGS_reduction < 1.0); // Load the STL. auto reader = vtkSmartPointer<vtkSTLReader>::New(); reader->SetFileName(FLAGS_input.c_str()); reader->Update(); vtkPolyData* to_be_written = reader->GetOutput(); log()->debug("The STL mesh has {} points and {} polygons", to_be_written->GetNumberOfPoints(), to_be_written->GetNumberOfPolys()); // Optionally decimate. We must to create these objects outside of the // "if" block (not as temporaries inside) so that they remain available // for the OBJWriter to read from, below. auto triangle_reader = vtkSmartPointer<vtkTriangleFilter>::New(); auto decimate = vtkSmartPointer<vtkDecimatePro>::New(); if (FLAGS_reduction > 0.0) { triangle_reader->SetInputData(to_be_written); triangle_reader->Update(); decimate->SetInputData(triangle_reader->GetOutput()); decimate->PreserveTopologyOff(); decimate->SplittingOn(); decimate->BoundaryVertexDeletionOn(); decimate->SetMaximumError(VTK_DOUBLE_MAX); decimate->SetTargetReduction(FLAGS_reduction); decimate->Update(); to_be_written = decimate->GetOutput(); } // Write the OBJ. log()->debug("The OBJ mesh has {} points and {} polygons", to_be_written->GetNumberOfPoints(), to_be_written->GetNumberOfPolys()); auto writer = vtkSmartPointer<vtkOBJWriter>::New(); writer->SetFileName(FLAGS_output.c_str()); writer->SetInputData(to_be_written); writer->Write(); } } // namespace } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( R"""(Reads in an *.stl mesh and writes it out as an *.obj mesh. NOTE: The mesh conversion simply uses VTK's default mesh reading and writing. As with any automated conversion tool, the output might not satisfy your requirements. Be careful to confirm that the conversion meets your needs. )"""); gflags::ParseCommandLineFlags(&argc, &argv, true); drake::main(); return 0; }
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/move_ik_demo_base.cc
#include "drake/manipulation/util/move_ik_demo_base.h" #include <utility> #include "drake/common/drake_throw.h" #include "drake/common/fmt_eigen.h" #include "drake/manipulation/util/robot_plan_utils.h" #include "drake/multibody/parsing/parser.h" namespace drake { namespace manipulation { namespace util { using multibody::ConstraintRelaxingIk; MoveIkDemoBase::MoveIkDemoBase(std::string robot_description, std::string base_link, std::string ik_link, int print_interval) : robot_description_(std::move(robot_description)), ik_link_(std::move(ik_link)), print_interval_(print_interval), plant_(0.0), constraint_relaxing_ik_(robot_description_, ik_link_) { multibody::Parser(&plant_).AddModels(robot_description_); plant_.WeldFrames(plant_.world_frame(), plant_.GetBodyByName(base_link).body_frame()); plant_.Finalize(); context_ = plant_.CreateDefaultContext(); joint_names_ = GetJointNames(plant_); joint_velocity_limits_ = plant_.GetVelocityUpperLimits(); } MoveIkDemoBase::~MoveIkDemoBase() {} void MoveIkDemoBase::set_joint_velocity_limits( const Eigen::Ref<const Eigen::VectorXd>& velocity_limits) { DRAKE_THROW_UNLESS(velocity_limits.size() == joint_velocity_limits_.size()); joint_velocity_limits_ = velocity_limits; } void MoveIkDemoBase::HandleStatus(const Eigen::Ref<const Eigen::VectorXd>& q) { status_count_++; plant_.SetPositions(context_.get(), q); if (status_count_ % print_interval_ == 1) { const math::RigidTransform<double> current_link_pose = plant_.EvalBodyPoseInWorld(*context_, plant_.GetBodyByName(ik_link_)); const math::RollPitchYaw<double> rpy(current_link_pose.rotation()); drake::log()->info("{} at: {} {}", ik_link_, fmt_eigen(current_link_pose.translation().transpose()), fmt_eigen(rpy.vector().transpose())); } } std::optional<lcmt_robot_plan> MoveIkDemoBase::Plan( const math::RigidTransformd& goal_pose) { DRAKE_THROW_UNLESS(status_count_ > 0); // Create a single waypoint for our plan (the destination). // This results in a trajectory with two knot points (the // current pose (read from the status message currently being // processes and passed directly to PlanSequentialTrajectory as // iiwa_q) and the calculated final pose). ConstraintRelaxingIk::IkCartesianWaypoint wp; wp.pose = goal_pose; wp.constrain_orientation = true; std::vector<ConstraintRelaxingIk::IkCartesianWaypoint> waypoints; waypoints.push_back(wp); std::vector<Eigen::VectorXd> q_sol; const bool result = constraint_relaxing_ik_.PlanSequentialTrajectory( waypoints, plant_.GetPositions(*context_), &q_sol); drake::log()->info("IK result: {}", result); if (result) { drake::log()->info("IK sol size {}", q_sol.size()); // Run the resulting plan over 2 seconds (which is a fairly // arbitrary choice). This may be slowed down if executing // the plan in that time would exceed any joint velocity // limits. std::vector<double> times{0, 2}; DRAKE_DEMAND(q_sol.size() == times.size()); ApplyJointVelocityLimits(q_sol, joint_velocity_limits_, &times); lcmt_robot_plan plan = EncodeKeyFrames(joint_names_, times, q_sol); return plan; } return std::nullopt; } } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/robot_plan_utils.h
#pragma once /// @file /// Functions to help with the creation of lcmt_robot_plan messages. #include <string> #include <vector> #include "drake/lcmt_robot_plan.hpp" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace manipulation { namespace util { /// @return A vector of joint names corresponding to the positions in @p plant /// in the order of the joint indices. If joints with duplicate names exist /// in different model instance in the plant, the names will be duplicated in /// the output. template <typename T> std::vector<std::string> GetJointNames( const multibody::MultibodyPlant<T>& plant); /// Scales a plan so that no step exceeds the robot's maximum joint /// velocities. The size of @p keyframes must match the size of @p times. /// Times must be in strictly increasing order and start with zero. Per-joint /// velocity limits are specified by @p limits, which much be the same size ad /// the number of joints in each element of @p keyframes. Assumes that /// velocity limits are equal regardless of direction. If any step does /// exceed the maximum velocities in @p limits, @p times will be modified to /// reduce the velocity. void ApplyJointVelocityLimits(const std::vector<Eigen::VectorXd>& keyframes, const Eigen::VectorXd& limits, std::vector<double>* times); /// Makes an lcmt_robot_plan message. The entries in @p /// joint_names should be unique, though the behavior if names are duplicated /// depends on how the returned plan is evaluated. The size of each vector in /// @p keyframes must match the size of @p joint_names. The size of @p /// keyframes must match the size of @p times. Times must be in strictly /// increasing order. lcmt_robot_plan EncodeKeyFrames(const std::vector<std::string>& joint_names, const std::vector<double>& times, const std::vector<Eigen::VectorXd>& keyframes); } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/zero_force_driver_functions.cc
#include "drake/manipulation/util/zero_force_driver_functions.h" #include "drake/common/eigen_types.h" #include "drake/systems/primitives/constant_vector_source.h" namespace drake { namespace manipulation { using multibody::ModelInstanceIndex; using multibody::MultibodyPlant; using multibody::parsing::ModelInstanceInfo; using systems::ConstantVectorSource; using systems::DiagramBuilder; using systems::lcm::LcmBuses; void ApplyDriverConfig(const ZeroForceDriver&, const std::string& model_instance_name, const MultibodyPlant<double>& sim_plant, const std::map<std::string, ModelInstanceInfo>&, const LcmBuses&, DiagramBuilder<double>* builder) { DRAKE_THROW_UNLESS(builder != nullptr); const ModelInstanceIndex& model_instance = sim_plant.GetModelInstanceByName(model_instance_name); const int num_dofs = sim_plant.num_actuated_dofs(model_instance); // Fail-fast if we try to actuate an inert model. DRAKE_THROW_UNLESS(num_dofs > 0); auto actuation = builder->AddSystem<ConstantVectorSource<double>>( VectorX<double>::Zero(num_dofs)); actuation->set_name("zero_force_source_for_" + model_instance_name); builder->Connect(actuation->get_output_port(), sim_plant.get_actuation_input_port(model_instance)); } } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/moving_average_filter.h
#pragma once #include <stddef.h> #include <queue> #include "drake/common/drake_copyable.h" namespace drake { namespace manipulation { namespace util { /** * The implementation of a Moving Average Filter. This discrete time filter * outputs the average of the last n samples i.e. * y[k] = 1/n ∑ⱼ x[k-j] ∀ j = 0..n-1, when n<k and, * = 1/k ∑ⱼ x[j] ∀ j = 0..k otherwise; * where n is the window size and x being the discrete-time signal that is * to be filtered, y is the filtered signal and k is the index of latest * element in the signal time-series. * * Note that this class is meant to serve as a standalone simple utility and * a filter of this form in a more `drake::systems` flavour can be generated * from a `systems::AffineSystem` since this is a LTI filter. * * @tparam T The element type. * Instantiated templates for the following kinds of T's are provided: * * - double * - VectorX<double> */ template <typename T> class MovingAverageFilter { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(MovingAverageFilter) /** * Constructs the filter with the specified `window_size`. * @param window_size The size of the window. * @throws std::exception when window_size <= 0. */ explicit MovingAverageFilter(int window_size); /** * Updates the average filter result. Every call to this method modifies * the internal state of this filter thus resulting in a computation of * the moving average of the data present within the filter window. * * @param new_data * @return */ T Update(const T& new_data); const std::queue<T>& window() const { return window_; } /** * Returns the most recent result of the averaging filter. */ const T moving_average() const { return (1.0 / window_.size()) * sum_; } private: std::queue<T> window_; int window_size_{0}; T sum_; }; } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/zero_force_driver_functions.h
#pragma once #include <map> #include <string> #include "drake/manipulation/util/zero_force_driver.h" #include "drake/multibody/parsing/model_instance_info.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_buses.h" namespace drake { namespace manipulation { /** Applies zero actuation to every joint of a model mainly for debugging and testing purposes. @pre The sim_plant.is_finalized() is true. */ void ApplyDriverConfig( const ZeroForceDriver& driver_config, const std::string& model_instance_name, const multibody::MultibodyPlant<double>& sim_plant, const std::map<std::string, multibody::parsing::ModelInstanceInfo>& models_from_directives, const systems::lcm::LcmBuses& lcms, systems::DiagramBuilder<double>* builder); } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/moving_average_filter.cc
#include "drake/manipulation/util/moving_average_filter.h" #include "drake/common/drake_throw.h" #include "drake/common/eigen_types.h" namespace drake { namespace manipulation { namespace util { namespace { int get_dimensions(double) { return 1; } int get_dimensions(VectorX<double> data) { return data.size(); } } // namespace template <typename T> MovingAverageFilter<T>::MovingAverageFilter(int window_size) : window_size_(window_size) { DRAKE_THROW_UNLESS(window_size_ > 0); } template <typename T> T MovingAverageFilter<T>::Update(const T& new_data) { // First initialize sum (needed when type is not a scalar) if (window_.size() == 0) { sum_ = new_data; } else { // Check if new_data has the same dimension as the pre-existing data in the // window. DRAKE_THROW_UNLESS(get_dimensions(new_data) == get_dimensions(window_.front())); sum_ += new_data; } window_.push(new_data); if (window_.size() > static_cast<size_t>(window_size_)) { sum_ -= window_.front(); window_.pop(); } return moving_average(); } template class MovingAverageFilter<double>; template class MovingAverageFilter<VectorX<double>>; } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/util/apply_driver_configs.h
#pragma once #include <map> #include <string> #include <variant> #include <vector> #include "drake/multibody/parsing/process_model_directives.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_buses.h" namespace drake { namespace manipulation { // TODO(ggould) Eliminate our reliance on models_from_directives below, once we // have a better alternative to `MakeArmControllerModel`. // TODO(jeremy.nimmer) This function is not unit tested; it's just acceptance- // tested via drake/examples/hardware_sim. Consider whether there is any direct // unit test that would add value. /// Apply 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). /// /// The caller of this function is responsible for including the variant /// members' apply function, such as schunk_wsg_driver_functions.h. /// /// @p driver_configs The configurations to apply. /// @p sim_plant The plant containing the model. /// @p models_from_directives All of the `ModelInstanceInfo`s from previously- /// loaded directives. /// @p lcm_buses The available LCM buses to drive and/or sense from this driver. /// @p builder The `DiagramBuilder` into which to install this driver. template <typename... Types> void ApplyDriverConfigs( const std::map<std::string, std::variant<Types...>>& driver_configs, const multibody::MultibodyPlant<double>& sim_plant, const std::vector<multibody::parsing::ModelInstanceInfo>& models_from_directives, const systems::lcm::LcmBuses& lcm_buses, systems::DiagramBuilder<double>* builder) { std::map<std::string, multibody::parsing::ModelInstanceInfo> models_from_directives_map; for (const auto& info : models_from_directives) { models_from_directives_map.emplace(info.model_name, info); } for (const auto& config_pair : driver_configs) { // N.B. We can't use a structured binding here due to a Clang bug. const std::string& model_instance_name = config_pair.first; const auto& driver_config = config_pair.second; std::visit( [&](const auto& driver) { ApplyDriverConfig(driver, model_instance_name, sim_plant, models_from_directives_map, lcm_buses, builder); }, driver_config); } } } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/simple_nested_model.sdf
<?xml version="1.0"?> <sdf version="1.8"> <model name="top"> <model name="mid"> <link name="link"> <visual name="visual"> <geometry> <box> <size>0.2 0.2 0.2</size> </box> </geometry> </visual> <collision name="collision"> <geometry> <box> <size>0.2 0.2 0.2</size> </box> </geometry> </collision> </link> </model> </model> </sdf>
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/moving_average_filter_test.cc
#include "drake/manipulation/util/moving_average_filter.h" #include <memory> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" namespace drake { namespace manipulation { namespace util { namespace test { namespace { const unsigned int kWindowSize{3}; GTEST_TEST(MovingAverageFilterTest, InstantiationTest) { DRAKE_EXPECT_NO_THROW(MovingAverageFilter<double>(2)); EXPECT_ANY_THROW(MovingAverageFilter<double>(0)); } GTEST_TEST(MovingAverageDoubleTest, UpdateTest) { MovingAverageFilter<double> filter(kWindowSize); std::vector<double> window{-4.5, 1.0, 21.6}; double sum = 0; for (size_t i = 0; i < window.size(); ++i) { sum += window[i]; EXPECT_EQ((1.0 / (i + 1)) * sum, filter.Update(window[i])); } const double new_data_point = -12.8; EXPECT_EQ((1.0 / kWindowSize) * (sum + new_data_point - window[0]), filter.Update(new_data_point)); } GTEST_TEST(MovingAverageVectorTest, UpdateVectorTest) { MovingAverageFilter<VectorX<double>> filter(kWindowSize); std::vector<VectorX<double>> window; window.push_back( (VectorX<double>(5) << 0.3, 0.45, 0.76, -0.45, -0.32).finished()); window.push_back( (VectorX<double>(5) << 0.2, -5.2, 0.0, 0.45, -0.21).finished()); window.push_back( (VectorX<double>(5) << 0.5, 0.32, -5.0, -0.91, 0.54).finished()); VectorX<double> sum(5); sum.setZero(); // Output represents moving average. for (size_t i = 0; i < window.size(); ++i) { sum += window[i]; EXPECT_TRUE(CompareMatrices(((1.0 / (i + 1)) * sum), (filter.Update(window[i])), 1e-12, drake::MatrixCompareType::absolute)); } const VectorX<double> new_data_point = (VectorX<double>(5) << 0.67, -78.9, 3.6, 3.5, -10.0).finished(); EXPECT_TRUE(CompareMatrices( ((1.0 / kWindowSize) * (sum + new_data_point - window[0])), (filter.Update(new_data_point)), 1e-12, drake::MatrixCompareType::absolute)); // Check for death on wrong sized data. EXPECT_ANY_THROW(filter.Update((VectorX<double>(2) << -5.6, 9.0).finished())); } } // namespace } // namespace test } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/panda_arm_and_hand.dmd.yaml
directives: - add_model: name: panda file: package://drake_models/franka_description/urdf/panda_arm.urdf - add_weld: parent: world child: panda::panda_link0 - add_model: name: panda_hand file: package://drake_models/franka_description/urdf/panda_hand.urdf - add_weld: parent: panda::panda_link8 child: panda_hand::panda_hand X_PC: translation: [0, 0, 0] rotation: !Rpy { deg: [0, 0, -45] }
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/iiwa7_wsg.dmd.yaml
directives: - add_model: name: iiwa7 file: package://drake_models/iiwa_description/sdf/iiwa7_no_collision.sdf - add_model: name: schunk_wsg file: package://drake_models/wsg_50_description/sdf/schunk_wsg_50_with_tip.sdf # Weld iiwa7 to the world frame. - add_weld: parent: world child: iiwa7::iiwa_link_0 # Weld schunk_wsg to iiwa7. - add_frame: name: schunk_wsg_on_iiwa X_PF: base_frame: iiwa_link_7 translation: [0, 0, 0.114] rotation: !Rpy { deg: [90, 0, 90] } - add_weld: parent: schunk_wsg_on_iiwa child: schunk_wsg::body # Add `grasp_frame` to schunk_wsg model. - add_frame: name: schunk_wsg::grasp_frame X_PF: base_frame: schunk_wsg::body_frame translation: [0.0, 0.11, 0.0] rotation: !Rpy { deg: [0, 0, 0] }
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/move_ik_demo_base_test.cc
#include "drake/manipulation/util/move_ik_demo_base.h" #include <gtest/gtest.h> #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/multibody/parsing/package_map.h" namespace drake { namespace manipulation { namespace util { using multibody::PackageMap; const char kIiwaUrdf[] = "package://drake_models/iiwa_description/urdf/iiwa14_no_collision.urdf"; GTEST_TEST(MoveIkDemoBaseTest, IiwaTest) { math::RigidTransformd pose(math::RollPitchYawd(0, 0, -1.57), Eigen::Vector3d(0.8, -0.3, 0.25)); MoveIkDemoBase dut(PackageMap{}.ResolveUrl(kIiwaUrdf), "base", "iiwa_link_ee", 100); dut.set_joint_velocity_limits(kuka_iiwa::get_iiwa_max_joint_velocities()); dut.HandleStatus(Eigen::VectorXd::Ones(7)); auto plan = dut.Plan(pose); EXPECT_TRUE(plan.has_value()); dut.HandleStatus(Eigen::VectorXd::Ones(7) * 1.1); pose.set_translation(Eigen::Vector3d(0.7, -0.3, 0.25)); plan = dut.Plan(pose); EXPECT_TRUE(plan.has_value()); // TODO(sammy-tri) It would be good to have a test for planning failures // here, but this causes test timeouts under IPOPT (all builds) and SNOPT // (debug/asan builds). If ConstraintRelaxingIk were configurable, we could // make it fail quickly enough to add a test here. } } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/fake_camera.sdf
<?xml version="1.0"?> <sdf version="1.7"> <model name="fake_camera"> <link name="body"> <inertial> <mass>0.1</mass> <pose>0.01 0.02 0.03 0 0 0</pose> <inertia> <ixx>0.1</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.1</iyy> <iyz>0</iyz> <izz>0.1</izz> </inertia> </inertial> </link> </model> </sdf>
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/zero_force_driver_functions_test.cc
#include "drake/manipulation/util/zero_force_driver_functions.h" #include <gtest/gtest.h> #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant_config_functions.h" #include "drake/systems/analysis/simulator.h" namespace drake { namespace manipulation { namespace { using multibody::MultibodyPlant; using multibody::MultibodyPlantConfig; using multibody::Parser; using systems::DiagramBuilder; using systems::Simulator; GTEST_TEST(ZeroForceDriverFunctionsTest, SmokeTest) { // Create a MultibodyPlant containing a WSG gripper. DiagramBuilder<double> builder; MultibodyPlant<double>& plant = AddMultibodyPlant(MultibodyPlantConfig{}, &builder); Parser(&plant).AddModelsFromUrl( "package://drake_models/wsg_50_description/sdf/schunk_wsg_50.sdf"); plant.Finalize(); // Apply zero actuation input. const ZeroForceDriver config; ApplyDriverConfig(config, "Schunk_Gripper", plant, {}, {}, &builder); // Prove that simulation does not crash. Simulator<double> simulator(builder.Build()); simulator.AdvanceTo(0.1); } } // namespace } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/iiwa7_wsg_cameras.dmd.yaml
# This is meant to test attaching extra models welded to an arm # for `make_arm_controller_model_test`. directives: - add_directives: file: package://drake/manipulation/util/test/iiwa7_wsg.dmd.yaml - add_model: name: fake_camera_1 file: package://drake/manipulation/util/test/fake_camera.sdf - add_weld: parent: iiwa7::iiwa_link_4 child: fake_camera_1::__model__ - add_model: name: fake_camera_2 file: package://drake/manipulation/util/test/fake_camera.sdf - add_weld: parent: iiwa7::iiwa_link_6 child: fake_camera_2::__model__ - add_model: name: fake_camera_3 file: package://drake/manipulation/util/test/fake_camera.sdf - add_weld: parent: iiwa7::iiwa_link_7 child: fake_camera_3::__model__
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/robot_plan_interpolator_test.cc
#include "drake/manipulation/util/robot_plan_interpolator.h" #include <gtest/gtest.h> #include "drake/lcmt_robot_plan.hpp" #include "drake/multibody/parsing/package_map.h" namespace drake { namespace manipulation { namespace util { namespace { using multibody::PackageMap; static const int kNumJoints = 7; const char* const kIiwaUrdf = "package://drake_models/iiwa_description/urdf/" "iiwa14_polytope_collision.urdf"; const char* const kDualIiwaUrdf = "package://drake_models/iiwa_description/urdf/" "dual_iiwa14_polytope_collision.urdf"; GTEST_TEST(RobotPlanInterpolatorTest, InstanceTest) { // Test that the constructor works and that the expected ports are // present. RobotPlanInterpolator dut(PackageMap{}.ResolveUrl(kIiwaUrdf)); EXPECT_EQ(dut.get_plan_input_port().get_data_type(), systems::kAbstractValued); EXPECT_EQ(dut.get_state_output_port().get_data_type(), systems::kVectorValued); EXPECT_EQ(dut.get_state_output_port().size(), kNumJoints * 2); EXPECT_EQ(dut.get_acceleration_output_port().get_data_type(), systems::kVectorValued); EXPECT_EQ(dut.get_acceleration_output_port().size(), kNumJoints); } GTEST_TEST(RobotPlanInterpolatorTest, DualInstanceTest) { // Check that the port sizes come out appropriately for a dual armed // model. RobotPlanInterpolator dut(PackageMap{}.ResolveUrl(kDualIiwaUrdf)); EXPECT_EQ(dut.plant().num_positions(), kNumJoints * 2); EXPECT_EQ(dut.plant().num_velocities(), kNumJoints * 2); EXPECT_EQ(dut.get_plan_input_port().get_data_type(), systems::kAbstractValued); EXPECT_EQ(dut.get_state_output_port().get_data_type(), systems::kVectorValued); EXPECT_EQ(dut.get_state_output_port().size(), kNumJoints * 4); EXPECT_EQ(dut.get_acceleration_output_port().get_data_type(), systems::kVectorValued); EXPECT_EQ(dut.get_acceleration_output_port().size(), kNumJoints * 2); } struct TrajectoryTestCase { TrajectoryTestCase(double time_in, double position_in, double velocity_in, double accel_in) : time(time_in), position(position_in), velocity(velocity_in), accel(accel_in) {} const double time{}; const double position{}; const double velocity{}; const double accel{}; }; void DoTrajectoryTest(InterpolatorType interp_type) { RobotPlanInterpolator dut(PackageMap{}.ResolveUrl(kIiwaUrdf), interp_type); std::vector<double> t{0, 1, 2, 3, 4}; Eigen::MatrixXd q = Eigen::MatrixXd::Zero(kNumJoints, t.size()); // Only bother with one joint. q(0, 1) = 1; q(0, 2) = 1.5; q(0, 3) = 1.5; q(0, 4) = 1; std::vector<int> info(t.size(), 1); const int num_time_steps = q.cols(); // Encode into an lcmt_robot_plan structure. lcmt_robot_plan plan{}; plan.num_states = num_time_steps; const lcmt_robot_state default_robot_state{}; plan.plan.resize(num_time_steps, default_robot_state); std::vector<std::string> joint_names; for (multibody::JointIndex i : dut.plant().GetJointIndices()) { const multibody::Joint<double>& joint = dut.plant().get_joint(i); if (joint.num_positions() != 1) { continue; } joint_names.push_back(joint.name()); } ASSERT_EQ(joint_names.size(), kNumJoints); for (int i = 0; i < num_time_steps; i++) { lcmt_robot_state& step = plan.plan[i]; step.utime = t[i] * 1e6; step.num_joints = q.rows(); step.joint_name = joint_names; for (int j = 0; j < step.num_joints; j++) { step.joint_position.push_back(q(j, i)); } } std::unique_ptr<systems::Context<double>> context = dut.CreateDefaultContext(); std::unique_ptr<systems::SystemOutput<double>> output = dut.AllocateOutput(); dut.get_plan_input_port().FixValue(context.get(), plan); dut.Initialize(0, Eigen::VectorXd::Zero(kNumJoints), &context->get_mutable_state()); dut.UpdatePlan(context.get()); // Test we're running the plan through time by watching the // positions, velocities, and acceleration change. std::vector<TrajectoryTestCase> cases; std::string interp_str; switch (interp_type) { case InterpolatorType::ZeroOrderHold: interp_str = "Zero Order Hold"; cases.push_back(TrajectoryTestCase{0.5, 0, 0, 0}); cases.push_back(TrajectoryTestCase{1.5, 1, 0, 0}); cases.push_back(TrajectoryTestCase{2.7, 1.5, 0, 0}); cases.push_back(TrajectoryTestCase{3.5, 1.5, 0, 0}); break; case InterpolatorType::FirstOrderHold: interp_str = "First Order Hold"; cases.push_back(TrajectoryTestCase{0.5, 0.5, 1, 0}); cases.push_back(TrajectoryTestCase{1.5, 1.25, 0.5, 0}); cases.push_back(TrajectoryTestCase{2.7, 1.5, 0, 0}); cases.push_back(TrajectoryTestCase{3.5, 1.25, -0.5, 0}); break; case InterpolatorType::Pchip: interp_str = "Pchip"; cases.push_back(TrajectoryTestCase{0.5, 0.417, 1.333, 0.666}); cases.push_back(TrajectoryTestCase{1.5, 1.333, 0.583, -0.666}); cases.push_back(TrajectoryTestCase{2.7, 1.5, 0, 0}); cases.push_back(TrajectoryTestCase{3.5, 1.250, -0.75, 0}); break; case InterpolatorType::Cubic: interp_str = "Cubic"; cases.push_back(TrajectoryTestCase{0.5, 0.3661, 1.232, 1.071}); cases.push_back(TrajectoryTestCase{1.5, 1.357, 0.429, -0.857}); cases.push_back(TrajectoryTestCase{2.7, 1.577, -0.101, -0.900}); cases.push_back(TrajectoryTestCase{3.5, 1.196, -0.642, 0.429}); break; } for (const TrajectoryTestCase& kase : cases) { context->SetTime(kase.time); dut.UpdatePlan(context.get()); dut.CalcOutput(*context, output.get()); const double position = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(0); const double velocity = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(kNumJoints); const double accel = output->get_vector_data(dut.get_acceleration_output_port().get_index()) ->GetAtIndex(0); const double err_tol = 1e-3; EXPECT_NEAR(position, kase.position, err_tol) << "Failed at interpolator type: " << interp_str; EXPECT_NEAR(velocity, kase.velocity, err_tol) << "Failed at interpolator type: " << interp_str; EXPECT_NEAR(accel, kase.accel, err_tol) << "Failed at interpolator type: " << interp_str; } // Check that the final knot point has zero acceleration and // velocity. if (interp_type == InterpolatorType::Cubic || interp_type == InterpolatorType::ZeroOrderHold || interp_type == InterpolatorType::Pchip) { context->SetTime(t.back() + 0.01); dut.UpdatePlan(context.get()); dut.CalcOutput(*context, output.get()); const double velocity = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(kNumJoints); const double accel = output->get_vector_data(dut.get_acceleration_output_port().get_index()) ->GetAtIndex(0); EXPECT_FLOAT_EQ(velocity, 0) << "Failed at interpolator type: " << interp_str; EXPECT_FLOAT_EQ(accel, 0) << "Failed at interpolator type: " << interp_str; } // Check that sending an empty plan causes us to continue to output // the same commanded position. context->SetTime(1); dut.UpdatePlan(context.get()); dut.CalcOutput(*context, output.get()); double position = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(0); EXPECT_DOUBLE_EQ(1, position) << "Failed at interpolator type: " << interp_str; plan.num_states = 0; plan.plan.clear(); dut.get_plan_input_port().FixValue(context.get(), plan); dut.UpdatePlan(context.get()); dut.CalcOutput(*context, output.get()); position = output->get_vector_data(dut.get_state_output_port().get_index()) ->GetAtIndex(0); EXPECT_DOUBLE_EQ(1, position) << "Failed at interpolator type: " << interp_str; } class TrajectoryTestClass : public testing::TestWithParam<InterpolatorType> { public: virtual void SetUp() {} virtual void TearDown() {} }; INSTANTIATE_TEST_SUITE_P(InstantiationName, TrajectoryTestClass, ::testing::Values(InterpolatorType::ZeroOrderHold, InterpolatorType::FirstOrderHold, InterpolatorType::Pchip, InterpolatorType::Cubic)); TEST_P(TrajectoryTestClass, TrajectoryTest) { DoTrajectoryTest(GetParam()); } } // namespace } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/make_arm_controller_model_test.cc
#include "drake/manipulation/util/make_arm_controller_model.h" #include <memory> #include <numeric> #include <vector> #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/parsing/process_model_directives.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/shared_pointer_system.h" namespace drake { namespace manipulation { namespace internal { namespace { using Eigen::Vector3d; using math::RigidTransform; using math::RollPitchYaw; using multibody::BodyIndex; using multibody::Frame; using multibody::ModelInstanceIndex; using multibody::MultibodyPlant; using multibody::PackageMap; using multibody::Parser; using multibody::RigidBody; using multibody::SpatialInertia; using multibody::parsing::LoadModelDirectives; using multibody::parsing::ModelDirectives; using multibody::parsing::ModelInstanceInfo; using systems::Context; using systems::DiagramBuilder; using systems::SharedPointerSystem; constexpr double kTolerance = 1e-9; class MakeArmControllerModelTest : public ::testing::Test { public: MakeArmControllerModelTest() : builder_{}, sim_plant_{builder_.AddSystem<MultibodyPlant<double>>(0.001)}, iiwa7_model_path_(PackageMap{}.ResolveUrl( "package://drake_models/iiwa_description/sdf/" "iiwa7_no_collision.sdf")), wsg_model_path_(PackageMap{}.ResolveUrl( "package://drake_models/wsg_50_description/sdf/" "schunk_wsg_50.sdf")) { // Add an `empty` model instance to ensure model instance lookups are // correct between this plant and the newly constructed control plant. sim_plant_->AddModelInstance("empty"); } protected: // Adds an Iiwa model into `sim_plant_` and returns its ModelInstanceInfo. ModelInstanceInfo AddIiwaModel() { const ModelInstanceIndex iiwa7_instance = Parser(sim_plant_).AddModels(iiwa7_model_path_).at(0); return {.model_name = sim_plant_->GetModelInstanceName(iiwa7_instance), .model_path = iiwa7_model_path_, .child_frame_name = "iiwa_link_0", .model_instance = iiwa7_instance}; } // Adds a Wsg model into `sim_plant_` and returns its ModelInstanceInfo. ModelInstanceInfo AddWsgModel() { const ModelInstanceIndex wsg_instance = Parser(sim_plant_).AddModels(wsg_model_path_).at(0); return {.model_name = sim_plant_->GetModelInstanceName(wsg_instance), .model_path = wsg_model_path_, .child_frame_name = "body", .model_instance = wsg_instance}; } DiagramBuilder<double> builder_; MultibodyPlant<double>* sim_plant_; const std::string iiwa7_model_path_; const std::string wsg_model_path_; }; // Returns all body indices in the `plant` except the world body index. std::vector<BodyIndex> GetAllBodyIndices(const MultibodyPlant<double>& plant) { // The world body is index zero, and thus the loop iterates from index one. std::vector<BodyIndex> body_indices(plant.num_bodies() - 1); std::iota(body_indices.begin(), body_indices.end(), BodyIndex(1)); return body_indices; } // This test blindly operates on the full simulation and control plants. // Therefore, the simulation plant's mass should be wholly contained in bodies // that belong to either the arm or (optional) gripper model instances, or be // welded to a body in those instances. void CompareInertialTerms(const MultibodyPlant<double>& sim_plant, ModelInstanceIndex sim_arm_model_instance, const MultibodyPlant<double>& control_plant, const Context<double>& sim_plant_context) { // Create analogous control context. std::unique_ptr<Context<double>> control_plant_context = control_plant.CreateDefaultContext(); const Eigen::VectorXd q_arm = sim_plant.GetPositions(sim_plant_context, sim_arm_model_instance); control_plant.SetPositions(control_plant_context.get(), q_arm); // Compare total mass. EXPECT_NEAR(sim_plant.CalcTotalMass(sim_plant_context), control_plant.CalcTotalMass(*control_plant_context), kTolerance); // Check the spatial inertial of the two plants. const SpatialInertia<double> M_CIo_W_sim = sim_plant.CalcSpatialInertia( sim_plant_context, sim_plant.world_frame(), GetAllBodyIndices(sim_plant)); const SpatialInertia<double> M_CIo_W_control = control_plant.CalcSpatialInertia(*control_plant_context, control_plant.world_frame(), GetAllBodyIndices(control_plant)); EXPECT_TRUE(CompareMatrices(M_CIo_W_sim.CopyToFullMatrix6(), M_CIo_W_control.CopyToFullMatrix6(), kTolerance)); const Eigen::VectorXd sim_gravity_full = sim_plant.CalcGravityGeneralizedForces(sim_plant_context); const Eigen::VectorXd sim_gravity = sim_plant.GetActuationFromArray(sim_arm_model_instance, sim_gravity_full); const Eigen::VectorXd control_gravity = control_plant.CalcGravityGeneralizedForces(*control_plant_context); EXPECT_TRUE(CompareMatrices(sim_gravity, control_gravity, kTolerance)); } /* Creates a simple simulation MultibodyPlant with only one Iiwa arm, and the corresponding MultibodyPlant for control. The two plants should share the same properties, e.g., the number of models and actuation. */ TEST_F(MakeArmControllerModelTest, SingleIiwaWithoutWsg) { // Manually add an Iiwa arm to `sim_plant_` MultibodyPlant and weld it to the // world frame. const ModelInstanceInfo iiwa7_info = AddIiwaModel(); // Create an arbitrary transform for testing. const RigidTransform<double> X_WIiwa_sim( RollPitchYaw<double>(0.0, 0.0, M_PI / 2), Eigen::Vector3d(1.0, -1.0, 0.0)); sim_plant_->WeldFrames(sim_plant_->world_frame(), sim_plant_->GetFrameByName(iiwa7_info.child_frame_name, iiwa7_info.model_instance), X_WIiwa_sim); sim_plant_->Finalize(); ASSERT_GT(sim_plant_->num_multibody_states(), 0); MultibodyPlant<double>* control_plant = SharedPointerSystem<double>::AddToBuilder( &builder_, MakeArmControllerModel(*sim_plant_, iiwa7_info)); ASSERT_NE(control_plant, nullptr); const auto diagram = builder_.Build(); std::unique_ptr<Context<double>> sim_plant_context = sim_plant_->CreateDefaultContext(); std::unique_ptr<Context<double>> control_plant_context = control_plant->CreateDefaultContext(); // Both plants should have 14 states, i.e., [q, v] for the 7-DoF Iiwa. EXPECT_EQ(control_plant->num_multibody_states(), sim_plant_->num_multibody_states()); // MultibodyPlant always creates at least two model instances, one for the // world and one for a default model instance for unspecified modeling // elements. Note that we add an additional model instance ("empty") to the // simulation plant to have meaningfully different model instance indices // between the two plants. EXPECT_EQ(control_plant->num_model_instances() + 1, sim_plant_->num_model_instances()); EXPECT_EQ(control_plant->num_actuators(), sim_plant_->num_actuators()); // Check the arm is welded to the world at the same pose. const Frame<double>& iiwa7_child_frame = control_plant->GetFrameByName(iiwa7_info.child_frame_name); EXPECT_TRUE(control_plant->IsAnchored(iiwa7_child_frame.body())); const RigidTransform<double> X_WIiwa_control = control_plant->CalcRelativeTransform(*control_plant_context, control_plant->world_frame(), iiwa7_child_frame); EXPECT_TRUE(X_WIiwa_control.IsExactlyEqualTo(X_WIiwa_sim)); // `grasp_frame` should not present in `control_plant`. EXPECT_FALSE(control_plant->HasFrameNamed("grasp_frame")); // Check inertial terms. CompareInertialTerms(*sim_plant_, iiwa7_info.model_instance, *control_plant, *sim_plant_context); } TEST_F(MakeArmControllerModelTest, DifferentGravity) { // Manually add an Iiwa arm to `sim_plant_` MultibodyPlant and weld it to the // world frame. const ModelInstanceInfo iiwa7_info = AddIiwaModel(); sim_plant_->WeldFrames(sim_plant_->world_frame(), sim_plant_->GetFrameByName(iiwa7_info.child_frame_name, iiwa7_info.model_instance), RigidTransform<double>()); sim_plant_->mutable_gravity_field().set_gravity_vector( Eigen::Vector3d(0.1, 0.2, -0.3)); sim_plant_->Finalize(); std::unique_ptr<MultibodyPlant<double>> control_plant = MakeArmControllerModel(*sim_plant_, iiwa7_info); ASSERT_NE(control_plant, nullptr); std::unique_ptr<Context<double>> sim_plant_context = sim_plant_->CreateDefaultContext(); CompareInertialTerms(*sim_plant_, iiwa7_info.model_instance, *control_plant, *sim_plant_context); } /* Creates a more complex simulation MultibodyPlant from a directives file (contains an Iiwa arm, a Wsg gripper, and other models), and the corresponding MultibodyPlant for control. As MakeArmControllerModel() replaces the gripper model (if provided) with a RigidBody attaching to the arm, the mass and dynamic properties should be preserved but some of the plant-specific properties should not. */ TEST_F(MakeArmControllerModelTest, LoadIiwaWsgFromDirectives) { const ModelDirectives directives = LoadModelDirectives( FindResourceOrThrow("drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")); Parser parser{sim_plant_}; const std::vector<ModelInstanceInfo> models_from_directives = multibody::parsing::ProcessModelDirectives(directives, &parser); sim_plant_->Finalize(); ASSERT_GT(sim_plant_->num_multibody_states(), 0); // Query the ModelInstanceInfo(s) from the directives. ModelInstanceInfo iiwa7_info; ModelInstanceInfo wsg_info; for (const ModelInstanceInfo& model_info : models_from_directives) { if (model_info.model_name == "iiwa7") { iiwa7_info = model_info; } else if (model_info.model_name == "schunk_wsg") { wsg_info = model_info; } } // In this test case, `grasp_frame` is assumed to exist. ASSERT_TRUE( sim_plant_->HasFrameNamed("grasp_frame", wsg_info.model_instance)); MultibodyPlant<double>* control_plant = SharedPointerSystem<double>::AddToBuilder( &builder_, MakeArmControllerModel(*sim_plant_, iiwa7_info, wsg_info)); ASSERT_NE(control_plant, nullptr); const auto diagram = builder_.Build(); std::unique_ptr<Context<double>> sim_plant_context = sim_plant_->CreateDefaultContext(); std::unique_ptr<Context<double>> control_plant_context = control_plant->CreateDefaultContext(); // The number of states for `control_plant` and `sim_plant_` should be // different. However, the number of states of the Iiwa arm instance should // be identical. EXPECT_NE(control_plant->num_multibody_states(), sim_plant_->num_multibody_states()); EXPECT_EQ(control_plant->num_multibody_states(), sim_plant_->num_multibody_states(iiwa7_info.model_instance)); EXPECT_NE(control_plant->num_model_instances(), sim_plant_->num_model_instances()); // `sim_plant_` should have 7 (Iiwa) + 2 (Wsg) actuations, while // `control_plant` should have only 7. However, the number of actuated DoFs // for the Iiwa arm should be identical. EXPECT_NE(control_plant->num_actuators(), sim_plant_->num_actuators()); EXPECT_EQ(control_plant->num_actuated_dofs(), sim_plant_->num_actuated_dofs(iiwa7_info.model_instance)); const Frame<double>& sim_iiwa7_child_frame = sim_plant_->GetFrameByName( iiwa7_info.child_frame_name, iiwa7_info.model_instance); const Frame<double>& control_iiwa7_child_frame = control_plant->GetFrameByName(iiwa7_info.child_frame_name); // Check the arm is welded to the world at the same pose. const RigidTransform<double> X_WIiwa_sim = sim_plant_->CalcRelativeTransform( *sim_plant_context, sim_plant_->world_frame(), sim_iiwa7_child_frame); const RigidTransform<double> X_WIiwa_control = control_plant->CalcRelativeTransform(*control_plant_context, control_plant->world_frame(), control_iiwa7_child_frame); EXPECT_TRUE(control_plant->IsAnchored(control_iiwa7_child_frame.body())); EXPECT_TRUE(X_WIiwa_sim.IsExactlyEqualTo(X_WIiwa_control)); // Check `grasp_frame` is added at the same pose as `sim_plant_`. EXPECT_TRUE(control_plant->HasFrameNamed("grasp_frame")); const Frame<double>& sim_wsg_child_frame = sim_plant_->GetFrameByName( wsg_info.child_frame_name, wsg_info.model_instance); const Frame<double>& sim_wsg_grasp_frame = sim_plant_->GetFrameByName("grasp_frame", wsg_info.model_instance); const RigidTransform<double> X_GF_sim = sim_wsg_grasp_frame.CalcPose(*sim_plant_context, sim_wsg_child_frame); const Frame<double>& control_wsg_child_frame = control_plant->GetFrameByName(wsg_info.child_frame_name); const Frame<double>& control_wsg_grasp_frame = control_plant->GetFrameByName("grasp_frame"); const RigidTransform<double> X_GF_control = control_wsg_grasp_frame.CalcPose( *control_plant_context, control_wsg_child_frame); EXPECT_TRUE(X_GF_sim.IsNearlyEqualTo(X_GF_control, kTolerance)); CompareInertialTerms(*sim_plant_, iiwa7_info.model_instance, *control_plant, *sim_plant_context); } TEST_F(MakeArmControllerModelTest, AdditionalAttachedModels) { const ModelDirectives directives = LoadModelDirectives(FindResourceOrThrow( "drake/manipulation/util/test/iiwa7_wsg_cameras.dmd.yaml")); Parser parser{sim_plant_}; const std::vector<ModelInstanceInfo> models_from_directives = multibody::parsing::ProcessModelDirectives(directives, &parser); sim_plant_->Finalize(); // Query the ModelInstanceInfo(s) from the directives. ModelInstanceInfo iiwa7_info; ModelInstanceInfo wsg_info; for (const ModelInstanceInfo& model_info : models_from_directives) { if (model_info.model_name == "iiwa7") { iiwa7_info = model_info; } else if (model_info.model_name == "schunk_wsg") { wsg_info = model_info; } } std::unique_ptr<MultibodyPlant<double>> control_plant = MakeArmControllerModel(*sim_plant_, iiwa7_info, wsg_info); ASSERT_NE(control_plant, nullptr); std::unique_ptr<Context<double>> sim_plant_context = sim_plant_->CreateDefaultContext(); CompareInertialTerms(*sim_plant_, iiwa7_info.model_instance, *control_plant, *sim_plant_context); } } // namespace } // namespace internal } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/simple_world_with_two_models.sdf
<?xml version="1.0"?> <sdf version="1.8"> <world name="simple_world_with_two_models"> <include> <name>top_a</name> <uri>package://drake/manipulation/util/test/simple_nested_model.sdf</uri> </include> <include> <name>top_b</name> <uri>package://drake/manipulation/util/test/simple_nested_model.sdf</uri> </include> </world> </sdf>
0
/home/johnshepherd/drake/manipulation/util
/home/johnshepherd/drake/manipulation/util/test/robot_plan_utils_test.cc
#include "drake/manipulation/util/robot_plan_utils.h" #include <vector> #include <gtest/gtest.h> #include "drake/multibody/parsing/parser.h" namespace drake { namespace manipulation { namespace util { const char kIiwaUrdf[] = "package://drake_models/iiwa_description/urdf/iiwa14_no_collision.urdf"; GTEST_TEST(RobotPlanUtilsTest, GetJointNamesTest) { multibody::MultibodyPlant<double> plant(0.001); multibody::Parser(&plant).AddModelsFromUrl(kIiwaUrdf); plant.WeldFrames(plant.world_frame(), plant.GetBodyByName("base").body_frame()); plant.Finalize(); std::vector<std::string> joint_names = GetJointNames(plant); ASSERT_EQ(joint_names.size(), 7); EXPECT_EQ(joint_names[0], "iiwa_joint_1"); EXPECT_EQ(joint_names[1], "iiwa_joint_2"); EXPECT_EQ(joint_names[2], "iiwa_joint_3"); EXPECT_EQ(joint_names[3], "iiwa_joint_4"); EXPECT_EQ(joint_names[4], "iiwa_joint_5"); EXPECT_EQ(joint_names[5], "iiwa_joint_6"); EXPECT_EQ(joint_names[6], "iiwa_joint_7"); } GTEST_TEST(RobotPlanUtilsTest, ApplyJointVelocityLimitsTest) { std::vector<double> times{0, 1}; std::vector<Eigen::VectorXd> keyframes; keyframes.push_back(Eigen::VectorXd::Zero(2)); keyframes.push_back(Eigen::VectorXd::Ones(2)); Eigen::Vector2d limit(0.9, 1); ApplyJointVelocityLimits(keyframes, limit, &times); EXPECT_EQ(times[1], 1. / 0.9); } GTEST_TEST(RobotPlanUtilsTest, EncodeKeyFramesTest) { multibody::MultibodyPlant<double> plant(0.001); multibody::Parser(&plant).AddModelsFromUrl(kIiwaUrdf); plant.WeldFrames(plant.world_frame(), plant.GetBodyByName("base").body_frame()); plant.Finalize(); std::vector<std::string> joint_names = GetJointNames(plant); std::vector<double> times{0, 2}; std::vector<Eigen::VectorXd> keyframes; Eigen::VectorXd q(7); q << 1, 2, 3, 4, 5, 6, 7; keyframes.push_back(q); q << 8, 9, 10, 11, 12, 13, 14; keyframes.push_back(q); lcmt_robot_plan plan = EncodeKeyFrames(joint_names, times, keyframes); ASSERT_EQ(plan.plan.size(), 2); EXPECT_EQ(plan.plan.size(), plan.num_states); for (int i = 0; i < static_cast<int>(plan.plan.size()); ++i) { const lcmt_robot_state& step = plan.plan[i]; EXPECT_EQ(step.utime, i * 2 * 1e6); ASSERT_EQ(step.num_joints, 7); for (int j = 0; j < step.num_joints; j++) { EXPECT_EQ(step.joint_position[j], i * 7 + j + 1); } } } } // namespace util } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_status_sender.cc
#include "drake/manipulation/kuka_iiwa/iiwa_status_sender.h" namespace drake { namespace manipulation { namespace kuka_iiwa { using drake::systems::Context; using drake::systems::kVectorValued; IiwaStatusSender::IiwaStatusSender(int num_joints) : num_joints_(num_joints), zero_vector_(Eigen::VectorXd::Zero(num_joints)) { DeclareInputPort("position_commanded", kVectorValued, num_joints_); DeclareInputPort("position_measured", kVectorValued, num_joints_); DeclareInputPort("velocity_estimated", kVectorValued, num_joints_); DeclareInputPort("torque_commanded", kVectorValued, num_joints_); DeclareInputPort("torque_measured", kVectorValued, num_joints_); DeclareInputPort("torque_external", kVectorValued, num_joints_); DeclareInputPort("time_measured", kVectorValued, 1); DeclareAbstractOutputPort("lcmt_iiwa_status", &IiwaStatusSender::CalcOutput); } IiwaStatusSender::~IiwaStatusSender() = default; using InPort = systems::InputPort<double>; const InPort& IiwaStatusSender::get_position_commanded_input_port() const { return LeafSystem<double>::get_input_port(0); } const InPort& IiwaStatusSender::get_position_measured_input_port() const { return LeafSystem<double>::get_input_port(1); } const InPort& IiwaStatusSender::get_velocity_estimated_input_port() const { return LeafSystem<double>::get_input_port(2); } const InPort& IiwaStatusSender::get_torque_commanded_input_port() const { return LeafSystem<double>::get_input_port(3); } const InPort& IiwaStatusSender::get_torque_measured_input_port() const { return LeafSystem<double>::get_input_port(4); } const InPort& IiwaStatusSender::get_torque_external_input_port() const { return LeafSystem<double>::get_input_port(5); } const InPort& IiwaStatusSender::get_time_measured_input_port() const { return LeafSystem<double>::get_input_port(6); } namespace { // Returns the first one of port1.Eval or port2.Eval that has a value. // If min_num_connected is zero and both ports are empty, return zeros. // If less than min_num_connected of (port1,port2) are connected, throws. // If more than max_num_connected of (port1,port2) are connected, throws. // If port2_tail is provided, a suffix of port2's value is returned. Eigen::Ref<const Eigen::VectorXd> EvalFirstConnected( const Context<double>& context, int min_num_connected, int max_num_connected, const Eigen::VectorXd& zeros, const InPort& port1, const InPort& port2, const int port2_tail = -1) { const int total_connected = (port1.HasValue(context) ? 1 : 0) + (port2.HasValue(context) ? 1 : 0); if (total_connected > max_num_connected) { throw std::logic_error( fmt::format("Both {} and {} cannot both be connected at the same time.", port1.GetFullDescription(), port2.GetFullDescription())); } if (total_connected < min_num_connected) { throw std::logic_error(fmt::format( "At least {} of {} or {} must be connected.", min_num_connected, port1.GetFullDescription(), port2.GetFullDescription())); } if (port1.HasValue(context)) { return port1.Eval(context); } if (port2.HasValue(context)) { if (port2_tail < 0) { return port2.Eval(context); } else { return port2.Eval(context).tail(port2_tail); } } return zeros; } } // namespace void IiwaStatusSender::CalcOutput(const Context<double>& context, lcmt_iiwa_status* output) const { const double time_measured = get_time_measured_input_port().HasValue(context) ? get_time_measured_input_port().Eval(context)[0] : context.get_time(); const auto& position_commanded = get_position_commanded_input_port().Eval(context); const auto& position_measured = get_position_measured_input_port().Eval(context); const auto& velocity_estimated = get_velocity_estimated_input_port().HasValue(context) ? get_velocity_estimated_input_port().Eval(context) : zero_vector_.head(num_joints_); const auto& torque_commanded = get_torque_commanded_input_port().Eval(context); const auto& torque_measured = EvalFirstConnected( context, 1, 2, zero_vector_, get_torque_measured_input_port(), get_torque_commanded_input_port()); const auto& torque_external = EvalFirstConnected( context, 0, 2, zero_vector_, get_torque_external_input_port(), get_torque_external_input_port()); lcmt_iiwa_status& status = *output; status.utime = time_measured * 1e6; status.num_joints = num_joints_; status.joint_position_measured.resize(num_joints_, 0); status.joint_velocity_estimated.resize(num_joints_, 0); status.joint_position_commanded.resize(num_joints_, 0); status.joint_position_ipo.resize(num_joints_, 0); status.joint_torque_measured.resize(num_joints_, 0); status.joint_torque_commanded.resize(num_joints_, 0); status.joint_torque_external.resize(num_joints_, 0); for (int i = 0; i < num_joints_; ++i) { status.joint_position_measured[i] = position_measured[i]; status.joint_velocity_estimated[i] = velocity_estimated[i]; status.joint_position_commanded[i] = position_commanded[i]; status.joint_torque_commanded[i] = torque_commanded[i]; status.joint_torque_measured[i] = torque_measured[i]; status.joint_torque_external[i] = torque_external[i]; } } } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_googletest", "drake_cc_library", "drake_cc_package_library", ) package( default_visibility = ["//visibility:public"], ) drake_cc_package_library( name = "kuka_iiwa", visibility = ["//visibility:public"], deps = [ ":build_iiwa_control", ":iiwa_command_receiver", ":iiwa_command_sender", ":iiwa_constants", ":iiwa_driver", ":iiwa_driver_functions", ":iiwa_status_receiver", ":iiwa_status_sender", ":sim_iiwa_driver", ], ) drake_cc_library( name = "iiwa_constants", srcs = ["iiwa_constants.cc"], hdrs = ["iiwa_constants.h"], deps = [ "//common:essential", "@fmt", ], ) drake_cc_library( name = "iiwa_command_receiver", srcs = ["iiwa_command_receiver.cc"], hdrs = ["iiwa_command_receiver.h"], deps = [ ":iiwa_constants", "//common:essential", "//lcmtypes:lcmtypes_drake_cc", "//systems/framework:leaf_system", "//systems/lcm:lcm_pubsub_system", ], ) drake_cc_library( name = "iiwa_command_sender", srcs = ["iiwa_command_sender.cc"], hdrs = ["iiwa_command_sender.h"], deps = [ ":iiwa_constants", "//common:essential", "//lcmtypes:lcmtypes_drake_cc", "//systems/framework:leaf_system", ], ) drake_cc_library( name = "iiwa_status_receiver", srcs = ["iiwa_status_receiver.cc"], hdrs = ["iiwa_status_receiver.h"], deps = [ ":iiwa_constants", "//common:essential", "//lcmtypes:lcmtypes_drake_cc", "//systems/framework:leaf_system", ], ) drake_cc_library( name = "iiwa_status_sender", srcs = ["iiwa_status_sender.cc"], hdrs = ["iiwa_status_sender.h"], deps = [ ":iiwa_constants", "//common:essential", "//lcmtypes:lcmtypes_drake_cc", "//systems/framework:leaf_system", ], ) drake_cc_library( name = "iiwa_driver", srcs = ["iiwa_driver.cc"], hdrs = ["iiwa_driver.h"], deps = [ "//common:essential", "//common:name_value", ], ) drake_cc_library( name = "iiwa_driver_functions", srcs = ["iiwa_driver_functions.cc"], hdrs = ["iiwa_driver_functions.h"], interface_deps = [ ":iiwa_driver", "//common:essential", "//multibody/parsing:model_instance_info", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/lcm:lcm_buses", ], deps = [ ":build_iiwa_control", "//manipulation/util:make_arm_controller_model", "//systems/primitives:shared_pointer_system", ], ) drake_cc_library( name = "sim_iiwa_driver", srcs = ["sim_iiwa_driver.cc"], hdrs = ["sim_iiwa_driver.h"], deps = [ ":iiwa_constants", "//common:essential", "//multibody/plant", "//systems/controllers:inverse_dynamics_controller", "//systems/framework:diagram_builder", "//systems/primitives:adder", "//systems/primitives:demultiplexer", "//systems/primitives:discrete_derivative", "//systems/primitives:first_order_low_pass_filter", ], ) drake_cc_library( name = "build_iiwa_control", srcs = ["build_iiwa_control.cc"], hdrs = ["build_iiwa_control.h"], deps = [ ":iiwa_command_receiver", ":iiwa_constants", ":iiwa_status_sender", ":sim_iiwa_driver", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/lcm", "//systems/primitives:demultiplexer", "//systems/primitives:gain", "@eigen", ], ) # === test/ === drake_cc_googletest( name = "iiwa_constants_test", deps = [":iiwa_constants"], ) drake_cc_googletest( name = "iiwa_command_receiver_test", deps = [ ":iiwa_command_receiver", "//common/test_utilities:eigen_matrix_compare", ], ) drake_cc_googletest( name = "iiwa_command_sender_test", deps = [ ":iiwa_command_sender", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:limit_malloc", ], ) drake_cc_googletest( name = "iiwa_status_receiver_test", deps = [ ":iiwa_status_receiver", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:limit_malloc", ], ) drake_cc_googletest( name = "iiwa_status_sender_test", deps = [ ":iiwa_status_sender", "//common/test_utilities:eigen_matrix_compare", ], ) drake_cc_googletest( name = "build_iiwa_control_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":build_iiwa_control", ":iiwa_constants", "//lcm", "//manipulation/util:make_arm_controller_model", "//multibody/parsing:model_instance_info", "//multibody/parsing:parser", "//multibody/plant", "//systems/analysis:simulator", "//systems/framework:diagram_builder", "//systems/lcm", "//systems/primitives:constant_vector_source", "//systems/primitives:shared_pointer_system", ], ) drake_cc_googletest( name = "iiwa_driver_functions_test", data = [ "//manipulation/util:test_directives", "@drake_models//:iiwa_description", "@drake_models//:wsg_50_description", ], deps = [ ":iiwa_driver_functions", "//common:find_resource", "//common/test_utilities:expect_throws_message", "//lcm:drake_lcm_params", "//manipulation/util:zero_force_driver_functions", "//multibody/parsing:parser", "//multibody/parsing:process_model_directives", "//multibody/plant", "//systems/analysis:simulator", "//systems/framework:diagram_builder", "//systems/lcm:lcm_config_functions", ], ) drake_cc_googletest( name = "sim_iiwa_driver_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":iiwa_constants", ":sim_iiwa_driver", "//multibody/parsing", "//multibody/plant", "//systems/framework/test_utilities:scalar_conversion", ], ) add_lint_tests()
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/build_iiwa_control.h
#pragma once #include <optional> #include <string> #include <Eigen/Dense> #include "drake/lcm/drake_lcm_interface.h" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/multibody/plant/multibody_plant.h" /// @file /// Iiwa controller and controller plant setup /// /// This class implements the software stack of the Iiwa arm and the LCM-to-FRI /// adapter installed in it as it is exposed in /// https://github.com/RobotLocomotion/drake-iiwa-driver. /// The driver in this repository exposes three options: /// - position-only control, /// - position-and-torque control, where feedforward torque command is /// optional, and /// - torque-only control, added with nominal gravity compensation. /// The arm receives position and/or torque commands (`lcmt_iiwa_command`) and /// emits status (`lcmt_iiwa_status`); the Iiwa controller built here takes /// care of translating the command into torques on the Iiwa joints and the /// Iiwa measured positions and torques into those status messages. Note that /// only the 7 DoF Iiwa arm is supported. /// /// A simulated controller maintains an entire separate Iiwa plant (*not* the /// simulated plant!) to perform inverse dynamics computations. These /// computations correspond to the servoing and gravity compensation done on /// the real Iiwa; disagreement between the controller model and the simulated /// model represents errors in the servo, end-effector, and /// gravity-compensation configuration. namespace drake { namespace manipulation { namespace kuka_iiwa { /// Given a @p plant (and associated @p iiwa_instance) and a @p builder, /// installs in that builder the systems necessary to control and monitor an /// Iiwa described by @p controller_plant in that plant. /// /// The installed plant will communicate over the LCM interface @p lcm. /// /// The installed plant will connect itself to the actuation input port and /// state output ports in `plant` corresponding to the Iiwa model. /// /// @p desired_iiwa_kp_gains is an optional argument to pass in gains /// corresponding to the Iiwa Dof (7) in the controller. If no argument is /// passed, the gains derived from hardware will be used instead (hardcoded /// within the implementation of this function). These gains must be nullopt /// if @p control_mode does not include position control. /// /// @p control_mode the control mode for the controller. /// /// Note: The Diagram will maintain an internal reference to `controller_plant`, /// so you must ensure that `controller_plant` has a longer lifetime than the /// Diagram. void BuildIiwaControl( const multibody::MultibodyPlant<double>& plant, const multibody::ModelInstanceIndex iiwa_instance, const multibody::MultibodyPlant<double>& controller_plant, lcm::DrakeLcmInterface* lcm, systems::DiagramBuilder<double>* builder, double ext_joint_filter_tau = 0.01, const std::optional<Eigen::VectorXd>& desired_iiwa_kp_gains = std::nullopt, IiwaControlMode control_mode = IiwaControlMode::kPositionAndTorque); /// The return type of BuildSimplifiedIiwaControl(). Depending on the /// `control_mode`, some of the input ports might be null. The output ports are /// never null. struct IiwaControlPorts { /// This will be non-null iff the control_mode denotes commanded positions. const systems::InputPort<double>* commanded_positions{}; /// This will be non-null iff the control_mode denotes commanded torques. const systems::InputPort<double>* commanded_torque{}; const systems::OutputPort<double>* position_commanded{}; const systems::OutputPort<double>* position_measured{}; const systems::OutputPort<double>* velocity_estimated{}; const systems::OutputPort<double>* joint_torque{}; // aka torque_commanded const systems::OutputPort<double>* torque_measured{}; const systems::OutputPort<double>* external_torque{}; // aka torque_external }; /// A simplified Iiwa controller builder to construct an /// InverseDynamicsController without adding LCM I/O systems. /// @sa BuildIiwaControl() IiwaControlPorts BuildSimplifiedIiwaControl( const multibody::MultibodyPlant<double>& plant, const multibody::ModelInstanceIndex iiwa_instance, const multibody::MultibodyPlant<double>& controller_plant, systems::DiagramBuilder<double>* builder, double ext_joint_filter_tau = 0.01, const std::optional<Eigen::VectorXd>& desired_iiwa_kp_gains = std::nullopt, IiwaControlMode control_mode = IiwaControlMode::kPositionAndTorque); } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_command_receiver.cc
#include "drake/manipulation/kuka_iiwa/iiwa_command_receiver.h" #include <limits> #include "drake/common/drake_throw.h" #include "drake/lcm/lcm_messages.h" namespace drake { namespace manipulation { namespace kuka_iiwa { using Eigen::VectorXd; using lcm::AreLcmMessagesEqual; using systems::BasicVector; using systems::CompositeEventCollection; using systems::Context; using systems::DiscreteUpdateEvent; using systems::DiscreteValues; using systems::kVectorValued; using systems::NumericParameterIndex; IiwaCommandReceiver::IiwaCommandReceiver(int num_joints, IiwaControlMode control_mode) : num_joints_(num_joints), control_mode_(control_mode) { DRAKE_THROW_UNLESS(num_joints > 0); message_input_ = &DeclareAbstractInputPort("lcmt_iiwa_command", Value<lcmt_iiwa_command>()); position_measured_input_ = &DeclareInputPort("position_measured", kVectorValued, num_joints); // This cache entry provides either the input (iff connected) or else zero. position_measured_or_zero_ = &DeclareCacheEntry( "position_measured_or_zero", BasicVector<double>(num_joints), &IiwaCommandReceiver::CalcPositionMeasuredOrZero, {position_measured_input_->ticket()}); // When a simulation begins, we will latch position_measured_or_zero into a // state variable, so that we will hold that pose until the first message is // received. Prior to that event, we continue to use the unlatched value. latched_position_measured_is_set_ = DeclareDiscreteState(VectorXd::Zero(1)); latched_position_measured_ = DeclareDiscreteState(VectorXd::Zero(num_joints)); defaulted_command_ = &DeclareCacheEntry( "defaulted_command", &IiwaCommandReceiver::CalcDefaultedCommand, {message_input_->ticket(), discrete_state_ticket(latched_position_measured_is_set_), discrete_state_ticket(latched_position_measured_), position_measured_or_zero_->ticket()}); if (position_enabled(control_mode_)) { commanded_position_output_ = &DeclareVectorOutputPort( "position", num_joints, &IiwaCommandReceiver::CalcPositionOutput, {defaulted_command_->ticket()}); } if (torque_enabled(control_mode_)) { commanded_torque_output_ = &DeclareVectorOutputPort( "torque", num_joints, &IiwaCommandReceiver::CalcTorqueOutput, {defaulted_command_->ticket()}); } time_output_ = &DeclareVectorOutputPort("time", 1, &IiwaCommandReceiver::CalcTimeOutput, {defaulted_command_->ticket()}); } IiwaCommandReceiver::~IiwaCommandReceiver() = default; void IiwaCommandReceiver::CalcPositionMeasuredOrZero( const Context<double>& context, BasicVector<double>* result) const { if (position_measured_input_->HasValue(context)) { result->SetFromVector(position_measured_input_->Eval(context)); } else { result->SetZero(); } } void IiwaCommandReceiver::LatchInitialPosition( const Context<double>& context, DiscreteValues<double>* result) const { const auto& bool_index = latched_position_measured_is_set_; const auto& value_index = latched_position_measured_; result->get_mutable_value(bool_index)[0] = 1.0; result->get_mutable_vector(value_index) .SetFrom(position_measured_or_zero_->Eval<BasicVector<double>>(context)); } void IiwaCommandReceiver::LatchInitialPosition(Context<double>* context) const { DRAKE_THROW_UNLESS(context != nullptr); LatchInitialPosition(*context, &context->get_mutable_discrete_state()); } // TODO(jwnimmer-tri) This is quite a cumbersome syntax to use for declaring a // "now" event. We should try to consolidate it with other similar uses within // the source tree. Relates to #11403 somewhat. void IiwaCommandReceiver::DoCalcNextUpdateTime( const Context<double>& context, CompositeEventCollection<double>* events, double* time) const { if (!position_enabled(control_mode_)) { // No need to schedule events. *time = std::numeric_limits<double>::infinity(); return; } // We do not support events other than our own message timing events. LeafSystem<double>::DoCalcNextUpdateTime(context, events, time); DRAKE_THROW_UNLESS(events->HasEvents() == false); DRAKE_THROW_UNLESS(std::isinf(*time)); // If we have a latched position already, then we do not have any updates. if (context.get_discrete_state(0).get_value()[0] != 0.0) { return; } // Schedule a discrete update event at now to latch the current position. *time = context.get_time(); auto& discrete_events = events->get_mutable_discrete_update_events(); discrete_events.AddEvent(DiscreteUpdateEvent<double>( [this](const System<double>&, const Context<double>& event_context, const DiscreteUpdateEvent<double>&, DiscreteValues<double>* next_values) { LatchInitialPosition(event_context, next_values); return systems::EventStatus::Succeeded(); })); } void IiwaCommandReceiver::CalcDefaultedCommand( const Context<double>& context, lcmt_iiwa_command* result) const { // Copy the input value into our tentative result. *result = message_input_->Eval<lcmt_iiwa_command>(context); // If we haven't received a message yet, then fall back to the default // position. if (AreLcmMessagesEqual(*result, lcmt_iiwa_command{})) { const BasicVector<double>& latch_is_set = context.get_discrete_state(latched_position_measured_is_set_); const BasicVector<double>& default_position = latch_is_set[0] ? context.get_discrete_state(latched_position_measured_) : position_measured_or_zero_->Eval<BasicVector<double>>(context); const VectorXd vec = default_position.CopyToVector(); result->num_joints = vec.size(); result->joint_position = {vec.data(), vec.data() + vec.size()}; } } void IiwaCommandReceiver::CalcPositionOutput( const Context<double>& context, BasicVector<double>* output) const { const auto& message = defaulted_command_->Eval<lcmt_iiwa_command>(context); if (message.num_joints != num_joints_) { throw std::runtime_error(fmt::format( "IiwaCommandReceiver expected num_joints = {}, but received {}", num_joints_, message.num_joints)); } output->SetFromVector(Eigen::Map<const VectorXd>( message.joint_position.data(), message.joint_position.size())); } void IiwaCommandReceiver::CalcTorqueOutput(const Context<double>& context, BasicVector<double>* output) const { const auto& message = defaulted_command_->Eval<lcmt_iiwa_command>(context); if (message.num_torques == 0) { // If torques were not sent, use zeros. output->SetZero(); return; } if (message.num_torques != num_joints_) { throw std::runtime_error(fmt::format( "IiwaCommandReceiver expected num_torques = {}, but received {}", num_joints_, message.num_torques)); } output->SetFromVector(Eigen::Map<const VectorXd>( message.joint_torque.data(), message.joint_torque.size())); } void IiwaCommandReceiver::CalcTimeOutput(const Context<double>& context, BasicVector<double>* output) const { const auto& message = defaulted_command_->Eval<lcmt_iiwa_command>(context); (*output)[0] = static_cast<double>(message.utime) / 1e6; } } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_driver_functions.h
#pragma once #include <map> #include <string> #include "drake/manipulation/kuka_iiwa/iiwa_driver.h" #include "drake/multibody/parsing/model_instance_info.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_buses.h" namespace drake { namespace manipulation { namespace kuka_iiwa { /** Wires up Drake systems between an LCM interface and the actuation input ports of a MultibodyPlant. This simulates the role that driver software and control cabinets would take in real life. @pre model_instance_name is in models_from_directives. @pre driver_config.hand_model_name is in models_from_directives. */ void ApplyDriverConfig( const IiwaDriver& driver_config, const std::string& model_instance_name, const multibody::MultibodyPlant<double>& sim_plant, const std::map<std::string, multibody::parsing::ModelInstanceInfo>& models_from_directives, const systems::lcm::LcmBuses& lcms, systems::DiagramBuilder<double>* builder); } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_driver.h
#pragma once #include <string> #include "drake/common/drake_copyable.h" #include "drake/common/name_value.h" namespace drake { namespace manipulation { namespace kuka_iiwa { /** This config struct specifies how to wire up Drake systems between an LCM interface and the actuation input ports of a MultibodyPlant. This simulates the role that driver software and control cabinets would take in real life. It creates an LCM publisher on the `IIWA_STATUS` channel and an LCM subscriber on the `IIWA_COMMAND` channel. */ struct IiwaDriver { /** The name of the model (`name` element of the `add_model` directive) in the simulation that the driver will analyze to compute end effector inertia for its copy of the arm in inverse dynamics. */ std::string hand_model_name; /** Per BuildIiwaControl. */ double ext_joint_filter_tau{0.01}; /** The driver's control mode. Valid options (per ParseIiwaControlMode) are: - "position_only" - "position_and_torque" (default) - "torque_only" */ std::string control_mode{"position_and_torque"}; std::string lcm_bus{"default"}; template <typename Archive> void Serialize(Archive* a) { a->Visit(DRAKE_NVP(hand_model_name)); a->Visit(DRAKE_NVP(ext_joint_filter_tau)); a->Visit(DRAKE_NVP(control_mode)); a->Visit(DRAKE_NVP(lcm_bus)); } }; } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_driver_functions.cc
#include "drake/manipulation/kuka_iiwa/iiwa_driver_functions.h" #include <optional> #include "drake/manipulation/kuka_iiwa/build_iiwa_control.h" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/manipulation/kuka_iiwa/sim_iiwa_driver.h" #include "drake/manipulation/util/make_arm_controller_model.h" #include "drake/systems/primitives/shared_pointer_system.h" namespace drake { namespace manipulation { namespace kuka_iiwa { using lcm::DrakeLcmInterface; using multibody::MultibodyPlant; using multibody::parsing::ModelInstanceInfo; using systems::DiagramBuilder; using systems::SharedPointerSystem; using systems::lcm::LcmBuses; void ApplyDriverConfig( const IiwaDriver& driver_config, const std::string& model_instance_name, const MultibodyPlant<double>& sim_plant, const std::map<std::string, ModelInstanceInfo>& models_from_directives, const LcmBuses& lcms, DiagramBuilder<double>* builder) { DRAKE_THROW_UNLESS(builder != nullptr); const std::string& arm_name = model_instance_name; const std::string& hand_name = driver_config.hand_model_name; if (!models_from_directives.contains(arm_name)) { throw std::runtime_error(fmt::format( "IiwaDriver could not find arm model directive '{}' to actuate", arm_name)); } const ModelInstanceInfo& arm_model = models_from_directives.at(arm_name); std::optional<ModelInstanceInfo> hand_model; if (!hand_name.empty()) { if (!models_from_directives.contains(hand_name)) { throw std::runtime_error(fmt::format( "IiwaDriver could not find hand model directive '{}' to actuate", hand_name)); } hand_model = models_from_directives.at(hand_name); } DrakeLcmInterface* lcm = lcms.Find("Driver for " + arm_name, driver_config.lcm_bus); MultibodyPlant<double>* controller_plant = SharedPointerSystem<double>::AddToBuilder( builder, manipulation::internal::MakeArmControllerModel( sim_plant, arm_model, hand_model)); builder->GetMutableSystems().back()->set_name( fmt::format("{}_controller_plant", arm_name)); // TODO(jwnimmer-tri) Make desired_iiwa_kp_gains configurable. std::optional<Eigen::VectorXd> desired_iiwa_kp_gains; const IiwaControlMode control_mode = ParseIiwaControlMode(driver_config.control_mode); if (lcm->get_lcm_url() == LcmBuses::kLcmUrlMemqNull) { SimIiwaDriver<double>::AddToBuilder( builder, sim_plant, arm_model.model_instance, *controller_plant, driver_config.ext_joint_filter_tau, desired_iiwa_kp_gains, control_mode); } else { BuildIiwaControl(sim_plant, arm_model.model_instance, *controller_plant, lcm, builder, driver_config.ext_joint_filter_tau, desired_iiwa_kp_gains, control_mode); } } } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_status_sender.h
#pragma once #include "drake/common/drake_copyable.h" #include "drake/lcmt_iiwa_status.hpp" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace manipulation { namespace kuka_iiwa { /// Creates and outputs lcmt_iiwa_status messages. /// /// Note that this system does not actually send the message an LCM channel. To /// send the message, the output of this system should be connected to a /// systems::lcm::LcmPublisherSystem::Make<lcmt_iiwa_status>(). /// /// This system has many vector-valued input ports, most of which have exactly /// num_joints elements. The exception is `time_measured` which is the /// one-dimensional time in seconds to set as the message timestamp (i.e. the /// time inputted will be converted to microseconds and sent to the hardware). /// It is optional and if unset, the context time is used. /// /// - `position_commanded`: the most recently received position command. /// - `position_measured`: the plant's current position. /// - `velocity_estimated` (optional): the plant's current velocity (this /// should be a low-pass filter of the position's derivative; see detailed /// comments in `lcmt_iiwa_status.lcm`); when absent, the output message /// will use zeros. /// - `torque_commanded`: the most recently received joint torque command. /// - `torque_measured` (optional): the plant's measured joint torque; when /// absent, the output message will duplicate torque_commanded. /// - `torque_external` (optional): the plant's external joint torque; when /// absent, the output message will use zeros. /// /// This system has one abstract-valued output port of type lcmt_iiwa_status. /// /// This system is presently only used in simulation. The robot hardware drivers /// publish directly to LCM and do not make use of this system. /// /// @system /// name: IiwaStatusSender /// input_ports: /// - position_commanded /// - position_measured /// - velocity_estimated /// - torque_commanded /// - torque_measured /// - torque_external /// - time_measured /// output_ports: /// - lcmt_iiwa_status /// @endsystem /// /// The ports `velocity_estimated`, `torque_measured`, `torque_external`, and /// `time_measured` may be left unconnected, as detailed above. /// /// @see `lcmt_iiwa_status.lcm` for additional documentation. class IiwaStatusSender final : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(IiwaStatusSender) explicit IiwaStatusSender(int num_joints = kIiwaArmNumJoints); ~IiwaStatusSender() final; /// @name Named accessors for this System's input and output ports. //@{ const systems::InputPort<double>& get_time_measured_input_port() const; const systems::InputPort<double>& get_position_commanded_input_port() const; const systems::InputPort<double>& get_position_measured_input_port() const; const systems::InputPort<double>& get_velocity_estimated_input_port() const; const systems::InputPort<double>& get_torque_commanded_input_port() const; const systems::InputPort<double>& get_torque_measured_input_port() const; const systems::InputPort<double>& get_torque_external_input_port() const; //@} private: void CalcOutput(const systems::Context<double>&, lcmt_iiwa_status*) const; const int num_joints_; const Eigen::VectorXd zero_vector_; }; } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/sim_iiwa_driver.h
#pragma once #include <optional> #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" // IiwaControlMode #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram.h" namespace drake { namespace manipulation { namespace kuka_iiwa { /** SimIiwaDriver simulates the IIWA control and status interface using a MultibodyPlant. @experimental @system name: SimIiwaDriver input_ports: - <b style="color:orange">state</b> - <b style="color:orange">generalized_contact_forces</b> - position (in kPositionOnly or kPositionAndTorque mode) - torque (in kTorqueOnly or kPositionAndTorque mode) output_ports: - <b style="color:orange">actuation</b> - position_commanded - position_measured - velocity_estimated - state_estimated - torque_commanded - torque_measured - torque_external @endsystem Ports shown in <b style="color:orange">orange</b> are intended to connect to the MultibodyPlant's per-model-instance ports of the same name. All other ports are intended to mimic the LCM command and status message fields. @tparam_default_scalar */ template <typename T> class SimIiwaDriver : public systems::Diagram<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SimIiwaDriver); /** Constructs a diagram with the given parameters. A reference to the `controller_plant` is retained by this system, so the `controller_plant` must outlive `this`. */ SimIiwaDriver(IiwaControlMode control_mode, const multibody::MultibodyPlant<T>* controller_plant, double ext_joint_filter_tau, const std::optional<Eigen::VectorXd>& kp_gains); /** Scalar-converting copy constructor. See @ref system_scalar_conversion. */ template <typename U> explicit SimIiwaDriver(const SimIiwaDriver<U>&); /** Given a `plant` (and associated `iiwa_instance`) and a `builder`, installs in that builder the `SimIiwaDriver` system to control and monitor an iiwa described by `controller_plant`. The added `SimIiwaDriver` system is connected to the actuation input port, state and generalized contact forces output ports in `plant` corresponding to the iiwa model. Returns the newly-added `SimIiwaDriver` System. Note: The Diagram will maintain an internal reference to `controller_plant`, so you must ensure that `controller_plant` has a longer lifetime than the Diagram. */ static const systems::System<double>& AddToBuilder( systems::DiagramBuilder<double>* builder, const multibody::MultibodyPlant<double>& plant, const multibody::ModelInstanceIndex iiwa_instance, const multibody::MultibodyPlant<double>& controller_plant, double ext_joint_filter_tau, const std::optional<Eigen::VectorXd>& desired_iiwa_kp_gains, IiwaControlMode control_mode); }; } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_driver.cc
#include "drake/manipulation/kuka_iiwa/iiwa_driver.h"
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_command_receiver.h
#pragma once #include "drake/common/drake_copyable.h" #include "drake/lcmt_iiwa_command.hpp" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace manipulation { namespace kuka_iiwa { /// Handles lcmt_iiwa_command message from a LcmSubscriberSystem. /// /// Note that this system does not actually subscribe to an LCM channel. To /// receive the message, the input of this system should be connected to a /// LcmSubscriberSystem::Make<drake::lcmt_iiwa_command>(). /// /// It has one required input port, "lcmt_iiwa_command". /// /// It has three output ports: one for the commanded position for each joint, /// one for commanded additional feedforward joint torque, and one for the /// timestamp in the most recently received message. /// /// @system /// name: IiwaCommandReceiver /// input_ports: /// - lcmt_iiwa_command /// - position_measured (optional) /// output_ports: /// - position /// - torque /// - time /// @endsystem /// /// @par Output prior to receiving a valid lcmt_iiwa_command message: The /// "position" output initially feeds through from the "position_measured" /// input port -- or if not connected, outputs zero. When discrete update /// events are enabled (e.g., during a simulation), the system latches the /// "position_measured" input into state during the first event, and the /// "position" output comes from the latched state, no longer fed through from /// the "position" input. Alternatively, the LatchInitialPosition() method is /// available to achieve the same effect without using events. The "torque" /// output will be a vector of zeros, and the "time" output will be a /// vector of a single zero. class IiwaCommandReceiver final : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(IiwaCommandReceiver) explicit IiwaCommandReceiver( int num_joints = kIiwaArmNumJoints, IiwaControlMode control_mode = IiwaControlMode::kPositionAndTorque); ~IiwaCommandReceiver() final; /// (Advanced.) Copies the current "position_measured" input (or zero if not /// connected) into Context state, and changes the behavior of the "position" /// output to produce the latched state if no message has been received yet. /// The latching already happens automatically during the first discrete /// update event (e.g., when using a Simulator); this method exists for use /// when not already using a Simulator or other special cases. void LatchInitialPosition(systems::Context<double>* context) const; /// @name Named accessors for this System's input and output ports. //@{ const systems::InputPort<double>& get_message_input_port() const { return *message_input_; } const systems::InputPort<double>& get_position_measured_input_port() const { return *position_measured_input_; } /// @throws std::exception if control_mode does not include position control. const systems::OutputPort<double>& get_commanded_position_output_port() const { DRAKE_THROW_UNLESS(commanded_position_output_ != nullptr); return *commanded_position_output_; } /// @throws std::exception if control_mode does not include torque control. const systems::OutputPort<double>& get_commanded_torque_output_port() const { DRAKE_THROW_UNLESS(commanded_torque_output_ != nullptr); return *commanded_torque_output_; } const systems::OutputPort<double>& get_time_output_port() const { return *time_output_; } //@} private: void DoCalcNextUpdateTime(const systems::Context<double>&, systems::CompositeEventCollection<double>*, double*) const final; void CalcPositionMeasuredOrZero(const systems::Context<double>&, systems::BasicVector<double>*) const; void LatchInitialPosition(const systems::Context<double>&, systems::DiscreteValues<double>*) const; void CalcDefaultedCommand(const systems::Context<double>&, lcmt_iiwa_command*) const; void CalcPositionOutput(const systems::Context<double>&, systems::BasicVector<double>*) const; void CalcTorqueOutput(const systems::Context<double>&, systems::BasicVector<double>*) const; void CalcTimeOutput(const systems::Context<double>&, systems::BasicVector<double>*) const; const int num_joints_{}; const IiwaControlMode control_mode_{IiwaControlMode::kPositionAndTorque}; const systems::InputPort<double>* message_input_{}; const systems::InputPort<double>* position_measured_input_{}; const systems::CacheEntry* position_measured_or_zero_{}; systems::DiscreteStateIndex latched_position_measured_is_set_; systems::DiscreteStateIndex latched_position_measured_; const systems::CacheEntry* defaulted_command_{}; const systems::OutputPort<double>* commanded_position_output_{}; const systems::OutputPort<double>* commanded_torque_output_{}; const systems::OutputPort<double>* time_output_{}; }; } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/sim_iiwa_driver.cc
#include "drake/manipulation/kuka_iiwa/sim_iiwa_driver.h" #include <string> #include "drake/common/default_scalars.h" #include "drake/systems/controllers/inverse_dynamics_controller.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/adder.h" #include "drake/systems/primitives/demultiplexer.h" #include "drake/systems/primitives/discrete_derivative.h" #include "drake/systems/primitives/first_order_low_pass_filter.h" #include "drake/systems/primitives/pass_through.h" namespace drake { namespace manipulation { namespace kuka_iiwa { using multibody::ModelInstanceIndex; using multibody::MultibodyPlant; using systems::Adder; using systems::Context; using systems::Demultiplexer; using systems::Diagram; using systems::DiagramBuilder; using systems::FirstOrderLowPassFilter; using systems::PassThrough; using systems::StateInterpolatorWithDiscreteDerivative; using systems::System; using systems::controllers::InverseDynamics; using systems::controllers::InverseDynamicsController; namespace { /* The return type of MakeInverseDynamicsGains(), immediately below. */ struct Gains { VectorX<double> kp; VectorX<double> ki; VectorX<double> kd; }; /* Given the user-provided `kp` gains (if any), return all PID gains. */ Gains MakeInverseDynamicsGains(const std::optional<Eigen::VectorXd>& kp) { Gains result; // The default values are taken from the current FRI driver. // TODO(EricCousineau-TRI): These seem like *very* high values for inverse // dynamics on a simulated plant. Investigate overshoot from // `robot_follow_joint_sequence`, see if it's just a timing issue. result.kp = kp.value_or((Eigen::VectorXd(7) << 2000, 1500, 1500, 1500, 1500, 500, 500) .finished()); // Critical damping gains. result.kd = 2 * result.kp.array().sqrt(); result.ki = VectorX<double>::Constant(result.kp.size(), 1.0); return result; } } // namespace template <typename T> SimIiwaDriver<T>::SimIiwaDriver( const IiwaControlMode control_mode, const multibody::MultibodyPlant<T>* const controller_plant, const double ext_joint_filter_tau, const std::optional<Eigen::VectorXd>& kp_gains) : Diagram<T>(systems::SystemTypeTag<SimIiwaDriver>{}) { DRAKE_THROW_UNLESS(controller_plant != nullptr); const int num_positions = controller_plant->num_positions(); DiagramBuilder<T> builder; // Declare the `state` input port to accept MbP's {i'th}_state output port, // and demux it into separate positions and velocities. auto state_demux = builder.template AddNamedSystem<Demultiplexer>( "demultiplexer", 2 * num_positions, num_positions); builder.ExportInput(state_demux->get_input_port(), "state"); // Declare the `generalized_contact_forces` input port to accept the MbP's // {i'th}_generalized_contact_forces output port. Filter this because unlike // the real robot external torques in sim are rather noisy (which propagates // into the computed external wrench). auto contact_forces = builder.template AddNamedSystem<FirstOrderLowPassFilter>( "low_pass_filter", ext_joint_filter_tau, num_positions); builder.ExportInput(contact_forces->get_input_port(), "generalized_contact_forces"); // When position control is enabled, declare the `position` input port, // interpolate position commands into state commands, and then use a full // inverse dynamics controller. Otherwise, use inverse dynamics only for // gravity compensation. const System<T>* inverse_dynamics{}; if (position_enabled(control_mode)) { using StateInterpolator = StateInterpolatorWithDiscreteDerivative<T>; auto interpolator = builder.template AddNamedSystem<StateInterpolator>( "velocity_interpolator", num_positions, kIiwaLcmStatusPeriod, true /* suppress initial transient */); builder.ExportInput(interpolator->get_input_port(), "position"); const Gains inverse_dynamics_gains = MakeInverseDynamicsGains(kp_gains); inverse_dynamics = builder.template AddNamedSystem<InverseDynamicsController>( "inverse_dynamics_controller", *controller_plant, inverse_dynamics_gains.kp, inverse_dynamics_gains.ki, inverse_dynamics_gains.kd, false /* no feedforward acceleration */); builder.Connect(interpolator->GetOutputPort("state"), inverse_dynamics->GetInputPort("desired_state")); } else { inverse_dynamics = builder.template AddNamedSystem<InverseDynamics>( "gravity_compensation", controller_plant, InverseDynamics<T>::InverseDynamicsMode::kGravityCompensation); } builder.ConnectInput("state", inverse_dynamics->GetInputPort("estimated_state")); // When torque control is enabled, declare the `torque` input port and add it // to the inverse dynamics output. Otherwise, use the inverse dynamics output // by itself. const System<T>* actuation = nullptr; if (torque_enabled(control_mode)) { actuation = builder.template AddNamedSystem<Adder>("+", 2, num_positions); builder.Connect(inverse_dynamics->GetOutputPort("generalized_force"), actuation->get_input_port(0)); builder.ExportInput(actuation->get_input_port(1), "torque"); } else { actuation = inverse_dynamics; } // Declare the various output ports. builder.ExportOutput(actuation->get_output_port(), "actuation"); if (position_enabled(control_mode)) { auto pass = builder.template AddNamedSystem<PassThrough>( "position_pass_through", num_positions); builder.ConnectInput("position", pass->get_input_port()); builder.ExportOutput(pass->get_output_port(), "position_commanded"); } else { builder.ExportOutput(state_demux->get_output_port(0), "position_commanded"); } builder.ExportOutput(state_demux->get_output_port(0), "position_measured"); builder.ExportOutput(state_demux->get_output_port(1), "velocity_estimated"); { auto pass = builder.template AddNamedSystem<PassThrough>( "state_pass_through", 2 * num_positions); builder.ConnectInput("state", pass->get_input_port()); builder.ExportOutput(pass->get_output_port(), "state_estimated"); } builder.ExportOutput(actuation->get_output_port(), "torque_commanded"); // TODO(amcastro-tri): is this what we want to send as the "measured // torque"? why coming from the controllers instead of from the plant? builder.ExportOutput(actuation->get_output_port(), "torque_measured"); builder.ExportOutput(contact_forces->get_output_port(), "torque_external"); builder.BuildInto(this); } template <typename T> template <typename U> SimIiwaDriver<T>::SimIiwaDriver(const SimIiwaDriver<U>& other) : Diagram<T>(systems::SystemTypeTag<SimIiwaDriver>{}, other) {} template <typename T> const System<double>& SimIiwaDriver<T>::AddToBuilder( DiagramBuilder<double>* builder, const MultibodyPlant<double>& plant, const ModelInstanceIndex iiwa_instance, const MultibodyPlant<double>& controller_plant, double ext_joint_filter_tau, const std::optional<Eigen::VectorXd>& desired_iiwa_kp_gains, IiwaControlMode control_mode) { const std::string name = fmt::format("IiwaDriver({})", plant.GetModelInstanceName(iiwa_instance)); auto system = builder->AddNamedSystem<SimIiwaDriver<double>>( name, control_mode, &controller_plant, ext_joint_filter_tau, desired_iiwa_kp_gains); builder->Connect(plant.get_state_output_port(iiwa_instance), system->GetInputPort("state")); builder->Connect( plant.get_generalized_contact_forces_output_port(iiwa_instance), system->GetInputPort("generalized_contact_forces")); builder->Connect(system->GetOutputPort("actuation"), plant.get_actuation_input_port(iiwa_instance)); return *system; } } // namespace kuka_iiwa } // namespace manipulation } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::manipulation::kuka_iiwa::SimIiwaDriver)
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_status_receiver.cc
#include "drake/manipulation/kuka_iiwa/iiwa_status_receiver.h" #include "drake/common/drake_throw.h" namespace drake { namespace manipulation { namespace kuka_iiwa { using systems::BasicVector; using systems::Context; IiwaStatusReceiver::IiwaStatusReceiver(int num_joints) : num_joints_(num_joints) { this->DeclareAbstractInputPort("lcmt_iiwa_status", Value<lcmt_iiwa_status>{}); this->DeclareVectorOutputPort("time_measured", 1, &IiwaStatusReceiver::CalcTimeOutput); this->DeclareVectorOutputPort( "position_commanded", num_joints_, &IiwaStatusReceiver::CalcLcmOutput< &lcmt_iiwa_status::joint_position_commanded>); this->DeclareVectorOutputPort( "position_measured", num_joints_, &IiwaStatusReceiver::CalcLcmOutput< &lcmt_iiwa_status::joint_position_measured>); this->DeclareVectorOutputPort( "velocity_estimated", num_joints_, &IiwaStatusReceiver::CalcLcmOutput< &lcmt_iiwa_status::joint_velocity_estimated>); this->DeclareVectorOutputPort("torque_commanded", num_joints_, &IiwaStatusReceiver::CalcLcmOutput< &lcmt_iiwa_status::joint_torque_commanded>); this->DeclareVectorOutputPort("torque_measured", num_joints_, &IiwaStatusReceiver::CalcLcmOutput< &lcmt_iiwa_status::joint_torque_measured>); this->DeclareVectorOutputPort("torque_external", num_joints_, &IiwaStatusReceiver::CalcLcmOutput< &lcmt_iiwa_status::joint_torque_external>); } IiwaStatusReceiver::~IiwaStatusReceiver() = default; using OutPort = systems::OutputPort<double>; const OutPort& IiwaStatusReceiver::get_time_measured_output_port() const { return LeafSystem<double>::get_output_port(0); } const OutPort& IiwaStatusReceiver::get_position_commanded_output_port() const { return LeafSystem<double>::get_output_port(1); } const OutPort& IiwaStatusReceiver::get_position_measured_output_port() const { return LeafSystem<double>::get_output_port(2); } const OutPort& IiwaStatusReceiver::get_velocity_estimated_output_port() const { return LeafSystem<double>::get_output_port(3); } const OutPort& IiwaStatusReceiver::get_torque_commanded_output_port() const { return LeafSystem<double>::get_output_port(4); } const OutPort& IiwaStatusReceiver::get_torque_measured_output_port() const { return LeafSystem<double>::get_output_port(5); } const OutPort& IiwaStatusReceiver::get_torque_external_output_port() const { return LeafSystem<double>::get_output_port(6); } template <std::vector<double> drake::lcmt_iiwa_status::*field_ptr> void IiwaStatusReceiver::CalcLcmOutput(const Context<double>& context, BasicVector<double>* output) const { const auto& status = get_input_port().Eval<lcmt_iiwa_status>(context); // If we're using a default constructed message (i.e., we haven't received // any status message yet), output zero. if (status.num_joints == 0) { output->get_mutable_value().setZero(); } else { const auto& status_field = status.*field_ptr; DRAKE_THROW_UNLESS(status.num_joints == num_joints_); DRAKE_THROW_UNLESS(static_cast<int>(status_field.size()) == num_joints_); output->get_mutable_value() = Eigen::Map<const Eigen::VectorXd>(status_field.data(), num_joints_); } } void IiwaStatusReceiver::CalcTimeOutput(const Context<double>& context, BasicVector<double>* output) const { const auto& status = get_input_port().Eval<lcmt_iiwa_status>(context); // If we're using a default constructed message (i.e., we haven't received // any status message yet), output zero. if (status.num_joints == 0) { output->get_mutable_value().setZero(); } else { (*output)[0] = static_cast<double>(status.utime) / 1e6; } } } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/build_iiwa_control.cc
#include "drake/manipulation/kuka_iiwa/build_iiwa_control.h" #include "drake/lcm/drake_lcm_interface.h" #include "drake/manipulation/kuka_iiwa/iiwa_command_receiver.h" #include "drake/manipulation/kuka_iiwa/iiwa_status_sender.h" #include "drake/manipulation/kuka_iiwa/sim_iiwa_driver.h" #include "drake/systems/lcm/lcm_publisher_system.h" #include "drake/systems/lcm/lcm_subscriber_system.h" #include "drake/systems/primitives/demultiplexer.h" #include "drake/systems/primitives/gain.h" namespace drake { namespace manipulation { namespace kuka_iiwa { using drake::lcm::DrakeLcmInterface; using multibody::ModelInstanceIndex; using multibody::MultibodyPlant; using systems::Demultiplexer; using systems::DiagramBuilder; using systems::Gain; using systems::System; using systems::lcm::LcmPublisherSystem; using systems::lcm::LcmSubscriberSystem; void BuildIiwaControl( const MultibodyPlant<double>& plant, const ModelInstanceIndex iiwa_instance, const MultibodyPlant<double>& controller_plant, DrakeLcmInterface* lcm, DiagramBuilder<double>* builder, double ext_joint_filter_tau, const std::optional<Eigen::VectorXd>& desired_iiwa_kp_gains, IiwaControlMode control_mode) { const IiwaControlPorts sim_ports = BuildSimplifiedIiwaControl( plant, iiwa_instance, controller_plant, builder, ext_joint_filter_tau, desired_iiwa_kp_gains, control_mode); const int num_iiwa_positions = controller_plant.num_positions(); const std::string model_name = plant.GetModelInstanceName(iiwa_instance); // Create the Iiwa command receiver. auto command_sub = builder->AddNamedSystem( fmt::format("{}_iiwa_command_subscriber", model_name), LcmSubscriberSystem::Make<lcmt_iiwa_command>("IIWA_COMMAND", lcm)); auto command_decode = builder->AddNamedSystem<IiwaCommandReceiver>( fmt::format("{}_iiwa_command_receiver", model_name), num_iiwa_positions, control_mode); builder->Connect(command_sub->get_output_port(), command_decode->get_message_input_port()); // Use the current position until the first command is received. Note that we // connect the position directly from the plant, not the (possibly sampled or // delayed) `sim_port.position_measured` output of the driver. auto state_demux = builder->template AddNamedSystem<Demultiplexer>( fmt::format("{}_iiwa_state_demultiplexer", model_name), 2 * num_iiwa_positions, num_iiwa_positions); builder->Connect(plant.get_state_output_port(iiwa_instance), state_demux->get_input_port()); builder->Connect(state_demux->get_output_port(0), command_decode->get_position_measured_input_port()); // Connect receiver output to sim controller input. if (position_enabled(control_mode)) { builder->Connect(command_decode->get_commanded_position_output_port(), *sim_ports.commanded_positions); } if (torque_enabled(control_mode)) { builder->Connect(command_decode->get_commanded_torque_output_port(), *sim_ports.commanded_torque); } // Create an Iiwa status sender. auto status_pub = builder->AddNamedSystem( fmt::format("{}_iiwa_status_publisher", model_name), LcmPublisherSystem::Make<lcmt_iiwa_status>("IIWA_STATUS", lcm, kIiwaLcmStatusPeriod)); auto status_encode = builder->AddNamedSystem<IiwaStatusSender>( fmt::format("{}_iiwa_status_sender", model_name), num_iiwa_positions); builder->Connect(status_encode->get_output_port(), status_pub->get_input_port()); // Connect sim controller output to status input. builder->Connect(*sim_ports.position_commanded, status_encode->get_position_commanded_input_port()); builder->Connect(*sim_ports.position_measured, status_encode->get_position_measured_input_port()); builder->Connect(*sim_ports.velocity_estimated, status_encode->get_velocity_estimated_input_port()); builder->Connect(*sim_ports.joint_torque, status_encode->get_torque_commanded_input_port()); builder->Connect(*sim_ports.torque_measured, status_encode->get_torque_measured_input_port()); builder->Connect(*sim_ports.external_torque, status_encode->get_torque_external_input_port()); } IiwaControlPorts BuildSimplifiedIiwaControl( const MultibodyPlant<double>& plant, const ModelInstanceIndex iiwa_instance, const MultibodyPlant<double>& controller_plant, DiagramBuilder<double>* builder, double ext_joint_filter_tau, const std::optional<Eigen::VectorXd>& desired_iiwa_kp_gains, IiwaControlMode control_mode) { const int num_positions = controller_plant.num_positions(); DRAKE_THROW_UNLESS(num_positions == 7); // Add the sim driver to the builder. const System<double>* const system = &SimIiwaDriver<double>::AddToBuilder( builder, plant, iiwa_instance, controller_plant, ext_joint_filter_tau, desired_iiwa_kp_gains, control_mode); // Return the necessary port pointers. IiwaControlPorts result; if (position_enabled(control_mode)) { result.commanded_positions = &system->GetInputPort("position"); } if (torque_enabled(control_mode)) { result.commanded_torque = &system->GetInputPort("torque"); } result.position_commanded = &system->GetOutputPort("position_commanded"); result.position_measured = &system->GetOutputPort("position_measured"); result.velocity_estimated = &system->GetOutputPort("velocity_estimated"); { // TODO(eric.cousineau): Why do we flip this? auto negate = builder->AddNamedSystem<Gain>( fmt::format("sign_flip_{}_torque_commanded", plant.GetModelInstanceName(iiwa_instance)), -1, num_positions); builder->Connect(system->GetOutputPort("torque_commanded"), negate->get_input_port()); result.joint_torque = &negate->get_output_port(); } { // TODO(eric.cousineau): Why do we flip this? auto negate = builder->AddNamedSystem<Gain>( fmt::format("sign_flip_{}_torque_measured", plant.GetModelInstanceName(iiwa_instance)), -1, num_positions); builder->Connect(system->GetOutputPort("torque_measured"), negate->get_input_port()); result.torque_measured = &negate->get_output_port(); } result.external_torque = &system->GetOutputPort("torque_external"); return result; } } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_constants.h
#pragma once #include <string> #include <vector> #include "drake/common/drake_assert.h" #include "drake/common/eigen_types.h" namespace drake { namespace manipulation { namespace kuka_iiwa { constexpr int kIiwaArmNumJoints = 7; /** Returns the maximum joint velocities (rad/s) provided by Kuka. */ VectorX<double> get_iiwa_max_joint_velocities(); extern const double kIiwaLcmStatusPeriod; /** Enumeration for control modes. */ enum class IiwaControlMode { kPositionOnly, kTorqueOnly, kPositionAndTorque }; /** Reports if the given control `mode` includes positions. */ constexpr inline bool position_enabled(IiwaControlMode control_mode) { return control_mode != IiwaControlMode::kTorqueOnly; } /** Reports if the given control `mode` includes torques. */ constexpr inline bool torque_enabled(IiwaControlMode control_mode) { return control_mode != IiwaControlMode::kPositionOnly; } /** Parses control mode with the following mapping: - "position_only": kPositionOnly - "torque_only": kTorqueOnly - "position_and_torque": kPositionAndTorque */ IiwaControlMode ParseIiwaControlMode(const std::string& control_mode); } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_command_sender.h
#pragma once #include "drake/common/drake_copyable.h" #include "drake/lcmt_iiwa_command.hpp" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace manipulation { namespace kuka_iiwa { /** Creates and outputs lcmt_iiwa_command messages. Note that this system does not actually send the message on an LCM channel. To send the message, the output of this system should be connected to a systems::lcm::LcmPublisherSystem::Make<lcmt_iiwa_command>(). This system has three vector-valued input ports: - one for the commanded position, which must be connected if position mode is specified, - one for commanded torque, which is optional if position and torque mode is specified (for backwards compatibility), but must be connected if it is torque only, and - one for the time to use, in seconds, for the message timestamp, which is optional. If position and torque mode is specified, the torque input port can remain unconnected; the message will contain torque values of size zero. If position mode is not specified, the message will contain position values of size zero. If the time input port is not connected, the context time will be used for message timestamp. This system has one abstract-valued output port of type lcmt_iiwa_command. @system name: IiwaCommandSender input_ports: - position (required if using position mode) - torque (optional if using position mode, required in torque mode) - time (optional) output_ports: - lcmt_iiwa_command @endsystem @see `lcmt_iiwa_command.lcm` for additional documentation. */ class IiwaCommandSender final : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(IiwaCommandSender) explicit IiwaCommandSender( int num_joints = kIiwaArmNumJoints, IiwaControlMode control_mode = IiwaControlMode::kPositionAndTorque); ~IiwaCommandSender() final; /** @name Named accessors for this System's input and output ports. */ //@{ const systems::InputPort<double>& get_time_input_port() const; const systems::InputPort<double>& get_position_input_port() const; const systems::InputPort<double>& get_torque_input_port() const; //@} private: void CalcOutput(const systems::Context<double>&, lcmt_iiwa_command*) const; const int num_joints_; const IiwaControlMode control_mode_{IiwaControlMode::kPositionAndTorque}; const drake::systems::InputPort<double>* position_input_port_{}; const drake::systems::InputPort<double>* torque_input_port_{}; const drake::systems::InputPort<double>* time_input_port_{}; }; } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_status_receiver.h
#pragma once #include <vector> #include "drake/common/drake_copyable.h" #include "drake/lcmt_iiwa_status.hpp" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace manipulation { namespace kuka_iiwa { /// Handles lcmt_iiwa_status messages from a LcmSubscriberSystem. /// /// Note that this system does not actually subscribe to an LCM channel. To /// receive the message, the input of this system should be connected to a /// systems::lcm::LcmSubscriberSystem::Make<lcmt_iiwa_status>(). /// /// This system has one abstract-valued input port of type lcmt_iiwa_status. /// /// This system has many vector-valued output ports, most of which emit vector /// values of exactly `num_joints` elements. The exception is `time_measured`, /// which has a one-dimensional measured time output in seconds, i.e., the /// timestamp from the hardware in microseconds converted into seconds. All /// ports will output zeros until an input message is received. // /// @system /// name: IiwaStatusReceiver /// input_ports: /// - lcmt_iiwa_status /// output_ports: /// - time_measured /// - position_commanded /// - position_measured /// - velocity_estimated /// - torque_commanded /// - torque_measured /// - torque_external /// @endsystem /// /// @see `lcmt_iiwa_status.lcm` for additional documentation. class IiwaStatusReceiver final : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(IiwaStatusReceiver) explicit IiwaStatusReceiver(int num_joints = kIiwaArmNumJoints); ~IiwaStatusReceiver() final; /// @name Named accessors for this System's input and output ports. //@{ const systems::OutputPort<double>& get_time_measured_output_port() const; const systems::OutputPort<double>& get_position_commanded_output_port() const; const systems::OutputPort<double>& get_position_measured_output_port() const; const systems::OutputPort<double>& get_velocity_estimated_output_port() const; const systems::OutputPort<double>& get_torque_commanded_output_port() const; const systems::OutputPort<double>& get_torque_measured_output_port() const; const systems::OutputPort<double>& get_torque_external_output_port() const; //@} private: template <std::vector<double> drake::lcmt_iiwa_status::*> void CalcLcmOutput(const systems::Context<double>&, systems::BasicVector<double>*) const; void CalcTimeOutput(const systems::Context<double>&, systems::BasicVector<double>*) const; const int num_joints_; }; } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_constants.cc
#include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include <fmt/format.h> namespace drake { namespace manipulation { namespace kuka_iiwa { VectorX<double> get_iiwa_max_joint_velocities() { // These are the maximum joint velocities given in Section 4.3.2 "Axis data, // LBR iiwa 14 R820" of the "LBR iiwa 7 R800, LBR iiwa 14 R820 Specification". // That document is available here: // https://www.kuka.com/-/media/kuka-downloads/imported/48ec812b1b2947898ac2598aff70abc0/spez_lbr_iiwa_en.pdf return (VectorX<double>(7) << 1.483529, // 85°/s in rad/s 1.483529, // 85°/s in rad/s 1.745329, // 100°/s in rad/s 1.308996, // 75°/s in rad/s 2.268928, // 130°/s in rad/s 2.356194, // 135°/s in rad/s 2.356194) // 135°/s in rad/s .finished(); } // This value is chosen to match the value in getSendPeriodMilliSec() // when initializing the FRI configuration on the iiwa's control // cabinet. const double kIiwaLcmStatusPeriod = 0.005; IiwaControlMode ParseIiwaControlMode(const std::string& control_mode) { if (control_mode == "position_only") { return IiwaControlMode::kPositionOnly; } else if (control_mode == "torque_only") { return IiwaControlMode::kTorqueOnly; } else if (control_mode == "position_and_torque") { return IiwaControlMode::kPositionAndTorque; } else { throw std::runtime_error( fmt::format("ParseIiwaControlMode: Invalid control_mode string: '{}'", control_mode)); } } } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation
/home/johnshepherd/drake/manipulation/kuka_iiwa/iiwa_command_sender.cc
#include "drake/manipulation/kuka_iiwa/iiwa_command_sender.h" namespace drake { namespace manipulation { namespace kuka_iiwa { IiwaCommandSender::IiwaCommandSender(int num_joints, IiwaControlMode control_mode) : num_joints_(num_joints), control_mode_(control_mode) { if (position_enabled(control_mode_)) { position_input_port_ = &this->DeclareInputPort( "position", systems::kVectorValued, num_joints_); } if (torque_enabled(control_mode_)) { torque_input_port_ = &this->DeclareInputPort("torque", systems::kVectorValued, num_joints_); } time_input_port_ = &this->DeclareInputPort("time", systems::kVectorValued, 1); this->DeclareAbstractOutputPort("lcmt_iiwa_command", &IiwaCommandSender::CalcOutput); } IiwaCommandSender::~IiwaCommandSender() = default; using InPort = systems::InputPort<double>; const InPort& IiwaCommandSender::get_position_input_port() const { DRAKE_THROW_UNLESS(position_enabled(control_mode_)); DRAKE_DEMAND(position_input_port_ != nullptr); return *position_input_port_; } const InPort& IiwaCommandSender::get_torque_input_port() const { DRAKE_THROW_UNLESS(torque_enabled(control_mode_)); DRAKE_DEMAND(torque_input_port_ != nullptr); return *torque_input_port_; } const InPort& IiwaCommandSender::get_time_input_port() const { DRAKE_DEMAND(time_input_port_ != nullptr); return *time_input_port_; } void IiwaCommandSender::CalcOutput(const systems::Context<double>& context, lcmt_iiwa_command* output) const { const double message_time = get_time_input_port().HasValue(context) ? get_time_input_port().Eval(context)[0] : context.get_time(); const bool has_position = position_enabled(control_mode_); bool has_torque = false; if (control_mode_ == IiwaControlMode::kTorqueOnly) { has_torque = true; } else if (control_mode_ == IiwaControlMode::kPositionAndTorque) { has_torque = get_torque_input_port().HasValue(context); } const int num_position = has_position ? num_joints_ : 0; const int num_torques = has_torque ? num_joints_ : 0; lcmt_iiwa_command& command = *output; command.utime = message_time * 1e6; command.num_joints = num_position; command.joint_position.resize(num_position); if (has_position) { const auto& position = get_position_input_port().Eval(context); for (int i = 0; i < num_joints_; ++i) { command.joint_position[i] = position[i]; } } command.num_torques = num_torques; command.joint_torque.resize(num_torques); if (has_torque) { const auto& torque = get_torque_input_port().Eval(context); for (int i = 0; i < num_torques; ++i) { command.joint_torque[i] = torque[i]; } } } } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/kuka_iiwa
/home/johnshepherd/drake/manipulation/kuka_iiwa/test/sim_iiwa_driver_test.cc
#include "drake/manipulation/kuka_iiwa/sim_iiwa_driver.h" #include <memory> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { using multibody::MultibodyPlant; using multibody::Parser; using systems::InputPortIndex; using systems::OutputPortIndex; using systems::System; class SimIiwaDriverTest : public ::testing::Test { public: SimIiwaDriverTest() = default; protected: void SetUp() { sim_plant_ = std::make_unique<MultibodyPlant<double>>(0.001); Parser parser{sim_plant_.get()}; iiwa_instance_ = parser.AddModelsFromUrl( "package://drake_models/iiwa_description/sdf/" "iiwa7_no_collision.sdf")[0]; sim_plant_->WeldFrames(sim_plant_->world_frame(), sim_plant_->GetFrameByName("iiwa_link_0")); sim_plant_->Finalize(); controller_plant_ = System<double>::Clone(*sim_plant_); } void TestSimIiwaDriverPorts(IiwaControlMode mode, const System<double>& dut) { // Check input port names. std::vector<std::string> inputs; for (InputPortIndex i{0}; i < dut.num_input_ports(); ++i) { inputs.push_back(dut.get_input_port(i).get_name()); } std::vector<std::string> expected_inputs{"state", "generalized_contact_forces"}; if (position_enabled(mode)) { expected_inputs.push_back("position"); } if (torque_enabled(mode)) { expected_inputs.push_back("torque"); } EXPECT_THAT(inputs, testing::ElementsAreArray(expected_inputs)); // Check output port names. std::vector<std::string> outputs; for (OutputPortIndex i{0}; i < dut.num_output_ports(); ++i) { outputs.push_back(dut.get_output_port(i).get_name()); } std::vector<std::string> expected_outputs{ "actuation", "position_commanded", "position_measured", "velocity_estimated", "state_estimated", "torque_commanded", "torque_measured", "torque_external"}; EXPECT_THAT(outputs, testing::ElementsAreArray(expected_outputs)); } std::unique_ptr<MultibodyPlant<double>> sim_plant_; std::unique_ptr<MultibodyPlant<double>> controller_plant_; multibody::ModelInstanceIndex iiwa_instance_; double ext_joint_filter_tau_{0.1}; const Eigen::VectorXd desired_iiwa_kp_gains_ = (Eigen::VectorXd(7) << 100, 100, 100, 100, 100, 100, 100).finished(); }; TEST_F(SimIiwaDriverTest, SanityCheck) { for (const auto& mode : {IiwaControlMode::kPositionOnly, IiwaControlMode::kTorqueOnly, IiwaControlMode::kPositionAndTorque}) { SCOPED_TRACE(fmt::format("mode = {}", static_cast<int>(mode))); const SimIiwaDriver<double> dut(mode, controller_plant_.get(), ext_joint_filter_tau_, {}); TestSimIiwaDriverPorts(mode, dut); // Check scalar conversion. EXPECT_TRUE(systems::is_autodiffxd_convertible(dut)); EXPECT_TRUE(systems::is_symbolic_convertible(dut)); } } TEST_F(SimIiwaDriverTest, AddToBuilder) { for (const auto& mode : {IiwaControlMode::kPositionOnly, IiwaControlMode::kTorqueOnly, IiwaControlMode::kPositionAndTorque}) { SCOPED_TRACE(fmt::format("mode = {}", static_cast<int>(mode))); systems::DiagramBuilder<double> builder; auto* sim_plant = builder.AddSystem(System<double>::Clone(*sim_plant_)); const System<double>* const dut = &SimIiwaDriver<double>::AddToBuilder( &builder, *sim_plant, iiwa_instance_, *controller_plant_, ext_joint_filter_tau_, desired_iiwa_kp_gains_, mode); TestSimIiwaDriverPorts(mode, *dut); } } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/kuka_iiwa
/home/johnshepherd/drake/manipulation/kuka_iiwa/test/iiwa_command_receiver_test.cc
#include "drake/manipulation/kuka_iiwa/iiwa_command_receiver.h" #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { using Eigen::VectorXd; constexpr int N = kIiwaArmNumJoints; class IiwaCommandReceiverTest : public testing::Test { public: IiwaCommandReceiverTest() {} template <typename... Args> void MakeDut(Args&&... args) { dut_ = std::make_unique<IiwaCommandReceiver>(kIiwaArmNumJoints, std::forward<Args>(args)...); context_ = dut().CreateDefaultContext(); fixed_input_ = &FixInput(); } IiwaCommandReceiver& dut() { return *dut_; } systems::Context<double>& context() { return *context_; } systems::FixedInputPortValue& fixed_input() { return *fixed_input_; } // For use only by our constructor. systems::FixedInputPortValue& FixInput() { return dut().get_message_input_port().FixValue(&context(), lcmt_iiwa_command{}); } // Test cases should call this to set the DUT's input value. void SetInput(lcmt_iiwa_command message) { // TODO(jwnimmer-tri) This systems framework API is not very ergonomic. fixed_input() .GetMutableData() ->template get_mutable_value<lcmt_iiwa_command>() = message; } VectorXd position() { const auto& port = dut().get_commanded_position_output_port(); const VectorXd result = port.Eval(context()); return result; } VectorXd torque() { return dut().get_commanded_torque_output_port().Eval(context()); } double time_output() { return dut().get_time_output_port().Eval(context())[0]; } protected: std::unique_ptr<IiwaCommandReceiver> dut_; std::unique_ptr<systems::Context<double>> context_; systems::FixedInputPortValue* fixed_input_{}; }; constexpr double kCommandTime = 1.2; TEST_F(IiwaCommandReceiverTest, AcceptanceTestWithoutMeasuredPositionInput) { MakeDut(); // When no message has been received and *no* position measurement is // connected, the command is all zeros. const VectorXd zero = VectorXd::Zero(N); EXPECT_TRUE(CompareMatrices(position(), zero)); EXPECT_TRUE(CompareMatrices(torque(), zero)); EXPECT_EQ(time_output(), 0); } TEST_F(IiwaCommandReceiverTest, AcceptanceTestWithMeasuredPositionInput) { MakeDut(); const VectorXd zero = VectorXd::Zero(N); // When no message has been received and a measurement *is* connected, the // command is to hold at the current position. const VectorXd q0 = VectorXd::LinSpaced(N, 0.2, 0.3); dut().get_position_measured_input_port().FixValue(&context(), q0); EXPECT_TRUE(CompareMatrices(position(), q0)); EXPECT_TRUE(CompareMatrices(torque(), zero)); EXPECT_EQ(time_output(), 0); // Check that a real command trumps the initial position. // First, try with empty torques. const VectorXd q1 = VectorXd::LinSpaced(N, 0.3, 0.4); lcmt_iiwa_command command{}; command.utime = kCommandTime * 1e6; command.num_joints = N; command.joint_position = {q1.data(), q1.data() + q1.size()}; SetInput(command); EXPECT_TRUE(CompareMatrices(position(), q1)); EXPECT_TRUE(CompareMatrices(torque(), zero)); EXPECT_EQ(time_output(), kCommandTime); // Now provide torques. const VectorXd t1 = VectorXd::LinSpaced(N, 0.5, 0.6); command.num_torques = N; command.joint_torque = {t1.data(), t1.data() + t1.size()}; SetInput(command); EXPECT_TRUE(CompareMatrices(position(), q1)); EXPECT_TRUE(CompareMatrices(torque(), t1)); } TEST_F(IiwaCommandReceiverTest, AcceptanceTestWithLatching) { MakeDut(); const VectorXd zero = VectorXd::Zero(N); // When no message has been received and a measurement *is* connected, the // command is to hold at the current position. const VectorXd q0 = VectorXd::LinSpaced(N, 0.0, 0.1); dut().get_position_measured_input_port().FixValue(&context(), q0); EXPECT_TRUE(CompareMatrices(position(), q0)); EXPECT_TRUE(CompareMatrices(torque(), zero)); EXPECT_EQ(time_output(), 0); // Prior to any update events, changes to position_measured feed through. const VectorXd q1 = VectorXd::LinSpaced(N, 0.1, 0.2); dut().get_position_measured_input_port().FixValue(&context(), q1); EXPECT_TRUE(CompareMatrices(position(), q1)); EXPECT_TRUE(CompareMatrices(torque(), zero)); // Once an update event occurs, further changes to position_measured have no // effect. dut().LatchInitialPosition(&context()); const VectorXd q2 = VectorXd::LinSpaced(N, 0.3, 0.4); dut().get_position_measured_input_port().FixValue(&context(), q2); EXPECT_TRUE(CompareMatrices(position(), q1)); EXPECT_TRUE(CompareMatrices(torque(), zero)); // Check that a real command trumps the initial position. // First, try with empty torques. const VectorXd q3 = VectorXd::LinSpaced(N, 0.4, 0.5); const VectorXd t3 = VectorXd::LinSpaced(N, 0.5, 0.6); lcmt_iiwa_command command{}; command.utime = kCommandTime * 1e6; command.num_joints = N; command.joint_position = {q3.data(), q3.data() + q3.size()}; command.num_torques = N; command.joint_torque = {t3.data(), t3.data() + t3.size()}; SetInput(command); EXPECT_TRUE(CompareMatrices(position(), q3)); EXPECT_TRUE(CompareMatrices(torque(), t3)); EXPECT_EQ(time_output(), kCommandTime); } TEST_F(IiwaCommandReceiverTest, TorqueOnly) { MakeDut(IiwaControlMode::kTorqueOnly); EXPECT_THROW(dut().get_commanded_position_output_port(), std::runtime_error); const VectorXd t0 = VectorXd::LinSpaced(N, 0.5, 0.6); lcmt_iiwa_command command{}; command.utime = kCommandTime * 1e6; command.num_joints = 0; command.num_torques = N; command.joint_torque = {t0.data(), t0.data() + t0.size()}; SetInput(command); EXPECT_TRUE(CompareMatrices(torque(), t0)); } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/kuka_iiwa
/home/johnshepherd/drake/manipulation/kuka_iiwa/test/iiwa_status_sender_test.cc
#include "drake/manipulation/kuka_iiwa/iiwa_status_sender.h" #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { using Eigen::VectorXd; constexpr int N = kIiwaArmNumJoints; class IiwaStatusSenderTest : public testing::Test { public: IiwaStatusSenderTest() : dut_(), context_ptr_(dut_.CreateDefaultContext()), context_(*context_ptr_) {} const lcmt_iiwa_status& output() const { const lcmt_iiwa_status& result = dut_.get_output_port().Eval<lcmt_iiwa_status>(context_); DRAKE_DEMAND(result.num_joints == N); DRAKE_DEMAND(result.joint_position_commanded.size() == N); DRAKE_DEMAND(result.joint_position_measured.size() == N); DRAKE_DEMAND(result.joint_velocity_estimated.size() == N); DRAKE_DEMAND(result.joint_torque_commanded.size() == N); DRAKE_DEMAND(result.joint_torque_measured.size() == N); DRAKE_DEMAND(result.joint_torque_external.size() == N); return result; } static std::vector<double> as_vector(const Eigen::VectorXd& v) { return {v.data(), v.data() + v.size()}; } void Fix(const systems::InputPort<double>& port, const Eigen::VectorXd& v) { port.FixValue(&context_, v); } protected: IiwaStatusSender dut_; std::unique_ptr<systems::Context<double>> context_ptr_; systems::Context<double>& context_; }; TEST_F(IiwaStatusSenderTest, AcceptanceTest) { const VectorXd time_measured = Vector1d(1.2); const VectorXd q0_commanded = VectorXd::LinSpaced(N, 0.1, 0.2); const VectorXd q0_measured = VectorXd::LinSpaced(N, 0.11, 0.22); const VectorXd v0_estimated = VectorXd::LinSpaced(N, 0.2, 0.3); const VectorXd t0_commanded = VectorXd::LinSpaced(N, 0.4, 0.5); const VectorXd t0_measured = VectorXd::LinSpaced(N, 0.44, 0.55); const VectorXd t0_external = VectorXd::LinSpaced(N, 0.6, 0.7); // Fix only the required inputs ... Fix(dut_.get_position_commanded_input_port(), q0_commanded); Fix(dut_.get_position_measured_input_port(), q0_measured); Fix(dut_.get_torque_commanded_input_port(), t0_commanded); // ... so that some outputs have passthrough values ... EXPECT_EQ(output().joint_position_commanded, as_vector(q0_commanded)); EXPECT_EQ(output().joint_position_measured, as_vector(q0_measured)); EXPECT_EQ(output().joint_torque_commanded, as_vector(t0_commanded)); // ... and some outputs have default values. EXPECT_EQ(output().utime, 0); EXPECT_EQ(output().joint_velocity_estimated, std::vector<double>(N, 0.0)); EXPECT_EQ(output().joint_torque_measured, as_vector(t0_commanded)); EXPECT_EQ(output().joint_torque_external, std::vector<double>(N, 0.0)); // Fix all of the inputs ... Fix(dut_.get_time_measured_input_port(), time_measured); Fix(dut_.get_velocity_estimated_input_port(), v0_estimated); Fix(dut_.get_torque_measured_input_port(), t0_measured); Fix(dut_.get_torque_external_input_port(), t0_external); // ... so all outputs have values. EXPECT_EQ(output().utime, time_measured[0] * 1e6); EXPECT_EQ(output().joint_position_commanded, as_vector(q0_commanded)); EXPECT_EQ(output().joint_position_measured, as_vector(q0_measured)); EXPECT_EQ(output().joint_torque_commanded, as_vector(t0_commanded)); EXPECT_EQ(output().joint_velocity_estimated, as_vector(v0_estimated)); EXPECT_EQ(output().joint_torque_measured, as_vector(t0_measured)); EXPECT_EQ(output().joint_torque_external, as_vector(t0_external)); } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/kuka_iiwa
/home/johnshepherd/drake/manipulation/kuka_iiwa/test/iiwa_command_sender_test.cc
#include "drake/manipulation/kuka_iiwa/iiwa_command_sender.h" #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/limit_malloc.h" namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { using drake::test::LimitMalloc; using Eigen::VectorXd; constexpr int N = kIiwaArmNumJoints; class IiwaCommandSenderTest : public testing::Test { public: IiwaCommandSenderTest() {} protected: template <typename... Args> void MakeDut(Args&&... args) { dut_ = std::make_unique<IiwaCommandSender>(kIiwaArmNumJoints, std::forward<Args>(args)...); context_ptr_ = dut().CreateDefaultContext(); } IiwaCommandSender& dut() { return *dut_; } systems::Context<double>& context() { return *context_ptr_; } const lcmt_iiwa_command& output() { return dut().get_output_port().Eval<lcmt_iiwa_command>(context()); } std::unique_ptr<IiwaCommandSender> dut_; std::unique_ptr<systems::Context<double>> context_ptr_; const Vector1d time_{Vector1d(1.2)}; const VectorXd q0_{VectorXd::LinSpaced(N, 0.1, 0.2)}; const std::vector<double> std_q0_{q0_.data(), q0_.data() + q0_.size()}; const VectorXd t0_{VectorXd::LinSpaced(N, 0.3, 0.4)}; const std::vector<double> std_t0_{t0_.data(), t0_.data() + t0_.size()}; }; TEST_F(IiwaCommandSenderTest, PositionAndTorqueTest) { // Default is position and torque. MakeDut(); // For position and torque control mode, an unconnected position input port // throws. EXPECT_THROW(output(), std::logic_error); dut().get_position_input_port().FixValue(&context(), q0_); EXPECT_EQ(output().utime, 0); EXPECT_EQ(output().num_joints, N); EXPECT_EQ(output().joint_position, std_q0_); EXPECT_EQ(output().num_torques, 0); // Time is optional. dut().get_time_input_port().FixValue(&context(), time_); // Torque is optional. dut().get_torque_input_port().FixValue(&context(), t0_); EXPECT_EQ(output().utime, time_[0] * 1e6); EXPECT_EQ(output().num_joints, N); EXPECT_EQ(output().joint_position, std_q0_); EXPECT_EQ(output().num_torques, N); EXPECT_EQ(output().joint_torque, std_t0_); } TEST_F(IiwaCommandSenderTest, PositionOnlyTest) { MakeDut(IiwaControlMode::kPositionOnly); // Should not have torque input port. EXPECT_THROW(dut().get_torque_input_port(), std::runtime_error); // For position-only control mode, an unconnected position input port throws. EXPECT_THROW(output(), std::logic_error); dut().get_position_input_port().FixValue(&context(), q0_); EXPECT_EQ(output().utime, 0); EXPECT_EQ(output().num_joints, N); EXPECT_EQ(output().joint_position, std_q0_); EXPECT_EQ(output().num_torques, 0); } TEST_F(IiwaCommandSenderTest, TorqueOnlyTest) { MakeDut(IiwaControlMode::kTorqueOnly); // Should not have position input port. EXPECT_THROW(dut().get_position_input_port(), std::runtime_error); // For torque-only control mode, an unconnected torque input port throws. EXPECT_THROW(output(), std::logic_error); dut().get_torque_input_port().FixValue(&context(), t0_); EXPECT_EQ(output().utime, 0); EXPECT_EQ(output().num_joints, 0); EXPECT_EQ(output().num_torques, N); EXPECT_EQ(output().joint_torque, std_t0_); } // This class is likely to be used on the critical path for robot control, so // we insist that it must not perform heap operations while in steady-state. TEST_F(IiwaCommandSenderTest, MallocTest) { MakeDut(); // Initialize and then invalidate the cached output. auto& q = dut().get_position_input_port().FixValue(&context(), q0_); output(); q.GetMutableVectorData<double>(); // Recompute the output. No heap changes are allowed. { LimitMalloc guard; output(); } // Add torques, re-initialize, and then invalidate the cached output. auto& tau = dut().get_torque_input_port().FixValue(&context(), t0_); output(); tau.GetMutableVectorData<double>(); // Recompute the output. No heap changes are allowed. { LimitMalloc guard; output(); } // Add time, re-initialize, and then invalidate the cached output. auto& utime = dut().get_time_input_port().FixValue(&context(), time_); output(); utime.GetMutableVectorData<double>(); // Recompute the output. No heap changes are allowed. { LimitMalloc guard; output(); } } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/kuka_iiwa
/home/johnshepherd/drake/manipulation/kuka_iiwa/test/iiwa_status_receiver_test.cc
#include "drake/manipulation/kuka_iiwa/iiwa_status_receiver.h" #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/limit_malloc.h" namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { using drake::test::LimitMalloc; using Eigen::VectorXd; constexpr int N = kIiwaArmNumJoints; class IiwaStatusReceiverTest : public testing::Test { public: IiwaStatusReceiverTest() : dut_(), context_ptr_(dut_.CreateDefaultContext()), context_(*context_ptr_), fixed_input_( dut_.get_input_port().FixValue(&context_, lcmt_iiwa_status{})) {} void Copy(const Eigen::VectorXd& from, std::vector<double>* to) { *to = {from.data(), from.data() + from.size()}; } protected: IiwaStatusReceiver dut_; std::unique_ptr<systems::Context<double>> context_ptr_; systems::Context<double>& context_; systems::FixedInputPortValue& fixed_input_; lcmt_iiwa_status status_{}; }; TEST_F(IiwaStatusReceiverTest, AcceptanceTest) { // Confirm that output is zero for uninitialized lcm input. const int num_output_ports = dut_.num_output_ports(); EXPECT_EQ(num_output_ports, 7); for (int i = 0; i < num_output_ports; ++i) { const systems::LeafSystem<double>& leaf = dut_; const auto& port = leaf.get_output_port(i); if (i > 0) { EXPECT_TRUE(CompareMatrices(port.Eval(context_), VectorXd::Zero(N))); } else { EXPECT_TRUE(CompareMatrices(port.Eval(context_), VectorXd::Zero(1))); } } // Populate the status message with distinct values. const int utime = 1661199485; const VectorXd position_commanded = VectorXd::LinSpaced(N, 0.0, 1.0); const VectorXd position_measured = VectorXd::LinSpaced(N, 2.0, 3.0); const VectorXd velocity_estimated = VectorXd::LinSpaced(N, 4.0, 5.0); const VectorXd torque_commanded = VectorXd::LinSpaced(N, 6.0, 7.0); const VectorXd torque_measured = VectorXd::LinSpaced(N, 8.0, 9.0); const VectorXd torque_external = VectorXd::LinSpaced(N, 10.0, 11.0); status_.utime = utime; status_.num_joints = N; Copy(position_commanded, &status_.joint_position_commanded); Copy(position_measured, &status_.joint_position_measured); Copy(velocity_estimated, &status_.joint_velocity_estimated); Copy(torque_commanded, &status_.joint_torque_commanded); Copy(torque_measured, &status_.joint_torque_measured); Copy(torque_external, &status_.joint_torque_external); // TODO(jwnimmer-tri) This systems framework API is not very ergonomic. fixed_input_.GetMutableData() ->template get_mutable_value<lcmt_iiwa_status>() = status_; // Confirm that real message values are output correctly. EXPECT_TRUE( CompareMatrices(dut_.get_time_measured_output_port().Eval(context_), Vector1d(utime) / 1e6)); EXPECT_TRUE( CompareMatrices(dut_.get_position_commanded_output_port().Eval(context_), position_commanded)); EXPECT_TRUE( CompareMatrices(dut_.get_position_measured_output_port().Eval(context_), position_measured)); EXPECT_TRUE( CompareMatrices(dut_.get_velocity_estimated_output_port().Eval(context_), velocity_estimated)); EXPECT_TRUE( CompareMatrices(dut_.get_torque_commanded_output_port().Eval(context_), torque_commanded)); EXPECT_TRUE(CompareMatrices( dut_.get_torque_measured_output_port().Eval(context_), torque_measured)); EXPECT_TRUE(CompareMatrices( dut_.get_torque_external_output_port().Eval(context_), torque_external)); } // This class is likely to be used on the critical path for robot control, so // we insist that it must not perform heap operations while in steady-state. TEST_F(IiwaStatusReceiverTest, MallocTest) { // Set as input a non-trivial message. status_.utime = 1; status_.num_joints = N; status_.joint_position_commanded.resize(N); status_.joint_position_measured.resize(N); status_.joint_velocity_estimated.resize(N); status_.joint_torque_commanded.resize(N); status_.joint_torque_measured.resize(N); status_.joint_torque_external.resize(N); // TODO(jwnimmer-tri) This systems framework API is not very ergonomic. fixed_input_.GetMutableData() ->template get_mutable_value<lcmt_iiwa_status>() = status_; // Compute the output. No heap changes are allowed. { LimitMalloc guard; const systems::LeafSystem<double>& leaf = dut_; const int num_output_ports = leaf.num_output_ports(); for (int i = 0; i < num_output_ports; ++i) { const auto& port = leaf.get_output_port(i); port.Eval(context_); } } } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/kuka_iiwa
/home/johnshepherd/drake/manipulation/kuka_iiwa/test/iiwa_constants_test.cc
#include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include <gtest/gtest.h> namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { GTEST_TEST(IiwaConstantsTest, ParseIiwaControlMode) { EXPECT_TRUE(position_enabled(IiwaControlMode::kPositionAndTorque) && position_enabled(IiwaControlMode::kPositionOnly) && !position_enabled(IiwaControlMode::kTorqueOnly)); EXPECT_TRUE(torque_enabled(IiwaControlMode::kPositionAndTorque) && torque_enabled(IiwaControlMode::kTorqueOnly) && !torque_enabled(IiwaControlMode::kPositionOnly)); EXPECT_EQ(ParseIiwaControlMode("position_only"), IiwaControlMode::kPositionOnly); EXPECT_EQ(ParseIiwaControlMode("torque_only"), IiwaControlMode::kTorqueOnly); EXPECT_EQ(ParseIiwaControlMode("position_and_torque"), IiwaControlMode::kPositionAndTorque); EXPECT_THROW(ParseIiwaControlMode("asdf"), std::runtime_error); } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/kuka_iiwa
/home/johnshepherd/drake/manipulation/kuka_iiwa/test/iiwa_driver_functions_test.cc
#include "drake/manipulation/kuka_iiwa/iiwa_driver_functions.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/lcm/drake_lcm_params.h" #include "drake/manipulation/kuka_iiwa/iiwa_driver.h" #include "drake/manipulation/util/zero_force_driver_functions.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/parsing/process_model_directives.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/plant/multibody_plant_config_functions.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_config_functions.h" namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { using lcm::DrakeLcmParams; using multibody::MultibodyPlant; using multibody::MultibodyPlantConfig; using multibody::Parser; using multibody::parsing::LoadModelDirectives; using multibody::parsing::ModelDirectives; using multibody::parsing::ModelInstanceInfo; using systems::DiagramBuilder; using systems::Simulator; using systems::System; using systems::lcm::ApplyLcmBusConfig; using systems::lcm::LcmBuses; /* A smoke test to apply simulated Iiwa driver with different driver configs. Specifically, whether a correct arm and hand model names are provided is tested. */ GTEST_TEST(IiwaDriverFunctionsTest, ApplyDriverConfig) { DiagramBuilder<double> builder; MultibodyPlant<double>& plant = AddMultibodyPlant(MultibodyPlantConfig{}, &builder); const ModelDirectives directives = LoadModelDirectives( FindResourceOrThrow("drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")); Parser parser{&plant}; std::vector<ModelInstanceInfo> models_from_directives = multibody::parsing::ProcessModelDirectives(directives, &parser); plant.Finalize(); std::map<std::string, ModelInstanceInfo> models_from_directives_map; for (const auto& info : models_from_directives) { models_from_directives_map.emplace(info.model_name, info); } const std::map<std::string, DrakeLcmParams> lcm_bus_config = { {"default", {}}}; const LcmBuses lcm_buses = ApplyLcmBusConfig(lcm_bus_config, &builder); // Supply incorrect arm model name should throw. DRAKE_EXPECT_THROWS_MESSAGE( ApplyDriverConfig(IiwaDriver{}, "arm", plant, models_from_directives_map, lcm_buses, &builder), "IiwaDriver could not find arm model.*"); // Supply an Iiwa driver with an incorrect `hand_model_name` should throw. DRAKE_EXPECT_THROWS_MESSAGE( ApplyDriverConfig(IiwaDriver{.hand_model_name = "hand"}, "iiwa7", plant, models_from_directives_map, lcm_buses, &builder), "IiwaDriver could not find hand model.*"); const ZeroForceDriver wsg_driver; const IiwaDriver iiwa_driver{.hand_model_name = "schunk_wsg"}; ApplyDriverConfig(wsg_driver, "schunk_wsg", plant, {}, {}, &builder); ApplyDriverConfig(iiwa_driver, "iiwa7", plant, models_from_directives_map, lcm_buses, &builder); // Prove that simulation does not crash. Simulator<double> simulator(builder.Build()); simulator.AdvanceTo(0.1); } /* Confirm that the user can opt-out of LCM. */ GTEST_TEST(IiwaDriverFunctionsTest, ApplyDriverConfigNoLcm) { // Prepare the plant. DiagramBuilder<double> builder; MultibodyPlant<double>& plant = AddMultibodyPlant(MultibodyPlantConfig{}, &builder); const ModelDirectives directives = LoadModelDirectives( FindResourceOrThrow("drake/manipulation/util/test/iiwa7_wsg.dmd.yaml")); Parser parser{&plant}; std::vector<ModelInstanceInfo> models_from_directives = multibody::parsing::ProcessModelDirectives(directives, &parser); plant.Finalize(); std::map<std::string, ModelInstanceInfo> models_from_directives_map; for (const auto& info : models_from_directives) { models_from_directives_map.emplace(info.model_name, info); } // Use nullopt for the LCM bus. const std::map<std::string, std::optional<DrakeLcmParams>> lcm_bus_config = { {"default", std::nullopt}}; const LcmBuses lcm_buses = ApplyLcmBusConfig(lcm_bus_config, &builder); // Add the driver. const IiwaDriver iiwa_driver; ApplyDriverConfig(iiwa_driver, "iiwa7", plant, models_from_directives_map, lcm_buses, &builder); // Check that no unwanted systems were added. auto diagram = builder.Build(); std::vector<std::string> names; for (const System<double>* system : diagram->GetSystems()) { names.push_back(system->get_name()); } const std::vector<std::string> expected{ // From AddMultibodyPlant. "plant", "scene_graph", // From ApplyDriverConfig. "IiwaDriver(iiwa7)", // TODO(jwnimmer-tri) Ideally this SharedPtrSystem would live within the // SimIiwaDriver, but for the moment it's a sibling instead of a child. "iiwa7_controller_plant", // This one SharedPtrSystem is the only remnant of LCM that gets added. // It is a DrakeLcmInterface that is never pumped (note that there is // no LcmInterfaceSystem anywhere in this list of `expected` systems. "DrakeLcm(bus_name=default)", }; EXPECT_THAT(names, testing::UnorderedElementsAreArray(expected)); } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake/manipulation/kuka_iiwa
/home/johnshepherd/drake/manipulation/kuka_iiwa/test/build_iiwa_control_test.cc
#include "drake/manipulation/kuka_iiwa/build_iiwa_control.h" #include <cmath> #include <memory> #include <Eigen/Dense> #include <gtest/gtest.h> #include "drake/lcm/drake_lcm.h" #include "drake/lcmt_iiwa_command.hpp" #include "drake/lcmt_iiwa_status.hpp" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/manipulation/util/make_arm_controller_model.h" #include "drake/multibody/parsing/model_instance_info.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/constant_vector_source.h" #include "drake/systems/primitives/shared_pointer_system.h" namespace drake { namespace manipulation { namespace kuka_iiwa { namespace { using Eigen::VectorXd; using math::RigidTransformd; using multibody::ModelInstanceIndex; using multibody::MultibodyPlant; using multibody::PackageMap; using multibody::Parser; using multibody::parsing::ModelInstanceInfo; using systems::ConstantVectorSource; using systems::DiagramBuilder; using systems::SharedPointerSystem; constexpr int N = manipulation::kuka_iiwa::kIiwaArmNumJoints; constexpr double kTolerance = 1e-3; class BuildIiwaControlTest : public ::testing::Test { public: BuildIiwaControlTest() = default; protected: void SetUp() { sim_plant_ = builder_.AddSystem<MultibodyPlant<double>>(0.001); Parser parser{sim_plant_}; const std::string iiwa7_model_path = PackageMap{}.ResolveUrl( "package://drake_models/iiwa_description/sdf/" "iiwa7_no_collision.sdf"); const ModelInstanceIndex iiwa7_instance = parser.AddModels(iiwa7_model_path).at(0); const std::string iiwa7_model_name = sim_plant_->GetModelInstanceName(iiwa7_instance); iiwa7_info_.model_name = iiwa7_model_name; iiwa7_info_.model_path = iiwa7_model_path; iiwa7_info_.child_frame_name = "iiwa_link_0"; iiwa7_info_.model_instance = iiwa7_instance; // Weld the arm to the world frame. sim_plant_->WeldFrames( sim_plant_->world_frame(), sim_plant_->GetFrameByName("iiwa_link_0", iiwa7_instance), RigidTransformd::Identity()); sim_plant_->Finalize(); controller_plant_ = SharedPointerSystem<double>::AddToBuilder( &builder_, manipulation::internal::MakeArmControllerModel(*sim_plant_, iiwa7_info_)); } DiagramBuilder<double> builder_; MultibodyPlant<double>* sim_plant_{nullptr}; MultibodyPlant<double>* controller_plant_{nullptr}; lcm::DrakeLcm lcm_; ModelInstanceInfo iiwa7_info_; }; TEST_F(BuildIiwaControlTest, BuildIiwaControl) { BuildIiwaControl(*sim_plant_, iiwa7_info_.model_instance, *controller_plant_, &lcm_, &builder_); const auto diagram = builder_.Build(); systems::Simulator<double> simulator(*diagram); lcm::Subscriber<lcmt_iiwa_status> sub{&lcm_, "IIWA_STATUS"}; // Publish commands and check whether the Iiwa arm moves to the correct poses. lcmt_iiwa_command command{}; const std::vector<double> q1{0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}; command.num_joints = N; command.joint_position = q1; Publish(&lcm_, "IIWA_COMMAND", command); lcm_.HandleSubscriptions(0); simulator.AdvanceTo(1.0); lcm_.HandleSubscriptions(0); EXPECT_EQ(sub.message().joint_position_commanded.size(), N); EXPECT_EQ(sub.message().joint_position_commanded, q1); for (int i = 0; i < N; ++i) { EXPECT_NEAR(sub.message().joint_position_measured[i], q1[i], kTolerance); } const std::vector<double> q2(N, 0.0); command.joint_position = q2; Publish(&lcm_, "IIWA_COMMAND", command); lcm_.HandleSubscriptions(0); simulator.AdvanceTo(2.0); lcm_.HandleSubscriptions(0); EXPECT_EQ(sub.message().joint_position_commanded.size(), N); EXPECT_EQ(sub.message().joint_position_commanded, q2); for (int i = 0; i < N; ++i) { EXPECT_NEAR(sub.message().joint_position_measured[i], q2[i], kTolerance); } } TEST_F(BuildIiwaControlTest, PositionOnly) { IiwaControlPorts control_ports{}; control_ports = BuildSimplifiedIiwaControl( *sim_plant_, iiwa7_info_.model_instance, *controller_plant_, &builder_, 0.01, {}, IiwaControlMode::kPositionOnly); const auto diagram = builder_.Build(); // Expect position as input. ASSERT_NE(control_ports.commanded_positions, nullptr); EXPECT_EQ(control_ports.commanded_positions->size(), N); // No torque input. Should be nullptr if enable_feedforward_torque is false. EXPECT_EQ(control_ports.commanded_torque, nullptr); // Check that outputs are never null. ASSERT_NE(control_ports.position_commanded, nullptr); ASSERT_NE(control_ports.position_measured, nullptr); ASSERT_NE(control_ports.velocity_estimated, nullptr); ASSERT_NE(control_ports.joint_torque, nullptr); ASSERT_NE(control_ports.torque_measured, nullptr); ASSERT_NE(control_ports.external_torque, nullptr); // Check output sizes. EXPECT_EQ(control_ports.position_commanded->size(), N); EXPECT_EQ(control_ports.position_measured->size(), N); EXPECT_EQ(control_ports.velocity_estimated->size(), N); EXPECT_EQ(control_ports.joint_torque->size(), N); EXPECT_EQ(control_ports.torque_measured->size(), N); EXPECT_EQ(control_ports.external_torque->size(), N); } TEST_F(BuildIiwaControlTest, TorqueOnly) { IiwaControlPorts control_ports{}; control_ports = BuildSimplifiedIiwaControl( *sim_plant_, iiwa7_info_.model_instance, *controller_plant_, &builder_, 0.01, {}, IiwaControlMode::kTorqueOnly); const auto diagram = builder_.Build(); // Expect torque as input. ASSERT_NE(control_ports.commanded_torque, nullptr); EXPECT_EQ(control_ports.commanded_torque->size(), N); // No position input. EXPECT_EQ(control_ports.commanded_positions, nullptr); // Check that outputs are never null. ASSERT_NE(control_ports.position_commanded, nullptr); ASSERT_NE(control_ports.position_measured, nullptr); ASSERT_NE(control_ports.velocity_estimated, nullptr); ASSERT_NE(control_ports.joint_torque, nullptr); ASSERT_NE(control_ports.torque_measured, nullptr); ASSERT_NE(control_ports.external_torque, nullptr); // Check output sizes. EXPECT_EQ(control_ports.position_commanded->size(), N); EXPECT_EQ(control_ports.position_measured->size(), N); EXPECT_EQ(control_ports.velocity_estimated->size(), N); EXPECT_EQ(control_ports.joint_torque->size(), N); EXPECT_EQ(control_ports.torque_measured->size(), N); EXPECT_EQ(control_ports.external_torque->size(), N); } TEST_F(BuildIiwaControlTest, PositionAndTorque) { IiwaControlPorts control_ports{}; const double ext_joint_filter_tau{0.01}; control_ports = BuildSimplifiedIiwaControl( *sim_plant_, iiwa7_info_.model_instance, *controller_plant_, &builder_, ext_joint_filter_tau, {}); /* Send a non-zero position command and a zero-feedforward-torque command. The Iiwa arm should reach the commanded position without a problem. */ VectorXd position_command = VectorXd::LinSpaced(N, 0.3, 0.4); auto p_input_source = builder_.AddSystem<ConstantVectorSource<double>>(position_command); builder_.Connect(p_input_source->get_output_port(), *control_ports.commanded_positions); VectorXd zero_feedforward_command = VectorXd::Zero(N); auto torque_input_source = builder_.AddSystem<ConstantVectorSource<double>>( zero_feedforward_command); builder_.Connect(torque_input_source->get_output_port(), *control_ports.commanded_torque); auto diagram = builder_.Build(); // Check that both inputs exist. ASSERT_NE(control_ports.commanded_positions, nullptr); ASSERT_NE(control_ports.commanded_torque, nullptr); EXPECT_EQ(control_ports.commanded_positions->size(), N); EXPECT_EQ(control_ports.commanded_torque->size(), N); // Check that outputs are never null. ASSERT_NE(control_ports.position_commanded, nullptr); ASSERT_NE(control_ports.position_measured, nullptr); ASSERT_NE(control_ports.velocity_estimated, nullptr); ASSERT_NE(control_ports.joint_torque, nullptr); ASSERT_NE(control_ports.torque_measured, nullptr); ASSERT_NE(control_ports.external_torque, nullptr); // Check output sizes. EXPECT_EQ(control_ports.position_commanded->size(), N); EXPECT_EQ(control_ports.position_measured->size(), N); EXPECT_EQ(control_ports.velocity_estimated->size(), N); EXPECT_EQ(control_ports.joint_torque->size(), N); EXPECT_EQ(control_ports.torque_measured->size(), N); EXPECT_EQ(control_ports.external_torque->size(), N); systems::Simulator<double> simulator(*diagram); auto& diagram_context = simulator.get_mutable_context(); simulator.AdvanceTo(1.0); VectorXd iiwa_positions = sim_plant_->GetPositions( sim_plant_->GetMyContextFromRoot(diagram_context), iiwa7_info_.model_instance); EXPECT_EQ(iiwa_positions.size(), N); for (int i = 0; i < N; ++i) { EXPECT_NEAR(iiwa_positions(i), position_command(i), kTolerance); } /* Same position command with a non-zero feedforward torque. The extra torque should take effect and move the Iiwa arm from its commanded position. */ VectorXd nonzero_feedforward_command = VectorXd::Constant(N, 10.0); torque_input_source ->get_mutable_source_value( &torque_input_source->GetMyMutableContextFromRoot(&diagram_context)) .set_value(nonzero_feedforward_command); simulator.AdvanceTo(2.0); iiwa_positions = sim_plant_->GetPositions( sim_plant_->GetMyContextFromRoot(diagram_context), iiwa7_info_.model_instance); for (int i = 0; i < N; ++i) { EXPECT_TRUE(std::abs(iiwa_positions(i) - position_command(i)) > kTolerance); } } } // namespace } // namespace kuka_iiwa } // namespace manipulation } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/robot_clearance.h
#pragma once #include <vector> #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/multibody/tree/multibody_tree_indexes.h" #include "drake/planning/robot_collision_type.h" namespace drake { namespace planning { /** A summary of the clearance -- a collection of distance measurements -- between the robot and everything in the world. This data can be used to define collision avoidance strategies. Conceptually, this class represents a table: | body index R | body index O | type | ϕᴼ(R) | Jq_ϕᴼ(R) | | :----------: | :----------: | :--: | :---: | :------: | | ... | ... | .. | ... | ... | Member functions return each column of the table as an ordered collection. The iᵗʰ entry in each collection belongs to the iᵗʰ row. Each row characterizes the relationship between a particular *robot* body (annotated as body R) and some "other" body (annotated as body O) in the model. That other body O may be part of the robot or the environment. - `body index R` is the BodyIndex of body R. - `body index O` is the BodyIndex of body O. - `type` implies the type of body O. Given that we know body R is a robot body, `type` indicates that body O is also a robot body with the value RobotCollisionType::kSelfCollision or an environment body with the value RobotCollisionType::kEnvironmentCollision. For a correct implementation of CollisionChecker, it will never be RobotCollisionType::kEnvironmentAndSelfCollision. - `ϕᴼ(R)` is the signed distance function of the other body O evaluated on body R. The reported distance is offset by the padding value for the body pair recorded in the CollisionChecker. It is the minimum padded distance between bodies O and R. A point on the padded surface of body O would report a distance of zero. Points inside that boundary report negative distance and points outside have positive distance. - `Jqᵣ_ϕᴼ(R)` is the Jacobian of ϕᴼ(R) with respect to the robot configuration vector `qᵣ`. The Jacobian is the derivative as observed in the world frame. - The vector `qᵣ` will be a subset of the plant's full configuration `q` when there are floating bodies or joints in the plant other than the robot. The Jacobian is only taken with respect to the robot. - The `jacobians()` matrix has `plant.num_positions()` columns and the column order matches up with the full `plant.GetPositions()` order. The columns associated with non-robot joints will be zero. Several important notes: - A single robot body index can appear many times as there may be many measured distances between that robot body and other bodies in the model. - A row *may* contain a zero-valued Jacobian Jqᵣ_ϕᴼ(R). Appropriately filtering collisions will cull most of these Jacobians. But depending on the structure of the robot and its representative collision geometry, it is still possible to evaluate the Jacobian at a configuration that represents a local optimum (zero-valued Jacobian). @ingroup planning_collision_checker */ class RobotClearance { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(RobotClearance) /** Creates an empty clearance with size() == 0 and num_positions as given. */ explicit RobotClearance(int num_positions) : nq_(num_positions) { DRAKE_THROW_UNLESS(num_positions >= 0); } ~RobotClearance(); /** @returns the number of distance measurements (rows in the table). */ int size() const { return robot_indices_.size(); } /** @returns the number of positions (i.e., columns) in jacobians(). */ int num_positions() const { return nq_; } // TODO(sean.curtis) Provide a guaranteed order on the rows, based on body // index. /** @returns the vector of *robot* body indices. */ const std::vector<multibody::BodyIndex>& robot_indices() const { return robot_indices_; } /** @returns the vector of *other* body indices. */ const std::vector<multibody::BodyIndex>& other_indices() const { return other_indices_; } /** @returns the vector of body collision types. */ const std::vector<RobotCollisionType>& collision_types() const { return collision_types_; } /** @returns the vector of distances (`ϕᴼ(R)`). */ Eigen::Map<const Eigen::VectorXd> distances() const { return Eigen::Map<const Eigen::VectorXd>(distances_.data(), size()); } /** @returns the vector of distance Jacobians (`Jqᵣ_ϕᴼ(R)`); the return type is a readonly Eigen::Map with size() rows and num_positions() columns. */ auto jacobians() const { using RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; return Eigen::Map<const RowMatrixXd>(jacobians_.data(), size(), nq_); } /** (Advanced) The mutable flavor of jacobians(). */ auto mutable_jacobians() { using RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; return Eigen::Map<RowMatrixXd>(jacobians_.data(), size(), nq_); } /** Ensures this object has storage for at least `size` rows. */ void Reserve(int size); /** Appends one measurement to this table. */ void Append(multibody::BodyIndex robot_index, multibody::BodyIndex other_index, RobotCollisionType collision_type, double distance, const Eigen::Ref<const Eigen::RowVectorXd>& jacobian); private: std::vector<multibody::BodyIndex> robot_indices_; std::vector<multibody::BodyIndex> other_indices_; std::vector<RobotCollisionType> collision_types_; std::vector<double> distances_; std::vector<double> jacobians_; // Stored in row-major order. int nq_{}; }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/collision_checker.h
#pragma once #include <list> #include <map> #include <memory> #include <mutex> #include <optional> #include <string> #include <utility> #include <vector> #include "drake/common/drake_throw.h" #include "drake/common/parallelism.h" #include "drake/multibody/plant/multibody_plant.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/robot_clearance.h" #include "drake/planning/robot_collision_type.h" #include "drake/planning/robot_diagram.h" namespace drake { namespace planning { /** Interface for collision checkers to use. <!-- TODO(SeanCurtis-TRI): This documentation focuses on the context management aspect of this class. We need to extend the documentation to give a broader overview of the class. The goal is to give sufficient context that they'd know what kind of nail this is a hammer for and how to swing it. Topics include, but are not limited to: - Emphasis that everything is characterized w.r.t. *robot* bodies. Distinguish the terms "full model" (robot and environment), "robot" or "robot model", and "environment bodies". - Performing collision queries - individual configurations - "edges" - Clearance - Padding - Collision filtering - Adding additional collision geometries. - Clear guidance on the minimal acts that constitute correct usage. E.g., do I have to call `AllocateContexts()`? When should I not? etc. - Clear delineation of serial queries that can be performed in parallel and queries that themselves parallelize and guidance on not mixing them. It's also important to partition the guidance between "user" documentation and "implementer" documentation. --> This interface builds on the basic multi-threading idiom of Drake: one context per thread. It offers two models to achieve multi-threaded parallel collision checking: - using thread pools (e.g. OpenMP or similar) and "implicit contexts" managed by this object - using arbitrary threads and "explicit contexts" created by this object @anchor ccb_implicit_contexts <h5>Implicit Context Parallelism</h5> Many methods of this class aren't designed for entry from arbitrary threads (e.g. from std::async threads), but rather are designed for use with a main thread and various thread-pool-parallel operations achieved by using directives like `omp parallel`. To support this usage, the base class `AllocateContexts()` protected method establishes a pool of contexts to support the implicit context parallelism specified in the constructor. (Note: if the collision checker declares that parallel checking is not supported, only one implict context will be allocated). `AllocateContexts()` must be called and only be called as part of the constructor of a derived class defined as final. Once the context pool is created, clients can access a thread-associated context by using `model_context(optional<int> context_number)` and related methods. These methods may be called in two ways: - without a context number, the association between thread and context uses the OpenMP notion of thread number - with a context number, the method uses the context corresponding to the provided number Without a context number, these context access methods are only safe under the following conditions: - the caller is the "main thread" - the caller is an OpenMP team thread *during execution of a parallel region* With a context number, these context access methods are only safe under the following conditions: - no two or more threads simultaneously use the same context number Methods supporting implicit context parallelism are noted below by having a reference to this section; as a rule of thumb, any public method that takes a `context_number` argument uses implicit context parallelism. Users of this class (derived classes and others) can write their own parallel operations using implicit contexts, provided they limit parallel blocks to only use `const` methods or methods marked to support implicit contexts parallelism, and the parallel operations are: - without a context number, only with parallelism using OpenMP directives - with a context number, via a parallelization method that provides a notion of thread numbers similar in behavior to OpenMP's (i.e. a thread number in [0, number of threads), not arbitrary values like `std::this_thread::get_id()`) To determine the greatest implicit context parallelism that can be achieved in a parallelized operation, `GetNumberOfThreads(Parallelism parallelize)` returns the lesser of the provided `parallelism` and the supported implicit context parallelism. <!-- TODO(calderpg-tri, rick-poyner) Add parallel for-loop examples once drakelint supports OpenMP pragmas in docs. --> @anchor ccb_explicit_contexts <h5>Explicit Context Parallelism</h5> It is also possible to use arbitrary thread models to perform collision checking in parallel using explicitly created contexts from this class. Contexts returned from MakeStandaloneModelContext() may be used in any thread, using only `const` methods of this class, or "explicit context" methods. Explicit contexts are tracked by this class using `std::weak_ptr` to track their lifetimes. This mechanism is used by PerformOperationAgainstAllModelContexts to map an operation over all collision contexts, whether explicit or implicit. Methods supporting explicit context parallelism are noted below by having a reference to this section; as a rule of thumb, any public method that takes a `model_context` first argument uses explicit context parallelism. In practice, multi-threaded collision checking with explicit contexts may look something like the example below. @code const Eigen::VectorXd start_q ... const Eigen::VectorXd sample_q1 ... const Eigen::VectorXd sample_q2 ... const auto check_edge_to = [&collision_checker, &start_q] ( const Eigen::VectorXd& sample_q, CollisionCheckerContext* explicit_context) { return collision_checker.CheckContextEdgeCollisionFree( explicit_context, start_q, sample_q); }; const auto context_1 = collision_checker.MakeStandaloneModelContext(); const auto context_2 = collision_checker.MakeStandaloneModelContext(); auto future_q1 = std::async(std::launch::async, check_edge_to, sample_q1, context_1.get()); auto future_q2 = std::async(std::launch::async, check_edge_to, sample_q2, context_2.get()); const double edge_1_valid = future_q1.get(); const double edge_2_valid = future_q2.get(); @endcode <h5>Mixing Threading Models</h5> It is possible to support mixed threading models, i.e., using both OpenMP thread pools and arbitrary threads. In this case, each arbitrary thread (say, from std::async) should have its own instance of a collision checker made using Clone(). Then each arbitrary thread will have its own implicit context pool. <h5>Implementing Derived Classes</h5> Collision checkers deriving from CollisionChecker *must* support parallel operations from both of the above parallelism models. This is generally accomplished by placing all mutable state within the per-thread context. If this cannot be accomplished, the shared mutable state must be accessed in a thread-safe manner. There are APIs that depend on SupportsParallelChecking() (e.g., CheckConfigsCollisionFree(), CheckEdgeCollisionFreeParallel(), CheckEdgesCollisionFree(), etc); a derived implementation should return `false` from SupportsParallelChecking() if there is no meaningful benefit to attempting to do work in parallel (e.g., they must fully serialize on shared state). @ingroup planning_collision_checker */ class CollisionChecker { public: // N.B. The copy constructor is protected for use in implementing Clone(). /** @name Does not allow copy, move, or assignment. */ //@{ CollisionChecker(CollisionChecker&&) = delete; CollisionChecker& operator=(const CollisionChecker&) = delete; CollisionChecker& operator=(CollisionChecker&&) = delete; //@} virtual ~CollisionChecker(); std::unique_ptr<CollisionChecker> Clone() const { return DoClone(); } /** @name Robot Model These methods all provide access to the underlying robot model's contents. */ //@{ /** @returns a `const` reference to the full model. */ const RobotDiagram<double>& model() const { if (IsInitialSetup()) { return *setup_model_; } else { DRAKE_DEMAND(model_ != nullptr); return *model_; } } /** @returns a `const reference to the full model's plant. */ const multibody::MultibodyPlant<double>& plant() const { return model().plant(); } /** @returns a `const` body reference to a body in the full model's plant for the given `body_index`. */ const multibody::RigidBody<double>& get_body( multibody::BodyIndex body_index) const { return plant().get_body(body_index); } /** Gets the set of model instances belonging to the robot. The returned vector has no duplicates and is in sorted order. */ const std::vector<multibody::ModelInstanceIndex>& robot_model_instances() const { return robot_model_instances_; } /** @returns true if the indicated body is part of the robot. */ bool IsPartOfRobot(const multibody::RigidBody<double>& body) const; /** @returns true if the indicated body is part of the robot. */ bool IsPartOfRobot(multibody::BodyIndex body_index) const; /** @returns a generalized position vector, sized according to the full model, whose values are all zero. @warning A zero vector is not necessarily a valid configuration, e.g., in case the configuration has quaternions, or position constraints, or etc. */ const Eigen::VectorXd& GetZeroConfiguration() const { return zero_configuration_; } //@} /** @name Context management */ //@{ /** @returns the number of internal (not standalone) per-thread contexts. */ int num_allocated_contexts() const { return owned_contexts_.num_contexts(); } /** Accesses a collision checking context from within the implicit context pool owned by this collision checker. @param context_number Optional implicit context number. @returns a `const` reference to either the collision checking context given by the `context_number`, or when nullopt the context to be used with the current OpenMP thread. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ const CollisionCheckerContext& model_context( std::optional<int> context_number = std::nullopt) const; // TODO(jeremy.nimmer) This is only lightly used, maybe we should toss it? /** Accesses a multibody plant sub-context context from within the implicit context pool owned by this collision checker. @param context_number Optional implicit context number. @returns a `const` reference to the multibody plant sub-context within the context given by the `context_number`, or when nullopt the context to be used with the current OpenMP thread. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ const systems::Context<double>& plant_context( std::optional<int> context_number = std::nullopt) const { return model_context(context_number).plant_context(); } /** Updates the generalized positions `q` in the implicit context specified and returns a reference to the MultibodyPlant's now-updated context. The implicit context is either that specified by `context_number`, or when nullopt the context to be used with the current OpenMP thread. @param context_number Optional implicit context number. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ const systems::Context<double>& UpdatePositions( const Eigen::VectorXd& q, std::optional<int> context_number = std::nullopt) const { return UpdateContextPositions(&mutable_model_context(context_number), q); } /** Explicit Context-based version of UpdatePositions(). @throws std::exception if `model_context` is `nullptr`. @see @ref ccb_explicit_contexts "Explicit Context Parallelism". */ const systems::Context<double>& UpdateContextPositions( CollisionCheckerContext* model_context, const Eigen::VectorXd& q) const { DRAKE_THROW_UNLESS(model_context != nullptr); plant().SetPositions(&model_context->mutable_plant_context(), q); DoUpdateContextPositions(model_context); return model_context->plant_context(); } /** Make and track a CollisionCheckerContext. The returned context will participate in PerformOperationAgainstAllModelContexts() until it is destroyed. */ std::shared_ptr<CollisionCheckerContext> MakeStandaloneModelContext() const; /** Allows externally-provided operations that must be performed against all contexts in the per-thread context pool, and any standalone contexts made with MakeStandaloneModelContext(). For any standalone contexts, note that it is illegal to mutate a context from two different threads. No other threads should be mutating any of our standalone contexts when this function is called. */ void PerformOperationAgainstAllModelContexts( const std::function<void(const RobotDiagram<double>&, CollisionCheckerContext*)>& operation); //@} /** @name Adding geometries to a body While the underlying model will have some set of geometries to represent each body, it can be useful to extend the representative set of geometries. These APIs admit adding and removing such geometries to the underlying model. We'll distinguish the geometries added by the checker from those in the underlying model by referring to them as "checker" geometries and "model" geometries, respectively. For example, when an end effector has successfully grasped a manipuland, we can add additional geometry to the end effector body, representing the extent of the manipuland, causing the motion planning to likewise consider collisions with the manipuland. Note, this implicitly treats the manipuland as being rigidly affixed to the end effector. Checker geometries are managed in groups, identified by "group names". Each group can contain one or more checker geometries. This is particularly useful when multiple geometries should be added and removed as a whole. Simply by storing the shared group name, all checker geometries in the group can be removed with a single invocation, relying on the collision checker to do the book keeping for you. Note that different collision checker implementations may limit the set of supported Shape types; e.g. sphere-robot-model collision checkers only add sphere shapes to robot bodies, and voxel-based collision checkers cannot add individual collision geometries to the environment at all. Therefore, all methods for adding collision geometries report if the geometries were added. The derived classes should clearly document which shapes they support. */ //@{ // TODO(sean.curtis): These BodyShapeDescription APIs are not used. Just cut // them? // TODO(sean.curtis): Make these functions [[nodiscard]]. /** Requests the addition of a shape to a body, both given in `description`. If added, the shape will belong to the named geometry group. @param group_name The name of the group to add the geometry to. @param description The data describing the shape and target body. @returns `true` if the shape was added. */ bool AddCollisionShape(const std::string& group_name, const BodyShapeDescription& description); // TODO(sean.curtis): Convert this to a simple `bool` return; either all of // the shapes were accepted or none were. /** Requests the addition of N shapes to N bodies, each given in the set of `descriptions`. Each added shape will belong to the named geometry group. @param group_name The name of the group to add the geometry to. @param descriptions The descriptions of N (shape, body) pairs. @returns The total number of shapes in `descriptions` that got added. */ int AddCollisionShapes(const std::string& group_name, const std::vector<BodyShapeDescription>& descriptions); /** Requests the addition of a collection of shapes to bodies across multiple geometry groups. `geometry_groups` specifies a collection of (shape, body) descriptors across multiple geometry groups. @param geometry_groups A map from a named geometry group to the (shape, body) pairs to add to that group. @returns A map from input named geometry group to the *number* of geometries added to that group. */ std::map<std::string, int> AddCollisionShapes( const std::map<std::string, std::vector<BodyShapeDescription>>& geometry_groups); /** Requests the addition of `shape` to the frame A in the checker's model. The added `shape` will belong to the named geometry group. @param group_name The name of the group to add the geometry to. @param frameA The frame the shape should be rigidly affixed to. @param shape The requested shape, defined in its canonical frame G. @param X_AG The pose of the shape in the frame A. @returns `true` if the shape was added. */ bool AddCollisionShapeToFrame(const std::string& group_name, const multibody::Frame<double>& frameA, const geometry::Shape& shape, const math::RigidTransform<double>& X_AG); /** Requests the addition of `shape` to the body A in the checker's model The added `shape` will belong to the named geometry group. @param group_name The name of the group to add the geometry to. @param bodyA The body the shape should be rigidly affixed to. @param shape The requested shape, defined in its canonical frame G. @param X_AG The pose of the shape in body A's frame. @returns `true` if the shape was added. */ bool AddCollisionShapeToBody(const std::string& group_name, const multibody::RigidBody<double>& bodyA, const geometry::Shape& shape, const math::RigidTransform<double>& X_AG); /** Gets all checker geometries currently added across the whole checker. @returns A mapping from each geometry group name to the collection of (shape, body) descriptions in that group. */ std::map<std::string, std::vector<BodyShapeDescription>> GetAllAddedCollisionShapes() const; // TODO(sean.curtis): Consider returning the total number of geometries // deleted; here and for "remove all". /** Removes all added checker geometries which belong to the named group. */ void RemoveAllAddedCollisionShapes(const std::string& group_name); /** Removes all added checker geometries from all geometry groups. */ void RemoveAllAddedCollisionShapes(); //@} /** @name Padding the distance between bodies Ultimately, the model's bodies are represented with geometries. The distance between bodies is the distance between their representative geometries. However, the exact distance between those geometries is not necessarily helpful in planning. For example, - You may want to add padding when real-world objects differ from the planning geometry. - In some cases, limited penetration is expected, and possibly desirable, such as when grasping in clutter. Padding is a mechanism where these distances can be "fudged" without modifying the underlying model. The *reported* distance between two bodies can be decreased by adding *positive* padding or increased by adding *negative* padding. One could think of it as padding the geometries -- making the objects larger (positive) or smaller (negative). This isn't quite true. Padding is defined for *pairs* of geometries. Ultimately, the padding data is stored in an NxN matrix (where the underlying model has N total bodies). The matrix is symmetric and the entry at (i, j) -- and (j, i) -- is the padding value to be applied to distance measurements between bodies i and j. It is meaningless to apply padding between a body and itself. Furthermore, as %CollisionChecker is concerned with the state of the *robot*, it is equally meaningless to apply padding between *environment* bodies. To avoid the illusion of padding, those entries on the diagonal and corresponding to environment body pairs are kept at zero. <u>Configuring padding</u> <!-- TODO(sean.curtis): We have a function for setting the padding between one robot body and *all* environment bodies, but not between a robot body and all *other* robot bodies. This apparent hole is only due to the judgement that it wouldn't be helpful. If we have a use case that would benefit, we can add it. --> Padding can be applied at different levels of scope: - For all pairs, via SetPaddingMatrix(). - For all (robot, environment) or (robot, robot) pairs via SetPaddingAllRobotEnvironmentPairs() and SetPaddingAllRobotRobotPairs(). - For all (robot i, environment) pairs via SetPaddingOneRobotBodyAllEnvironmentPairs(). - For pair (body i, body j) via SetPaddingBetween(). Invocations of these methods make immediate changes to the underlying padding data. Changing the order of invocations will change the final padding state. In other words, setting padding for a particular pair (A, B) followed by calling, for example, SetPaddingOneRobotBodyAllEnvironmentPairs(A) could erase the effect of the first invocation. @anchor collision_checker_padding_prereqs <u>Configuration prerequisites</u> In all these configuration methods, there are some specific requirements: - The padding value must always be finite. - Body indices must be in range (i.e., in [0, N) for a model with N total bodies). - If the parameters include one or more more body indices, at least one of them must reference a robot body. <u>Introspection</u> The current state of collision padding can be introspected via a number of methods: - View the underlying NxN padding matrix via GetPaddingMatrix(). - Find out if padding values are heterogeneous via MaybeGetUniformRobotEnvironmentPadding() and MaybeGetUniformRobotRobotPadding(). - Query the specific padding value between a pair of bodies via GetPaddingBetween(). - Find out the maximum padding value via GetLargestPadding(). */ //@{ /** If the padding between all robot bodies and environment bodies is the same, returns the common padding value. Returns nullopt otherwise. */ std::optional<double> MaybeGetUniformRobotEnvironmentPadding() const; /** If the padding between all pairs of robot bodies is the same, returns the common padding value. Returns nullopt otherwise. */ std::optional<double> MaybeGetUniformRobotRobotPadding() const; /** Gets the padding value for the pair of bodies specified. If the body indices are the same, zero will always be returned. @throws std::exception if either body index is out of range. */ double GetPaddingBetween(multibody::BodyIndex bodyA_index, multibody::BodyIndex bodyB_index) const { DRAKE_THROW_UNLESS(bodyA_index >= 0 && bodyA_index < collision_padding_.rows()); DRAKE_THROW_UNLESS(bodyB_index >= 0 && bodyB_index < collision_padding_.rows()); return collision_padding_(int{bodyA_index}, int{bodyB_index}); } /** Overload that uses body references. */ double GetPaddingBetween(const multibody::RigidBody<double>& bodyA, const multibody::RigidBody<double>& bodyB) const { return GetPaddingBetween(bodyA.index(), bodyB.index()); } /** Sets the padding value for the pair of bodies specified. @throws std::exception if the @ref collision_checker_padding_prereqs "configuration prerequisites" are not met or `bodyA_index == bodyB_index`. */ void SetPaddingBetween(multibody::BodyIndex bodyA_index, multibody::BodyIndex bodyB_index, double padding); /** Overload that uses body references. */ void SetPaddingBetween(const multibody::RigidBody<double>& bodyA, const multibody::RigidBody<double>& bodyB, double padding) { SetPaddingBetween(bodyA.index(), bodyB.index(), padding); } /** Gets the collision padding matrix. */ const Eigen::MatrixXd& GetPaddingMatrix() const { return collision_padding_; } /** Sets the collision padding matrix. Note that this matrix contains all padding data, both robot-robot "self" padding, and robot-environment padding. `collision_padding` must have the following properties to be considered valid. - It is a square NxN matrix (where N is the total number of bodies). - Diagonal values are all zero. - Entries involving only environment bodies are all zero. - It is symmetric. - All values are finite. @throws std::exception if `collision_padding` doesn't have the enumerated properties. */ void SetPaddingMatrix(const Eigen::MatrixXd& collision_padding); /** Gets the current largest collision padding across all (robot, *) body pairs. This excludes the meaningless zeros on the diagonal and environment-environment pairs; the return value *can* be negative. */ double GetLargestPadding() const { return max_collision_padding_; } /** Sets the environment collision padding for the provided robot body with respect to all environment bodies. @throws std::exception if the @ref collision_checker_padding_prereqs "configuration prerequisites" are not met. */ void SetPaddingOneRobotBodyAllEnvironmentPairs( multibody::BodyIndex body_index, double padding); /** Sets the padding for all (robot, environment) pairs. @throws std::exception if the @ref collision_checker_padding_prereqs "configuration prerequisites" are not met. */ void SetPaddingAllRobotEnvironmentPairs(double padding); /** Sets the padding for all (robot, robot) pairs. @throws std::exception if the @ref collision_checker_padding_prereqs "configuration prerequisites" are not met. */ void SetPaddingAllRobotRobotPairs(double padding); //@} /** @name Collision filtering The %CollisionChecker adapts the idea of "collision filtering" to *bodies* (see geometry::CollisionFilterManager). In addition to whatever collision filters have been declared within the underlying model, %CollisionChecker provides mechanisms to layer *additional* filters by specifying a pair of bodies as being "filtered". No collisions or distance measurements are reported on filtered body pairs. The "filter" state of all possible body pairs are stored in a symmetric NxN integer-valued matrix, where N is the number of bodies reported by the plant owned by this collision checker. The matrix can only contain one of three values: 0, 1, and -1. For the (i, j) entry in the matrix, each value would be interpreted as follows: 0: The collision is *not* filtered. Collision checker will report collisions and clearance between bodies I and J. 1: The collision *is* filtered. Collision checker will *not* report collisions and clearance between bodies I and J. -1: The collision *is* filtered *by definition*. Collision checker will *not* report collisions and clearance between bodies I and J and the user cannot change this state. CollisionChecker limits itself to characterizing the state of the *robot*. As such, it *always* filters collisions between pairs of environment bodies. It also filters collisions between a body and itself as nonsensical. Therefore, the matrix will always have immutable -1s along the diagonal and for every cell representing an environment-environment pair. The collision filter matrix must remain *consistent*. Only valid values for body pairs are accepted. I.e., assigning an (environment, environment) pair a value of 0 or 1 is "inconsistent". Likewise doing the same on the diagonal. Alternatively, assigning a -1 to any pair with a robot body would be inconsistent. The functions for configuring collision filters will throw if explicitly asked to make an inconsistent change. The %CollisionChecker's definition of filtered body pairs is initially drawn from the underlying model's configuration (see GetNominalFilteredCollisionMatrix()). However, the CollisionChecker's definition of the set of collision filters is independent of the model after construction and can be freely modified to allow for greater freedom in determining which bodies can affect each other. */ //@{ /** Returns the "nominal" collision filter matrix. The nominal matrix is initialized at construction time and represents the configuration of the model's plant and scene graph. It serves as a reference point to assess any changes to collision filters beyond this checker's intrinsic model. Collisions between bodies A and B are filtered in the following cases: - There exists a welded path between A and B. - SceneGraph has filtered the collisions between *all* pairs of geometries of A and B. Note: SceneGraph allows arbitrary collision filter configuration at the *geometry* level. The filters on one geometry of body need not be the same as another geometry on the same body. %CollisionChecker is body centric. It requires all geometries on a body to be filtered homogeneously. A SceneGraph that violates this stricter requirement cannot be used in a %CollisionChecker. It is highly unlikely that a SceneGraph instance will ever be in this configuration by accident. */ const Eigen::MatrixXi& GetNominalFilteredCollisionMatrix() const { return nominal_filtered_collisions_; } /** Gets the "active" collision filter matrix. */ const Eigen::MatrixXi& GetFilteredCollisionMatrix() const { return filtered_collisions_; } /** Sets the "active" collision filter matrix @param filter_matrix must meet the above conditions to be a "consistent" collision filter matrix. @throws std::exception if the given matrix is incompatible with this collision checker, or if it is inconsistent. */ void SetCollisionFilterMatrix(const Eigen::MatrixXi& filter_matrix); /** Checks if collision is filtered between the two bodies specified. Note: collision between two environment bodies is *always* filtered. @throws std::exception if either body index is out of range. */ bool IsCollisionFilteredBetween(multibody::BodyIndex bodyA_index, multibody::BodyIndex bodyB_index) const; /** Overload that uses body references. */ bool IsCollisionFilteredBetween( const multibody::RigidBody<double>& bodyA, const multibody::RigidBody<double>& bodyB) const { return IsCollisionFilteredBetween(bodyA.index(), bodyB.index()); } /** Declares the body pair (bodyA, bodyB) to be filtered (or not) based on `filter_collision`. @param filter_collision Sets the to body pair to be filtered if `true`. @throws std::exception if either body index is out of range. @throws std::exception if both indices refer to the same body. @throws std::exception if both indices refer to environment bodies. */ void SetCollisionFilteredBetween(multibody::BodyIndex bodyA_index, multibody::BodyIndex bodyB_index, bool filter_collision); /** Overload that uses body references. */ void SetCollisionFilteredBetween(const multibody::RigidBody<double>& bodyA, const multibody::RigidBody<double>& bodyB, bool filter_collision) { SetCollisionFilteredBetween(bodyA.index(), bodyB.index(), filter_collision); } /** Declares that body pair (B, O) is filtered (for all bodies O in this checker's plant). @throws std::exception if `body_index` is out of range. @throws std::exception if `body_index` refers to an environment body. */ void SetCollisionFilteredWithAllBodies(multibody::BodyIndex body_index); /** Overload that uses body references. */ void SetCollisionFilteredWithAllBodies( const multibody::RigidBody<double>& body) { SetCollisionFilteredWithAllBodies(body.index()); } //@} /** @name Configuration collision checking */ //@{ /** Checks a single configuration for collision using the current thread's associated context. @param q Configuration to check @param context_number Optional implicit context number. @returns true if collision free, false if in collision. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ bool CheckConfigCollisionFree( const Eigen::VectorXd& q, std::optional<int> context_number = std::nullopt) const; /** Explicit Context-based version of CheckConfigCollisionFree(). @throws std::exception if model_context is nullptr. @see @ref ccb_explicit_contexts "Explicit Context Parallelism". */ bool CheckContextConfigCollisionFree(CollisionCheckerContext* model_context, const Eigen::VectorXd& q) const; // TODO(SeanCurtis-TRI): This isn't tested. /** Checks a vector of configurations for collision, evaluating in parallel when supported and enabled by `parallelize`. Parallelization in configuration collision checks is provided using OpenMP and is supported when both: (1) the collision checker declares that parallelization is supported (i.e. when SupportsParallelChecking() is true) and (2) when multiple OpenMP threads are available for execution. See @ref collision_checker_parallel_edge "function-level parallelism" for guidance on proper usage. @param configs Configurations to check @param parallelize How much should collision checks be parallelized? @returns std::vector<uint8_t>, one for each configuration in configs. For each configuration, 1 if collision free, 0 if in collision. */ std::vector<uint8_t> CheckConfigsCollisionFree( const std::vector<Eigen::VectorXd>& configs, Parallelism parallelize = Parallelism::Max()) const; //@} /** @name Edge collision checking These functions serve motion planning methods, such as sampling-based planners and shortcut smoothers, which are concerned about checking that an "edge" between two configurations, q1 and q2, is free of collision. These functions *approximately* answer the question: is the edge collision free. The answer is determined by sampling configurations along the edge and reporting the edge to be collision free if all samples are collision free. Otherwise, we report the fraction of samples (starting with the start configuration) that reported to be collision free. The tested samples include the start and end configurations, q1 and q2, respectively. %CollisionChecker doesn't know how an edge is defined. An edge can be anything from a simple line segment (e.g. a linear path in C-space) to an arbitrarily complex path (e.g. a Reeds-Shepp path). The shape of the edge is defined implicitly by the ConfigurationInterpolationFunction as an interpolation between two configurations `q1` and `q2` (see SetConfigurationDistanceFunction() and SetConfigurationInterpolationFunction()). %CollisionChecker picks configuration samples along an edge by uniformly sampling the interpolation *parameter* from zero to one. (By definition, the interpolation at zero is equal to `q1` and at one is equal to `q2`.) The number of samples is determined by the distance between `q1` and `q2`, as provided by a ConfigurationDistanceFunction, divided by "edge step size" (see set_edge_step_size()). As a result, the selection of interpolation function, distance function, and edge step size must be coordinated to ensure that edge collision checking is sufficiently accurate for your application. <u>Default functions</u> The configuration distance function is defined at construction (from CollisionCheckerParams). It can be as simple as `|q1 - q2|` or could be a weighted norm `|wᵀ⋅(q1 − q2)|` based on joint importance or unit reconciliation (e.g., some qs are translational and some are rotational). Because of this, the "distance" reported may have arbitrary units. Whatever the units are, the edge step size must match. The step size value and distance function will determine the number of samples on the edge. The smaller the step size, the more samples (and the more expensive the collision check becomes). If all joints are revolute joints, one reasonable distance function is the weighted function `|wᵀ⋅(q1 − q2)|` where the weights are based on joint speed. For joint dofs `J = [J₀, J₁, ...]` with corresponding positive maximum speeds `[s₀, s₁, ...]`, we identify the speed of the fastest joint `sₘₐₓ = maxᵢ(sᵢ)` and define the per-dof weights as `wᵢ = sₘₐₓ / sᵢ`. Intuitively, the more time a particular joint requires to cover an angular distance, the more significance we attribute to that distance -- it's a _time_-biased weighting function. The weights are unitless so the reported distance is in radians. For some common arms (IIWA, Panda, UR, Jaco, etc.), we have found that an edge step size of 0.05 radians produces reasonable results. %CollisionChecker has a default interpolation function, as defined by MakeDefaultConfigurationInterpolationFunction(). It performs Slerp for quaternion-valued dofs and linear interpolation for all other dofs. Note that this is not appropriate for all robots, (e.g. those using a BallRpyJoint, or any non-holonomic robot). You will need to provide your own interpolation function in such cases. @anchor collision_checker_parallel_edge <u>Function-level parallelism</u> Parallelization in some edge collision checks is provided using OpenMP and is enabled when both: (1) the collision checker declares that parallelization is supported (i.e. when SupportsParallelChecking() is true) and (2) when multiple OpenMP threads are available for execution. Due to this internal parallelism, special care must be paid when calling these methods from any thread that is not the main thread; ensure that, for a given collision checker instance, implicit context methods are only called from one non-OpenMP thread at a given time. <u>Thoughts on configuring %CollisionChecker for edge collision detection</u> Because the edge collision check samples the edge, there is a perpetual trade off between the cost of evaluating the edge and the likelihood that a real collision is missed. In practice, the %CollisionChecker should be configured to maximize performance for a reasonable level of collision detection reliability. There is no definitive method for tuning the parameters. Rather than advocating a tuning strategy, we'll simply elaborate on the available parameters and leave the actual tuning as an exercise for the reader. There are two properties that will most directly contribute to the accuracy of the edge tests: edge step size and padding. Ultimately, any obstacle in _C-space_ whose measure is smaller than the edge step size is likely to be missed. The goal is to tune the parameters such that such features -- located in an area of interest (i.e., where you want your robot to operate) -- will have a low probability of being missed. Edge step size is very much a global parameter. It will increase the cost of _every_ collision check. If you are unable to anticipate where the small features are, a small edge step size will be robust to that uncertainty. As such, it serves as a good backstop. It comes at a cost of increasing the cost of *every* test, even for large geometries with nothing but coarse features. Increasing the padding can likewise reduce the likelihood of missing features. Adding padding has the effect of increasing the size of the workspace obstacles in C-space. The primary benefit is that it can be applied locally. If there is a particular obstacle with fine features that your robot will be near, padding between robot and that obstacle can be added so that interactions between robot and obstacle are more likely to be caught. Doing so leaves the global cost low for coarse features. However, padding comes at the cost that physically free edges may no longer be considered free. The best tuning will likely include configuring both edge step size and applying appropriate padding. */ //@{ /** Sets the distance and interpolation provider to use. Note that in case any of the (to-be-deprecated) separate distance and interpolation functions were in use, this supplants _both_ of them. @pre provider satisfies the requirements documents on DistanceAndInterpolationProvider. */ void SetDistanceAndInterpolationProvider( std::shared_ptr<const DistanceAndInterpolationProvider> provider); /** Gets the DistanceAndInterpolationProvider in use. */ const DistanceAndInterpolationProvider& distance_and_interpolation_provider() const { return *distance_and_interpolation_provider_; } /** Sets the configuration distance function to `distance_function`. @pre distance_function satisfies the requirements documented on ConfigurationDistanceFunction and a DistanceAndInterpolationProvider is not already in use. @pre the collision checker was created with separate distance and interpolation functions, not a combined DistanceAndInterpolationProvider. @note the `distance_function` object will be copied and retained by this collision checker, so if the function has any lambda-captured data then that data must outlive this collision checker. */ // TODO(calderpg-tri, jwnimmer-tri) Deprecate support for separate distance // and interpolation functions. void SetConfigurationDistanceFunction( const ConfigurationDistanceFunction& distance_function); /** Computes configuration-space distance between the provided configurations `q1` and `q2`, using the distance function configured at construction- time or via SetConfigurationDistanceFunction(). */ double ComputeConfigurationDistance(const Eigen::VectorXd& q1, const Eigen::VectorXd& q2) const { return distance_and_interpolation_provider_->ComputeConfigurationDistance( q1, q2); } /** @returns a functor that captures this object, so it can be used like a free function. The returned functor is only valid during the lifetime of this object. The math of the function is equivalent to ComputeConfigurationDistance(). @warning do not pass this standalone function back into SetConfigurationDistanceFunction() function; doing so would create an infinite loop. */ ConfigurationDistanceFunction MakeStandaloneConfigurationDistanceFunction() const; /** Sets the configuration interpolation function to `interpolation_function`. @param interpolation_function a functor, or nullptr. If nullptr, the default function will be configured and used. @pre interpolation_function satisfies the requirements documented on ConfigurationInterpolationFunction, or is nullptr and a DistanceAndInterpolationProvider is not already in use. @pre the collision checker was created with separate distance and interpolation functions, not a combined DistanceAndInterpolationProvider. @note the `interpolation_function` object will be copied and retained by this collision checker, so if the function has any lambda-captured data then that data must outlive this collision checker. @note the default function uses linear interpolation for most variables, and uses slerp for quaternion valued variables.*/ // TODO(calderpg-tri, jwnimmer-tri) Deprecate support for separate distance // and interpolation functions. void SetConfigurationInterpolationFunction( const ConfigurationInterpolationFunction& interpolation_function); /** Interpolates between provided configurations `q1` and `q2`. @param ratio Interpolation ratio. @returns Interpolated configuration. @throws std::exception if ratio is not in range [0, 1]. @see ConfigurationInterpolationFunction for more. */ Eigen::VectorXd InterpolateBetweenConfigurations(const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, double ratio) const { return distance_and_interpolation_provider_ ->InterpolateBetweenConfigurations(q1, q2, ratio); } /** @returns a functor that captures this object, so it can be used like a free function. The returned functor is only valid during the lifetime of this object. The math of the function is equivalent to InterpolateBetweenConfigurations(). @warning do not pass this standalone function back into our SetConfigurationInterpolationFunction() function; doing so would create an infinite loop. */ ConfigurationInterpolationFunction MakeStandaloneConfigurationInterpolationFunction() const; /** Gets the current edge step size. */ double edge_step_size() const { return edge_step_size_; } /** Sets the edge step size to `edge_step_size`. @throws std::exception if `edge_step_size` is not positive. */ void set_edge_step_size(double edge_step_size) { DRAKE_THROW_UNLESS(edge_step_size > 0.0); edge_step_size_ = edge_step_size; } /** Checks a single configuration-to-configuration edge for collision, using the current thread's associated context. @param q1 Start configuration for edge. @param q2 End configuration for edge. @param context_number Optional implicit context number. @returns true if collision free, false if in collision. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ bool CheckEdgeCollisionFree( const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, std::optional<int> context_number = std::nullopt) const; /** Explicit Context-based version of CheckEdgeCollisionFree(). @throws std::exception if `model_context` is nullptr. @see @ref ccb_explicit_contexts "Explicit Context Parallelism". */ bool CheckContextEdgeCollisionFree(CollisionCheckerContext* model_context, const Eigen::VectorXd& q1, const Eigen::VectorXd& q2) const; /** Checks a single configuration-to-configuration edge for collision. Collision check is parallelized via OpenMP when supported. See @ref collision_checker_parallel_edge "function-level parallelism" for guidance on proper usage. @param q1 Start configuration for edge. @param q2 End configuration for edge. @param parallelize How much should edge collision check be parallelized? @returns true if collision free, false if in collision. */ bool CheckEdgeCollisionFreeParallel( const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, Parallelism parallelize = Parallelism::Max()) const; /** Checks multiple configuration-to-configuration edges for collision. Collision checks are parallelized via OpenMP when supported and enabled by `parallelize`. See @ref collision_checker_parallel_edge "function-level parallelism" for guidance on proper usage. @param edges Edges to check, each in the form of pair<q1, q2>. @param parallelize How much should edge collision checks be parallelized? @returns std::vector<uint8_t>, one for each edge in edges. For each edge, 1 if collision free, 0 if in collision. */ std::vector<uint8_t> CheckEdgesCollisionFree( const std::vector<std::pair<Eigen::VectorXd, Eigen::VectorXd>>& edges, Parallelism parallelize = Parallelism::Max()) const; /** Checks a single configuration-to-configuration edge for collision, using the current thread's associated context. @param q1 Start configuration for edge. @param q2 End configuration for edge. @param context_number Optional implicit context number. @returns A measure of how much of the edge is collision free. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ EdgeMeasure MeasureEdgeCollisionFree( const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, std::optional<int> context_number = std::nullopt) const; /** Explicit Context-based version of MeasureEdgeCollisionFree(). @throws std::exception if `model_context` is nullptr. @see @ref ccb_explicit_contexts "Explicit Context Parallelism". */ EdgeMeasure MeasureContextEdgeCollisionFree( CollisionCheckerContext* model_context, const Eigen::VectorXd& q1, const Eigen::VectorXd& q2) const; /** Checks a single configuration-to-configuration edge for collision. Collision check is parallelized via OpenMP when supported. See @ref collision_checker_parallel_edge "function-level parallelism" for guidance on proper usage. @param q1 Start configuration for edge. @param q2 End configuration for edge. @param parallelize How much should edge collision check be parallelized? @returns A measure of how much of the edge is collision free. */ EdgeMeasure MeasureEdgeCollisionFreeParallel( const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, Parallelism parallelize = Parallelism::Max()) const; /** Checks multiple configuration-to-configuration edge for collision. Collision checks are parallelized via OpenMP when supported and enabled by `parallelize`. See @ref collision_checker_parallel_edge "function-level parallelism" for guidance on proper usage. @param edges Edges to check, each in the form of pair<q1, q2>. @param parallelize How much should edge collision checks be parallelized? @returns A measure of how much of each edge is collision free. The iᵗʰ entry is the result for the iᵗʰ edge. */ std::vector<EdgeMeasure> MeasureEdgesCollisionFree( const std::vector<std::pair<Eigen::VectorXd, Eigen::VectorXd>>& edges, Parallelism parallelize = Parallelism::Max()) const; //@} /** @name Robot collision state These methods help characterize the robot's collision state with respect to a particular robot configuration. In this section, the "collision state" is characterized with two different APIs: - "clearance", a measure of how near to collision the robot as computed by CalcRobotClearance(), and - a boolean colliding state for each robot body as computed by ClassifyBodyCollisions(). */ //@{ /** Calculates the distance, ϕ, and distance Jacobian, Jqᵣ_ϕ, for each potential collision whose distance is less than `influence_distance`, using the current thread's associated context. Distances for filtered collisions will not be returned. Distances between a pair of robot bodies (i.e., where `collision_types()` reports `SelfCollision`) report one body's index in `robot_indices()` and the the other body's in `other_indices()`; which body appears in which column is arbitrary. The total number of rows can depend on how the model is defined and how a particular CollisionChecker instance is implemented (see MaxNumDistances()). @see RobotClearance for details on the quantities ϕ and Jqᵣ_ϕ (and other details). @param context_number Optional implicit context number. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ RobotClearance CalcRobotClearance( const Eigen::VectorXd& q, double influence_distance, std::optional<int> context_number = std::nullopt) const; /** Explicit Context-based version of CalcRobotClearance(). @throws std::exception if `model_context` is nullptr. @see @ref ccb_explicit_contexts "Explicit Context Parallelism". */ RobotClearance CalcContextRobotClearance( CollisionCheckerContext* model_context, const Eigen::VectorXd& q, double influence_distance) const; // TODO(calderpg-tri) Improve MaxNumDistances to use the prototype context // instead, and deprecate context-specific forms. /** Returns an upper bound on the number of distances returned by CalcRobotClearance(), using the current thread's associated context. @param context_number Optional implicit context number. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ int MaxNumDistances(std::optional<int> context_number = std::nullopt) const; /** Explicit Context-based version of MaxNumDistances(). @see @ref ccb_explicit_contexts "Explicit Context Parallelism". */ int MaxContextNumDistances( const CollisionCheckerContext& model_context) const; /** Classifies which robot bodies are in collision (and which type of collision) for the provided configuration `q`, using the current thread's associated context. @param context_number Optional implicit context number. @returns a vector of collision types arranged in body index order. Only entries for robot bodies are guaranteed to be valid; entries for environment bodies are populated with kNoCollision, regardless of their actual status. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ std::vector<RobotCollisionType> ClassifyBodyCollisions( const Eigen::VectorXd& q, std::optional<int> context_number = std::nullopt) const; /** Explicit Context-based version of ClassifyBodyCollisions(). @throws std::exception if `model_context` is nullptr. @see @ref ccb_explicit_contexts "Explicit Context Parallelism". */ std::vector<RobotCollisionType> ClassifyContextBodyCollisions( CollisionCheckerContext* model_context, const Eigen::VectorXd& q) const; //@} /** Does the collision checker support true parallel collision checks? @returns true if parallel checking is supported. */ bool SupportsParallelChecking() const { return supports_parallel_checking_; } protected: /** Derived classes declare upon construction whether they support parallel checking (see SupportsParallelChecking()). If a derived class does not support parallel checking, it must set params.implicit_context_parallelism to Parallelism::None(); otherwise this constructor will throw. @throws std::exception if params is invalid. @see CollisionCheckerParams. */ CollisionChecker(CollisionCheckerParams params, bool supports_parallel_checking); /** To support Clone(), allow copying (but not move nor assign). */ CollisionChecker(const CollisionChecker&); /** Allocate the per-thread context pool, and discontinue mutable access to the robot model. This must be called and only be called as part of the constructor in a derived class defined as final. @pre This cannot have already been called for this instance. */ void AllocateContexts(); /** Collision checkers that use derived context types can override this implementation to allocate their context type instead. */ virtual std::unique_ptr<CollisionCheckerContext> CreatePrototypeContext() const { return std::make_unique<CollisionCheckerContext>(&model()); } /** @returns true if called during initial setup (before AllocateContexts() is called). */ bool IsInitialSetup() const { return setup_model_ != nullptr; } /** @returns a mutable reference to the robot model. @throws std::exception if IsInitialSetup() == false. */ RobotDiagram<double>& GetMutableSetupModel() { DRAKE_THROW_UNLESS(IsInitialSetup()); return *setup_model_; } /** @name Internal overridable implementations of public methods. */ //@{ /** Derived collision checkers implement can make use of the protected copy constructor to implement DoClone(). */ virtual std::unique_ptr<CollisionChecker> DoClone() const = 0; /** Derived collision checkers can do further work in this function in response to updates to the MultibodyPlant positions. CollisionChecker guarantees that `model_context` will not be nullptr and that the new positions are present in model_context->plant_context(). */ virtual void DoUpdateContextPositions( CollisionCheckerContext* model_context) const = 0; /** Derived collision checkers are responsible for reporting the collision status of the configuration. CollisionChecker guarantees that the passed `model_context` has been updated with the configuration `q` supplied to the public method. */ virtual bool DoCheckContextConfigCollisionFree( const CollisionCheckerContext& model_context) const = 0; /** Does the work of adding a shape to be rigidly affixed to the body. Derived checkers can choose to ignore the request, but must return `nullopt` if they do so. */ virtual std::optional<geometry::GeometryId> DoAddCollisionShapeToBody( const std::string& group_name, const multibody::RigidBody<double>& bodyA, const geometry::Shape& shape, const math::RigidTransform<double>& X_AG) = 0; /** Representation of an "added" shape. These are shapes that get added to the model via the CollisionChecker's Shape API. They encode the id for the added geometry and the index of the body (robot or environment) to which the geometry is affixed. */ struct AddedShape { /** The id of the geometry. */ geometry::GeometryId geometry_id; /** The index of the body the shape was added; could be robot or environment. */ multibody::BodyIndex body_index; /** The full body description. We have the invariant that `body_index` has the body and model instance names recorded in the description. */ BodyShapeDescription description; }; /** Removes all of the given added shapes (if they exist) from the checker. */ virtual void RemoveAddedGeometries(const std::vector<AddedShape>& shapes) = 0; /** Derived collision checkers can do further work in this function in response to changes in collision filters. This is called after any changes are made to the collision filter matrix. */ virtual void UpdateCollisionFilters() = 0; /** Derived collision checkers are responsible for defining the reported measurements. But they must adhere to the characteristics documented on RobotClearance, e.g., one measurement per row. CollisionChecker guarantees that `influence_distance` is finite and non-negative. */ virtual RobotClearance DoCalcContextRobotClearance( const CollisionCheckerContext& model_context, double influence_distance) const = 0; /** Derived collision checkers are responsible for choosing a collision type for each of the robot bodies. They should adhere to the semantics documented for ClassifyBodyCollisions. CollisionChecker guarantees that the passed `model_context` has been updated with the configuration `q` supplied to the public method. */ virtual std::vector<RobotCollisionType> DoClassifyContextBodyCollisions( const CollisionCheckerContext& model_context) const = 0; /** Derived collision checkers must implement the semantics documented for MaxNumDistances. CollisionChecker does nothing; it just calls this method. */ virtual int DoMaxContextNumDistances( const CollisionCheckerContext& model_context) const = 0; //@} /** @returns true if this object SupportsParallelChecking() and more than one thread is available. */ bool CanEvaluateInParallel() const; /* (Testing only.) Checks that the padding matrix in this instance is valid, returning an error message if problems are found, or an empty string if not. */ std::string CriticizePaddingMatrix() const; private: /* @param context_number Optional implicit context number. @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ CollisionCheckerContext& mutable_model_context( std::optional<int> context_number) const; /* Tests the given filtered collision matrix for several invariants, throwing if they are not satisfied: - The matrix is square. - The diagonal is all -1. - The matrix is symmetric. - For off-diagonal, non-zero values: - 1: at least one of the bodies in the pair is a robot body - -1: both bodies in the pair are environment bodies. - All entries are either 0, 1, or -1. */ void ValidateFilteredCollisionMatrix(const Eigen::MatrixXi& filtered, const char* func) const; /* The "nominal" collision matrix. This is intended to be called only upon construction. The nominal filtered collision matrix has the following properties: - All diagonal entries are set to -1 (a body colliding with itself is meaningless). - All environment-environment pairs are set to -1. CollisionChecker ignores them; so it might as well be explicit about it in the matrix. - For bodies I and J, - if all geometries of I have "filtered collisions" (in the SceneGraph sense), with all the geometries of J, the matrix is set to 1. - If *no* geometries of I and J are filtered, the matrix is set to 0. - If some geometry pairs are filtered, and some are not, an error is thrown. - If a welded path exists between two bodies (in the MultibodyPlant), the matrix is set to 1. */ Eigen::MatrixXi GenerateFilteredCollisionMatrix() const; /* Updates the stored value representing the largest value found in the padding matrix -- this excludes the meaningless zeros on the diagonal. */ void UpdateMaxCollisionPadding(); /* Tests the given collision padding matrix for several invariants, throwing if they are not satisfied: - It is a square NxN matrix (where N is the total number of bodies). - Diagonal values are all zero. - Entries involving only environment bodies are all zero. - It is symmetric. - All values are finite. */ void ValidatePaddingMatrix(const Eigen::MatrixXd& padding, const char* func) const; /* Checks the same conditions as ValidatePaddingMatrix, but instead of throwing, returns the error message, or an empty string if no errors were found. */ std::string CriticizePaddingMatrix(const Eigen::MatrixXd& padding, const char* func) const; /* Gets the number of threads that may be used in an OpenMP-parallelized loop, which is the lesser of (a) the number of implicit contexts or (b) the number of threads specified by `parallelize`. If OpenMP is not available, returns 1. */ int GetNumberOfThreads(Parallelism parallelize) const; /* @returns a generalized position vector, sized according to the full model, whose values come from the plant's default context. */ const Eigen::VectorXd& GetDefaultConfiguration() const { return default_configuration_; } /* This class allocates and maintains the implicit context pool. When the CollisionChecker is evaluated in its implicit mode, the contexts used are drawn from this collection, either by a `context_number` or by the OpenMP thread number associated with the context. In addition, this container takes ownership of a reference "prototype" context (see below for details about the prototype context). @note this class has two phases: `empty()` (before calling AllocateOwnedContexts()), and `allocated()`. In the `empty()` phase, `num_contexts()` returns 0, and all methods that access a context will throw. */ class OwnedContextKeeper { public: OwnedContextKeeper() {} ~OwnedContextKeeper(); /* The copy constructor is used to implement our outer class's Clone(). */ explicit OwnedContextKeeper(const OwnedContextKeeper& other); /* Does not allow assignment. */ void operator=(const OwnedContextKeeper&) = delete; /* Allocates the requested number of contexts, for later access by index, and clones the passed prototype context. @note This method is exposed since CollisionChecker::AllocateContexts can't be called in the CollisionChecker constructor. @throws std::exception if called more than once. */ void AllocateOwnedContexts(const CollisionCheckerContext& prototype_context, int num_contexts); /* @returns true if the keeper is empty. In the empty state, there are no contexts allocated and no prototype context is available. */ bool empty() const { DRAKE_DEMAND((prototype_context_ == nullptr) == model_contexts_.empty()); return model_contexts_.empty(); } /* @returns true if the keeper has allocated contexts. In the allocated state, there are contexts available for access by index, and the prototype context is available. */ bool allocated() const { return !empty(); } int num_contexts() const { return model_contexts_.size(); } /* Gets the special "prototype" context used for copy & clone operations. */ const CollisionCheckerContext& prototype_context() const { // The prototype context is only available in the allocated phase. DRAKE_THROW_UNLESS(allocated()); return *prototype_context_; } CollisionCheckerContext& get_mutable_model_context(int index) const { return *model_contexts_.at(index); } const CollisionCheckerContext& get_model_context(int index) const { return *model_contexts_.at(index); } /* Performs the provided `operation` on all owned contexts. @pre operation != nullptr; */ void PerformOperationAgainstAllOwnedContexts( const RobotDiagram<double>& model, const std::function<void(const RobotDiagram<double>&, CollisionCheckerContext*)>& operation); private: std::vector<std::unique_ptr<CollisionCheckerContext>> model_contexts_; /* This prototype context plays an important role. The CollisionChecker is supposed to allow the execution of *any* const methods in parallel without incident. This prototype is vital to include Clone() in that set. The various const query methods (e.g., CheckConfigCollisionFree()) treat the underlying per-thread context as being functionally mutable. To evaluate the query, the positions in the MbP's context must be updated to the given configuration values. Therefore, if we were to attempt to clone this checker while such a query is being evaluated, we *must* not read from that thread's Context so we don't catch it in an intermediate state. Instead, we clone the collision checker's contexts by cloning this prototype context (which is not accessed by any other const method) repeatedly. For this approach to be valid, we maintain the invariant that this prototype context is bit-identical with all of the owned and standalone contexts for this CollisionChecker (except for those differences directly attributable to setting the qs in MbP). */ std::unique_ptr<CollisionCheckerContext> prototype_context_; }; /* When using explicit context parallelism (e.g. when using a parallelization system that does not have a strong concept of "thread number" like OpenMP), users of CollisionChecker must request "standalone" contexts. This keeps a *weak* reference to each of the allocated standalone contexts so that they can be updated in lock step with all other contexts in response to PerformOperationAgainstAllModelContexts(). The references are weak references so that the user has full control over the lifespan of the standalone contexts. */ class StandaloneContextReferenceKeeper { public: StandaloneContextReferenceKeeper() {} ~StandaloneContextReferenceKeeper(); /* The copy constructor is used to implement our outer class's Clone(). */ explicit StandaloneContextReferenceKeeper( const StandaloneContextReferenceKeeper&) { // Nothing to do here; contexts should NOT be copied during Clone(). } /* Does not allow assignment. */ void operator=(const StandaloneContextReferenceKeeper&) = delete; void AddStandaloneContext(const std::shared_ptr<CollisionCheckerContext>& standalone_context) const; /* Performs the provided `operation` on all live referenced contexts, and removes any references to dead contexts. @pre operation != nullptr; */ void PerformOperationAgainstAllStandaloneContexts( const RobotDiagram<double>& model, const std::function<void(const RobotDiagram<double>&, CollisionCheckerContext*)>& operation); private: mutable std::list<std::weak_ptr<CollisionCheckerContext>> standalone_contexts_; mutable std::mutex standalone_contexts_mutex_; }; /* Model of the robot used during initial setup only. */ std::shared_ptr<RobotDiagram<double>> setup_model_; /* Model of the robot to perform collision checks with. */ std::shared_ptr<const RobotDiagram<double>> model_; /* We maintain per-thread contexts to allow multiple simultaneous queries. */ OwnedContextKeeper owned_contexts_; /* We maintain weak references to standalone contexts to allow updates to standalone contexts. These must be weak refs to avoid keeping standalone contexts alive indefinitely. */ StandaloneContextReferenceKeeper standalone_contexts_; /* We maintain a set of all robot model instances for lookups. This vector is already de-duplicated and sorted. */ const std::vector<multibody::ModelInstanceIndex> robot_model_instances_; /* The set of indices in q that kinematically affect the robot_model_instances but which are not themselves part of robot_model_instances (e.g., a mobile base). In many cases this vector will be empty. */ const std::vector<int> uncontrolled_dofs_that_kinematically_affect_the_robot_; /* Provider for distance and interpolation functions */ std::shared_ptr<const DistanceAndInterpolationProvider> distance_and_interpolation_provider_; /* Step size for edge collision checking. */ double edge_step_size_ = 0.0; /* Storage for body-body collision padding. */ Eigen::MatrixXd collision_padding_; /* The current maximum collision padding. */ double max_collision_padding_ = 0.0; /* Internal storage of the filtered collision matrix. */ Eigen::MatrixXi filtered_collisions_; /* Internal storage of the nominal filtered collision matrix generated at setup time. */ Eigen::MatrixXi nominal_filtered_collisions_; /* We maintain a "zero configuration" of the model. */ Eigen::VectorXd zero_configuration_; /* We maintain a "default configuration" of the model (based on the plant's default allocated context). */ Eigen::VectorXd default_configuration_; /* Determines whether the checker reports support for parallel evaluation. This is defined upon construction by implementations. */ bool supports_parallel_checking_{}; /* Specifies how much parallelism can be used in implicit context operations. If the checker does not support parallel evaluation, this will specify no parallelism. */ Parallelism implicit_context_parallelism_; /* The names of all groups with added geometries. */ std::map<std::string, std::vector<AddedShape>> geometry_groups_; }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/robot_collision_type.h
#pragma once #include <cstdint> namespace drake { namespace planning { /** Enumerates these predicates (and their combinations): - is the robot in collision with itself? - is the robot in collision with something in the environment? @ingroup planning_collision_checker */ enum class RobotCollisionType : uint8_t { kNoCollision = 0x00, kEnvironmentCollision = 0x01, kSelfCollision = 0x02, kEnvironmentAndSelfCollision = kEnvironmentCollision | kSelfCollision }; /** @returns a RobotCollisionType where the environment-collision value is that asserted by `in_environment_collision`, and the self-collision value is that asserted by `collision_type`. */ inline RobotCollisionType SetInEnvironmentCollision( RobotCollisionType collision_type, bool in_environment_collision) { constexpr uint8_t mask = static_cast<uint8_t>(RobotCollisionType::kEnvironmentCollision); return static_cast<RobotCollisionType>( (static_cast<uint8_t>(collision_type) & ~mask) | (in_environment_collision * mask)); } /** @returns a RobotCollisionType where the self-collision value is that asserted by `in_self_collision`, and the environment-collision value is that asserted by `collision_type`. */ inline RobotCollisionType SetInSelfCollision(RobotCollisionType collision_type, bool in_self_collision) { constexpr uint8_t mask = static_cast<uint8_t>(RobotCollisionType::kSelfCollision); return static_cast<RobotCollisionType>( (static_cast<uint8_t>(collision_type) & ~mask) | (in_self_collision * mask)); } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_googletest", "drake_cc_library", "drake_cc_package_library", ) package(default_visibility = ["//visibility:public"]) drake_cc_package_library( name = "planning", visibility = ["//visibility:public"], deps = [ ":body_shape_description", ":collision_avoidance", ":collision_checker", ":collision_checker_context", ":collision_checker_params", ":distance_and_interpolation_provider", ":linear_distance_and_interpolation_provider", ":robot_clearance", ":robot_collision_type", ":robot_diagram", ":robot_diagram_builder", ":scene_graph_collision_checker", ":unimplemented_collision_checker", ":visibility_graph", ], ) drake_cc_library( name = "body_shape_description", srcs = ["body_shape_description.cc"], hdrs = ["body_shape_description.h"], deps = [ "//common:essential", "//geometry", "//multibody/plant", ], ) drake_cc_library( name = "collision_avoidance", srcs = ["collision_avoidance.cc"], hdrs = ["collision_avoidance.h"], deps = [ ":collision_checker", ], ) drake_cc_library( name = "collision_checker", srcs = ["collision_checker.cc"], hdrs = [ "collision_checker.h", "edge_measure.h", ], interface_deps = [ ":body_shape_description", ":collision_checker_context", ":collision_checker_params", ":distance_and_interpolation_provider", ":robot_clearance", ":robot_collision_type", ":robot_diagram", "//common:essential", "//common:parallelism", "//geometry", "//multibody/plant", ], deps = [ ":linear_distance_and_interpolation_provider", "@common_robotics_utilities", ], ) drake_cc_library( name = "collision_checker_context", srcs = ["collision_checker_context.cc"], hdrs = ["collision_checker_context.h"], deps = [ ":robot_diagram", "//common:essential", ], ) drake_cc_library( name = "collision_checker_params", hdrs = ["collision_checker_params.h"], deps = [ ":distance_and_interpolation_provider", ":robot_diagram", "//common:parallelism", "//multibody/tree:multibody_tree_indexes", ], ) drake_cc_library( name = "distance_and_interpolation_provider", srcs = ["distance_and_interpolation_provider.cc"], hdrs = ["distance_and_interpolation_provider.h"], deps = [ "//common:essential", ], ) drake_cc_library( name = "linear_distance_and_interpolation_provider", srcs = ["linear_distance_and_interpolation_provider.cc"], hdrs = ["linear_distance_and_interpolation_provider.h"], interface_deps = [ ":distance_and_interpolation_provider", "//multibody/plant", ], deps = [ "//common:essential", "@common_robotics_utilities", ], ) drake_cc_library( name = "robot_clearance", srcs = ["robot_clearance.cc"], hdrs = ["robot_clearance.h"], deps = [ ":robot_collision_type", "//common:essential", "//multibody/tree:multibody_tree_indexes", ], ) drake_cc_library( name = "robot_collision_type", hdrs = ["robot_collision_type.h"], ) drake_cc_library( name = "robot_diagram", srcs = ["robot_diagram.cc"], hdrs = ["robot_diagram.h"], deps = [ "//common:default_scalars", "//geometry:scene_graph", "//multibody/plant", "//systems/framework:diagram", "//systems/framework:diagram_builder", ], ) drake_cc_library( name = "robot_diagram_builder", srcs = ["robot_diagram_builder.cc"], hdrs = ["robot_diagram_builder.h"], deps = [ ":robot_diagram", "//common:default_scalars", "//geometry:scene_graph", "//multibody/parsing", "//multibody/plant", "//systems/framework:diagram_builder", ], ) drake_cc_library( name = "scene_graph_collision_checker", srcs = ["scene_graph_collision_checker.cc"], hdrs = ["scene_graph_collision_checker.h"], interface_deps = [ ":collision_checker", ":collision_checker_params", ], deps = [ ":robot_diagram", "//geometry", "//multibody/plant", ], ) drake_cc_library( name = "unimplemented_collision_checker", srcs = ["unimplemented_collision_checker.cc"], hdrs = ["unimplemented_collision_checker.h"], deps = [ ":collision_checker", ":collision_checker_params", ], ) drake_cc_library( name = "planning_test_helpers", testonly = True, srcs = ["test/planning_test_helpers.cc"], hdrs = ["test/planning_test_helpers.h"], visibility = ["//visibility:private"], deps = [ ":collision_checker", ":robot_diagram_builder", "//multibody/parsing", ], ) drake_cc_library( name = "visibility_graph", srcs = ["visibility_graph.cc"], hdrs = ["visibility_graph.h"], interface_deps = [ ":collision_checker", "//common:parallelism", ], deps = [ "@common_robotics_utilities", ], ) # === test/ === drake_cc_googletest( name = "body_shape_description_test", deps = [ ":body_shape_description", ":robot_diagram_builder", "//multibody/parsing", "//multibody/plant", ], ) drake_cc_googletest( name = "collision_avoidance_test", deps = [ ":collision_avoidance", ":robot_diagram_builder", ":unimplemented_collision_checker", "//common/test_utilities:eigen_matrix_compare", ], ) drake_cc_googletest( name = "collision_checker_test", # Running with multiple threads is an essential part of our test coverage. num_threads = 2, deps = [ ":collision_checker", ":planning_test_helpers", ":unimplemented_collision_checker", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "@common_robotics_utilities", ], ) drake_cc_googletest( name = "collision_checker_context_test", deps = [ ":collision_checker_context", ":robot_diagram_builder", ], ) drake_cc_googletest( name = "distance_and_interpolation_provider_test", deps = [ ":distance_and_interpolation_provider", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "@common_robotics_utilities", ], ) drake_cc_googletest( name = "linear_distance_and_interpolation_provider_test", data = [ "//planning/test_utilities:collision_ground_plane.sdf", "//planning/test_utilities:flying_robot_base.sdf", "@drake_models//:iiwa_description", "@drake_models//:ycb", ], deps = [ ":linear_distance_and_interpolation_provider", ":planning_test_helpers", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "@common_robotics_utilities", ], ) drake_cc_googletest( name = "robot_clearance_test", deps = [ ":robot_clearance", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", ], ) drake_cc_googletest( name = "robot_collision_type_test", deps = [ ":robot_collision_type", ], ) drake_cc_googletest( name = "robot_diagram_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":robot_diagram", ":robot_diagram_builder", "//common/test_utilities:expect_throws_message", "//systems/primitives:shared_pointer_system", ], ) drake_cc_googletest( name = "scene_graph_collision_checker_test", timeout = "moderate", data = [ "@drake_models//:ycb", ], # Running with multiple threads is an essential part of our test coverage. num_threads = 2, deps = [ ":linear_distance_and_interpolation_provider", ":planning_test_helpers", ":scene_graph_collision_checker", "//common/test_utilities:eigen_matrix_compare", "//planning/test_utilities:collision_checker_abstract_test_suite", ], ) drake_cc_googletest( name = "visibility_graph_test", # Running with multiple threads is an essential part of our test coverage. num_threads = 2, deps = [ ":robot_diagram_builder", ":scene_graph_collision_checker", ":visibility_graph", "//common/test_utilities:eigen_matrix_compare", ], ) drake_cc_googletest( name = "unimplemented_collision_checker_test", deps = [ ":robot_diagram_builder", ":unimplemented_collision_checker", "//common/test_utilities:expect_throws_message", ], ) add_lint_tests()
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/body_shape_description.h
#pragma once #include <string> #include <utility> #include "drake/common/copyable_unique_ptr.h" #include "drake/common/drake_copyable.h" #include "drake/geometry/shape_specification.h" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace planning { /** %BodyShapeDescription captures all the information necessary to describe a SceneGraph collision shape associated with a MultibodyPlant Body: a shape S, the MultibodyPlant body B (identified by model instance and body names), and the rigid pose of the shape S relative to the body B, X_BS. Most clients should use the factory method MakeBodyShapeDescription() to construct a valid %BodyShapeDescription; it will extract and verify the correct information from a multibody plant and its context. When moved-from, this object models a "null" description and all of the getter functions will throw. @ingroup planning_collision_checker */ class BodyShapeDescription final { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(BodyShapeDescription) /** Constructs a description with the given attributes. Does not check or enforce correctness; callers are responsible for providing consistent input. */ BodyShapeDescription(const geometry::Shape& shape, const math::RigidTransformd& X_BS, std::string model_instance_name, std::string body_name); /** @returns the shape passed at construction. */ const geometry::Shape& shape() const { DRAKE_THROW_UNLESS(!is_moved_from()); return *shape_; } /** @retval X_BS The pose passed at construction. */ const math::RigidTransformd& pose_in_body() const { DRAKE_THROW_UNLESS(!is_moved_from()); return X_BS_; } /** @returns the model instance name passed at construction. */ const std::string& model_instance_name() const { DRAKE_THROW_UNLESS(!is_moved_from()); return model_instance_name_; } /** @returns the body name passed at construction. */ const std::string& body_name() const { DRAKE_THROW_UNLESS(!is_moved_from()); return body_name_; } private: bool is_moved_from() const { return shape_ == nullptr; } copyable_unique_ptr<geometry::Shape> shape_; math::RigidTransformd X_BS_; std::string model_instance_name_; std::string body_name_; }; /** Constructs a BodyShapeDescription by extracting the shape, pose, and names associated with the provided geometry_id. @pre @p plant_context is compatible with @p plant. @pre @p plant is connected to a scene graph. @pre @p geometry_id refers to a geometry rigidly affixed to a body of @p plant. */ BodyShapeDescription MakeBodyShapeDescription( const multibody::MultibodyPlant<double>& plant, const systems::Context<double>& plant_context, const geometry::GeometryId& geometry_id); } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/visibility_graph.cc
#include "drake/planning/visibility_graph.h" #include <algorithm> #include <iterator> #include <vector> #include <common_robotics_utilities/parallelism.hpp> using common_robotics_utilities::parallelism::DegreeOfParallelism; using common_robotics_utilities::parallelism::DynamicParallelForIndexLoop; using common_robotics_utilities::parallelism::ParallelForBackend; using common_robotics_utilities::parallelism::StaticParallelForIndexLoop; namespace drake { namespace planning { namespace { /* A custom iterator that turns undirected edges encoded in the given std::vector<std::vector<int>> `edges` into a sequence of Eigen::SparseMatrix triplets which define a symmetric matrix. The edges in `edges` are undirected, so each such edge creates two triplets: (i, j, value) and (j, i, value). */ class EdgesIterator { public: using T = Eigen::Triplet<bool>; using iterator_category = std::input_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T&; EdgesIterator(const std::vector<std::vector<int>>& edges, int outer_idx = 0, int inner_idx = 0, bool upper_triangle = false) : edges_(edges), outer_idx_(outer_idx), inner_idx_(inner_idx), upper_triangle_(upper_triangle) { skip_empty_outer(); } EdgesIterator begin() { return EdgesIterator(edges_, /* outer_idx = */ 0, /* inner_idx = */ 0, /* upper_triangle = */ false); } // To implement end(), we create the element that will be obtained by // incrementing past the final reasonable edge output. EdgesIterator end() { return EdgesIterator(edges_, /* outer_idx = */ edges_.size(), /* inner_idx = */ 0, /* upper_triangle = */ false); } // Returns a Triplet* with the address of a static Eigen::Triplet<bool> object // representing the current edge. This works in this context because // setFromTriplets() just reads from the iterators and doesn't store them for // later. const Eigen::Triplet<bool>& operator*() const { static Eigen::Triplet<bool> e; if (upper_triangle_) { e = Eigen::Triplet<bool>(edges_[outer_idx_][inner_idx_], outer_idx_, true); } else { e = Eigen::Triplet<bool>(outer_idx_, edges_[outer_idx_][inner_idx_], true); } return e; } const Eigen::Triplet<bool>* operator->() const { return &**this; } // Advance the iterator to the next edge. EdgesIterator& operator++() { /* Each edge in `edges` produces a lower- and upper-triplet. In that order. So, we flip the upper/lower bit on each advance. When flipping to lower, it's time to advance to the next edge in `edges`. */ upper_triangle_ = !upper_triangle_; if (!upper_triangle_) { if (++inner_idx_ >= ssize(edges_[outer_idx_])) { ++outer_idx_; inner_idx_ = 0; skip_empty_outer(); } } return *this; } // Compares two iterators. bool operator!=(const EdgesIterator& other) const { return outer_idx_ != other.outer_idx_ || inner_idx_ != other.inner_idx_ || upper_triangle_ != other.upper_triangle_; } private: // If a row is empty, skip to the next non-empty row void skip_empty_outer() { while (outer_idx_ < ssize(edges_) && edges_[outer_idx_].empty()) { ++outer_idx_; } } // Iterators pointing to each vector in the list of vectors. const std::vector<std::vector<int>>& edges_; int outer_idx_{0}; int inner_idx_{0}; bool upper_triangle_{false}; }; } // namespace Eigen::SparseMatrix<bool> VisibilityGraph( const CollisionChecker& checker, const Eigen::Ref<const Eigen::MatrixXd>& points, const Parallelism parallelize) { DRAKE_THROW_UNLESS(checker.plant().num_positions() == points.rows()); const int num_points = points.cols(); const int num_threads_to_use = checker.SupportsParallelChecking() ? std::min(parallelize.num_threads(), checker.num_allocated_contexts()) : 1; drake::log()->debug("Generating VisibilityGraph using {} threads", num_threads_to_use); // Choose std::vector<uint8_t> as a thread-safe data structure for the // parallel evaluations. std::vector<uint8_t> points_free(num_points, 0x00); const auto point_check_work = [&](const int thread_num, const int64_t i) { points_free[i] = static_cast<uint8_t>( checker.CheckConfigCollisionFree(points.col(i), thread_num)); }; StaticParallelForIndexLoop(DegreeOfParallelism(num_threads_to_use), 0, num_points, point_check_work, ParallelForBackend::BEST_AVAILABLE); // Choose std::vector as a thread-safe data structure for the parallel // evaluations. std::vector<std::vector<int>> edges(num_points); const auto edge_check_work = [&](const int thread_num, const int64_t index) { const int i = static_cast<int>(index); if (points_free[i] > 0) { edges[i].push_back(i); for (int j = i + 1; j < num_points; ++j) { if (points_free[j] > 0 && checker.CheckEdgeCollisionFree(points.col(i), points.col(j), thread_num)) { edges[i].push_back(j); } } } }; DynamicParallelForIndexLoop(DegreeOfParallelism(num_threads_to_use), 0, num_points, edge_check_work, ParallelForBackend::BEST_AVAILABLE); // Convert edges into the SparseMatrix format, using a custom iterator to // avoid explicitly copying the data into a list of Eigen::Triplet. Eigen::SparseMatrix<bool> mat(num_points, num_points); EdgesIterator edges_iterator(edges); mat.setFromTriplets(edges_iterator.begin(), edges_iterator.end()); return mat; } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/collision_checker.cc
#include "drake/planning/collision_checker.h" #include <algorithm> #include <atomic> #include <limits> #include <map> #include <optional> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include <common_robotics_utilities/math.hpp> #include <common_robotics_utilities/openmp_helpers.hpp> #include <common_robotics_utilities/parallelism.hpp> #include <common_robotics_utilities/print.hpp> #include <common_robotics_utilities/utility.hpp> #include "drake/common/drake_throw.h" #include "drake/common/fmt_eigen.h" #include "drake/planning/linear_distance_and_interpolation_provider.h" namespace drake { namespace planning { using common_robotics_utilities::openmp_helpers::GetContextOmpThreadNum; using common_robotics_utilities::parallelism::DegreeOfParallelism; using common_robotics_utilities::parallelism::ParallelForBackend; using common_robotics_utilities::parallelism::StaticParallelForIndexLoop; using geometry::GeometryId; using geometry::QueryObject; using geometry::SceneGraphInspector; using geometry::Shape; using math::RigidTransform; using multibody::BodyIndex; using multibody::Frame; using multibody::Joint; using multibody::JointIndex; using multibody::ModelInstanceIndex; using multibody::MultibodyPlant; using multibody::RigidBody; using multibody::world_model_instance; using systems::Context; namespace { // TODO(calderpg-tri, jwnimmer-tri) Remove unnecessary helpers once standalone // distance and interpolation functions are no longer supported. void SanityCheckConfigurationDistanceFunction( const ConfigurationDistanceFunction& distance_function, const Eigen::VectorXd& default_configuration) { const double test_distance = distance_function(default_configuration, default_configuration); DRAKE_THROW_UNLESS(test_distance == 0.0); } void SanityCheckConfigurationInterpolationFunction( const ConfigurationInterpolationFunction& interpolation_function, const Eigen::VectorXd& default_configuration) { const Eigen::VectorXd test_interpolated_q = interpolation_function(default_configuration, default_configuration, 0.0); DRAKE_THROW_UNLESS(test_interpolated_q.size() == default_configuration.size()); for (int index = 0; index < test_interpolated_q.size(); ++index) { DRAKE_THROW_UNLESS(test_interpolated_q(index) == default_configuration(index)); } } class LegacyDistanceAndInterpolationProvider final : public DistanceAndInterpolationProvider { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LegacyDistanceAndInterpolationProvider); LegacyDistanceAndInterpolationProvider( const ConfigurationDistanceFunction& distance_function, const ConfigurationInterpolationFunction& interpolation_function) : distance_function_(distance_function), interpolation_function_(interpolation_function) { DRAKE_THROW_UNLESS(distance_function_ != nullptr); DRAKE_THROW_UNLESS(interpolation_function_ != nullptr); } std::shared_ptr<const LegacyDistanceAndInterpolationProvider> WithConfigurationDistanceFunction( const ConfigurationDistanceFunction& distance_function) const { return std::make_shared<LegacyDistanceAndInterpolationProvider>( distance_function, interpolation_function_); } std::shared_ptr<const LegacyDistanceAndInterpolationProvider> WithConfigurationInterpolationFunction( const ConfigurationInterpolationFunction& interpolation_function) const { return std::make_shared<LegacyDistanceAndInterpolationProvider>( distance_function_, interpolation_function); } private: double DoComputeConfigurationDistance(const Eigen::VectorXd& from, const Eigen::VectorXd& to) const final { return distance_function_(from, to); } Eigen::VectorXd DoInterpolateBetweenConfigurations( const Eigen::VectorXd& from, const Eigen::VectorXd& to, double ratio) const final { return interpolation_function_(from, to, ratio); } private: const ConfigurationDistanceFunction distance_function_; const ConfigurationInterpolationFunction interpolation_function_; }; // Default interpolator; it uses SLERP for quaternion-valued groups of dofs and // LERP for everything else. See the documentation in CollisionChecker's // edge checking group. ConfigurationInterpolationFunction MakeDefaultConfigurationInterpolationFunction( const std::vector<int>& quaternion_dof_start_indices) { return [quaternion_dof_start_indices](const Eigen::VectorXd& q_1, const Eigen::VectorXd& q_2, double ratio) { // Start with linear interpolation between q_1 and q_2. Eigen::VectorXd interpolated_q = common_robotics_utilities::math::InterpolateXd(q_1, q_2, ratio); // Handle quaternion dof properly. for (const int quat_dof_start_index : quaternion_dof_start_indices) { const Eigen::Quaterniond quat_1(q_1.segment<4>(quat_dof_start_index)); const Eigen::Quaterniond quat_2(q_2.segment<4>(quat_dof_start_index)); const Eigen::Quaterniond interpolated_quat = common_robotics_utilities::math::Interpolate(quat_1, quat_2, ratio); interpolated_q.segment<4>(quat_dof_start_index) = interpolated_quat.coeffs(); } return interpolated_q; }; } std::vector<int> GetQuaternionDofStartIndices( const MultibodyPlant<double>& plant) { return LinearDistanceAndInterpolationProvider(plant) .quaternion_dof_start_indices(); } // Returns the set of indices in `q` that kinematically affect the robot model // but that are not a part of the robot dofs (e.g., a floating or mobile base). // This pre-computed analysis will be used for RobotClearance calculations. // None of these indices are in qᵣ (the dofs controlled by the robot). It // doesn't include all dofs that aren't in qᵣ, only those inboard of the robot. std::vector<int> CalcUncontrolledDofsThatKinematicallyAffectTheRobot( const MultibodyPlant<double>& plant, const std::vector<ModelInstanceIndex>& robot) { // TODO(SeanCurtis-TRI): This algorithm was originally implemented to account // for floating bodies (bodies that had dofs that weren't controlled by // joints). Since #18390 all dofs are related to joints. We could rephrase // to determine the inboard, non-robot dofs directly, possibly simplifying // this function. // Our tactic in the loop below is to identify dofs that are either controlled // by one of our robot joints, or controlled by a non-robot joint but anyway // don't kinematically affect our robot. Then at the end, we'll return the // complement of this set. std::vector<const Joint<double>*> controlled_or_unaffecting; for (JointIndex joint_i : plant.GetJointIndices()) { const Joint<double>& joint = plant.get_joint(joint_i); // Skip these (or else GetBodiesKinematicallyAffectedBy will throw). if (joint.num_positions() == 0) { continue; } // Identify joints that are part of the robot. auto iter = std::find(robot.begin(), robot.end(), joint.model_instance()); if (iter != robot.end()) { controlled_or_unaffecting.push_back(&joint); continue; } // Identify whether the joint affects any robot bodies. std::vector<BodyIndex> outboard_bodies = plant.GetBodiesKinematicallyAffectedBy({joint_i}); bool affects_robot = false; for (const BodyIndex& body_i : outboard_bodies) { const RigidBody<double>& body = plant.get_body(body_i); iter = std::find(robot.begin(), robot.end(), body.model_instance()); if (iter != robot.end()) { affects_robot = true; break; } } if (!affects_robot) { controlled_or_unaffecting.push_back(&joint); } } // Compute the list of controlled or unaffected indices in a position vector. using boolish = uint8_t; std::vector<boolish> controlled_or_unaffecting_array; controlled_or_unaffecting_array.resize(plant.num_positions(), false); for (const auto* joint : controlled_or_unaffecting) { const int start = joint->position_start(); const int nq = joint->num_positions(); for (int i = 0; i < nq; ++i) { controlled_or_unaffecting_array[start + i] = true; } } // Now return the complement: the uncontrolled & affecting indices. std::vector<int> result; for (int i = 0; i < plant.num_positions(); ++i) { if (!controlled_or_unaffecting_array[i]) { result.push_back(i); } } return result; } } // namespace CollisionChecker::~CollisionChecker() = default; bool CollisionChecker::IsPartOfRobot(const RigidBody<double>& body) const { const ModelInstanceIndex needle = body.model_instance(); const auto& haystack = robot_model_instances_; return std::binary_search(haystack.begin(), haystack.end(), needle); } bool CollisionChecker::IsPartOfRobot(BodyIndex body_index) const { return IsPartOfRobot(get_body(body_index)); } const CollisionCheckerContext& CollisionChecker::model_context( const std::optional<int> context_number) const { const int context_index = context_number.has_value() ? *context_number : GetContextOmpThreadNum(); return owned_contexts_.get_model_context(context_index); } std::shared_ptr<CollisionCheckerContext> CollisionChecker::MakeStandaloneModelContext() const { // Make a shared clone of the special "prototype" context. std::shared_ptr<CollisionCheckerContext> standalone_context( owned_contexts_.prototype_context().Clone()); // Save a weak reference to the shared standalone context. standalone_contexts_.AddStandaloneContext(standalone_context); return standalone_context; } void CollisionChecker::PerformOperationAgainstAllModelContexts( const std::function<void(const RobotDiagram<double>&, CollisionCheckerContext*)>& operation) { DRAKE_THROW_UNLESS(operation != nullptr); owned_contexts_.PerformOperationAgainstAllOwnedContexts(model(), operation); standalone_contexts_.PerformOperationAgainstAllStandaloneContexts( // BR model(), operation); } bool CollisionChecker::AddCollisionShape( const std::string& group_name, const BodyShapeDescription& description) { const RigidBody<double>& body = plant().GetBodyByName( description.body_name(), plant().GetModelInstanceByName(description.model_instance_name())); return AddCollisionShapeToBody(group_name, body, description.shape(), description.pose_in_body()); } int CollisionChecker::AddCollisionShapes( const std::string& group_name, const std::vector<BodyShapeDescription>& descriptions) { int added = 0; for (const auto& body_shape : descriptions) { if (AddCollisionShape(group_name, body_shape)) { ++added; } } return added; } std::map<std::string, int> CollisionChecker::AddCollisionShapes( const std::map<std::string, std::vector<BodyShapeDescription>>& geometry_groups) { std::map<std::string, int> group_added_shapes; for (const auto& [group_name, group_shapes] : geometry_groups) { const int num_added_shapes = AddCollisionShapes(group_name, group_shapes); group_added_shapes.emplace(group_name, num_added_shapes); } return group_added_shapes; } bool CollisionChecker::AddCollisionShapeToFrame( const std::string& group_name, const Frame<double>& frameA, const Shape& shape, const RigidTransform<double>& X_AG) { const RigidBody<double>& bodyA = frameA.body(); const RigidTransform<double>& X_BA = frameA.GetFixedPoseInBodyFrame(); const RigidTransform<double> X_BG = X_BA * X_AG; return AddCollisionShapeToBody(group_name, bodyA, shape, X_BG); } bool CollisionChecker::AddCollisionShapeToBody( const std::string& group_name, const RigidBody<double>& bodyA, const Shape& shape, const RigidTransform<double>& X_AG) { const std::optional<GeometryId> maybe_geometry = DoAddCollisionShapeToBody(group_name, bodyA, shape, X_AG); if (maybe_geometry.has_value()) { const std::string& model_instance_name = plant().GetModelInstanceName(bodyA.model_instance()); geometry_groups_[group_name].push_back(AddedShape{ *maybe_geometry, bodyA.index(), BodyShapeDescription(shape, X_AG, model_instance_name, bodyA.name())}); } return maybe_geometry.has_value(); } std::map<std::string, std::vector<BodyShapeDescription>> CollisionChecker::GetAllAddedCollisionShapes() const { std::map<std::string, std::vector<BodyShapeDescription>> result; for (const auto& [group_name, group_shapes] : geometry_groups_) { result[group_name].reserve(group_shapes.size()); for (const auto& shape : group_shapes) { result[group_name].push_back(shape.description); } } return result; } void CollisionChecker::RemoveAllAddedCollisionShapes( const std::string& group_name) { auto iter = geometry_groups_.find(group_name); if (iter != geometry_groups_.end()) { drake::log()->debug("Removing geometries from group [{}].", group_name); RemoveAddedGeometries(iter->second); geometry_groups_.erase(iter); } } void CollisionChecker::RemoveAllAddedCollisionShapes() { drake::log()->debug("Removing all added geometries"); for (const auto& [group_name, group_ids] : geometry_groups_) { RemoveAddedGeometries(group_ids); } geometry_groups_.clear(); } std::optional<double> CollisionChecker::MaybeGetUniformRobotEnvironmentPadding() const { // TODO(SeanCurtis-TRI): We have three functions that walk a triangular // portion of the padding matrix. Consider unifying the logic for the // triangular indices. std::optional<double> check_padding; for (BodyIndex body_index(0); body_index < plant().num_bodies(); ++body_index) { for (BodyIndex other_body_index(body_index + 1); other_body_index < plant().num_bodies(); ++other_body_index) { if (IsPartOfRobot(get_body(body_index)) != IsPartOfRobot(get_body(other_body_index))) { const double this_padding = GetPaddingBetween(body_index, other_body_index); if (!check_padding.has_value()) { check_padding = this_padding; } if (check_padding.value() != this_padding) { return std::nullopt; } } } } return check_padding; } std::optional<double> CollisionChecker::MaybeGetUniformRobotRobotPadding() const { std::optional<double> check_padding; for (BodyIndex body_index(0); body_index < plant().num_bodies(); ++body_index) { for (BodyIndex other_body_index(body_index + 1); other_body_index < plant().num_bodies(); ++other_body_index) { if (IsPartOfRobot(get_body(body_index)) && IsPartOfRobot(get_body(other_body_index))) { const double this_padding = GetPaddingBetween(body_index, other_body_index); if (!check_padding.has_value()) { check_padding = this_padding; } if (check_padding.value() != this_padding) { return std::nullopt; } } } } return check_padding; } void CollisionChecker::SetPaddingBetween(BodyIndex bodyA_index, BodyIndex bodyB_index, double padding) { DRAKE_THROW_UNLESS(bodyA_index >= 0 && bodyA_index < collision_padding_.rows()); DRAKE_THROW_UNLESS(bodyB_index >= 0 && bodyB_index < collision_padding_.rows()); DRAKE_THROW_UNLESS(bodyA_index != bodyB_index); DRAKE_THROW_UNLESS(std::isfinite(padding)); DRAKE_THROW_UNLESS(IsPartOfRobot(get_body(bodyA_index)) || IsPartOfRobot(get_body(bodyB_index))); collision_padding_(int{bodyA_index}, int{bodyB_index}) = padding; collision_padding_(int{bodyB_index}, int{bodyA_index}) = padding; UpdateMaxCollisionPadding(); } void CollisionChecker::SetPaddingMatrix( const Eigen::MatrixXd& requested_padding) { // First confirm it is of appropriate *size*. if (requested_padding.rows() != collision_padding_.rows() || requested_padding.cols() != collision_padding_.cols()) { throw std::logic_error( fmt::format("CollisionChecker::SetPaddingMatrix(): The padding" " matrix must be {}x{}. The given padding matrix is the" " wrong size: {}x{}.", collision_padding_.rows(), collision_padding_.cols(), requested_padding.rows(), requested_padding.cols())); } ValidatePaddingMatrix(requested_padding, __func__); collision_padding_ = requested_padding; UpdateMaxCollisionPadding(); } void CollisionChecker::SetPaddingOneRobotBodyAllEnvironmentPairs( const BodyIndex body_index, const double padding) { DRAKE_THROW_UNLESS(std::isfinite(padding)); DRAKE_THROW_UNLESS(IsPartOfRobot(get_body(body_index))); for (BodyIndex other_body_index(0); other_body_index < plant().num_bodies(); ++other_body_index) { if (!IsPartOfRobot(get_body(other_body_index))) { collision_padding_(int{body_index}, int{other_body_index}) = padding; collision_padding_(int{other_body_index}, int{body_index}) = padding; } } UpdateMaxCollisionPadding(); } void CollisionChecker::SetPaddingAllRobotEnvironmentPairs( const double padding) { DRAKE_THROW_UNLESS(std::isfinite(padding)); for (BodyIndex body_index(0); body_index < plant().num_bodies(); ++body_index) { for (BodyIndex other_body_index(body_index + 1); other_body_index < plant().num_bodies(); ++other_body_index) { if (IsPartOfRobot(get_body(body_index)) != IsPartOfRobot(get_body(other_body_index))) { collision_padding_(int{body_index}, int{other_body_index}) = padding; collision_padding_(int{other_body_index}, int{body_index}) = padding; } } } UpdateMaxCollisionPadding(); } void CollisionChecker::SetPaddingAllRobotRobotPairs(const double padding) { DRAKE_THROW_UNLESS(std::isfinite(padding)); for (BodyIndex body_index(0); body_index < plant().num_bodies(); ++body_index) { for (BodyIndex other_body_index(body_index + 1); other_body_index < plant().num_bodies(); ++other_body_index) { if (IsPartOfRobot(get_body(body_index)) && IsPartOfRobot(get_body(other_body_index))) { collision_padding_(int{body_index}, int{other_body_index}) = padding; collision_padding_(int{other_body_index}, int{body_index}) = padding; } } } UpdateMaxCollisionPadding(); } void CollisionChecker::SetCollisionFilterMatrix( const Eigen::MatrixXi& filter_matrix) { // First confirm it is of appropriate *size*. if (filter_matrix.rows() != filtered_collisions_.rows() || filter_matrix.cols() != filtered_collisions_.cols()) { throw std::logic_error( fmt::format("CollisionChecker::SetCollisionFilterMatrix(): The filter " "matrix must be {}x{};. The given matrix is the wrong " "size: {}x{}.", filtered_collisions_.rows(), filtered_collisions_.cols(), filter_matrix.rows(), filter_matrix.cols())); } // Only perform additional work if the provided filter matrix is different // from the current matrix. if (filtered_collisions_ != filter_matrix) { // Now test for consistency. ValidateFilteredCollisionMatrix(filter_matrix, __func__); filtered_collisions_ = filter_matrix; // Allow derived checkers to perform any post-filter-change work. UpdateCollisionFilters(); } } bool CollisionChecker::IsCollisionFilteredBetween(BodyIndex bodyA_index, BodyIndex bodyB_index) const { DRAKE_THROW_UNLESS(bodyA_index >= 0 && bodyA_index < filtered_collisions_.rows()); DRAKE_THROW_UNLESS(bodyB_index >= 0 && bodyB_index < filtered_collisions_.rows()); return (filtered_collisions_(int{bodyA_index}, int{bodyB_index}) != 0); } void CollisionChecker::SetCollisionFilteredBetween(BodyIndex bodyA_index, BodyIndex bodyB_index, bool filter_collision) { const int N = filtered_collisions_.rows(); DRAKE_THROW_UNLESS(bodyA_index >= 0 && bodyA_index < N); DRAKE_THROW_UNLESS(bodyB_index >= 0 && bodyB_index < N); DRAKE_THROW_UNLESS(bodyA_index != bodyB_index); if (!(IsPartOfRobot(bodyA_index) || IsPartOfRobot(bodyB_index))) { throw std::logic_error( fmt::format("CollisionChecker::SetCollisionFilteredBetween(): cannot " "be used on pairs of environment bodies: ({}, {})", bodyA_index, bodyB_index)); } const int current_value = filtered_collisions_(int{bodyA_index}, int{bodyB_index}); const int new_value = filter_collision ? 1 : 0; // Only perform additional work if the specified filter will change the filter // matrix. if (new_value != current_value) { // The tests above should mean that we're not trying to write to an entry // that is locked in a filtered state (-1); just in case, we'll add one more // explicit test. DRAKE_ASSERT(current_value != -1); filtered_collisions_(int{bodyA_index}, int{bodyB_index}) = new_value; filtered_collisions_(int{bodyB_index}, int{bodyA_index}) = new_value; // Allow derived checkers to perform any post-filter-change work. UpdateCollisionFilters(); } } void CollisionChecker::SetCollisionFilteredWithAllBodies(BodyIndex body_index) { DRAKE_THROW_UNLESS(body_index >= 0 && body_index < filtered_collisions_.rows()); DRAKE_THROW_UNLESS(IsPartOfRobot(body_index)); const Eigen::MatrixXi prior_filter_matrix = filtered_collisions_; filtered_collisions_.row(body_index).setConstant(1); filtered_collisions_.col(body_index).setConstant(1); // Maintain the invariant that the diagonal is always -1. filtered_collisions_(int{body_index}, int{body_index}) = -1; // Only perform additional work if the filter matrix has changed. if (prior_filter_matrix != filtered_collisions_) { // Allow derived checkers to perform any post-filter-change work. UpdateCollisionFilters(); } } bool CollisionChecker::CheckConfigCollisionFree( const Eigen::VectorXd& q, const std::optional<int> context_number) const { return CheckContextConfigCollisionFree(&mutable_model_context(context_number), q); } bool CollisionChecker::CheckContextConfigCollisionFree( CollisionCheckerContext* model_context, const Eigen::VectorXd& q) const { DRAKE_THROW_UNLESS(model_context != nullptr); UpdateContextPositions(model_context, q); return DoCheckContextConfigCollisionFree(*model_context); } std::vector<uint8_t> CollisionChecker::CheckConfigsCollisionFree( const std::vector<Eigen::VectorXd>& configs, const Parallelism parallelize) const { // Note: vector<uint8_t> is used since vector<bool> is not thread safe. std::vector<uint8_t> collision_checks(configs.size(), 0); const int number_of_threads = GetNumberOfThreads(parallelize); drake::log()->debug("CheckConfigsCollisionFree uses {} thread(s)", number_of_threads); const auto config_work = [&](const int thread_num, const int64_t index) { collision_checks.at(index) = CheckConfigCollisionFree(configs.at(index), thread_num); }; StaticParallelForIndexLoop(DegreeOfParallelism(number_of_threads), 0, configs.size(), config_work, ParallelForBackend::BEST_AVAILABLE); return collision_checks; } void CollisionChecker::SetDistanceAndInterpolationProvider( std::shared_ptr<const DistanceAndInterpolationProvider> provider) { DRAKE_THROW_UNLESS(provider != nullptr); const Eigen::VectorXd& default_q = GetDefaultConfiguration(); const double test_distance = provider->ComputeConfigurationDistance(default_q, default_q); DRAKE_THROW_UNLESS(test_distance == 0.0); const Eigen::VectorXd test_interpolated_q = provider->InterpolateBetweenConfigurations(default_q, default_q, 0.0); DRAKE_THROW_UNLESS(test_interpolated_q.size() == default_q.size()); for (int index = 0; index < test_interpolated_q.size(); ++index) { DRAKE_THROW_UNLESS(test_interpolated_q(index) == default_q(index)); } distance_and_interpolation_provider_ = std::move(provider); } void CollisionChecker::SetConfigurationDistanceFunction( const ConfigurationDistanceFunction& distance_function) { auto legacy = std::dynamic_pointer_cast<const LegacyDistanceAndInterpolationProvider>( distance_and_interpolation_provider_); if (legacy == nullptr) { throw std::logic_error( "CollisionChecker::SetConfigurationDistanceFunction() " "is not supported after a DistanceAndInterpolationProvider " "has already been set."); } DRAKE_THROW_UNLESS(distance_function != nullptr); SanityCheckConfigurationDistanceFunction(distance_function, GetDefaultConfiguration()); distance_and_interpolation_provider_ = legacy->WithConfigurationDistanceFunction(distance_function); } ConfigurationDistanceFunction CollisionChecker::MakeStandaloneConfigurationDistanceFunction() const { return [this](const Eigen::VectorXd& q_1, const Eigen::VectorXd& q_2) { return this->ComputeConfigurationDistance(q_1, q_2); }; } void CollisionChecker::SetConfigurationInterpolationFunction( const ConfigurationInterpolationFunction& interpolation_function) { auto legacy = std::dynamic_pointer_cast<const LegacyDistanceAndInterpolationProvider>( distance_and_interpolation_provider_); if (legacy == nullptr) { throw std::logic_error( "CollisionChecker::SetConfigurationInterpolationFunction() " "is not supported after a DistanceAndInterpolationProvider " "has already been set."); } if (interpolation_function == nullptr) { SetConfigurationInterpolationFunction( MakeDefaultConfigurationInterpolationFunction( GetQuaternionDofStartIndices(plant()))); return; } SanityCheckConfigurationInterpolationFunction(interpolation_function, GetDefaultConfiguration()); distance_and_interpolation_provider_ = legacy->WithConfigurationInterpolationFunction(interpolation_function); } ConfigurationInterpolationFunction CollisionChecker::MakeStandaloneConfigurationInterpolationFunction() const { return [this](const Eigen::VectorXd& q_1, const Eigen::VectorXd& q_2, double ratio) { return this->InterpolateBetweenConfigurations(q_1, q_2, ratio); }; } bool CollisionChecker::CheckEdgeCollisionFree( const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, const std::optional<int> context_number) const { return CheckContextEdgeCollisionFree(&mutable_model_context(context_number), q1, q2); } bool CollisionChecker::CheckContextEdgeCollisionFree( CollisionCheckerContext* model_context, const Eigen::VectorXd& q1, const Eigen::VectorXd& q2) const { DRAKE_THROW_UNLESS(model_context != nullptr); // Fail fast if q2 is in collision. This method is used by motion planners // that extend/connect towards some target configuration, and thus require a // number of edge collision checks in which q1 is often known to be // collision-free while q2 is unknown. Many of these potential // extensions/connections will result in a colliding configuration, so failing // fast on a colliding q2 helps reduce the work of checking colliding edges. // There is also no need to special case checking q1, since it will be the // first configuration checked in the loop. if (!CheckContextConfigCollisionFree(model_context, q2)) { return false; } const double distance = ComputeConfigurationDistance(q1, q2); const int num_steps = static_cast<int>(std::max(1.0, std::ceil(distance / edge_step_size()))); for (int step = 0; step < num_steps; ++step) { const double ratio = static_cast<double>(step) / static_cast<double>(num_steps); const Eigen::VectorXd qinterp = InterpolateBetweenConfigurations(q1, q2, ratio); if (!CheckContextConfigCollisionFree(model_context, qinterp)) { return false; } } return true; } bool CollisionChecker::CheckEdgeCollisionFreeParallel( const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, const Parallelism parallelize) const { const int number_of_threads = GetNumberOfThreads(parallelize); drake::log()->debug("CheckEdgeCollisionFreeParallel uses {} thread(s)", number_of_threads); // Only perform parallel operations if `omp parallel for` will use >1 thread. if (number_of_threads > 1) { // Fail fast if q2 is in collision. This method is used by motion planners // that extend/connect towards some target configuration, and thus require a // number of edge collision checks in which q1 is often known to be // collision-free while q2 is unknown. Many of these potential // extensions/connections will result in a colliding configuration, so // failing fast on a colliding q2 helps reduce the work of checking // colliding edges. // There is also no need to special case checking q1, since it will be the // first configuration checked in the loop. if (!CheckConfigCollisionFree(q2)) { return false; } const double distance = ComputeConfigurationDistance(q1, q2); const int num_steps = static_cast<int>(std::max(1.0, std::ceil(distance / edge_step_size()))); std::atomic<bool> edge_valid(true); const auto step_work = [&](const int thread_num, const int64_t step) { if (edge_valid.load()) { const double ratio = static_cast<double>(step) / static_cast<double>(num_steps); const Eigen::VectorXd qinterp = InterpolateBetweenConfigurations(q1, q2, ratio); if (!CheckConfigCollisionFree(qinterp, thread_num)) { edge_valid.store(false); } } }; StaticParallelForIndexLoop(DegreeOfParallelism(number_of_threads), 0, num_steps, step_work, ParallelForBackend::BEST_AVAILABLE); return edge_valid.load(); } else { // If OpenMP cannot parallelize, fall back to the serial version. return CheckEdgeCollisionFree(q1, q2); } } std::vector<uint8_t> CollisionChecker::CheckEdgesCollisionFree( const std::vector<std::pair<Eigen::VectorXd, Eigen::VectorXd>>& edges, const Parallelism parallelize) const { // Note: vector<uint8_t> is used since vector<bool> is not thread safe. std::vector<uint8_t> collision_checks(edges.size(), 0); const int number_of_threads = GetNumberOfThreads(parallelize); drake::log()->debug("CheckEdgesCollisionFree uses {} thread(s)", number_of_threads); const auto edge_work = [&](const int thread_num, const int64_t index) { const std::pair<Eigen::VectorXd, Eigen::VectorXd>& edge = edges.at(index); collision_checks.at(index) = CheckEdgeCollisionFree(edge.first, edge.second, thread_num); }; StaticParallelForIndexLoop(DegreeOfParallelism(number_of_threads), 0, edges.size(), edge_work, ParallelForBackend::BEST_AVAILABLE); return collision_checks; } EdgeMeasure CollisionChecker::MeasureEdgeCollisionFree( const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, const std::optional<int> context_number) const { return MeasureContextEdgeCollisionFree(&mutable_model_context(context_number), q1, q2); } EdgeMeasure CollisionChecker::MeasureContextEdgeCollisionFree( CollisionCheckerContext* model_context, const Eigen::VectorXd& q1, const Eigen::VectorXd& q2) const { DRAKE_THROW_UNLESS(model_context != nullptr); const double distance = ComputeConfigurationDistance(q1, q2); const int num_steps = static_cast<int>(std::max(1.0, std::ceil(distance / edge_step_size()))); double last_valid_ratio = -1.0; for (int step = 0; step <= num_steps; ++step) { const double ratio = static_cast<double>(step) / static_cast<double>(num_steps); const Eigen::VectorXd qinterp = InterpolateBetweenConfigurations(q1, q2, ratio); if (!CheckContextConfigCollisionFree(model_context, qinterp)) { return EdgeMeasure(distance, last_valid_ratio); } last_valid_ratio = ratio; } return EdgeMeasure(distance, 1.0); } EdgeMeasure CollisionChecker::MeasureEdgeCollisionFreeParallel( const Eigen::VectorXd& q1, const Eigen::VectorXd& q2, const Parallelism parallelize) const { const int number_of_threads = GetNumberOfThreads(parallelize); drake::log()->debug("MeasureEdgeCollisionFreeParallel uses {} thread(s)", number_of_threads); // Only perform parallel operations if `omp parallel for` will use >1 thread. if (number_of_threads > 1) { const double distance = ComputeConfigurationDistance(q1, q2); const int num_steps = static_cast<int>(std::max(1.0, std::ceil(distance / edge_step_size()))); // The "highest" interpolant value, alpha, (uninterrupted from q1) for // which there is no collision. std::atomic<double> alpha; // Start by assuming the whole edge is fine; we'll whittle away at it. alpha.store(1.0); std::mutex alpha_mutex; const auto step_work = [&](const int thread_num, const int64_t step) { const double ratio = static_cast<double>(step) / static_cast<double>(num_steps); // If this step fails, this is the alpha which we would report. const double possible_alpha = static_cast<double>(step - 1) / static_cast<double>(num_steps); if (possible_alpha < alpha.load()) { const Eigen::VectorXd qinterp = InterpolateBetweenConfigurations(q1, q2, ratio); if (!CheckConfigCollisionFree(qinterp, thread_num)) { std::lock_guard<std::mutex> update_lock(alpha_mutex); // Between the initial decision to interpolate and check collisions // and now, another thread may have proven a *lower* alpha is invalid; // check again before setting *this* as the lowest known invalid step. if (possible_alpha < alpha.load()) { alpha.store(possible_alpha); } } } }; StaticParallelForIndexLoop(DegreeOfParallelism(number_of_threads), 0, num_steps + 1, step_work, ParallelForBackend::BEST_AVAILABLE); return EdgeMeasure(distance, alpha.load()); } else { // If OpenMP cannot parallelize, fall back to the serial version. return MeasureEdgeCollisionFree(q1, q2); } } std::vector<EdgeMeasure> CollisionChecker::MeasureEdgesCollisionFree( const std::vector<std::pair<Eigen::VectorXd, Eigen::VectorXd>>& edges, const Parallelism parallelize) const { std::vector<EdgeMeasure> collision_checks(edges.size(), EdgeMeasure(0.0, -1.0)); const int number_of_threads = GetNumberOfThreads(parallelize); drake::log()->debug("MeasureEdgesCollisionFree uses {} thread(s)", number_of_threads); const auto edge_work = [&](const int thread_num, const int64_t index) { const std::pair<Eigen::VectorXd, Eigen::VectorXd>& edge = edges.at(index); collision_checks.at(index) = MeasureEdgeCollisionFree(edge.first, edge.second, thread_num); }; StaticParallelForIndexLoop(DegreeOfParallelism(number_of_threads), 0, edges.size(), edge_work, ParallelForBackend::BEST_AVAILABLE); return collision_checks; } RobotClearance CollisionChecker::CalcRobotClearance( const Eigen::VectorXd& q, const double influence_distance, const std::optional<int> context_number) const { return CalcContextRobotClearance(&mutable_model_context(context_number), q, influence_distance); } RobotClearance CollisionChecker::CalcContextRobotClearance( CollisionCheckerContext* model_context, const Eigen::VectorXd& q, const double influence_distance) const { DRAKE_THROW_UNLESS(model_context != nullptr); DRAKE_THROW_UNLESS(influence_distance >= 0.0); DRAKE_THROW_UNLESS(std::isfinite(influence_distance)); UpdateContextPositions(model_context, q); auto result = DoCalcContextRobotClearance(*model_context, influence_distance); for (int j : uncontrolled_dofs_that_kinematically_affect_the_robot_) { result.mutable_jacobians().col(j).setZero(); } return result; } int CollisionChecker::MaxNumDistances( const std::optional<int> context_number) const { return MaxContextNumDistances(model_context(context_number)); } int CollisionChecker::MaxContextNumDistances( const CollisionCheckerContext& model_context) const { return DoMaxContextNumDistances(model_context); } std::vector<RobotCollisionType> CollisionChecker::ClassifyBodyCollisions( const Eigen::VectorXd& q, const std::optional<int> context_number) const { return ClassifyContextBodyCollisions(&mutable_model_context(context_number), q); } std::vector<RobotCollisionType> CollisionChecker::ClassifyContextBodyCollisions( CollisionCheckerContext* model_context, const Eigen::VectorXd& q) const { DRAKE_THROW_UNLESS(model_context != nullptr); UpdateContextPositions(model_context, q); return DoClassifyContextBodyCollisions(*model_context); } CollisionChecker::CollisionChecker(CollisionCheckerParams params, bool supports_parallel_checking) : setup_model_(std::move(params.model)), robot_model_instances_([&params]() { // Sort (and de-duplicate) the robot model instances for faster lookups. DRAKE_THROW_UNLESS(params.robot_model_instances.size() > 0); const std::set<ModelInstanceIndex> sorted_set( params.robot_model_instances.begin(), params.robot_model_instances.end()); const std::vector<ModelInstanceIndex> sorted_vec(sorted_set.begin(), sorted_set.end()); const ModelInstanceIndex world = world_model_instance(); for (const auto& robot_model_instance : sorted_vec) { DRAKE_THROW_UNLESS(robot_model_instance != world); } return sorted_vec; }()), uncontrolled_dofs_that_kinematically_affect_the_robot_( CalcUncontrolledDofsThatKinematicallyAffectTheRobot( setup_model_->plant(), robot_model_instances_)), supports_parallel_checking_(supports_parallel_checking), implicit_context_parallelism_(params.implicit_context_parallelism) { // Sanity check the supported implicit context parallelism. if (!SupportsParallelChecking() && implicit_context_parallelism_.num_threads() > 1) { throw std::runtime_error( "implicit context parallelism > 1 cannot be used with a collision " "checker that does not support parallel operations"); } // Initialize the zero configuration. zero_configuration_ = Eigen::VectorXd::Zero(plant().num_positions()); // Initialize the default configuration. default_configuration_ = plant().GetPositions(*plant().CreateDefaultContext()); // Initialize the collision padding matrix. collision_padding_ = Eigen::MatrixXd::Zero(plant().num_bodies(), plant().num_bodies()); SetPaddingAllRobotEnvironmentPairs(params.env_collision_padding); SetPaddingAllRobotRobotPairs(params.self_collision_padding); // Set distance and interpolation provider/functions. const bool params_has_provider = params.distance_and_interpolation_provider != nullptr; const bool params_has_distance_function = params.configuration_distance_function != nullptr; if (params_has_provider && params_has_distance_function) { throw std::runtime_error( "CollisionCheckerParams may contain either " "distance_and_interpolation_provider != nullptr " "or distance_function != nullptr, not both"); } if (params_has_provider) { SetDistanceAndInterpolationProvider( std::move(params.distance_and_interpolation_provider)); } else if (params_has_distance_function) { SanityCheckConfigurationDistanceFunction( params.configuration_distance_function, GetDefaultConfiguration()); // Generate the default interpolation function. const ConfigurationInterpolationFunction default_interpolation_fn = MakeDefaultConfigurationInterpolationFunction( GetQuaternionDofStartIndices(plant())); distance_and_interpolation_provider_ = std::make_unique<LegacyDistanceAndInterpolationProvider>( params.configuration_distance_function, default_interpolation_fn); } else { SetDistanceAndInterpolationProvider( std::make_unique<LinearDistanceAndInterpolationProvider>(plant())); } // Set edge step size. set_edge_step_size(params.edge_step_size); // Generate the filtered collision matrix. nominal_filtered_collisions_ = GenerateFilteredCollisionMatrix(); filtered_collisions_ = nominal_filtered_collisions_; log()->debug("Collision filter matrix:\n{}", fmt_eigen(filtered_collisions_)); } CollisionChecker::CollisionChecker(const CollisionChecker&) = default; void CollisionChecker::AllocateContexts() { DRAKE_THROW_UNLESS(IsInitialSetup()); // Move to a const model. model_ = std::move(setup_model_); // Make enough contexts to support the specified implicit context parallelism. log()->info("Allocating contexts to support implicit context parallelism {}", implicit_context_parallelism_.num_threads()); // Make the prototype context. const std::unique_ptr<CollisionCheckerContext> prototype_context = CreatePrototypeContext(); DRAKE_THROW_UNLESS(prototype_context != nullptr); owned_contexts_.AllocateOwnedContexts( *prototype_context, implicit_context_parallelism_.num_threads()); } void CollisionChecker::OwnedContextKeeper::AllocateOwnedContexts( const CollisionCheckerContext& prototype_context, const int num_contexts) { DRAKE_THROW_UNLESS(num_contexts >= 1); DRAKE_THROW_UNLESS(empty()); for (int index = 0; index < num_contexts; ++index) { auto cloned = prototype_context.Clone(); // Enforce the invariant that contexts are non-null. DRAKE_THROW_UNLESS(cloned != nullptr); model_contexts_.emplace_back(std::move(cloned)); } prototype_context_ = prototype_context.Clone(); DRAKE_THROW_UNLESS(prototype_context_ != nullptr); } bool CollisionChecker::CanEvaluateInParallel() const { return SupportsParallelChecking() && num_allocated_contexts() > 1; } std::string CollisionChecker::CriticizePaddingMatrix() const { return CriticizePaddingMatrix(collision_padding_, __func__); } CollisionCheckerContext& CollisionChecker::mutable_model_context( const std::optional<int> context_number) const { const int context_index = context_number.has_value() ? *context_number : GetContextOmpThreadNum(); return owned_contexts_.get_mutable_model_context(context_index); } void CollisionChecker::ValidateFilteredCollisionMatrix( const Eigen::MatrixXi& filtered, const char* func) const { DRAKE_THROW_UNLESS(filtered.rows() == filtered.cols()); const int count = filtered.rows(); // TODO(sean.curtis): These messages have the prefix CollisionChecker. // Consider whether that should be replaced with NiceTypeName::Get(*this). // Loop counters below use `int` for Eigen indexing compatibility. for (int i = 0; i < count; ++i) { if (filtered(i, i) != -1) { throw std::logic_error(fmt::format( "CollisionChecker::{}(): The filtered collision matrix has invalid " "values on the diagonal ({}, {}) = {}; the values on the diagonal " "must always be -1.", func, i, i, filtered(i, i))); } const bool i_is_robot = IsPartOfRobot(BodyIndex(i)); for (int j = i + 1; j < count; ++j) { const bool pair_has_robot = i_is_robot || IsPartOfRobot(BodyIndex(j)); // Both are environment bodies. if (!pair_has_robot && filtered(i, j) != -1) { throw std::logic_error(fmt::format( "CollisionChecker::{}(): The filtered collision matrix must " "contain -1 for pairs of environment bodies. Found {} at ({}, {}).", func, filtered(i, j), i, j)); } // Values must lie in the range [-1, 1]. if (filtered(i, j) > 1 || filtered(i, j) < -1) { throw std::logic_error(fmt::format( "CollisionChecker::{}(): The filtered collision matrix must " "contain values that are 0, 1, or -1. Found {} at ({}, {}).", func, filtered(i, j), i, j)); } // Matrix must be symmetric. if (filtered(i, j) != filtered(j, i)) { throw std::logic_error(fmt::format( "CollisionChecker::{}(): The filtered collision matrix must be " "symmetric. Values at ({}, {}) and ({}, {}) are not equal; " "{} != {}.", func, i, j, j, i, filtered(i, j), filtered(j, i))); } // (Body, *) pairs cannot have -1. if (filtered(i, j) < 0 && pair_has_robot) { throw std::logic_error(fmt::format( "CollisionChecker::{}(): The filtered collision matrix can only be " "1 or 0 for a pair with a robot body ({}, {}), found {}.", func, i, j, filtered(i, j))); } } } } Eigen::MatrixXi CollisionChecker::GenerateFilteredCollisionMatrix() const { const int num_bodies = plant().num_bodies(); // Initialize matrix to zero (no filtered collisions). Eigen::MatrixXi filtered_collisions = Eigen::MatrixXi::Zero(num_bodies, num_bodies); const auto& inspector = model().scene_graph().model_inspector(); // Generate a mapping from body to subgraph for use in identifying welds. std::vector<int> body_subgraph_mapping(num_bodies, -1); const std::vector<std::set<BodyIndex>> subgraphs = plant().FindSubgraphsOfWeldedBodies(); for (size_t subgraph_id = 0; subgraph_id < subgraphs.size(); ++subgraph_id) { const std::set<BodyIndex>& subgraph = subgraphs.at(subgraph_id); for (const BodyIndex& body_id : subgraph) { body_subgraph_mapping.at(body_id) = static_cast<int>(subgraph_id); } } // For consistency, (B, B) is always filtered. // Loop variables below use `int` for Eigen indexing compatibility. for (int i = 0; i < num_bodies; ++i) { filtered_collisions(i, i) = -1; const int body_i_subgraph_id = body_subgraph_mapping.at(i); // We expect FindSubgraphsOfWeldedBodies to cover all bodies, but check to // make sure no bodies are left with the default subgraph id. DRAKE_DEMAND(body_i_subgraph_id >= 0); const bool i_is_robot = IsPartOfRobot(BodyIndex(i)); const RigidBody<double>& body_i = get_body(BodyIndex(i)); const std::vector<GeometryId>& geometries_i = plant().GetCollisionGeometriesForBody(body_i); for (int j = i + 1; j < num_bodies; ++j) { const int body_j_subgraph_id = body_subgraph_mapping.at(j); const bool j_is_robot = IsPartOfRobot(BodyIndex(j)); // (Env, env) pairs are immutably filtered (marked -1). if (!(i_is_robot || j_is_robot)) { filtered_collisions(i, j) = -1; filtered_collisions(j, i) = -1; continue; } const RigidBody<double>& body_j = get_body(BodyIndex(j)); // Check if collisions between the geometries are already filtered. bool collisions_filtered = false; const std::vector<GeometryId>& geometries_j = plant().GetCollisionGeometriesForBody(body_j); if (geometries_i.size() > 0 && geometries_j.size() > 0) { collisions_filtered = inspector.CollisionFiltered(geometries_i.at(0), geometries_j.at(0)); // Ensure that the collision filtering is homogeneous across all body // geometries. for (const auto& id_i : geometries_i) { for (const auto& id_j : geometries_j) { const bool current_filtered = inspector.CollisionFiltered(id_i, id_j); if (current_filtered != collisions_filtered) { throw std::runtime_error(fmt::format( "SceneGraph's collision filters on the geometries of bodies " " {} [{}] and {} [{}] are not homogeneous", i, body_i.scoped_name(), j, body_j.scoped_name())); } } } } // While MbP already filters collisions in SceneGraph between welded // bodies, this is only recorded if both bodies have collision geometries // when this filter is applied. Since we want to handle collision // geometries added later, we must record if bodies are welded together. // If the body pair has a welded path between them, it should be filtered. const bool bodies_welded_together = body_i_subgraph_id == body_j_subgraph_id; // Add the filter accordingly. if (collisions_filtered) { // Filter the collision log()->debug( "Collision between body {} [{}] and body {} [{}] filtered " "(filtered in SceneGraph)", body_i.scoped_name(), i, body_j.scoped_name(), j); filtered_collisions(i, j) = 1; filtered_collisions(j, i) = 1; } else if (bodies_welded_together) { // Filter the collision log()->debug( "Collision between body {} [{}] and body {} [{}] filtered " "(bodies are welded together)", body_i.scoped_name(), i, body_j.scoped_name(), j); filtered_collisions(i, j) = 1; filtered_collisions(j, i) = 1; } else { log()->debug( "Collision between body {} [{}] and body {} [{}] not filtered", body_i.scoped_name(), i, body_j.scoped_name(), j); } } } return filtered_collisions; } void CollisionChecker::UpdateMaxCollisionPadding() { max_collision_padding_ = -std::numeric_limits<double>::infinity(); const int N = plant().num_bodies(); // We want to exclude the diagonal (which is always zero) so that the // maximum padding can be negative. We accomplish this by walking the upper // triangle of the padding matrix, relying on the symmetry invariant. // We also need to exclude environment-environment pairs. for (int r = 0; r < N - 1; ++r) { const bool r_is_robot = IsPartOfRobot(BodyIndex(r)); for (int c = r + 1; c < N; ++c) { const bool c_is_robot = IsPartOfRobot(BodyIndex(c)); if (r_is_robot || c_is_robot) { max_collision_padding_ = std::max(max_collision_padding_, collision_padding_(r, c)); } } } if (!std::isfinite(max_collision_padding_)) { // If there are *no* robot bodies, we'd end up returning -infinity. max_collision_padding_ = 0; } } void CollisionChecker::ValidatePaddingMatrix(const Eigen::MatrixXd& padding, const char* func) const { const std::string criticism = CriticizePaddingMatrix(padding, func); if (!criticism.empty()) { throw std::logic_error(criticism); } } std::string CollisionChecker::CriticizePaddingMatrix( const Eigen::MatrixXd& padding, const char* func) const { if (padding.rows() != padding.cols()) { return fmt::format( "CollisionChecker::{}(): The padding" " matrix must be square. The given padding matrix is the" " wrong shape: {}x{}.", func, padding.rows(), padding.cols()); } const int count = padding.rows(); // TODO(sean.curtis): These messages have the prefix CollisionChecker. // Consider whether that should be replaced with NiceTypeName::Get(*this). // Loop variables below use `int` for Eigen indexing compatibility. for (int i = 0; i < count; ++i) { if (padding(i, i) != 0.0) { return fmt::format( "CollisionChecker::{}(): The collision padding matrix has invalid " "values on the diagonal ({}, {}) = {}; the values on the diagonal " "must always be 0.", func, i, i, padding(i, i)); } const bool i_is_robot = IsPartOfRobot(BodyIndex(i)); for (int j = i + 1; j < count; ++j) { const bool pair_has_robot = i_is_robot || IsPartOfRobot(BodyIndex(j)); // Both are environment bodies. if (!pair_has_robot && padding(i, j) != 0.0) { return fmt::format( "CollisionChecker::{}(): The collision padding matrix must contain " "0 for pairs of environment bodies. Found {} at ({}, {}).", func, padding(i, j), i, j); } // Values must be finite. if (!std::isfinite(padding(i, j))) { return fmt::format( "CollisionChecker::{}(): The collision padding matrix must contain " "finite values. Found {} at ({}, {}).", func, padding(i, j), i, j); } // Matrix must be symmetric. if (padding(i, j) != padding(j, i)) { return fmt::format( "CollisionChecker::{}(): The collision padding matrix must be " "symmetric. Values at ({}, {}) and ({}, {}) are not equal; " "{} != {}.", func, i, j, j, i, padding(i, j), padding(j, i)); } } } return {}; } int CollisionChecker::GetNumberOfThreads(const Parallelism parallelize) const { const bool check_in_parallel = CanEvaluateInParallel() && parallelize.num_threads() > 1; if (check_in_parallel) { return std::min(num_allocated_contexts(), parallelize.num_threads()); } else { return 1; } } CollisionChecker::OwnedContextKeeper::~OwnedContextKeeper() = default; CollisionChecker::OwnedContextKeeper::OwnedContextKeeper( const CollisionChecker::OwnedContextKeeper& other) { AllocateOwnedContexts(other.prototype_context(), other.num_contexts()); } void CollisionChecker::OwnedContextKeeper:: PerformOperationAgainstAllOwnedContexts( const RobotDiagram<double>& model, const std::function<void(const RobotDiagram<double>&, CollisionCheckerContext*)>& operation) { DRAKE_DEMAND(operation != nullptr); DRAKE_THROW_UNLESS(allocated()); for (auto& model_context : model_contexts_) { operation(model, model_context.get()); } operation(model, prototype_context_.get()); } CollisionChecker::StandaloneContextReferenceKeeper:: ~StandaloneContextReferenceKeeper() = default; void CollisionChecker::StandaloneContextReferenceKeeper::AddStandaloneContext( const std::shared_ptr<CollisionCheckerContext>& standalone_context) const { std::lock_guard<std::mutex> lock(standalone_contexts_mutex_); standalone_contexts_.push_back( std::weak_ptr<CollisionCheckerContext>(standalone_context)); } void CollisionChecker::StandaloneContextReferenceKeeper:: PerformOperationAgainstAllStandaloneContexts( const RobotDiagram<double>& model, const std::function<void(const RobotDiagram<double>&, CollisionCheckerContext*)>& operation) { DRAKE_DEMAND(operation != nullptr); std::lock_guard<std::mutex> lock(standalone_contexts_mutex_); for (auto standalone_context = standalone_contexts_.begin(); standalone_context != standalone_contexts_.end();) { auto maybe_context = standalone_context->lock(); if (maybe_context != nullptr) { operation(model, maybe_context.get()); // Advance to next item. ++standalone_context; } else { // If the pointed-to context is no longer alive, remove it. // Note that erase() returns the iterator to the next item. standalone_context = standalone_contexts_.erase(standalone_context); } } } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/robot_diagram.h
#pragma once #include <memory> #include "drake/common/default_scalars.h" #include "drake/geometry/scene_graph.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace planning { /** Storage for a combined diagram, plant, and scene graph. This class is a convenient syntactic sugar, especially in C++ code where it simplifies object lifetime tracking and downcasting of the plant and scene graph references. It's purpose is to serve as planner-specific syntactic sugar for operating on a MultibodyPlant. For other purposes (e.g., simulation), users should generally prefer to just use a Diagram, instead. Use RobotDiagramBuilder to construct a RobotDiagram. By default, the ports exposed by a %RobotDiagram are the set of all ports provided by the plant and scene graph (excluding the internal connections between the two). Refer to their individual overview figures for details (see multibody::MultibodyPlant and geometry::SceneGraph), or see the full list by viewing the robot_diagram.GetGraphvizString(). @system name: RobotDiagram input_ports: - plant_actuation - plant_applied_generalized_force - ... etc ... output_ports: - plant_state - ... etc ... - scene_graph_query @endsystem However, if the RobotDiagramBuilder::builder() was used to change the diagram or if either the plant or scene graph were renamed, then no ports will be exported by default. In that case, you can use the builder to export any desired ports. @tparam_default_scalar @ingroup planning_infrastructure */ template <typename T> class RobotDiagram final : public systems::Diagram<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RobotDiagram) // There are no user-serviceable constructors for this class. To make an // instance of this class, use RobotDiagramBuilder. // Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit RobotDiagram(const RobotDiagram<U>&); ~RobotDiagram() final; /** Creates a default context for this diagram. This is one way to create a valid `root_context` argument to pass to the context-related helper functions below. */ using systems::Diagram<T>::CreateDefaultContext; /** Gets the contained plant (readonly). */ const multibody::MultibodyPlant<T>& plant() const { return plant_; } /** Gets the contained scene graph (mutable). */ geometry::SceneGraph<T>& mutable_scene_graph() { return scene_graph_; } /** Gets the contained scene graph (readonly). */ const geometry::SceneGraph<T>& scene_graph() const { return scene_graph_; } /** Gets the contained plant's context (mutable) out of the given root context. Refer to drake::systems::System::GetMyContextFromRoot() to understand `root_context`. @throws std::exception if the `root_context` is not a root context. */ systems::Context<T>& mutable_plant_context( systems::Context<T>* root_context) const { return plant_.GetMyMutableContextFromRoot(root_context); } /** Gets the contained plant's context (readonly) out of the given root context. Refer to drake::systems::System::GetMyContextFromRoot() to understand `root_context`. @throws std::exception if the `root_context` is not a root context. */ const systems::Context<T>& plant_context( const systems::Context<T>& root_context) const { return plant_.GetMyContextFromRoot(root_context); } /** Gets the contained scene graph's context (mutable) out of the given root context. Refer to drake::systems::System::GetMyContextFromRoot() to understand `root_context`. @throws std::exception if the `root_context` is not a root context. */ systems::Context<T>& mutable_scene_graph_context( systems::Context<T>* root_context) const { return scene_graph_.GetMyMutableContextFromRoot(root_context); } /** Gets the contained scene graph's context (readonly) out of the given root context. Refer to drake::systems::System::GetMyContextFromRoot() to understand `root_context`. @throws std::exception if the `root_context` is not a root context. */ const systems::Context<T>& scene_graph_context( const systems::Context<T>& root_context) const { return scene_graph_.GetMyContextFromRoot(root_context); } private: // To access our private constructor. template <typename> friend class RobotDiagramBuilder; // For use by RobotDiagramBuilder. explicit RobotDiagram(std::unique_ptr<systems::DiagramBuilder<T>>); // Aliases for the plant and scene graph (which are owned by our base class). multibody::MultibodyPlant<T>& plant_; geometry::SceneGraph<T>& scene_graph_; }; } // namespace planning } // namespace drake DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::planning::RobotDiagram)
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/visibility_graph.h
#pragma once #include <Eigen/Sparse> #include "drake/common/parallelism.h" #include "drake/planning/collision_checker.h" namespace drake { namespace planning { /** Given some number of sampled points in the configuration space of `checker`'s plant(), computes the "visibility graph" -- two `points` have an edge between them if the line segment connecting them is collision free. See CollisionChecker documentation for more information on how edge collision checks are performed. Note that this method assumes the collision checker has symmetric behavior (i.e. checking edge (q1, q2) is the same as checking edge (q2, q1)). This is true for many collision checkers (e.g. those using LinearDistanceAndInterpolationProvider, which is the default), but some more complex spaces with non-linear interpolation (e.g. a Dubin's car) are not symmetric. If `parallelize` specifies more than one thread, then the CollisionCheckerParams::distance_and_interpolation_provider for `checker` must be implemented in C++, either by providing the C++ implementation directly directly or by using the default provider. @returns the adjacency matrix, A(i,j) == true iff points.col(i) is visible from points.col(j). A is always symmetric. @pre points.rows() == total number of positions in the collision checker plant. */ Eigen::SparseMatrix<bool> VisibilityGraph( const CollisionChecker& checker, const Eigen::Ref<const Eigen::MatrixXd>& points, Parallelism parallelize = Parallelism::Max()); } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/unimplemented_collision_checker.cc
#include "drake/planning/unimplemented_collision_checker.h" #include <stdexcept> #include <utility> #include <fmt/format.h> namespace drake { namespace planning { namespace { [[noreturn]] void ThrowNotImplemented(const char* func) { throw std::runtime_error(fmt::format("{} is not implemented", func)); } } // namespace UnimplementedCollisionChecker::UnimplementedCollisionChecker( CollisionCheckerParams params, bool supports_parallel_checking) : CollisionChecker(std::move(params), supports_parallel_checking) {} UnimplementedCollisionChecker::UnimplementedCollisionChecker( const UnimplementedCollisionChecker&) = default; UnimplementedCollisionChecker::~UnimplementedCollisionChecker() {} std::unique_ptr<CollisionChecker> UnimplementedCollisionChecker::DoClone() const { ThrowNotImplemented(__func__); } void UnimplementedCollisionChecker::DoUpdateContextPositions( CollisionCheckerContext*) const { ThrowNotImplemented(__func__); } bool UnimplementedCollisionChecker::DoCheckContextConfigCollisionFree( const CollisionCheckerContext&) const { ThrowNotImplemented(__func__); } std::optional<geometry::GeometryId> UnimplementedCollisionChecker::DoAddCollisionShapeToBody( const std::string&, const multibody::RigidBody<double>&, const geometry::Shape&, const math::RigidTransform<double>&) { ThrowNotImplemented(__func__); } void UnimplementedCollisionChecker::RemoveAddedGeometries( const std::vector<CollisionChecker::AddedShape>&) { ThrowNotImplemented(__func__); } void UnimplementedCollisionChecker::UpdateCollisionFilters() { ThrowNotImplemented(__func__); } RobotClearance UnimplementedCollisionChecker::DoCalcContextRobotClearance( const CollisionCheckerContext&, double) const { ThrowNotImplemented(__func__); } std::vector<RobotCollisionType> UnimplementedCollisionChecker::DoClassifyContextBodyCollisions( const CollisionCheckerContext&) const { ThrowNotImplemented(__func__); } int UnimplementedCollisionChecker::DoMaxContextNumDistances( const CollisionCheckerContext&) const { ThrowNotImplemented(__func__); } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/unimplemented_collision_checker.h
#pragma once #include <memory> #include <optional> #include <string> #include <vector> #include "drake/planning/collision_checker.h" #include "drake/planning/collision_checker_params.h" namespace drake { namespace planning { /** A concrete collision checker implementation that throws an exception for every virtual function hook. This might be useful for unit testing or for deriving your own collision checker without providing for the full suite of operations. */ class UnimplementedCollisionChecker : public CollisionChecker { public: /** Constructs a checker. @param supports_parallel_checking will serve as the return value of the CollisionChecker::SupportsParallelChecking() function. */ UnimplementedCollisionChecker(CollisionCheckerParams params, bool supports_parallel_checking); /** @name Does not allow copy, move, or assignment. */ /** @{ */ // N.B. The copy constructor is protected for use in implementing Clone(). UnimplementedCollisionChecker(UnimplementedCollisionChecker&&) = delete; UnimplementedCollisionChecker& operator=( const UnimplementedCollisionChecker&) = delete; UnimplementedCollisionChecker& operator=(UnimplementedCollisionChecker&&) = delete; /** @} */ ~UnimplementedCollisionChecker(); protected: // To support Clone(), allow copying (but not move nor assign). UnimplementedCollisionChecker(const UnimplementedCollisionChecker&); std::unique_ptr<CollisionChecker> DoClone() const override; void DoUpdateContextPositions( CollisionCheckerContext* model_context) const override; bool DoCheckContextConfigCollisionFree( const CollisionCheckerContext&) const override; std::optional<geometry::GeometryId> DoAddCollisionShapeToBody( const std::string& group_name, const multibody::RigidBody<double>& bodyA, const geometry::Shape& shape, const math::RigidTransform<double>& X_AG) override; void RemoveAddedGeometries( const std::vector<CollisionChecker::AddedShape>& shapes) override; void UpdateCollisionFilters() override; RobotClearance DoCalcContextRobotClearance(const CollisionCheckerContext&, double) const override; std::vector<RobotCollisionType> DoClassifyContextBodyCollisions( const CollisionCheckerContext&) const override; int DoMaxContextNumDistances(const CollisionCheckerContext&) const override; }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/robot_clearance.cc
#include "drake/planning/robot_clearance.h" #include "drake/common/drake_throw.h" namespace drake { namespace planning { using multibody::BodyIndex; RobotClearance::~RobotClearance() = default; void RobotClearance::Reserve(int size) { robot_indices_.reserve(size); other_indices_.reserve(size); collision_types_.reserve(size); distances_.reserve(size); jacobians_.reserve(size * nq_); } void RobotClearance::Append( BodyIndex robot_index, BodyIndex other_index, RobotCollisionType collision_type, double distance, const Eigen::Ref<const Eigen::RowVectorXd>& jacobian) { DRAKE_THROW_UNLESS(jacobian.cols() == nq_); robot_indices_.push_back(robot_index); other_indices_.push_back(other_index); collision_types_.push_back(collision_type); distances_.push_back(distance); for (int j = 0; j < nq_; ++j) { jacobians_.push_back(jacobian[j]); } } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/robot_diagram.cc
#include "drake/planning/robot_diagram.h" #include <vector> namespace drake { namespace planning { using geometry::SceneGraph; using multibody::MultibodyPlant; using systems::Diagram; using systems::DiagramBuilder; using systems::System; using systems::SystemTypeTag; // These reflect how AddMultibodyPlantSceneGraph currently works. In case we // ever change it to a different order, our unit tests will crash and we should // update these to reflect the new order. constexpr size_t kPlantIndex = 0; constexpr size_t kSceneGraphIndex = 1; // Returns the index'th subsystem from the given diagram, downcasting it to // the requested subtype. // // @pre The index'th system actually exists and is of the correct subtype. // // @tparam_default_scalar // @tparam ChildSystem the subsystem class to extract, e.g., MultibodyPlant. // @tparam DiagramOrDiagramBuilder duck type for either a diagram or a builder. template <typename T, template <typename> class ChildSystem, template <typename> class DiagramOrDiagramBuilder> ChildSystem<T>& DowncastSubsystem(DiagramOrDiagramBuilder<T>* diagram, size_t index) { DRAKE_DEMAND(diagram != nullptr); const std::vector<const System<T>*>& items = diagram->GetSystems(); const auto* child = dynamic_cast<const ChildSystem<T>*>(items.at(index)); DRAKE_DEMAND(child != nullptr); return const_cast<ChildSystem<T>&>(*child); } template <typename T> RobotDiagram<T>::RobotDiagram( std::unique_ptr<DiagramBuilder<T>> diagram_builder) : Diagram<T>(SystemTypeTag<RobotDiagram>{}), plant_(DowncastSubsystem<T, MultibodyPlant>(diagram_builder.get(), kPlantIndex)), scene_graph_(DowncastSubsystem<T, SceneGraph>(diagram_builder.get(), kSceneGraphIndex)) { diagram_builder->BuildInto(this); } template <typename T> RobotDiagram<T>::~RobotDiagram() = default; template <typename T> template <typename U> RobotDiagram<T>::RobotDiagram(const RobotDiagram<U>& other) : Diagram<T>(SystemTypeTag<RobotDiagram>{}, other), plant_(DowncastSubsystem<T, MultibodyPlant>(this, kPlantIndex)), scene_graph_(DowncastSubsystem<T, SceneGraph>(this, kSceneGraphIndex)) {} } // namespace planning } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::planning::RobotDiagram)
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/scene_graph_collision_checker.h
#pragma once #include <memory> #include <optional> #include <string> #include <vector> #include "drake/planning/collision_checker.h" #include "drake/planning/collision_checker_params.h" namespace drake { namespace planning { /** An implementation of CollisionChecker that uses SceneGraph to provide collision checks. Its behavior and limitations are exactly those of SceneGraph, e.g., in terms of what kinds of geometries can be collided. @ingroup planning_collision_checker */ class SceneGraphCollisionChecker final : public CollisionChecker { public: /** @name Does not allow copy, move, or assignment. */ /** @{ */ // N.B. The copy constructor is private for use in implementing Clone(). void operator=(const SceneGraphCollisionChecker&) = delete; /** @} */ /** Creates a new checker with the given params. */ explicit SceneGraphCollisionChecker(CollisionCheckerParams params); private: // To support Clone(), allow copying (but not move nor assign). explicit SceneGraphCollisionChecker(const SceneGraphCollisionChecker&); std::unique_ptr<CollisionChecker> DoClone() const final; void DoUpdateContextPositions(CollisionCheckerContext*) const final; bool DoCheckContextConfigCollisionFree( const CollisionCheckerContext& model_context) const final; std::optional<geometry::GeometryId> DoAddCollisionShapeToBody( const std::string& group_name, const multibody::RigidBody<double>& bodyA, const geometry::Shape& shape, const math::RigidTransform<double>& X_AG) final; void RemoveAddedGeometries( const std::vector<CollisionChecker::AddedShape>& shapes) final; void UpdateCollisionFilters() final; RobotClearance DoCalcContextRobotClearance( const CollisionCheckerContext& model_context, double influence_distance) const final; std::vector<RobotCollisionType> DoClassifyContextBodyCollisions( const CollisionCheckerContext& model_context) const final; int DoMaxContextNumDistances( const CollisionCheckerContext& model_context) const final; // Applies filters defined in the filtered collision matrix to SceneGraph. // This must be called in the constructor to ensure that additional filters // applied by CollisionChecker are present in SceneGraph, and after any // geometry is added to SceneGraph, as any existing filters will not include // the new geometry. void ApplyCollisionFiltersToSceneGraph(); }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/collision_avoidance.cc
#include "drake/planning/collision_avoidance.h" #include <algorithm> #include <cmath> namespace drake { namespace planning { namespace internal { Eigen::VectorXd ComputeCollisionAvoidanceDisplacement( const CollisionChecker& checker, const Eigen::VectorXd& q, double max_penetration, double max_clearance, const std::optional<int> context_number, CollisionCheckerContext* context) { DRAKE_THROW_UNLESS(max_penetration <= 0.0); DRAKE_THROW_UNLESS(std::isfinite(max_penetration)); DRAKE_THROW_UNLESS(max_clearance >= 0.0); DRAKE_THROW_UNLESS(std::isfinite(max_clearance)); DRAKE_THROW_UNLESS(max_clearance > max_penetration); DRAKE_THROW_UNLESS(context_number == std::nullopt || context == nullptr); const double penetration_range = max_clearance - max_penetration; // Collect the distances and Jacobians. const RobotClearance robot_clearance = context == nullptr ? checker.CalcRobotClearance(q, max_clearance, context_number) : checker.CalcContextRobotClearance(context, q, max_clearance); const int num_measurements = robot_clearance.size(); if (num_measurements == 0) { // No collisions within the safety range; so no displacement required. return Eigen::VectorXd::Zero(q.size()); } // Compute weights based on distance. Eigen::VectorXd weights(num_measurements); for (int row = 0; row < num_measurements; ++row) { const double distance = robot_clearance.distances()(row); const double penetration = max_clearance - distance; weights(row) = std::clamp(penetration / penetration_range, 0.0, 1.0); } // Here we compute ∇f = Σᵢ(wᵢ⋅Jqᵣ_ϕᵢ)ᵀ. Per the RobotClearance API docs we // have ϕᵢ as the iᵗʰ distance measurement and Jqᵣ_ϕᵢ as the partial of ϕᵢ // with respect to qᵣ, the robot state; wᵢ is our weight for iᵗʰ measurement. // // Note that Jqᵣ_ϕ is dimensioned as (num_measurements, nq) and weights is // (num_measurements, 1), so we can use Jᵀ as a convenient way to calculate // the sum in a single pass. return robot_clearance.jacobians().transpose() * weights; } } // namespace internal } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/body_shape_description.cc
#include "drake/planning/body_shape_description.h" #include "drake/common/drake_throw.h" #include "drake/geometry/query_object.h" #include "drake/geometry/scene_graph.h" namespace drake { namespace planning { BodyShapeDescription::BodyShapeDescription(const geometry::Shape& shape, const math::RigidTransformd& X_BS, std::string model_instance_name, std::string body_name) : shape_(shape.Clone()), X_BS_(X_BS), model_instance_name_(std::move(model_instance_name)), body_name_(std::move(body_name)) {} BodyShapeDescription MakeBodyShapeDescription( const multibody::MultibodyPlant<double>& plant, const systems::Context<double>& plant_context, const geometry::GeometryId& geometry_id) { DRAKE_DEMAND(plant.geometry_source_is_registered()); plant.ValidateContext(plant_context); DRAKE_DEMAND(geometry_id.is_valid()); // Grab query object to get the inspector. const auto& query_object = plant.get_geometry_query_input_port() .template Eval<geometry::QueryObject<double>>(plant_context); const auto& inspector = query_object.inspector(); // Make sure the geometry_id is associated with the passed plant. DRAKE_DEMAND(inspector.BelongsToSource(geometry_id, *plant.get_source_id())); const auto frame_id = inspector.GetFrameId(geometry_id); // inspector gives us the shape's pose w.r.t. the parent geometry frame F. We // rely on MbP registering the geometry frame F to the body B as X_BF = I. const math::RigidTransformd& X_BS = inspector.GetPoseInFrame(geometry_id); const auto body = plant.GetBodyFromFrameId(frame_id); DRAKE_DEMAND(body != nullptr); const std::string& model_instance_name = plant.GetModelInstanceName(body->model_instance()); return BodyShapeDescription(inspector.GetShape(geometry_id), X_BS, model_instance_name, body->name()); } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/edge_measure.h
#pragma once #include "drake/common/drake_copyable.h" namespace drake { namespace planning { /** The measure of the distance of the edge from q1 to q2 and the portion of that is collision free. Distance is that produced by CollisionChecker::ComputeConfigurationDistance() for the entire edge between q1 and q2. The portion of the edge between q1 and q2 that is collision free is encoded as the value α with the following semantics: - α = 1: No collisions were detected. The full edge can be considered collision free. This is the *only* time completely_free() reports `true`. - 0 ≤ α < 1: A collision was detected between q1 and q2. α is the *largest* interpolation value such that an edge from q to qα can be considered collision free (where qα = interpolate(q1, q2, α)). partially_free() reports `true`. - α is undefined: q1 was found to be in collision. That means there exists no α for which the edge (q1, qα) can be collision free. @note The length of the collision-free edge can be computed via distance * α. To simplify comparisons between a number of edges, some of which may not have a defined α, the function alpha_or(default_value) is provided. This is equivalent to `edge.partially_free() ? edge.alpha() : default_value`. @note For α to be meaningful, the caller is obliged to make sure that they use the same interpolating function as the CollisionChecker did when generating the measure. Calling CollisionChecker::InterpolateBetweenConfigurations() on the same checker instance would satisfy that requirement. @ingroup planning_collision_checker */ class EdgeMeasure { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(EdgeMeasure) /** @pre `0 ≤ distance` @pre `0 ≤ alpha ≤ 1` to indicate defined `alpha`, negative otherwise. */ EdgeMeasure(double distance, double alpha) : distance_(distance), alpha_(alpha < 0 ? -1 : alpha) { DRAKE_THROW_UNLESS(distance >= 0.0); DRAKE_THROW_UNLESS(alpha <= 1.0); } /** Reports `true` if all samples were collision free. */ bool completely_free() const { return alpha_ == 1.0; } /** Reports `true` if there's *any* portion of the edge (starting from q1) that is collision free. By implication, if completely_free() reports `true`, so will this. */ bool partially_free() const { return alpha_ >= 0.0; } /** Returns the edge distance. */ double distance() const { return distance_; } /** Returns the value of alpha, if defined. Note: Due to the sampling nature of the edge check, the edge (q1, qα) may not actually be collision free (due to a missed collision). There's a further subtlety. Subsequently calling CheckEdgeCollisionFree(q1, qα) may return `false`. This apparent contradiction is due to the fact that the samples on the edge (q1, qα) will not necessarily be the same as the samples originally tested on the edge (q1, q2). It is possible for those new samples to detect a previously missed collision. This is not a bug, merely a property of sampling-based testing. @pre partially_free() returns `true`. */ double alpha() const { DRAKE_THROW_UNLESS(partially_free()); return alpha_; } /** Returns the value of alpha, if defined, or the provided default value. */ double alpha_or(double default_value) const { if (partially_free()) { return alpha_; } else { return default_value; } } private: double distance_{}; double alpha_{}; // -1 implies invalid; caller is not obliged to know this. }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/collision_avoidance.h
#pragma once #include <optional> #include "drake/planning/collision_checker.h" namespace drake { namespace planning { namespace internal { /* Computes the gradient ∇f = (∂f/∂q)ᵀ of an unspecifed distance function "f". "f" combines the distances ϕᵢ of the given collision checker's RobotClearance data, reconciling multiple simultaneous potential collisions via a penalty method. The closer to penetration, the more weight that potential collision has. No measurements greater than `max_clearance` contribute to the calculation, and any distances less than `max_penetration` are all treated equally, regardless of the degree of penetration. Therefore, the gradient ∇f points `q` into a "clearer" state, reducing the likelihood of collision. @param checker The checker used to calculate clearance data. @param q The robot configuration at which we compute ∂f/∂q. @param max_penetration The bottom of the range; a non-positive value representing the level of penetration that saturates the weight. Penetration occurs inside an object where ϕ < 0. Setting the value to zero will give all penetration equal weight, regardless of depth. Making this value *more* negative won't increase the weight of deep penetrations, but it will reduce the weight of shallow penetrations. @param max_clearance The top of the range; a non-negative value beyond which possible collisions do not contribute. Two objects are "clear" where ϕ > 0. Setting the value to zero will only consider collisions and not nearby objects. As the value increases, more and more distant objects will influence the calculation. @param context_number An optional context number to specify the implicit context to use. @param context An optional collision checker context. @note Either a context, a context number, or neither may be provided. If neither is provided, the implicit context corresponding to the current OpenMP thread is used. @pre q.size() == checker.GetZeroConfiguration().size(). @pre max_penetration <= 0. @pre max_clearance >= 0. @pre max_clearance > max_penetration. @pre if context != nullptr, it is a context managed by checker. @pre context != nullptr and context_number != nullopt cannot be combined. @ingroup planning_collision_checker */ Eigen::VectorXd ComputeCollisionAvoidanceDisplacement( const CollisionChecker& checker, const Eigen::VectorXd& q, double max_penetration, double max_clearance, std::optional<int> context_number = std::nullopt, CollisionCheckerContext* context = nullptr); // TODO(jwnimmer-tri) Before we promote the above function out of the internal // namespace, consider renaming "Displacement" to "Gradient" to better reflect // the units on the return type. // TODO(jwnimmer-tri) Before we promote the above function out of the internal // namespace, consider changing its optional `context` parameter above into a // distinct function named ComputeContextCollisionAvoidanceDisplacement, for // consistency with how CollisionChecker names its member functions. } // namespace internal } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/collision_checker_params.h
#pragma once #include <functional> #include <memory> #include <vector> #include <Eigen/Core> #include "drake/common/parallelism.h" #include "drake/multibody/tree/multibody_tree_indexes.h" #include "drake/planning/distance_and_interpolation_provider.h" #include "drake/planning/robot_diagram.h" namespace drake { namespace planning { /** Configuration distance takes two configurations of the robot, q1 and q2, both as Eigen::VectorXd, and returns (potentially weighted) C-space distance as a double. The returned distance will be strictly non-negative. To be valid, the function must satisfy the following condition: - dist(q, q) ≡ 0 for values of q that are valid for the CollisionChecker's plant. */ using ConfigurationDistanceFunction = std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)>; // TODO(SeanCurtis-TRI): Move the default interpolator into the params. /** Configuration interpolation function takes two configurations of the robot, q1, and q2, both as Eigen::VectorXd, plus a ratio, r, in [0, 1] and returns the interpolated configuration. Behavior of the function for values of r outside of the range [0,1] is undefined. To be valid, the function must satisfy the following conditions: - interpolate(q1, q2, 0) ≡ q1 - interpolate(q1, q2, 1) ≡ q2 - interpolate(q, q, r) ≡ q, for all r in [0, 1] for values of q, q1, and q2 that are valid for the CollisionChecker's plant. */ using ConfigurationInterpolationFunction = std::function<Eigen::VectorXd( const Eigen::VectorXd&, const Eigen::VectorXd&, double)>; /** A set of common constructor parameters for a CollisionChecker. Not all subclasses of CollisionChecker will necessarily support this configuration struct, but many do so. @ingroup planning_collision_checker */ struct CollisionCheckerParams { /** A RobotDiagram model of the robot and environment. Must not be nullptr. */ std::unique_ptr<RobotDiagram<double>> model; /** A DistanceAndInterpolationProvider to support configuration distance and interpolation operations. @note Either a DistanceAndInterpolationProvider OR a ConfigurationDistanceFunction may be provided, not both. If neither is provided, a LinearDistanceAndInterpolationProvider with default weights is used. */ std::shared_ptr<const DistanceAndInterpolationProvider> distance_and_interpolation_provider; // TODO(SeanCurtis-TRI): add doc hyperlinks to edge checking doc. /** A vector of model instance indices that identify which model instances belong to the robot. The list must be non-empty and must not include the world model instance. */ std::vector<drake::multibody::ModelInstanceIndex> robot_model_instances; // TODO(SeanCurtis-TRI): add doc hyperlinks to edge checking doc. // TODO(calderpg-tri, jwnimmer-tri) Deprecate support for separate distance // and interpolation functions. /** Configuration (probably weighted) distance function. @note Either a DistanceAndInterpolationProvider OR a ConfigurationDistanceFunction may be provided, not both. If neither is provided, a LinearDistanceAndInterpolationProvider with default weights is used. @note the `configuration_distance_function` object will be copied and retained by a collision checker, so if the function has any lambda-captured data then that data must outlive the collision checker. */ ConfigurationDistanceFunction configuration_distance_function; // TODO(SeanCurtis-TRI): add doc hyperlinks to edge checking doc. /** Step size for edge checking; in units compatible with the configuration distance function. Collision checking of edges q1->q2 is performed by interpolating from q1 to q2 at edge_step_size steps and checking the interpolated configuration for collision. The value must be positive. */ double edge_step_size{}; // TODO(SeanCurtis-TRI): add doc hyperlinks to edge checking doc. /** Additional padding to apply to all robot-environment collision queries. If distance between robot and environment is less than padding, the checker reports a collision. */ double env_collision_padding{}; // TODO(SeanCurtis-TRI): add doc hyperlinks to edge checking doc. /** Additional padding to apply to all robot-robot self collision queries. If distance between robot and itself is less than padding, the checker reports a collision. */ double self_collision_padding{}; /** Specify how many contexts should be allocated to support collision checker implicit context parallelism. Defaults to the maximum parallelism. If the specific collision checker type in use declares that it *does not* support parallel queries, then implicit context parallelism is set to None(). @see @ref ccb_implicit_contexts "Implicit Context Parallelism". */ Parallelism implicit_context_parallelism = Parallelism::Max(); }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/robot_diagram_builder.h
#pragma once #include <memory> #include <type_traits> #include <utility> #include "drake/common/default_scalars.h" #include "drake/geometry/scene_graph.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/planning/robot_diagram.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace planning { /** Storage for a combined diagram builder, plant, and scene graph. When T == double, a parser (and package map) is also available. This class is a convenient syntactic sugar to help build a robot diagram, especially in C++ code where it simplifies object lifetime tracking and downcasting of the plant and scene graph references. @tparam_default_scalar @ingroup planning_infrastructure */ template <typename T> class RobotDiagramBuilder { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RobotDiagramBuilder) /** Constructs with the specified time step for the contained plant. @param time_step Governs whether the MultibodyPlant is modeled as a discrete system (`time_step > 0`) or as a continuous system (`time_step = 0`). See @ref time_advancement_strategy "Choice of Time Advancement Strategy" for further details. The default here matches the default value from multibody::MultibodyPlantConfig. */ explicit RobotDiagramBuilder(double time_step = 0.001); ~RobotDiagramBuilder(); /** Gets the contained DiagramBuilder (mutable). Do not call Build() on the return value; instead, call Build() on this. @throws exception when IsDiagramBuilt() already. */ systems::DiagramBuilder<T>& builder() { ThrowIfAlreadyBuiltOrCorrupted(); return *builder_; } /** Gets the contained DiagramBuilder (readonly). @throws exception when IsDiagramBuilt() already. */ const systems::DiagramBuilder<T>& builder() const { ThrowIfAlreadyBuiltOrCorrupted(); return *builder_; } /** Gets the contained Parser (mutable). @throws exception when IsDiagramBuilt() already. */ template <typename T1 = T, typename std::enable_if_t<std::is_same_v<T1, double>>* = nullptr> multibody::Parser& parser() { ThrowIfAlreadyBuiltOrCorrupted(); return parser_; } /** Gets the contained Parser (readonly). @throws exception when IsDiagramBuilt() already. */ template <typename T1 = T, typename std::enable_if_t<std::is_same_v<T1, double>>* = nullptr> const multibody::Parser& parser() const { ThrowIfAlreadyBuiltOrCorrupted(); return parser_; } /** Gets the contained plant (mutable). @throws exception when IsDiagramBuilt() already. */ multibody::MultibodyPlant<T>& plant() { ThrowIfAlreadyBuiltOrCorrupted(); return plant_; } /** Gets the contained plant (readonly). @throws exception when IsDiagramBuilt() already. */ const multibody::MultibodyPlant<T>& plant() const { ThrowIfAlreadyBuiltOrCorrupted(); return plant_; } /** Gets the contained scene graph (mutable). @throws exception when IsDiagramBuilt() already. */ geometry::SceneGraph<T>& scene_graph() { ThrowIfAlreadyBuiltOrCorrupted(); return scene_graph_; } /** Gets the contained scene graph (readonly). @throws exception when IsDiagramBuilt() already. */ const geometry::SceneGraph<T>& scene_graph() const { ThrowIfAlreadyBuiltOrCorrupted(); return scene_graph_; } /** Checks if the diagram has already been built. */ bool IsDiagramBuilt() const; /** Builds the diagram and returns the diagram plus plant and scene graph in a RobotDiagram. The plant will be finalized during this function, unless it's already been finalized. @throws exception when IsDiagramBuilt() already. */ std::unique_ptr<RobotDiagram<T>> Build(); private: void ThrowIfAlreadyBuiltOrCorrupted() const; bool ShouldExportDefaultPorts() const; void ExportDefaultPorts() const; // Storage for the diagram and its plant and scene graph. // After Build(), the `builder_` is set to nullptr. std::unique_ptr<systems::DiagramBuilder<T>> builder_; multibody::AddMultibodyPlantSceneGraphResult<T> pair_; multibody::MultibodyPlant<T>& plant_; geometry::SceneGraph<T>& scene_graph_; // The Parser object only exists when T == double. using MaybeParser = std::conditional_t<std::is_same_v<T, double>, multibody::Parser, void*>; MaybeParser parser_; }; } // namespace planning } // namespace drake DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::planning::RobotDiagramBuilder)
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/linear_distance_and_interpolation_provider.h
#pragma once #include <map> #include <vector> #include <Eigen/Core> #include "drake/multibody/plant/multibody_plant.h" #include "drake/planning/distance_and_interpolation_provider.h" namespace drake { namespace planning { /** This class represents a basic "linear" implementation of DistanceAndInterpolationProvider. - Configuration distance is computed as difference.cwiseProduct(weights).norm(), where difference is computed as the angle between quaternion DoF and difference between all other positions. Default weights are (1, 0, 0, 0) for quaternion DoF and 1 for all other positions. - Configuration interpolation is performed using slerp for quaternion DoF and linear interpolation for all other positions. */ class LinearDistanceAndInterpolationProvider final : public DistanceAndInterpolationProvider { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearDistanceAndInterpolationProvider); /** Constructs a LinearDistanceAndInterpolationProvider for the specified `plant` using the provided map of distance weights `joint_distance_weights` and default weights (i.e. 1) for all other positions. @pre all distance weights must be non-negative and finite. */ LinearDistanceAndInterpolationProvider( const multibody::MultibodyPlant<double>& plant, const std::map<multibody::JointIndex, Eigen::VectorXd>& joint_distance_weights); /** Constructs a LinearDistanceAndInterpolationProvider for the specified `plant` with the provided distance weights `distance_weights`. @pre distance_weights must be the same size as plant.num_positions(), all weights must be non-negative and finite, and weights for quaternion DoF must be of the form (weight, 0, 0, 0). */ LinearDistanceAndInterpolationProvider( const multibody::MultibodyPlant<double>& plant, const Eigen::VectorXd& distance_weights); /** Constructs a LinearDistanceAndInterpolationProvider for the specified `plant` with default distance weights (i.e. 1) for all positions. Equivalent to constructing with an empty map of named joint distance weights. */ explicit LinearDistanceAndInterpolationProvider( const multibody::MultibodyPlant<double>& plant); ~LinearDistanceAndInterpolationProvider() final; /** Gets the distance weights. */ const Eigen::VectorXd& distance_weights() const { return distance_weights_; } /** Gets the start indices for quaternion DoF in the position vector. */ const std::vector<int>& quaternion_dof_start_indices() const { return quaternion_dof_start_indices_; } private: double DoComputeConfigurationDistance(const Eigen::VectorXd& from, const Eigen::VectorXd& to) const final; Eigen::VectorXd DoInterpolateBetweenConfigurations( const Eigen::VectorXd& from, const Eigen::VectorXd& to, double ratio) const final; const std::vector<int> quaternion_dof_start_indices_; const Eigen::VectorXd distance_weights_; }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/collision_checker_context.h
#pragma once #include <memory> #include "drake/common/drake_copyable.h" #include "drake/planning/robot_diagram.h" namespace drake { namespace planning { /** This class represents the data necessary for CollisionChecker to operate safely across multiple threads in its `const` API. Instances of this class are owned and managed by a particular CollisionChecker. If using OMP to perform parallel const queries on a CollisionChecker, it will never be necessary to interact with %CollisionCheckerContext instances. Only if using some other threading paradigm will it be necessary to work with "stand alone" instances. See CollisionChecker's documentation for more details. In all cases, modifying context should happen through CollisionChecker::PerformOperationAgainstAllModelContexts(). Modifying the contained Drake Contexts directly is generally erroneous. @ingroup planning_collision_checker */ class CollisionCheckerContext { public: /** \name Does not allow copy, move, or assignment generally. Protected copy construction is enabled for sub-classes to use in their implementation of DoClone(). */ //@{ CollisionCheckerContext& operator=(const CollisionCheckerContext&) = delete; CollisionCheckerContext(CollisionCheckerContext&&) = delete; CollisionCheckerContext& operator=(CollisionCheckerContext&&) = delete; //@} /** The resulting object stores an alias to `model`; the passed model should have a lifetime greater than the constructed object. @pre model is not null. */ explicit CollisionCheckerContext(const RobotDiagram<double>* model); virtual ~CollisionCheckerContext(); std::unique_ptr<CollisionCheckerContext> Clone() const { return DoClone(); } /** Gets the contained model context. */ const systems::Context<double>& model_context() const { return *model_context_; } /** Gets the contained plant context. */ const systems::Context<double>& plant_context() const { return *plant_context_; } /** Gets the contained scene graph context. */ const systems::Context<double>& scene_graph_context() const { return *scene_graph_context_; } /** Gets the scene graph geometry query object. */ const geometry::QueryObject<double>& GetQueryObject() const; // TODO(SeanCurtis-TRI) Eliminate these public members that provide access to // mutable sub-contexts. /* (Internal use only) Gets the contained model context. */ systems::Context<double>& mutable_model_context() { return *model_context_; } /* (Internal use only) Gets the contained plant context. */ systems::Context<double>& mutable_plant_context() { return *plant_context_; } /* (Internal use only) Gets the contained scene graph context. */ systems::Context<double>& mutable_scene_graph_context() { return *scene_graph_context_; } protected: /** Derived classes can use this copy constructor to help implement their own DoClone() methods. */ CollisionCheckerContext(const CollisionCheckerContext& other); /** Allow derived context types to implement additional clone behavior. */ virtual std::unique_ptr<CollisionCheckerContext> DoClone() const; private: /* The resulting object stores an alias to `model`; the passed model should have a lifetime greater than the constructed object. */ CollisionCheckerContext( const RobotDiagram<double>* model, std::unique_ptr<systems::Context<double>> model_context); const RobotDiagram<double>& model_; std::unique_ptr<systems::Context<double>> model_context_; /* These are aliases into model_context_. */ systems::Context<double>* const plant_context_; systems::Context<double>* const scene_graph_context_; }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/planning_doxygen.h
/** @addtogroup planning @{ A collection of algorithms for finding configurations and/or trajectories of dynamical systems. Many planning algorithms make heavy use of @ref solvers::MathematicalProgram "MathematicalProgram" and the numerous @ref solver_evaluators. There are also some useful classes in @ref manipulation_systems. @defgroup planning_kinematics @defgroup planning_trajectory @defgroup planning_collision_checker @defgroup planning_infrastructure @} */ /** @addtogroup planning_kinematics Inverse kinematics @{ These algorithms help define configurations of dynamical systems based on inverse kinematics (IK). @} */ /** @addtogroup planning_trajectory Trajectories @{ These algorithms compute trajectories based on various criteria. @} */ /** @addtogroup planning_collision_checker Collision checking @{ The CollisionChecker interface provides a basis for performing distance queries on robots in environments for various planning problems (e.g., sampling planning). @} */ /** @addtogroup planning_infrastructure Convenience classes @{ Simplifications for managing @ref drake::systems::Diagram "Diagrams" containing @ref drake::multibody::MultibodyPlant "MultibodyPlant" and @ref drake::geometry::SceneGraph "SceneGraph" systems in planning tasks. @} */
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/scene_graph_collision_checker.cc
#include "drake/planning/scene_graph_collision_checker.h" #include <algorithm> #include <functional> #include <set> #include <utility> #include "drake/common/fmt_eigen.h" #include "drake/geometry/collision_filter_manager.h" #include "drake/geometry/geometry_instance.h" #include "drake/geometry/scene_graph.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/planning/robot_diagram.h" namespace drake { namespace planning { using Eigen::RowVectorXd; using Eigen::Vector3d; using geometry::CollisionFilterDeclaration; using geometry::FrameId; using geometry::GeometryId; using geometry::GeometryInstance; using geometry::GeometrySet; using geometry::QueryObject; using geometry::SceneGraph; using geometry::SceneGraphInspector; using geometry::Shape; using geometry::SignedDistancePair; using math::RigidTransform; using multibody::BodyIndex; using multibody::Frame; using multibody::JacobianWrtVariable; using multibody::MultibodyPlant; using multibody::RigidBody; using systems::Context; SceneGraphCollisionChecker::SceneGraphCollisionChecker( CollisionCheckerParams params) : CollisionChecker(std::move(params), true /* supports parallel */) { AllocateContexts(); // Enforce that all filters known to the collision checker are active in // SceneGraph, as CollisionChecker introduces additional filters that may not // already be present in SceneGraph (e.g. environment-environment body pairs). ApplyCollisionFiltersToSceneGraph(); } SceneGraphCollisionChecker::SceneGraphCollisionChecker( const SceneGraphCollisionChecker&) = default; std::unique_ptr<CollisionChecker> SceneGraphCollisionChecker::DoClone() const { // N.B. We cannot use make_unique due to private-only access. return std::unique_ptr<SceneGraphCollisionChecker>( new SceneGraphCollisionChecker(*this)); } void SceneGraphCollisionChecker::DoUpdateContextPositions( CollisionCheckerContext*) const { // No additional actions are required to update positions. } std::optional<GeometryId> SceneGraphCollisionChecker::DoAddCollisionShapeToBody( const std::string& group_name, const RigidBody<double>& bodyA, const Shape& shape, const RigidTransform<double>& X_AG) { const FrameId body_frame_id = plant().GetBodyFrameIdOrThrow(bodyA.index()); const GeometrySet bodyA_geometries = plant().CollectRegisteredGeometries(plant().GetBodiesWeldedTo(bodyA)); log()->debug("Adding shape (group: [{}]) to {} (FrameID {}) at X_AG =\n{}", group_name, bodyA.scoped_name(), body_frame_id, fmt_eigen(X_AG.GetAsMatrix4())); // The geometry instance template which will be copied into each per-thread // SceneGraph Context; the GeometryId will match across each thread this way. GeometryInstance geometry_template(X_AG, shape.Clone(), "temp"); geometry_template.set_name(fmt::format("Added collision geometry on {} ({})", bodyA.scoped_name(), geometry_template.id())); // Set proximity properties in order for this geometry to actually collide. geometry_template.set_proximity_properties({}); const auto operation = [&](const RobotDiagram<double>& model, CollisionCheckerContext* model_context) { auto& sg_context = model_context->mutable_scene_graph_context(); model.scene_graph().RegisterGeometry( &sg_context, model.plant().get_source_id().value(), body_frame_id, std::make_unique<GeometryInstance>(geometry_template)); }; PerformOperationAgainstAllModelContexts(operation); // Ensure that filters in SceneGraph cover the new geometry, including the // within-body filter for the new geometry. ApplyCollisionFiltersToSceneGraph(); return geometry_template.id(); } void SceneGraphCollisionChecker::RemoveAddedGeometries( const std::vector<CollisionChecker::AddedShape>& shapes) { const auto operation = [&shapes](const RobotDiagram<double>& model, CollisionCheckerContext* model_context) { for (const auto& checker_shape : shapes) { const GeometryId geometry_id = checker_shape.geometry_id; // Our public NVI wrapper logs "Removing geometries from group..." with // no indentation; we'll whitespace-indent our detail logging under it. log()->debug(" Removing geometry {}.", geometry_id); model.scene_graph().RemoveGeometry( &model_context->mutable_scene_graph_context(), model.plant().get_source_id().value(), geometry_id); } }; PerformOperationAgainstAllModelContexts(operation); } void SceneGraphCollisionChecker::UpdateCollisionFilters() { // Apply changes to the collision filters to SceneGraph. ApplyCollisionFiltersToSceneGraph(); } bool SceneGraphCollisionChecker::DoCheckContextConfigCollisionFree( const CollisionCheckerContext& model_context) const { const QueryObject<double>& query_object = model_context.GetQueryObject(); const SceneGraphInspector<double>& inspector = query_object.inspector(); const std::vector<SignedDistancePair<double>>& distance_pairs = query_object.ComputeSignedDistancePairwiseClosestPoints( GetLargestPadding()); for (const auto& distance_pair : distance_pairs) { // Get the bodies corresponding to the distance pair. const FrameId frame_id_A = inspector.GetFrameId(distance_pair.id_A); const FrameId frame_id_B = inspector.GetFrameId(distance_pair.id_B); const RigidBody<double>* body_A = plant().GetBodyFromFrameId(frame_id_A); const RigidBody<double>* body_B = plant().GetBodyFromFrameId(frame_id_B); DRAKE_THROW_UNLESS(body_A != nullptr); DRAKE_THROW_UNLESS(body_B != nullptr); // Enforce that our collision filters are consistent with query results. if (IsCollisionFilteredBetween(*body_A, *body_B)) { throw std::runtime_error(fmt::format( "Drake internal error at {}:{} in {}(): Collision between bodies [{}]" " and [{}] should already be filtered", __FILE__, __LINE__, __func__, body_A->scoped_name(), body_B->scoped_name())); } const bool body_A_part_of_robot = IsPartOfRobot(*body_A); const bool body_B_part_of_robot = IsPartOfRobot(*body_B); DRAKE_ASSERT(body_A_part_of_robot || body_B_part_of_robot); // What padding do we use? const double padding = GetPaddingBetween(*body_A, *body_B); if (distance_pair.distance <= padding) { if (body_A_part_of_robot && body_B_part_of_robot) { log()->trace("Self collision between bodies [{}] and [{}]", body_A->scoped_name(), body_B->scoped_name()); } else { log()->trace("Environment collision between bodies [{}] and [{}]", body_A->scoped_name(), body_B->scoped_name()); } return false; } } // No relevant collisions found. return true; } RobotClearance SceneGraphCollisionChecker::DoCalcContextRobotClearance( const CollisionCheckerContext& model_context, const double influence_distance) const { const Frame<double>& frame_W = plant().world_frame(); const Context<double>& plant_context = model_context.plant_context(); const QueryObject<double>& query_object = model_context.GetQueryObject(); // Compute the (sorted) list of SceneGraph distances. const double max_influence_distance = influence_distance + GetLargestPadding(); std::vector<SignedDistancePair<double>> signed_distance_pairs = query_object.ComputeSignedDistancePairwiseClosestPoints( max_influence_distance); std::sort(signed_distance_pairs.begin(), signed_distance_pairs.end(), [](const auto& item0, const auto& item1) { return (item0.id_A < item1.id_A) || ((item0.id_A == item1.id_A) && (item0.id_B < item1.id_B)); }); // For each signed distance pair we're computing ϕ and // ∂ϕ/∂qᵣ = ∂ϕ/∂p_BAᵀ⋅∂p_BA/∂qᵣ (as documented in RobotClearance). In this // code, they are dist, and ddist_dq = ddist_dp_BA * dp_BA_dq. // Temporary storage, reused each time though the loop. Matrix3X<double> dp_BA_dq(3, plant().num_positions()); Matrix3X<double> partial_temp(3, plant().num_positions()); RowVectorXd ddist_dq(plant().num_positions()); // Loop over the distances, converting to the robot clearance result. RobotClearance result(plant().num_positions()); result.Reserve(signed_distance_pairs.size()); for (const auto& signed_distance_pair : signed_distance_pairs) { const double unpadded_distance = signed_distance_pair.distance; DRAKE_ASSERT(unpadded_distance <= max_influence_distance); // Grab some nice, short names for the relevant data. const GeometryId geometry_id_A = signed_distance_pair.id_A; const GeometryId geometry_id_B = signed_distance_pair.id_B; const SceneGraphInspector<double>& inspector = query_object.inspector(); const FrameId frame_id_A = inspector.GetFrameId(geometry_id_A); const FrameId frame_id_B = inspector.GetFrameId(geometry_id_B); const RigidBody<double>* body_A_maybe = plant().GetBodyFromFrameId(frame_id_A); const RigidBody<double>* body_B_maybe = plant().GetBodyFromFrameId(frame_id_B); DRAKE_THROW_UNLESS(body_A_maybe != nullptr); DRAKE_THROW_UNLESS(body_B_maybe != nullptr); const RigidBody<double>& body_A = *body_A_maybe; const RigidBody<double>& body_B = *body_B_maybe; const Frame<double>& frame_A = body_A.body_frame(); const Frame<double>& frame_B = body_B.body_frame(); // Enforce that our collision filters are consistent with query results. if (IsCollisionFilteredBetween(body_A, body_B)) { throw std::runtime_error(fmt::format( "Drake internal error at {}:{} in {}(): Collision between bodies [{}]" " and [{}] should already be filtered", __FILE__, __LINE__, __func__, body_A.scoped_name(), body_B.scoped_name())); } // Adjust pair-specific padding, and skip now-unnecessary distances. // Two geometries must be >= padding apart to be treated as non-colliding. const double padding = GetPaddingBetween(body_A, body_B); const double distance = unpadded_distance - padding; if (distance > influence_distance) { continue; } // Classify the two bodies. const bool body_A_part_of_robot = IsPartOfRobot(body_A); const bool body_B_part_of_robot = IsPartOfRobot(body_B); DRAKE_ASSERT(body_A_part_of_robot || body_B_part_of_robot); const BodyIndex robot_index = body_A_part_of_robot ? body_A.index() : body_B.index(); const BodyIndex other_index = body_A_part_of_robot ? body_B.index() : body_A.index(); const RobotCollisionType collision_type = (body_A_part_of_robot && body_B_part_of_robot) ? RobotCollisionType::kSelfCollision : RobotCollisionType::kEnvironmentCollision; // Convert the witness points from geometry frame to body frame. (Note // that the monogram frame names are somewhat unhelpful here because // "A" and "B" are overloaded for frame points vs body points.) const Vector3d p_ACa = inspector.GetPoseInFrame(geometry_id_A) * signed_distance_pair.p_ACa; const Vector3d p_BCb = inspector.GetPoseInFrame(geometry_id_B) * signed_distance_pair.p_BCb; // Convert the witness points from body frame to world frame. // TODO(jwnimmer-tri) Instead of CalcPointsPositions, try either // RigidBody::EvalPoseInWorld or QueryObject::GetPoseInWorld. Vector3d p_WCa; plant().CalcPointsPositions(plant_context, frame_A, p_ACa, frame_W, &p_WCa); Vector3d p_WCb; plant().CalcPointsPositions(plant_context, frame_B, p_BCb, frame_W, &p_WCb); // Compute the spatial gradient of distance (expressed in the world). const Vector3d ddist_dp_BA = (distance > 0 ? 1 : -1) * (p_WCa - p_WCb).stableNormalized(); // We're computing ∂p_BA_W/∂qᵣ = ∂p_WA/∂qᵣ - ∂p_WB/∂qᵣ. Because we're // differentiating w.r.t. qᵣ, if either A or B is not a robot body, that // body's contribution goes to zero (and we skip computing that term as an // optimization). // // However, even with these zero terms, we are not necessarily returning // ∂ϕ/∂qᵣ. If either A or B has non-robot, movable bodies inboard of it, // our ∂p_BA_W/∂qᵣ may include additional non-zero columns; we rely on the // parent class to zero those columns out and make the result truly ∂ϕ/∂qᵣ. if (body_A_part_of_robot) { plant().CalcJacobianPositionVector( // BR plant_context, frame_A, p_ACa, frame_W, frame_W, // ∂p_WA/∂q after this invocation &dp_BA_dq); } else { dp_BA_dq.setZero(); } if (body_B_part_of_robot) { plant().CalcJacobianPositionVector( // BR plant_context, frame_B, p_BCb, frame_W, frame_W, // ∂p_WB/∂q &partial_temp); dp_BA_dq -= partial_temp; // ∂p_WA/∂qᵣ - ∂p_WB/∂qᵣ. } ddist_dq.noalias() = ddist_dp_BA.transpose() * dp_BA_dq; result.Append(robot_index, other_index, collision_type, distance, ddist_dq); } return result; } std::vector<RobotCollisionType> SceneGraphCollisionChecker::DoClassifyContextBodyCollisions( const CollisionCheckerContext& model_context) const { // Collision check to get colliding geometry. const QueryObject<double>& query_object = model_context.GetQueryObject(); const SceneGraphInspector<double>& inspector = query_object.inspector(); const std::vector<SignedDistancePair<double>>& distance_pairs = query_object.ComputeSignedDistancePairwiseClosestPoints( GetLargestPadding()); std::vector<RobotCollisionType> robot_collision_types( plant().num_bodies(), RobotCollisionType::kNoCollision); for (const auto& distance_pair : distance_pairs) { // Get the bodies corresponding to the distance pair. const FrameId frame_id_A = inspector.GetFrameId(distance_pair.id_A); const FrameId frame_id_B = inspector.GetFrameId(distance_pair.id_B); const RigidBody<double>* body_A = plant().GetBodyFromFrameId(frame_id_A); const RigidBody<double>* body_B = plant().GetBodyFromFrameId(frame_id_B); DRAKE_THROW_UNLESS(body_A != nullptr); DRAKE_THROW_UNLESS(body_B != nullptr); // Ignore distance pair involving allowed collisions. if (IsCollisionFilteredBetween(*body_A, *body_B)) { continue; } const bool body_A_part_of_robot = IsPartOfRobot(*body_A); const bool body_B_part_of_robot = IsPartOfRobot(*body_B); // What padding do we use? const double padding = GetPaddingBetween(*body_A, *body_B); if (distance_pair.distance <= padding) { if (body_A_part_of_robot && body_B_part_of_robot) { robot_collision_types.at(body_A->index()) = SetInSelfCollision(robot_collision_types.at(body_A->index()), true); robot_collision_types.at(body_B->index()) = SetInSelfCollision(robot_collision_types.at(body_B->index()), true); } else if (body_A_part_of_robot) { robot_collision_types.at(body_A->index()) = SetInEnvironmentCollision( robot_collision_types.at(body_A->index()), true); } else if (body_B_part_of_robot) { robot_collision_types.at(body_B->index()) = SetInEnvironmentCollision( robot_collision_types.at(body_B->index()), true); } } } return robot_collision_types; } int SceneGraphCollisionChecker::DoMaxContextNumDistances( const CollisionCheckerContext& model_context) const { const QueryObject<double>& query_object = model_context.GetQueryObject(); const SceneGraphInspector<double>& inspector = query_object.inspector(); // Maximum number of SignedDistancePairs returned by calls to // ComputeSignedDistancePairwiseClosestPoints(). const std::set<std::pair<GeometryId, GeometryId>>& collision_candidates = inspector.GetCollisionCandidates(); int valid_candidate_count = 0; for (const auto& candidate : collision_candidates) { const FrameId frame_id_A = inspector.GetFrameId(candidate.first); const FrameId frame_id_B = inspector.GetFrameId(candidate.second); const RigidBody<double>* body_A = plant().GetBodyFromFrameId(frame_id_A); const RigidBody<double>* body_B = plant().GetBodyFromFrameId(frame_id_B); DRAKE_THROW_UNLESS(body_A != nullptr); DRAKE_THROW_UNLESS(body_B != nullptr); if (IsPartOfRobot(*body_A) || IsPartOfRobot(*body_B)) { ++valid_candidate_count; } } return valid_candidate_count; } void SceneGraphCollisionChecker::ApplyCollisionFiltersToSceneGraph() { // Assemble the new collision filters. CollisionFilterDeclaration new_collision_filters; const int num_bodies = plant().num_bodies(); for (BodyIndex i(0); i < num_bodies; ++i) { const FrameId frame_i = plant().GetBodyFrameIdOrThrow(i); const GeometrySet geometries_i(frame_i); // Add within-body filter. new_collision_filters.ExcludeWithin(geometries_i); // Collect body-body filters. for (BodyIndex j(i + 1); j < num_bodies; ++j) { const FrameId frame_j = plant().GetBodyFrameIdOrThrow(j); const GeometrySet geometries_j(frame_j); if (IsCollisionFilteredBetween(i, j)) { new_collision_filters.ExcludeBetween(geometries_i, geometries_j); } else { new_collision_filters.AllowBetween(geometries_i, geometries_j); } } } // Apply the new collision filters to every context. const auto operation = [&new_collision_filters]( const RobotDiagram<double>& model, CollisionCheckerContext* model_context) { auto& sg_context = model_context->mutable_scene_graph_context(); model.scene_graph() .collision_filter_manager(&sg_context) .Apply(new_collision_filters); }; PerformOperationAgainstAllModelContexts(operation); } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/linear_distance_and_interpolation_provider.cc
#include "drake/planning/linear_distance_and_interpolation_provider.h" #include <stdexcept> #include <common_robotics_utilities/math.hpp> #include <fmt/format.h> #include "drake/common/drake_throw.h" #include "drake/multibody/tree/quaternion_floating_joint.h" namespace drake { namespace planning { using common_robotics_utilities::math::InterpolateXd; using multibody::BodyIndex; using multibody::Joint; using multibody::JointIndex; using multibody::MultibodyPlant; using multibody::QuaternionFloatingJoint; using multibody::RigidBody; namespace { std::vector<int> GetQuaternionDofStartIndices( const MultibodyPlant<double>& plant) { std::vector<int> quaternion_dof_start_indices; for (JointIndex joint_index(0); joint_index < plant.num_joints(); ++joint_index) { const Joint<double>& joint = plant.get_joint(joint_index); if (joint.type_name() == QuaternionFloatingJoint<double>::kTypeName) { quaternion_dof_start_indices.push_back(joint.position_start()); } } return quaternion_dof_start_indices; } Eigen::VectorXd GetDefaultDistanceWeights( int num_positions, const std::vector<int>& quaternion_dof_start_indices) { // The default weight for all joints is 1, except for quaternion DoF where // only the first weight may be non-zero. Eigen::VectorXd default_distance_weights = Eigen::VectorXd::Ones(num_positions); for (const int i : quaternion_dof_start_indices) { default_distance_weights.segment<4>(i) << 1.0, 0.0, 0.0, 0.0; } return default_distance_weights; } Eigen::VectorXd GetDistanceWeights( const MultibodyPlant<double>& plant, const std::vector<int>& quaternion_dof_start_indices, const std::map<JointIndex, Eigen::VectorXd>& joint_distance_weights) { // The default weight for all joints is 1, except for quaternion DoF where // only the first weight may be non-zero. Eigen::VectorXd distance_weights = GetDefaultDistanceWeights( plant.num_positions(), quaternion_dof_start_indices); for (const auto& [joint_index, joint_weights] : joint_distance_weights) { const Joint<double>& joint = plant.get_joint(joint_index); if (joint.num_positions() != joint_weights.size()) { throw std::runtime_error(fmt::format( "Provided distance weights for joint {} [{}] with type [{}] are [{}] " "which do not match that joint's num_positions {}", joint_index, joint.name(), joint.type_name(), fmt_eigen(joint_weights.transpose()), joint.num_positions())); } for (int i = 0; i < joint_weights.size(); ++i) { const double weight = joint_weights(i); if (!std::isfinite(weight) || weight < 0.0) { throw std::runtime_error(fmt::format( "Provided distance weights for joint {} [{}] are [{}] which are not" " non-negative and finite", joint_index, joint.name(), fmt_eigen(joint_weights.transpose()))); } } distance_weights.segment(joint.position_start(), joint.num_positions()) = joint_weights; } return distance_weights; } /* Checks that provided distance weights satisfy preconditions: - distance_weights.size() must match num_positions - all weights must be non-negative and finite - all quaternion DoF weights must be of the form (weight, 0, 0, 0) Returns distance_weights unchanged if preconditions are satisfied, throws otherwise. */ Eigen::VectorXd SanityCheckDistanceWeights( int num_positions, const std::vector<int>& quaternion_dof_start_indices, const Eigen::VectorXd& distance_weights) { if (num_positions != distance_weights.size()) { throw std::runtime_error(fmt::format( "Provided distance weights size {} does not match num_positions {}", distance_weights.size(), num_positions)); } // Every weight must be finite and >= 0. for (int i = 0; i < distance_weights.size(); ++i) { const double weight = distance_weights(i); if (!std::isfinite(weight)) { throw std::runtime_error( fmt::format("Provided distance weight {} with value {} is not finite", i, weight)); } if (weight < 0.0) { throw std::runtime_error(fmt::format( "Provided distance weight {} with value {} is less than zero", i, weight)); } } // Only the first weight for quaternion DoF may be non-zero. for (const int i : quaternion_dof_start_indices) { const double w_weight = distance_weights(i); const double x_weight = distance_weights(i + 1); const double y_weight = distance_weights(i + 2); const double z_weight = distance_weights(i + 3); if (x_weight != 0.0 || y_weight != 0.0 || z_weight != 0.0) { throw std::runtime_error(fmt::format( "Provided distance weights for quaternion dof starting at index {} " "with values ({}, {}, {}, {}) must be ({}, 0, 0, 0) instead", i, w_weight, x_weight, y_weight, z_weight, w_weight)); } } return distance_weights; } } // namespace LinearDistanceAndInterpolationProvider::LinearDistanceAndInterpolationProvider( const MultibodyPlant<double>& plant, const std::map<JointIndex, Eigen::VectorXd>& joint_distance_weights) : quaternion_dof_start_indices_(GetQuaternionDofStartIndices(plant)), distance_weights_(SanityCheckDistanceWeights( plant.num_positions(), quaternion_dof_start_indices_, GetDistanceWeights(plant, quaternion_dof_start_indices_, joint_distance_weights))) {} LinearDistanceAndInterpolationProvider::LinearDistanceAndInterpolationProvider( const MultibodyPlant<double>& plant, const Eigen::VectorXd& distance_weights) : quaternion_dof_start_indices_(GetQuaternionDofStartIndices(plant)), distance_weights_(SanityCheckDistanceWeights( plant.num_positions(), quaternion_dof_start_indices_, distance_weights)) {} LinearDistanceAndInterpolationProvider::LinearDistanceAndInterpolationProvider( const MultibodyPlant<double>& plant) : quaternion_dof_start_indices_(GetQuaternionDofStartIndices(plant)), distance_weights_(SanityCheckDistanceWeights( plant.num_positions(), quaternion_dof_start_indices_, GetDefaultDistanceWeights(plant.num_positions(), quaternion_dof_start_indices_))) {} LinearDistanceAndInterpolationProvider:: ~LinearDistanceAndInterpolationProvider() = default; double LinearDistanceAndInterpolationProvider::DoComputeConfigurationDistance( const Eigen::VectorXd& from, const Eigen::VectorXd& to) const { Eigen::VectorXd deltas = to - from; for (const int quat_dof_start_index : quaternion_dof_start_indices()) { const Eigen::Quaterniond from_quat(from.segment<4>(quat_dof_start_index)); const Eigen::Quaterniond to_quat(to.segment<4>(quat_dof_start_index)); const double quat_angle = from_quat.angularDistance(to_quat); deltas.segment<4>(quat_dof_start_index) << quat_angle, 0.0, 0.0, 0.0; } return deltas.cwiseProduct(distance_weights()).norm(); } Eigen::VectorXd LinearDistanceAndInterpolationProvider::DoInterpolateBetweenConfigurations( const Eigen::VectorXd& from, const Eigen::VectorXd& to, const double ratio) const { // Start with linear interpolation between from and to. Eigen::VectorXd interp = InterpolateXd(from, to, ratio); // Handle quaternion dof properly. for (const int quat_dof_start_index : quaternion_dof_start_indices()) { const Eigen::Quaterniond from_quat(from.segment<4>(quat_dof_start_index)); const Eigen::Quaterniond to_quat(to.segment<4>(quat_dof_start_index)); // Make sure interpolation always does shortest angle (<= 2pi) const Eigen::Quaterniond interp_quat = from_quat.slerp(ratio, to_quat); interp.segment<4>(quat_dof_start_index) = interp_quat.coeffs(); } return interp; } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/distance_and_interpolation_provider.cc
#include "drake/planning/distance_and_interpolation_provider.h" #include <cmath> #include "drake/common/drake_throw.h" namespace drake { namespace planning { DistanceAndInterpolationProvider::~DistanceAndInterpolationProvider() = default; double DistanceAndInterpolationProvider::ComputeConfigurationDistance( const Eigen::VectorXd& from, const Eigen::VectorXd& to) const { DRAKE_THROW_UNLESS(from.size() == to.size()); const double distance = DoComputeConfigurationDistance(from, to); DRAKE_THROW_UNLESS(distance >= 0.0); DRAKE_THROW_UNLESS(std::isfinite(distance)); return distance; } Eigen::VectorXd DistanceAndInterpolationProvider::InterpolateBetweenConfigurations( const Eigen::VectorXd& from, const Eigen::VectorXd& to, const double ratio) const { DRAKE_THROW_UNLESS(from.size() == to.size()); DRAKE_THROW_UNLESS(ratio >= 0.0); DRAKE_THROW_UNLESS(ratio <= 1.0); Eigen::VectorXd interpolated = DoInterpolateBetweenConfigurations(from, to, ratio); DRAKE_THROW_UNLESS(from.size() == interpolated.size()); return interpolated; } DistanceAndInterpolationProvider::DistanceAndInterpolationProvider() = default; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/collision_checker_context.cc
#include "drake/planning/collision_checker_context.h" #include <memory> #include <utility> namespace drake { namespace planning { using geometry::QueryObject; using std::unique_ptr; using systems::Context; namespace { template <typename T> T* NonNull(T* pointer) { DRAKE_DEMAND(pointer != nullptr); return pointer; } } // namespace CollisionCheckerContext::CollisionCheckerContext( const RobotDiagram<double>* model) : CollisionCheckerContext(NonNull(model), model->CreateDefaultContext()) {} CollisionCheckerContext::~CollisionCheckerContext() = default; const QueryObject<double>& CollisionCheckerContext::GetQueryObject() const { return model_.plant() .get_geometry_query_input_port() .template Eval<QueryObject<double>>(plant_context()); } CollisionCheckerContext::CollisionCheckerContext( const CollisionCheckerContext& other) : CollisionCheckerContext(&other.model_, other.model_context_->Clone()) {} unique_ptr<CollisionCheckerContext> CollisionCheckerContext::DoClone() const { return unique_ptr<CollisionCheckerContext>( new CollisionCheckerContext(*this)); } CollisionCheckerContext::CollisionCheckerContext( const RobotDiagram<double>* model, unique_ptr<Context<double>> model_context) : model_(*NonNull(model)), model_context_(std::move(model_context)), plant_context_(&model_.mutable_plant_context(model_context_.get())), scene_graph_context_( &model_.mutable_scene_graph_context(model_context_.get())) {} } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/distance_and_interpolation_provider.h
#pragma once #include <Eigen/Core> #include "drake/common/drake_copyable.h" namespace drake { namespace planning { /** This class represents the base interface for performing configuration distance and interpolation operations, used by CollisionChecker. See LinearDistanceAndInterpolationProvider for an implementation covering common "linear" distance and interpolation behavior. Configuration distance and interpolation are necessary for a CollisionChecker to perform edge collision checks, and an essential part of many motion planning problems. The C-spaces for many planning problems combine joints with widely differing effects (e.g. for a given angular change, the shoulder joint of a robot arm results in much more significant motion than the same change on a finger joint) or units (e.g. a mobile robot with translation in meters and yaw in radians). As a result, it is often necessary to weight elements of the configuration differently when computing configuration distance. Likewise, in more complex C-spaces, it may be necessary to perform more complex interpolation behavior (e.g. when planning for a mobile robot whose motion is modelled via Dubbins or Reeds-Shepp paths). Configuration distance takes two configurations of the robot, from and to, both as Eigen::VectorXd, and returns (potentially weighted) C-space distance as a double. The returned distance will be strictly non-negative. To be valid, distance must satisfy the following condition: - ComputeConfigurationDistance(q, q) ≡ 0 for values of q that are valid for the C-space in use. Configuration interpolation takes two configurations of the robot, from and to, both as Eigen::VectorXd, plus a ratio in [0, 1] and returns the interpolated configuration. To be valid, interpolation must satisfy the following conditions: - InterpolateBetweenConfigurations(from, to, 0) ≡ from - InterpolateBetweenConfigurations(from, to, 1) ≡ to - InterpolateBetweenConfigurations(q, q, ratio) ≡ q, for all ratio in [0, 1] for values of q, from, and to that are valid for the C-space in use.*/ class DistanceAndInterpolationProvider { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DistanceAndInterpolationProvider); virtual ~DistanceAndInterpolationProvider(); /** Computes the configuration distance from the provided configuration `from` to the provided configuration `to`. The returned distance will be strictly non-negative. @pre from.size() == to.size() */ double ComputeConfigurationDistance(const Eigen::VectorXd& from, const Eigen::VectorXd& to) const; /** Returns the interpolated configuration between `from` and `to` at `ratio`. @pre from.size() == to.size() @pre ratio in [0, 1] */ Eigen::VectorXd InterpolateBetweenConfigurations(const Eigen::VectorXd& from, const Eigen::VectorXd& to, double ratio) const; protected: DistanceAndInterpolationProvider(); /** Derived distance and interpolation providers must implement distance computation. The returned distance must be non-negative. DistanceAndInterpolationProvider ensures that `from` and `to` are the same size. */ virtual double DoComputeConfigurationDistance( const Eigen::VectorXd& from, const Eigen::VectorXd& to) const = 0; /** Derived distance and interpolation providers must implement interpolation. The returned configuration must be the same size as `from` and `to`. DistanceAndInterpolationProvider ensures that `from` and `to` are the same size and that `ratio` is in [0, 1]. */ virtual Eigen::VectorXd DoInterpolateBetweenConfigurations( const Eigen::VectorXd& from, const Eigen::VectorXd& to, double ratio) const = 0; }; } // namespace planning } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/planning/robot_diagram_builder.cc
#include "drake/planning/robot_diagram_builder.h" #include <stdexcept> #include <vector> #include "drake/common/drake_throw.h" namespace drake { namespace planning { using geometry::SceneGraph; using multibody::AddMultibodyPlantSceneGraph; using systems::DiagramBuilder; using systems::InputPort; using systems::InputPortIndex; using systems::OutputPort; using systems::OutputPortIndex; using systems::System; template <typename T> RobotDiagramBuilder<T>::RobotDiagramBuilder(double time_step) : builder_(std::make_unique<DiagramBuilder<T>>()), pair_(AddMultibodyPlantSceneGraph<T>(builder_.get(), time_step)), plant_(pair_.plant), scene_graph_(pair_.scene_graph), parser_(&plant_) {} template <typename T> RobotDiagramBuilder<T>::~RobotDiagramBuilder() = default; template <typename T> std::unique_ptr<RobotDiagram<T>> RobotDiagramBuilder<T>::Build() { ThrowIfAlreadyBuiltOrCorrupted(); if (!plant().is_finalized()) { plant().Finalize(); } // Unless the user has customized anything, by default it's convenient to // export everything. if (ShouldExportDefaultPorts()) { ExportDefaultPorts(); } return std::unique_ptr<RobotDiagram<T>>( new RobotDiagram<T>(std::move(builder_))); } template <typename T> bool RobotDiagramBuilder<T>::IsDiagramBuilt() const { if (builder_ == nullptr) { return true; } if (builder_->already_built()) { throw std::logic_error( "RobotDiagramBuilder: Do not call mutable_builder().Build() to create" " a Diagram; instead, call Build() to create a RobotDiagram."); } return false; } template <typename T> void RobotDiagramBuilder<T>::ThrowIfAlreadyBuiltOrCorrupted() const { if (IsDiagramBuilt()) { throw std::logic_error( "RobotDiagramBuilder: Build() has already been called to create a" " RobotDiagram; this RobotDiagramBuilder may no longer be used."); } // Check that the user didn't remove (delete) the plant or scene graph. std::vector<const System<T>*> systems = builder_->GetSystems(); const bool is_good = systems.size() >= 2 && systems[0] == &plant_ && systems[1] == &scene_graph_; if (!is_good) { throw std::logic_error( "RobotDiagramBuilder: The underlying DiagramBuilder has become " "corrupted. You must not remove the MultibodyPlant or SceneGraph."); } } /* Checks for whether or not the user has customized anything that would impact the default counts or names of exported ports. */ template <typename T> bool RobotDiagramBuilder<T>::ShouldExportDefaultPorts() const { return plant().get_name() == "plant" && scene_graph().get_name() == "scene_graph" && builder_->GetSystems().size() == 2 && builder_->num_input_ports() == 0 && builder_->num_output_ports() == 0; } template <typename T> void RobotDiagramBuilder<T>::ExportDefaultPorts() const { // Export ports per the contract in the RobotDiagram class overview. for (const System<T>* system : builder_->GetSystems()) { for (InputPortIndex i{0}; i < system->num_input_ports(); ++i) { if (system == &this->scene_graph()) { // Don't export any SceneGraph input ports. The fact that it has any // disconnected input ports is a bug that we'll paper over here. // TODO(jwnimmer-tri) We can (and should) remove this special case once // the deformable code resolves its messy "the configuration input port // is disconnected by default" status quo. break; // Skip all input ports. } const InputPort<T>& port = system->get_input_port(i); if (builder_->IsConnectedOrExported(port)) { // We can't export this input because it's internally-sourced already. continue; // Skip just this one input port. } builder_->ExportInput(port); } for (OutputPortIndex i{0}; i < system->num_output_ports(); ++i) { const OutputPort<T>& port = system->get_output_port(i); builder_->ExportOutput(port); } } } } // namespace planning } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::planning::RobotDiagramBuilder)
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/iris/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_googletest", "drake_cc_library", "drake_cc_package_library", ) load("//tools/skylark:test_tags.bzl", "gurobi_test_tags", "mosek_test_tags") package(default_visibility = ["//visibility:public"]) drake_cc_package_library( name = "iris", visibility = ["//visibility:public"], deps = [ ":iris_from_clique_cover", ], ) drake_cc_library( name = "iris_from_clique_cover", srcs = ["iris_from_clique_cover.cc"], hdrs = ["iris_from_clique_cover.h"], interface_deps = [ "//geometry/optimization:convex_set", "//geometry/optimization:iris", "//geometry:meshcat", "//planning/graph_algorithms:max_clique_solver_via_greedy", "//planning/graph_algorithms:max_clique_solver_base", "//solvers:gurobi_solver", "//solvers:mosek_solver", "//planning:scene_graph_collision_checker", "//planning:visibility_graph", ], deps = [ "@common_robotics_utilities", ], ) drake_cc_googletest( name = "iris_from_clique_cover_test", timeout = "moderate", data = [ "//examples/pendulum:models", "//multibody/parsing:test_models", ], # Running with multiple threads is an essential part of our test coverage. num_threads = 4, shard_count = 4, # Most of these tests take an exceptionally long time under # instrumentation, resulting in timeouts, and so are excluded. # These test also can only be run with either mosek or gurobi enabled. tags = [ "no_asan", "no_memcheck", # IPOPT is exceptionally slow with IRIS so only test with snopt. "snopt", ], deps = [ ":iris_from_clique_cover", "//common/test_utilities:expect_throws_message", "//common/test_utilities:maybe_pause_for_user", "//geometry/test_utilities:meshcat_environment", "//multibody/parsing:parser", "//planning:robot_diagram_builder", "//planning:scene_graph_collision_checker", "//planning/graph_algorithms:max_clique_solver_via_mip", "//systems/framework:diagram_builder", ], ) add_lint_tests()
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/iris/iris_from_clique_cover.h
#pragma once #include <algorithm> #include <memory> #include <optional> #include <vector> #include "drake/common/parallelism.h" #include "drake/geometry/meshcat.h" #include "drake/geometry/optimization/convex_set.h" #include "drake/geometry/optimization/hpolyhedron.h" #include "drake/geometry/optimization/iris.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/scene_graph_collision_checker.h" namespace drake { namespace planning { struct IrisFromCliqueCoverOptions { /** * The options used on internal calls to Iris. Currently, it is recommended * to only run Iris for one iteration when building from a clique so as to * avoid discarding the information gained from the clique. * * Note that `IrisOptions` can optionally include a meshcat instance to * provide debugging visualization. If this is provided `IrisFromCliqueCover` * will provide debug visualization in meshcat showing where in configuration * space it is drawing from. However, if the parallelism option is set to * allow more than 1 thread, then the debug visualizations of internal Iris * calls will be disabled. This is due to a limitation of drawing to meshcat * from outside the main thread. */ geometry::optimization::IrisOptions iris_options{.iteration_limit = 1}; /** * The fraction of the domain that must be covered before we terminate the * algorithm. */ double coverage_termination_threshold{0.7}; /** * The maximum number of iterations of the algorithm. */ int iteration_limit{100}; /** * The number of points to sample when testing coverage. */ int num_points_per_coverage_check{static_cast<int>(1e3)}; /** * The amount of parallelism to use. This algorithm makes heavy use of * parallelism at many points and thus it is highly recommended to set this to * the maximum tolerable parallelism. */ Parallelism parallelism{Parallelism::Max()}; /** * The minimum size of the cliques used to construct a region. If this is set * lower than the ambient dimension of the space we are trying to cover, then * this option will be overridden to be at least 1 + the ambient dimension. */ int minimum_clique_size{3}; /** * Number of points to sample when building visibilty cliques. If this option * is less than twice the minimum clique size, it will be overridden to be at * least twice the minimum clique size. If the algorithm ever fails to find a * single clique in a visibility round, then the number of points in a * visibility round will be doubled. */ int num_points_per_visibility_round{200}; /** * The rank tolerance used for computing the * MinimumVolumeCircumscribedEllipsoid of a clique. See * @MinimumVolumeCircumscribedEllipsoid. */ double rank_tol_for_minimum_volume_circumscribed_ellipsoid{1e-6}; /** * The tolerance used for checking whether a point is contained inside an * HPolyhedron. See @ConvexSet::PointInSet. */ double point_in_set_tol{1e-6}; // TODO(AlexandreAmice): Implement a constructor/option that automatically // sets up the ILP solver and selects MaxCliqueViaMip }; /** * Cover the configuration space in Iris regions using the Visibility Clique * Cover Algorithm as described in * * P. Werner, A. Amice, T. Marcucci, D. Rus, R. Tedrake "Approximating Robot * Configuration Spaces with few Convex Sets using Clique Covers of Visibility * Graphs" In 2024 IEEE Internation Conference on Robotics and Automation. * https://arxiv.org/abs/2310.02875 * * @param checker The collision checker containing the plant and its associated * scene_graph. * @param generator There are points in the algorithm requiring randomness. The * generator controls this source of randomness. * @param sets [in/out] initial sets covering the space (potentially empty). * The cover is written into this vector. * @param max_clique_solver The min clique cover problem is approximatley solved * by repeatedly solving max clique on the uncovered graph and adding this * largest clique to the cover. The max clique problem is solved by this solver. * If parallelism is set to allow more than 1 thread, then the solver **must** * be implemented in C++. * * If nullptr is passed as the `max_clique_solver`, then max clique will be * solved using an instance of MaxCliqueSolverViaGreedy, which is a fast * heuristic. If higher quality cliques are desired, consider changing the * solver to an instance of MaxCliqueSolverViaMip. Currently, the padding in the * collision checker is not forwarded to the algorithm, and therefore the final * regions do not necessarily respect this padding. Effectively, this means that * the regions are generated as if the padding is set to 0. This behavior may be * adjusted in the future at the resolution of #18830. * * Note that MaxCliqueSolverViaMip requires the availability of a * Mixed-Integer Linear Programming solver (e.g. Gurobi and/or Mosek). We * recommend enabling those solvers if possible because they produce higher * quality cliques (https://drake.mit.edu/bazel.html#proprietary_solvers). The * method will throw if @p max_clique_solver cannot solve the max clique * problem. */ void IrisInConfigurationSpaceFromCliqueCover( const CollisionChecker& checker, const IrisFromCliqueCoverOptions& options, RandomGenerator* generator, std::vector<geometry::optimization::HPolyhedron>* sets, const planning::graph_algorithms::MaxCliqueSolverBase* max_clique_solver = nullptr); } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/iris/iris_from_clique_cover.cc
#include "drake/planning/iris/iris_from_clique_cover.h" #include <algorithm> #include <atomic> #include <condition_variable> #include <future> #include <limits> #include <mutex> #include <queue> #include <string> #include <thread> #include <utility> #include <common_robotics_utilities/parallelism.hpp> #include "drake/common/ssize.h" #include "drake/geometry/optimization/iris.h" #include "drake/planning/collision_checker.h" #include "drake/planning/scene_graph_collision_checker.h" #include "drake/planning/visibility_graph.h" #include "drake/solvers/gurobi_solver.h" #include "drake/solvers/mosek_solver.h" #include "drake/solvers/solver_options.h" namespace drake { namespace planning { using common_robotics_utilities::parallelism::DegreeOfParallelism; using common_robotics_utilities::parallelism::ParallelForBackend; using common_robotics_utilities::parallelism::StaticParallelForIndexLoop; using Eigen::SparseMatrix; using geometry::Meshcat; using geometry::Rgba; using geometry::Sphere; using geometry::optimization::HPolyhedron; using geometry::optimization::Hyperellipsoid; using geometry::optimization::IrisInConfigurationSpace; using geometry::optimization::IrisOptions; using graph_algorithms::MaxCliqueSolverBase; using math::RigidTransform; namespace { // A very simple implementation of a thread-safe asynchronous queue for use when // exactly one thread fills the queue while one or more threads empty the // queue. // // When the producer pushes onto the queue, they automatically signal to the // consumers that a job is available. When the producer thread is done filling // the queue, they signal this via the done_filling() method. i.e the producer // code should be similar to: // while(true) { // queue.push(do_work(..)); // if(done) { // queue.done_filling(); // break; // } // } // // Consumers threads should be implemented as: // T elt; // while(queue.pop(elt)) { // do_work(...) // } // The loop will exit when: // * The producer thread has both signalled that no more jobs are being // created. // * The underlying queue is completely empty. // Note that this loop will not poll the pop method unnecessarily, as if // the queue is filling, pop will wait until a job is available. template <typename T> class AsyncQueue { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(AsyncQueue); AsyncQueue() : queue_{}, mutex_{}, condition_{}, still_filling_{true} {}; void push(const T& value) { DRAKE_THROW_UNLESS(still_filling_); std::unique_lock<std::mutex> lock(mutex_); queue_.push(value); condition_.notify_one(); } // A modification of the pop method which acquires an element of type T if the // queue is non-empty. If the queue is empty, but still filling, then pop will // wait until an element becomes available. If the queue is empty and done // filling, this method will return nullopt. std::optional<T> pop() { std::unique_lock<std::mutex> lock(mutex_); condition_.wait(lock, [this] { return !queue_.empty() || !still_filling_; }); if (!queue_.empty()) { const T ret = queue_.front(); queue_.pop(); return ret; } return std::nullopt; } // Signal that the producer thread will stop producing jobs. void done_filling() { still_filling_ = false; condition_.notify_all(); } int size() const { // We need to lock the mutex since the queue size is not necessarily atomic. std::unique_lock<std::mutex> lock(mutex_); return queue_.size(); } private: std::queue<T> queue_; mutable std::mutex mutex_; std::condition_variable condition_; std::atomic<bool> still_filling_ = true; }; // Sets mat(i, :) and mat(:, i) to false if mask(i) is true. void MakeFalseRowsAndColumns(const VectorX<bool>& mask, SparseMatrix<bool>* mat) { for (int j = 0; j < mat->outerSize(); ++j) { if (mask[j]) { for (SparseMatrix<bool>::InnerIterator it(*mat, j); it; ++it) { if (mask[it.index()]) { it.valueRef() = false; } } } } *mat = mat->pruned(); } // Computes the largest clique in the graph represented by @p adjacency_matrix // and adds this largest clique to @p computed_cliques. This clique is then // removed from the adjacency matrix, and a new maximal clique is computed. // This process continues until no clique of size @p minimum_clique can be // found. At this point, the queue calls done_filling() so that downstream // workers know to expect no more cliques. // // Note: The adjacency matrix will be mutated by this method and will be mostly // useless after this method is called. void ComputeGreedyTruncatedCliqueCover( const int minimum_clique_size, const graph_algorithms::MaxCliqueSolverBase& max_clique_solver, SparseMatrix<bool>* adjacency_matrix, AsyncQueue<VectorX<bool>>* computed_cliques) { int last_clique_size = std::numeric_limits<int>::max(); int num_cliques = 0; int num_points_left = adjacency_matrix->cols(); const int num_points_original = adjacency_matrix->cols(); while (last_clique_size > minimum_clique_size && num_points_left > minimum_clique_size) { const VectorX<bool> max_clique = max_clique_solver.SolveMaxClique(*adjacency_matrix); last_clique_size = max_clique.template cast<int>().sum(); log()->debug("Last Clique Size = {}", last_clique_size); num_points_left -= last_clique_size; if (last_clique_size >= minimum_clique_size) { computed_cliques->push(max_clique); ++num_cliques; MakeFalseRowsAndColumns(max_clique, adjacency_matrix); log()->info( "Clique added to queue. There are {}/{} points left to cover.", num_points_left, num_points_original); } } // This line signals to the IRIS workers that no further cliques will be added // to the queue. Removing this line will cause an infinite loop. computed_cliques->done_filling(); log()->info( "Finished adding cliques. Total of {} clique added. Number of cliques " "left to process = {}", num_cliques, computed_cliques->size()); } // Pulls cliques from @p computed_cliques and constructs IRIS regions using the // provided IrisOptions, but seeding IRIS with the minimum circumscribed // ellipse of the clique. As this method may run in a separate thread, we // provide an option to forcefully disable meshcat in IRIS. This must happen as // meshcat cannot be written to outside the main thread. std::queue<HPolyhedron> IrisWorker( const CollisionChecker& checker, const Eigen::Ref<const Eigen::MatrixXd>& points, const int builder_id, const IrisFromCliqueCoverOptions& options, AsyncQueue<VectorX<bool>>* computed_cliques, bool disable_meshcat = true) { // Copy the IrisOptions as we will change the value of the starting ellipse // in this worker. IrisOptions iris_options = options.iris_options; // Disable the IRIS meshcat option in this worker since we cannot write to // meshcat from a different thread. if (disable_meshcat) { iris_options.meshcat = nullptr; } std::queue<HPolyhedron> ret{}; std::optional<VectorX<bool>> current_clique = computed_cliques->pop(); while (current_clique.has_value()) { const int clique_size = current_clique->template cast<int>().sum(); Eigen::MatrixXd clique_points(points.rows(), clique_size); int clique_col = 0; for (int i = 0; i < ssize(current_clique.value()); ++i) { if (current_clique.value()(i)) { clique_points.col(clique_col) = points.col(i); ++clique_col; } } Hyperellipsoid clique_ellipse; try { clique_ellipse = Hyperellipsoid::MinimumVolumeCircumscribedEllipsoid( clique_points, options.rank_tol_for_minimum_volume_circumscribed_ellipsoid); } catch (const std::runtime_error& e) { log()->info( "Iris builder thread {} failed to compute an ellipse for a clique.", builder_id, e.what()); current_clique = computed_cliques->pop(); continue; } if (checker.CheckConfigCollisionFree(clique_ellipse.center(), builder_id)) { iris_options.starting_ellipse = clique_ellipse; } else { // Find the nearest clique member to the center that is not in collision. Eigen::Index nearest_point_col; (clique_points - clique_ellipse.center()) .colwise() .norm() .minCoeff(&nearest_point_col); Eigen::VectorXd center = clique_points.col(nearest_point_col); iris_options.starting_ellipse = Hyperellipsoid(center, clique_ellipse.A()); } checker.UpdatePositions(iris_options.starting_ellipse->center(), builder_id); log()->debug("Iris builder thread {} is constructing a set.", builder_id); ret.emplace(IrisInConfigurationSpace( checker.plant(), checker.plant_context(builder_id), iris_options)); log()->debug("Iris builder thread {} has constructed a set.", builder_id); current_clique = computed_cliques->pop(); } log()->debug("Iris builder thread {} has completed.", builder_id); return ret; } int ComputeMaxNumberOfCliquesInGreedyCliqueCover( const int num_vertices, const int minimum_clique_size) { // From "Restricted greedy clique decompositions and greedy clique // decompositions of K 4-free graphs" by Sean McGuinness, we have that the // most cliques that we could obtain from the greedy truncated clique // cover is the number of edges in the Turan graph T(num_vertices, // minimum_clique_size). This number is // 0.5* (1−1/r) * (num_vertices² − s²) + (s choose 2) // Where num_vertices= q*minimum_clique_size+s const int q = std::floor(num_vertices / minimum_clique_size); const int s = num_vertices - q * minimum_clique_size; return static_cast<int>((1 - 1.0 / minimum_clique_size) * (num_vertices * num_vertices - s * s) / 2 + (s * (s + 1)) / 2); } // Approximately compute the fraction of `domain` covered by `sets` by sampling // points uniformly at random in `domain` and checking whether the point lies in // one of the sets in `sets`. // // The `generator` is used as the source of randomness for drawing points from // domain. // // The sampled points are checked for inclusion in `sets` in parallel, with the // degree of parallelism determined by `parallelism`. // // The value of `last_polytope_sample` is used to initialize the distribution // over the domain. The value of the final sample is written to this vector so // that the MCMC sampling can continue. See @HPolyhedron for details. double ApproximatelyComputeCoverage( const HPolyhedron& domain, const std::vector<HPolyhedron>& sets, const CollisionChecker& checker, const int num_samples, const double point_in_set_tol, const Parallelism& parallelism, RandomGenerator* generator, Eigen::VectorXd* last_polytope_sample) { double fraction_covered = 0.0; if (sets.empty()) { log()->info("Current Fraction of Domain Covered = 0"); // Fail fast if there is nothing to check. return 0.0; } Eigen::MatrixXd sampled_points(domain.ambient_dimension(), num_samples); for (int i = 0; i < sampled_points.cols(); ++i) { do { *last_polytope_sample = domain.UniformSample(generator, *last_polytope_sample); } while (!checker.CheckConfigCollisionFree(*last_polytope_sample)); sampled_points.col(i) = *last_polytope_sample; } std::atomic<int> num_in_sets{0}; const auto point_in_cover = [&sets, &num_in_sets, &sampled_points, &point_in_set_tol](const int thread_num, const int i) { unused(thread_num); for (const auto& set : sets) { if (set.PointInSet(sampled_points.col(i), point_in_set_tol)) { num_in_sets.fetch_add(1); break; } } }; StaticParallelForIndexLoop(DegreeOfParallelism(parallelism.num_threads()), 0, sampled_points.cols(), point_in_cover, ParallelForBackend::BEST_AVAILABLE); fraction_covered = static_cast<double>(num_in_sets.load()) / num_samples; log()->info("Current Fraction of Domain Covered = {}", fraction_covered); return fraction_covered; } std::unique_ptr<planning::graph_algorithms::MaxCliqueSolverBase> MakeDefaultMaxCliqueSolver() { return std::unique_ptr<planning::graph_algorithms::MaxCliqueSolverBase>( new planning::graph_algorithms::MaxCliqueSolverViaGreedy()); } } // namespace void IrisInConfigurationSpaceFromCliqueCover( const CollisionChecker& checker, const IrisFromCliqueCoverOptions& options, RandomGenerator* generator, std::vector<HPolyhedron>* sets, const planning::graph_algorithms::MaxCliqueSolverBase* max_clique_solver_ptr) { DRAKE_THROW_UNLESS(options.coverage_termination_threshold > 0); DRAKE_THROW_UNLESS(options.iteration_limit > 0); // Note: Even though the iris_options.bounding_region may be provided, // IrisInConfigurationSpace (currently) requires finite joint limits. DRAKE_THROW_UNLESS( checker.plant().GetPositionLowerLimits().array().isFinite().all()); DRAKE_THROW_UNLESS( checker.plant().GetPositionUpperLimits().array().isFinite().all()); const HPolyhedron domain = options.iris_options.bounding_region.value_or( HPolyhedron::MakeBox(checker.plant().GetPositionLowerLimits(), checker.plant().GetPositionUpperLimits())); DRAKE_THROW_UNLESS(domain.ambient_dimension() == checker.plant().num_positions()); Eigen::VectorXd last_polytope_sample = domain.UniformSample(generator); // Override options which are set too aggressively. const int minimum_clique_size = std::max(options.minimum_clique_size, checker.plant().num_positions() + 1); int num_points_per_visibility_round = std::max( options.num_points_per_visibility_round, 2 * minimum_clique_size); Parallelism max_collision_checker_parallelism{std::min( options.parallelism.num_threads(), checker.num_allocated_contexts())}; log()->debug("Visibility Graph will use {} threads", max_collision_checker_parallelism.num_threads()); int num_iterations = 0; std::vector<HPolyhedron> visibility_graph_sets; std::unique_ptr<planning::graph_algorithms::MaxCliqueSolverBase> default_max_clique_solver; // Only construct the default solver if max_clique_solver is null. if (max_clique_solver_ptr == nullptr) { default_max_clique_solver = MakeDefaultMaxCliqueSolver(); log()->info("Using default max clique solver MaxCliqueSolverViaGreedy."); } const planning::graph_algorithms::MaxCliqueSolverBase* max_clique_solver = max_clique_solver_ptr == nullptr ? default_max_clique_solver.get() : max_clique_solver_ptr; auto approximate_coverage = [&]() { return ApproximatelyComputeCoverage( domain, *sets, checker, options.num_points_per_coverage_check, options.point_in_set_tol, options.parallelism, generator, &last_polytope_sample); }; while (approximate_coverage() < options.coverage_termination_threshold && num_iterations < options.iteration_limit) { log()->info("IrisFromCliqueCover Iteration {}/{}", num_iterations + 1, options.iteration_limit); Eigen::MatrixXd points(domain.ambient_dimension(), num_points_per_visibility_round); for (int i = 0; i < points.cols(); ++i) { do { last_polytope_sample = domain.UniformSample(generator, last_polytope_sample); } while ( // While the last polytope sample is in collision. !checker.CheckConfigCollisionFree(last_polytope_sample) || // While the last polytope sample is in any of the sets. std::any_of(sets->begin(), sets->end(), [&last_polytope_sample](const HPolyhedron& set) -> bool { return set.PointInSet(last_polytope_sample); })); points.col(i) = last_polytope_sample; } // Show the samples used in build cliques. Debugging visualization. if (options.iris_options.meshcat && domain.ambient_dimension() <= 3) { Eigen::Vector3d point_to_draw = Eigen::Vector3d::Zero(); for (int pt_to_draw = 0; pt_to_draw < points.cols(); ++pt_to_draw) { std::string path = fmt::format("iteration{:02}/sample_{:03}", num_iterations, pt_to_draw); options.iris_options.meshcat->SetObject( path, Sphere(0.01), geometry::Rgba(1, 0.1, 0.1, 1.0)); point_to_draw.head(domain.ambient_dimension()) = points.col(pt_to_draw); options.iris_options.meshcat->SetTransform( path, RigidTransform<double>(point_to_draw)); } } Eigen::SparseMatrix<bool> visibility_graph = VisibilityGraph(checker, points, max_collision_checker_parallelism); // Reserve more space for the newly built sets. Typically, we won't get // this worst case number of new cliques, so we only reserve half of the // worst case. sets->reserve(sets->size() + ComputeMaxNumberOfCliquesInGreedyCliqueCover( visibility_graph.cols(), minimum_clique_size) / 2); // Now solve the max clique cover and build new sets. int num_new_sets{0}; // The computed cliques from the max clique solver. These will get pulled // off the queue by the set builder workers to build the sets. AsyncQueue<VectorX<bool>> computed_cliques; if (options.parallelism.num_threads() == 1) { ComputeGreedyTruncatedCliqueCover(minimum_clique_size, *max_clique_solver, &visibility_graph, &computed_cliques); std::queue<HPolyhedron> new_set_queue = IrisWorker(checker, points, 0, options, &computed_cliques, false /* No need to disable meshcat */); while (!new_set_queue.empty()) { sets->push_back(std::move(new_set_queue.front())); new_set_queue.pop(); ++num_new_sets; } } else { // Compute truncated clique cover. std::future<void> clique_future{ std::async(std::launch::async, ComputeGreedyTruncatedCliqueCover, minimum_clique_size, std::ref(*max_clique_solver), &visibility_graph, &computed_cliques)}; // We will use one thread to build cliques and the remaining threads to // build IRIS regions. If this number is 0, then this function will end up // single threaded. const int num_builder_threads = options.parallelism.num_threads() - 1; std::vector<std::future<std::queue<HPolyhedron>>> build_sets_future; build_sets_future.reserve(num_builder_threads); // Build convex sets. for (int i = 0; i < num_builder_threads; ++i) { build_sets_future.emplace_back( std::async(std::launch::async, IrisWorker, std::ref(checker), points, i, std::ref(options), &computed_cliques, // NOLINTNEXTLINE true /* Disable meshcat since IRIS runs outside the main thread */)); } // The clique cover and the convex sets are computed asynchronously. Wait // for all the threads to join and then add the new sets to built sets. clique_future.get(); for (auto& new_set_queue_future : build_sets_future) { std::queue<HPolyhedron> new_set_queue{new_set_queue_future.get()}; while (!new_set_queue.empty()) { sets->push_back(std::move(new_set_queue.front())); new_set_queue.pop(); ++num_new_sets; } } } log()->info( "{} new sets added in IrisFromCliqueCover at iteration {}. Total sets " "= {}", num_new_sets, num_iterations, ssize(*sets)); if (num_new_sets == 0) { num_points_per_visibility_round *= 2; } ++num_iterations; } } } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning/iris
/home/johnshepherd/drake/planning/iris/test/iris_from_clique_cover_test.cc
#include "drake/planning/iris/iris_from_clique_cover.h" #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/common/ssize.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/test_utilities/maybe_pause_for_user.h" #include "drake/geometry/optimization/hpolyhedron.h" #include "drake/geometry/optimization/hyperrectangle.h" #include "drake/geometry/optimization/vpolytope.h" #include "drake/geometry/test_utilities/meshcat_environment.h" #include "drake/multibody/parsing/parser.h" #include "drake/planning/graph_algorithms/max_clique_solver_via_mip.h" #include "drake/planning/robot_diagram_builder.h" #include "drake/planning/scene_graph_collision_checker.h" #include "drake/solvers/gurobi_solver.h" #include "drake/solvers/mosek_solver.h" #include "drake/solvers/solver_options.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace planning { namespace { using common::MaybePauseForUser; using Eigen::Vector2d; using geometry::Meshcat; using geometry::Rgba; using geometry::optimization::ConvexSets; using geometry::optimization::HPolyhedron; using geometry::optimization::Hyperrectangle; using geometry::optimization::IrisOptions; using geometry::optimization::VPolytope; // Draw a two dimensional polytope in meshcat. void Draw2dVPolytope(const VPolytope& polytope, const std::string& meshcat_name, const Eigen::Ref<const Eigen::Vector3d>& color, std::shared_ptr<Meshcat> meshcat) { DRAKE_THROW_UNLESS(polytope.ambient_dimension() == 2); Eigen::Matrix3Xd points = Eigen::Matrix3Xd::Zero(3, polytope.vertices().cols() + 1); points.topLeftCorner(2, polytope.vertices().cols()) = polytope.vertices(); points.topRightCorner(2, 1) = polytope.vertices().col(0); points.bottomRows<1>().setZero(); meshcat->SetLine(meshcat_name, points, 2.0, Rgba(color(0), color(1), color(2))); } GTEST_TEST(IrisInConfigurationSpaceFromCliqueCover, TestIrisFromCliqueCoverOptions) { IrisFromCliqueCoverOptions options; EXPECT_EQ(options.iris_options.iteration_limit, 1); options.iris_options.iteration_limit = 100; EXPECT_EQ(options.iris_options.iteration_limit, 100); EXPECT_EQ(options.coverage_termination_threshold, 0.7); options.coverage_termination_threshold = 0.1; EXPECT_EQ(options.coverage_termination_threshold, 0.1); EXPECT_EQ(options.iteration_limit, 100); options.iteration_limit = 10; EXPECT_EQ(options.iteration_limit, 10); EXPECT_EQ(options.num_points_per_coverage_check, 1000); options.num_points_per_coverage_check = 10; EXPECT_EQ(options.num_points_per_coverage_check, 10); EXPECT_EQ(options.parallelism.num_threads(), Parallelism::Max().num_threads()); options.parallelism = Parallelism{100}; EXPECT_EQ(options.parallelism.num_threads(), 100); EXPECT_EQ(options.minimum_clique_size, 3); options.minimum_clique_size = 5; EXPECT_EQ(options.minimum_clique_size, 5); EXPECT_EQ(options.num_points_per_visibility_round, 200); options.num_points_per_visibility_round = 10; EXPECT_EQ(options.num_points_per_visibility_round, 10); EXPECT_EQ(options.rank_tol_for_minimum_volume_circumscribed_ellipsoid, 1e-6); options.rank_tol_for_minimum_volume_circumscribed_ellipsoid = 1e-3; EXPECT_EQ(options.rank_tol_for_minimum_volume_circumscribed_ellipsoid, 1e-3); EXPECT_EQ(options.point_in_set_tol, 1e-6); options.point_in_set_tol = 1e-3; EXPECT_EQ(options.point_in_set_tol, 1e-3); } /* A movable sphere in a box. ┌───────────────┐ │ │ │ │ │ │ │ o │ │ │ │ │ │ │ └───────────────┘ */ const char free_box[] = R"""( <robot name="boxes"> <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> )"""; // Test that we get perfect coverage GTEST_TEST(IrisInConfigurationSpaceFromCliqueCover, BoxConfigurationSpaceTest) { CollisionCheckerParams params; RobotDiagramBuilder<double> builder(0.0); params.robot_model_instances = builder.parser().AddModelsFromString(free_box, "urdf"); params.edge_step_size = 0.01; params.model = builder.Build(); auto checker = std::make_unique<SceneGraphCollisionChecker>(std::move(params)); IrisFromCliqueCoverOptions options; options.num_points_per_coverage_check = 100; options.num_points_per_visibility_round = 20; options.iteration_limit = 1; // Set a large bounding region to test the path where this is set in the // IrisOptions. options.iris_options.bounding_region = HPolyhedron::MakeBox(Eigen::Vector2d{-2, -2}, Eigen::Vector2d{2, 2}); // Run this test without parallelism to test that no bugs occur in the // non-parallel version. options.parallelism = Parallelism{1}; std::vector<HPolyhedron> sets; RandomGenerator generator(0); // This checks that errors in finding the minimum volume circumscribed // ellipsoid do not lead to an infinite loop or program crash. Setting this // tolerance very high has the effect of rejecting every clique as being in an // affine subspace. options.rank_tol_for_minimum_volume_circumscribed_ellipsoid = 1e10; IrisInConfigurationSpaceFromCliqueCover(*checker, options, &generator, &sets, nullptr); EXPECT_EQ(ssize(sets), 0); // Reverting to normal settings. options.rank_tol_for_minimum_volume_circumscribed_ellipsoid = 1e-6; // Checking that the adversarial setting of 1 point visibility graphs gets // overridden and correctly increases the number of samples. The result should // be perfect coverage in a single polytope. options.num_points_per_visibility_round = 1; IrisInConfigurationSpaceFromCliqueCover(*checker, options, &generator, &sets, nullptr); EXPECT_EQ(ssize(sets), 1); // expect perfect coverage VPolytope vpoly(sets.at(0)); EXPECT_EQ(vpoly.CalcVolume(), 16.0); } // Plants that don't have joint limits get a reasonable error message. GTEST_TEST(IrisInConfigurationSpaceFromCliqueCover, NoJointLimits) { CollisionCheckerParams params; RobotDiagramBuilder<double> builder(0.0); params.robot_model_instances = builder.parser().AddModelsFromUrl( "package://drake/examples/pendulum/Pendulum.urdf"); params.edge_step_size = 0.01; params.model = builder.Build(); auto checker = std::make_unique<SceneGraphCollisionChecker>(std::move(params)); IrisFromCliqueCoverOptions options; std::vector<HPolyhedron> sets; RandomGenerator generator(0); DRAKE_EXPECT_THROWS_MESSAGE( IrisInConfigurationSpaceFromCliqueCover(*checker, options, &generator, &sets, nullptr), ".*.GetPositionLowerLimits.*isFinite.* failed."); } /* A movable sphere with fixed boxes in all corners. ┌───────────────┐ │┌────┐ ┌────┐│ ││ │ │ ││ │└────┘ └────┘│ │ o │ │┌────┐ ┌────┐│ ││ │ │ ││ │└────┘ └────┘│ └───────────────┘ */ const char boxes_in_corners[] = R"""( <robot name="boxes"> <link name="fixed"> <collision name="top_left"> <origin rpy="0 0 0" xyz="-1 1 0"/> <geometry><box size="1.4 1.4 1.4"/></geometry> </collision> <collision name="top_right"> <origin rpy="0 0 0" xyz="1 1 0"/> <geometry><box size="1.4 1.4 1.4"/></geometry> </collision> <collision name="bottom_left"> <origin rpy="0 0 0" xyz="-1 -1 0"/> <geometry><box size="1.4 1.4 1.4"/></geometry> </collision> <collision name="bottom_right"> <origin rpy="0 0 0" xyz="1 -1 0"/> <geometry><box size="1.4 1.4 1.4"/></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.01"/></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> )"""; class IrisInConfigurationSpaceFromCliqueCoverTestFixture : public ::testing::Test { protected: void SetUp() override { params = CollisionCheckerParams(); meshcat = geometry::GetTestEnvironmentMeshcat(); meshcat->Delete("/drake"); meshcat->Set2dRenderMode(math::RigidTransformd(Eigen::Vector3d{0, 0, 1}), -3.25, 3.25, -3.25, 3.25); meshcat->SetProperty("/Grid", "visible", true); // Draw the true cspace. Eigen::Matrix3Xd env_points(3, 5); // clang-format off env_points << -2, 2, 2, -2, -2, 2, 2, -2, -2, 2, 0, 0, 0, 0, 0; // clang-format on meshcat->SetLine("Domain", env_points, 8.0, Rgba(0, 0, 0)); Eigen::Matrix3Xd centers(3, 4); double c = 1.0; // clang-format off centers << -c, c, c, -c, c, c, -c, -c, 0, 0, 0, 0; // clang-format on Eigen::Matrix3Xd obs_points(3, 5); // approximating offset due to sphere radius with fixed offset double s = 0.7 + 0.01; // clang-format off obs_points << -s, s, s, -s, -s, s, s, -s, -s, s, s, 0, 0, 0, 0; // clang-format on for (int obstacle_idx = 0; obstacle_idx < 4; ++obstacle_idx) { Eigen::Matrix3Xd obstacle = obs_points; obstacle.colwise() += centers.col(obstacle_idx); meshcat->SetLine(fmt::format("/obstacles/obs_{}", obstacle_idx), obstacle, 8.0, Rgba(0, 0, 0)); } RobotDiagramBuilder<double> builder(0.0); params.robot_model_instances = builder.parser().AddModelsFromString(boxes_in_corners, "urdf"); params.edge_step_size = 0.01; params.model = builder.Build(); checker = std::make_unique<SceneGraphCollisionChecker>(std::move(params)); options.iris_options.meshcat = meshcat; options.num_points_per_coverage_check = 1000; options.num_points_per_visibility_round = 140; options.coverage_termination_threshold = 0.9; options.minimum_clique_size = 25; generator = RandomGenerator(0); // A manual convex decomposition of the space. manual_decomposition.push_back( Hyperrectangle(Vector2d{-2, -2}, Vector2d{-1.7, 2})); manual_decomposition.push_back( Hyperrectangle(Vector2d{-2, -2}, Vector2d{2, -1.7})); manual_decomposition.push_back( Hyperrectangle(Vector2d{1.7, -2}, Vector2d{2, 2})); manual_decomposition.push_back( Hyperrectangle(Vector2d{-2, 1.7}, Vector2d{2, 2})); manual_decomposition.push_back( Hyperrectangle(Vector2d{-0.3, -2}, Vector2d{0.3, 2})); manual_decomposition.push_back( Hyperrectangle(Vector2d{-2, -0.3}, Vector2d{2, 0.3})); color = Eigen::VectorXd::Zero(3); // Show the manual decomposition in the meshcat debugger. for (int i = 0; i < ssize(manual_decomposition); ++i) { // Choose a random color. for (int j = 0; j < color.size(); ++j) { color[j] = abs(gaussian(generator)); } color.normalize(); VPolytope vregion = VPolytope(manual_decomposition.at(i).MakeHPolyhedron()) .GetMinimalRepresentation(); Draw2dVPolytope(vregion, fmt::format("manual_decomposition_{}", i), color, meshcat); } } CollisionCheckerParams params; std::shared_ptr<Meshcat> meshcat; std::unique_ptr<SceneGraphCollisionChecker> checker; IrisFromCliqueCoverOptions options; std::vector<HPolyhedron> sets; RandomGenerator generator; std::vector<Hyperrectangle> manual_decomposition; std::normal_distribution<double> gaussian; Eigen::VectorXd color; }; TEST_F(IrisInConfigurationSpaceFromCliqueCoverTestFixture, BoxWithCornerObstaclesTestMip) { // Only run this test if a MIP solver is available. if ((solvers::MosekSolver::is_available() && solvers::MosekSolver::is_enabled()) || (solvers::GurobiSolver::is_available() && solvers::GurobiSolver::is_enabled())) { // Set ILP settings for MaxCliqueSolverViaMip // limiting the work load for ILP solver solvers::SolverOptions solver_options; // Quit after finding 25 solutions. const int kFeasibleSolutionLimit = 25; // Quit at a 5% optimality gap const double kRelOptGap = 0.05; solver_options.SetOption(solvers::MosekSolver().id(), "MSK_IPAR_MIO_MAX_NUM_SOLUTIONS", kFeasibleSolutionLimit); solver_options.SetOption(solvers::MosekSolver().id(), "MSK_DPAR_MIO_TOL_REL_GAP", kRelOptGap); solver_options.SetOption(solvers::GurobiSolver().id(), "SolutionLimit", kFeasibleSolutionLimit); solver_options.SetOption(solvers::GurobiSolver().id(), "MIPGap", kRelOptGap); planning::graph_algorithms::MaxCliqueSolverViaMip solver{std::nullopt, solver_options}; IrisInConfigurationSpaceFromCliqueCover(*checker, options, &generator, &sets, &solver); EXPECT_EQ(ssize(sets), 6); // Show the IrisFromCliqueCoverDecomposition for (int i = 0; i < ssize(sets); ++i) { // Choose a random color. for (int j = 0; j < color.size(); ++j) { color[j] = abs(gaussian(generator)); } color.normalize(); VPolytope vregion = VPolytope(sets.at(i)).GetMinimalRepresentation(); Draw2dVPolytope(vregion, fmt::format("iris_from_clique_cover_mip{}", i), color, meshcat); } // Now check the coverage by drawing points from the manual decomposition // and checking if they are inside the IrisFromCliqueCover decomposition. int num_samples_per_set = 1000; int num_in_automatic_decomposition = 0; for (const auto& manual_set : manual_decomposition) { for (int i = 0; i < num_samples_per_set; ++i) { Eigen::Vector2d sample = manual_set.UniformSample(&generator); for (const auto& set : sets) { if (set.PointInSet(sample)) { ++num_in_automatic_decomposition; break; } } } } double coverage_estimate = static_cast<double>(num_in_automatic_decomposition) / static_cast<double>(num_samples_per_set * ssize(manual_decomposition)); // We set the termination threshold to be at 0.9 with 1000 points for a // coverage check. This number is low enough that the test passes regardless // of the random seed. (The probability of success is larger than 1-1e-9). EXPECT_GE(coverage_estimate, 0.8); MaybePauseForUser(); } } TEST_F(IrisInConfigurationSpaceFromCliqueCoverTestFixture, BoxWithCornerObstaclesTestGreedy) { // use default solver MaxCliqueSovlerViaGreedy IrisInConfigurationSpaceFromCliqueCover(*checker, options, &generator, &sets, nullptr); EXPECT_EQ(ssize(sets), 6); // Show the IrisFromCliqueCoverDecomposition for (int i = 0; i < ssize(sets); ++i) { // Choose a random color. for (int j = 0; j < color.size(); ++j) { color[j] = abs(gaussian(generator)); } color.normalize(); VPolytope vregion = VPolytope(sets.at(i)).GetMinimalRepresentation(); Draw2dVPolytope(vregion, fmt::format("iris_from_clique_cover_greedy{}", i), color, meshcat); } // Now check the coverage by drawing points from the manual decomposition and // checking if they are inside the IrisFromCliqueCover decomposition. int num_samples_per_set = 1000; int num_in_automatic_decomposition = 0; for (const auto& manual_set : manual_decomposition) { for (int i = 0; i < num_samples_per_set; ++i) { Eigen::Vector2d sample = manual_set.UniformSample(&generator); for (const auto& set : sets) { if (set.PointInSet(sample)) { ++num_in_automatic_decomposition; break; } } } } double coverage_estimate = static_cast<double>(num_in_automatic_decomposition) / static_cast<double>(num_samples_per_set * ssize(manual_decomposition)); // We set the termination threshold to be at 0.9 with 1000 points for a // coverage check. This number is low enough that the test passes regardless // of the random seed. (The probability of success is larger than 1-1e-9). EXPECT_GE(coverage_estimate, 0.8); MaybePauseForUser(); } } // namespace } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/direct_collocation.cc
#include "drake/planning/trajectory_optimization/direct_collocation.h" #include <cstddef> #include <stdexcept> #include <utility> #include <vector> #include "drake/math/autodiff.h" #include "drake/math/autodiff_gradient.h" namespace drake { namespace planning { namespace trajectory_optimization { using Eigen::MatrixXd; using Eigen::VectorXd; using math::AreAutoDiffVecXdEqual; using math::ExtractGradient; using math::ExtractValue; using math::InitializeAutoDiff; using math::InitializeAutoDiffTuple; using solvers::Binding; using solvers::Constraint; using solvers::MathematicalProgram; using solvers::VectorXDecisionVariable; using systems::Context; using systems::FixedInputPortValue; using systems::InputPort; using systems::InputPortIndex; using systems::InputPortSelection; using systems::PortDataType; using systems::System; using trajectories::PiecewisePolynomial; namespace { int CheckAndReturnStates(int states) { if (states <= 0) { throw std::logic_error( "This system doesn't have any continuous states. DirectCollocation " "only makes sense for systems with continuous-time dynamics."); } return states; } typedef std::pair<std::unique_ptr<System<AutoDiffXd>>, std::unique_ptr<Context<AutoDiffXd>>> OwnedPair; OwnedPair MakeAutoDiffXd(const systems::System<double>& system, const systems::Context<double>& context) { auto system_ad = System<double>::ToAutoDiffXd(system); auto context_ad = system_ad->CreateDefaultContext(); // TODO(russt): Add support for time-varying dynamics OR check for // time-invariance. context_ad->SetTimeStateAndParametersFrom(context); system_ad->FixInputPortsFrom(system, context, context_ad.get()); return OwnedPair{std::move(system_ad), std::move(context_ad)}; } } // namespace DirectCollocationConstraint::DirectCollocationConstraint( const System<double>& system, const Context<double>& context, std::variant<InputPortSelection, InputPortIndex> input_port_index, bool assume_non_continuous_states_are_fixed) : DirectCollocationConstraint( MakeAutoDiffXd(system, context), nullptr, // System nullptr, nullptr, nullptr, // Contexts context.num_continuous_states(), system.get_input_port_selection(input_port_index) ? system.get_input_port_selection(input_port_index)->size() : 0, input_port_index, assume_non_continuous_states_are_fixed) {} DirectCollocationConstraint::DirectCollocationConstraint( const systems::System<AutoDiffXd>& system, systems::Context<AutoDiffXd>* context_sample, systems::Context<AutoDiffXd>* context_next_sample, systems::Context<AutoDiffXd>* context_collocation, std::variant<systems::InputPortSelection, systems::InputPortIndex> input_port_index, bool assume_non_continuous_states_are_fixed) : DirectCollocationConstraint( OwnedPair{nullptr, nullptr}, &system, context_sample, context_next_sample, context_collocation, context_sample->num_continuous_states(), system.get_input_port_selection(input_port_index) ? system.get_input_port_selection(input_port_index)->size() : 0, input_port_index, assume_non_continuous_states_are_fixed) {} DirectCollocationConstraint::DirectCollocationConstraint( OwnedPair owned_pair, const systems::System<AutoDiffXd>* system, systems::Context<AutoDiffXd>* context_sample, systems::Context<AutoDiffXd>* context_next_sample, systems::Context<AutoDiffXd>* context_collocation, int num_states, int num_inputs, std::variant<InputPortSelection, InputPortIndex> input_port_index, bool assume_non_continuous_states_are_fixed) : Constraint(CheckAndReturnStates(num_states), 1 + (2 * num_states) + (2 * num_inputs), Eigen::VectorXd::Zero(num_states), Eigen::VectorXd::Zero(num_states)), owned_system_(std::move(owned_pair.first)), owned_context_(std::move(owned_pair.second)), system_(owned_system_ ? *owned_system_ : *system), context_sample_(owned_context_ ? owned_context_.get() : context_sample), context_next_sample_(owned_context_ ? owned_context_.get() : context_next_sample), context_collocation_(owned_context_ ? owned_context_.get() : context_collocation), input_port_(system_.get_input_port_selection(input_port_index)), num_states_(num_states), num_inputs_(num_inputs) { system_.ValidateContext(context_sample_); system_.ValidateContext(context_next_sample_); system_.ValidateContext(context_collocation_); if (!assume_non_continuous_states_are_fixed) { DRAKE_THROW_UNLESS(context_sample_->has_only_continuous_state()); } if (input_port_) { // Verify that the input port is not abstract valued. if (input_port_->get_data_type() == PortDataType::kAbstractValued) { throw std::logic_error( "The specified input port is abstract-valued, and this constraint " "only supports vector-valued input ports. Did you perhaps forget to " "pass a non-default `input_port_index` argument?"); } } } void DirectCollocationConstraint::CalcDynamics( const AutoDiffVecXd& x_with_dvars, const AutoDiffVecXd& u_with_dvars, Context<AutoDiffXd>* context, AutoDiffVecXd* xdot_with_dvars) const { // To have cache hits, we must match not only the x and u values, but also // the derivatives. To get cache hits even when dvars are different, we use // the chain rule locally in this method, so that the gradients in the cache // are always with respect to exactly the current x and u. AutoDiffVecXd x_with_dxu, u_with_dxu; std::tie(x_with_dxu, u_with_dxu) = InitializeAutoDiffTuple( ExtractValue(x_with_dvars), ExtractValue(u_with_dvars)); if (input_port_ && (!input_port_->HasValue(*context) || !AreAutoDiffVecXdEqual(u_with_dxu, input_port_->Eval(*context)))) { input_port_->FixValue(context, u_with_dxu); } if (!AreAutoDiffVecXdEqual( x_with_dxu, context->get_continuous_state_vector().CopyToVector())) { context->SetContinuousState(x_with_dxu); } AutoDiffVecXd xdot_with_dxu = system_.EvalTimeDerivatives(*context).CopyToVector(); const VectorXd xdot = ExtractValue(xdot_with_dxu); const MatrixXd dxdot_dxu = ExtractGradient(xdot_with_dxu); xdot_with_dvars->resize(num_states_); // dxdot_dvars = dxdot_dx * dx_dvars + dxdot_du * du_dvars. InitializeAutoDiff( xdot, dxdot_dxu.leftCols(num_states_) * ExtractGradient(x_with_dvars) + dxdot_dxu.rightCols(num_inputs_) * ExtractGradient(u_with_dvars, // pass in num_derivatives in case u is empty. x_with_dvars[0].derivatives().size()), xdot_with_dvars); } void DirectCollocationConstraint::DoEval( const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const { AutoDiffVecXd y_t; Eval(x.cast<AutoDiffXd>(), &y_t); *y = ExtractValue(y_t); } // The format of the input to the eval() function is the // tuple { time step, state 0, state 1, input 0, input 1 }, // which has a total length of 1 + 2*num_states + 2*num_inputs. void DirectCollocationConstraint::DoEval( const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const { DRAKE_ASSERT(x.size() == 1 + (2 * num_states_) + (2 * num_inputs_)); // Extract our input variables: // h - current time (breakpoint) // x0, x1 state vector at time steps k, k+1 // u0, u1 input vector at time steps k, k+1 const AutoDiffXd h = x(0); const auto x0 = x.segment(1, num_states_); const auto x1 = x.segment(1 + num_states_, num_states_); const auto u0 = x.segment(1 + (2 * num_states_), num_inputs_); const auto u1 = x.segment(1 + (2 * num_states_) + num_inputs_, num_inputs_); AutoDiffVecXd xdot0; CalcDynamics(x0, u0, context_sample_, &xdot0); AutoDiffVecXd xdot1; CalcDynamics(x1, u1, context_next_sample_, &xdot1); // Cubic interpolation to get xcol and xdotcol. const AutoDiffVecXd xcol = 0.5 * (x0 + x1) + h / 8 * (xdot0 - xdot1); const AutoDiffVecXd xdotcol = -1.5 * (x0 - x1) / h - .25 * (xdot0 + xdot1); AutoDiffVecXd g; CalcDynamics(xcol, 0.5 * (u0 + u1), context_collocation_, &g); *y = xdotcol - g; } void DirectCollocationConstraint::DoEval( const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const { throw std::logic_error( "DirectCollocationConstraint does not support symbolic evaluation."); } Binding<Constraint> AddDirectCollocationConstraint( std::shared_ptr<DirectCollocationConstraint> constraint, const Eigen::Ref<const VectorXDecisionVariable>& time_step, const Eigen::Ref<const VectorXDecisionVariable>& state, const Eigen::Ref<const VectorXDecisionVariable>& next_state, const Eigen::Ref<const VectorXDecisionVariable>& input, const Eigen::Ref<const VectorXDecisionVariable>& next_input, MathematicalProgram* prog) { DRAKE_DEMAND(time_step.size() == 1); DRAKE_DEMAND(state.size() == constraint->num_states()); DRAKE_DEMAND(next_state.size() == constraint->num_states()); DRAKE_DEMAND(input.size() == constraint->num_inputs()); DRAKE_DEMAND(next_input.size() == constraint->num_inputs()); return prog->AddConstraint(constraint, {time_step, state, next_state, input, next_input}); } DirectCollocation::DirectCollocation( const System<double>* system, const Context<double>& context, int num_time_samples, double minimum_time_step, double maximum_time_step, std::variant<InputPortSelection, InputPortIndex> input_port_index, bool assume_non_continuous_states_are_fixed, solvers::MathematicalProgram* prog) : MultipleShooting( system->get_input_port_selection(input_port_index) ? system->get_input_port_selection(input_port_index)->size() : 0, CheckAndReturnStates(context.num_continuous_states()), num_time_samples, minimum_time_step, maximum_time_step, prog), system_(system), context_(context.Clone()), input_port_index_(input_port_index), sample_contexts_(num_time_samples) { system->ValidateContext(context); if (!assume_non_continuous_states_are_fixed) { DRAKE_DEMAND(context.has_only_continuous_state()); } auto system_and_context = MakeAutoDiffXd(*system, context); system_ad_ = std::move(system_and_context.first); context_ad_ = std::move(system_and_context.second); // Allocated contexts for each sample time. We share contexts across multiple // constraints in order to exploit caching (the dynamics at time k are // evaluated both in constraint k and k+1). Note that the constraints cannot // be evaluated in parallel. for (int i = 0; i < N(); ++i) { sample_contexts_[i] = context_ad_->Clone(); } // We don't expect to have cache hits for the collocation contexts, so can // just use the one context_ad. // Add the dynamic constraints. // For N-1 time steps, add a constraint which depends on the breakpoint // along with the state and input vectors at that breakpoint and the // next. for (int i = 0; i < N() - 1; ++i) { auto constraint = std::make_shared<DirectCollocationConstraint>( *system_ad_, sample_contexts_[i].get(), sample_contexts_[i + 1].get(), context_ad_.get(), input_port_index, assume_non_continuous_states_are_fixed); this->prog() .AddConstraint(constraint, {h_vars().segment<1>(i), x_vars().segment(i * num_states(), num_states() * 2), u_vars().segment(i * num_inputs(), num_inputs() * 2)}) .evaluator() ->set_description( fmt::format("collocation constraint for segment {}", i)); } } void DirectCollocation::DoAddRunningCost(const symbolic::Expression& g) { // Trapezoidal integration: // sum_{i=0...N-2} h_i/2.0 * (g_i + g_{i+1}), or // g_0*h_0/2.0 + [sum_{i=1...N-2} g_i*(h_{i-1} + h_i)/2.0] + // g_{N-1}*h_{N-2}/2.0. prog().AddCost(SubstitutePlaceholderVariables(g * h_vars()(0) / 2, 0)); for (int i = 1; i <= N() - 2; i++) { prog().AddCost(SubstitutePlaceholderVariables( g * (h_vars()(i - 1) + h_vars()(i)) / 2, i)); } prog().AddCost( SubstitutePlaceholderVariables(g * h_vars()(N() - 2) / 2, N() - 1)); } PiecewisePolynomial<double> DirectCollocation::ReconstructInputTrajectory( const solvers::MathematicalProgramResult& result) const { const InputPort<double>* input_port = system_->get_input_port_selection(input_port_index_); if (!input_port) { return PiecewisePolynomial<double>(); } Eigen::VectorXd times = GetSampleTimes(result); std::vector<double> times_vec(N()); std::vector<Eigen::MatrixXd> inputs(N()); for (int i = 0; i < N(); i++) { times_vec[i] = times(i); inputs[i] = result.GetSolution(input(i)); } return PiecewisePolynomial<double>::FirstOrderHold(times_vec, inputs); } PiecewisePolynomial<double> DirectCollocation::ReconstructStateTrajectory( const solvers::MathematicalProgramResult& result) const { Eigen::VectorXd times = GetSampleTimes(result); std::vector<double> times_vec(N()); std::vector<Eigen::MatrixXd> states(N()); std::vector<Eigen::MatrixXd> derivatives(N()); // Provide a fixed value for the input port and keep an alias around. const InputPort<double>* input_port = system_->get_input_port_selection(input_port_index_); FixedInputPortValue* input_port_value{nullptr}; if (input_port) { input_port_value = &input_port->FixValue( context_.get(), system_->AllocateInputVector(*input_port)->get_value()); } for (int i = 0; i < N(); i++) { times_vec[i] = times(i); states[i] = result.GetSolution(state(i)); if (input_port) { input_port_value->GetMutableVectorData<double>()->SetFromVector( result.GetSolution(input(i))); } context_->SetContinuousState(states[i]); derivatives[i] = system_->EvalTimeDerivatives(*context_).CopyToVector(); } return PiecewisePolynomial<double>::CubicHermite(times_vec, states, derivatives); } } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_googletest", "drake_cc_library", "drake_cc_package_library", ) package(default_visibility = ["//visibility:public"]) drake_cc_package_library( name = "trajectory_optimization", visibility = ["//visibility:public"], deps = [ ":direct_collocation", ":direct_transcription", ":gcs_trajectory_optimization", ":integration_constraint", ":kinematic_trajectory_optimization", ":multiple_shooting", ":sequential_expression_manager", ], ) drake_cc_library( name = "sequential_expression_manager", srcs = ["sequential_expression_manager.cc"], hdrs = [ "sequential_expression_manager.h", ], deps = [ "//common:essential", "//common:string_container", "//common:unused", "//common/symbolic:expression", ], ) drake_cc_library( name = "multiple_shooting", srcs = ["multiple_shooting.cc"], hdrs = ["multiple_shooting.h"], deps = [ ":sequential_expression_manager", "//common:essential", "//common/trajectories:piecewise_polynomial", "//solvers:ipopt_solver", "//solvers:mathematical_program", "//solvers:solve", ], ) drake_cc_library( name = "direct_collocation", srcs = [ "direct_collocation.cc", ], hdrs = [ "direct_collocation.h", ], deps = [ ":multiple_shooting", "//math:autodiff", "//math:gradient", "//systems/framework", ], ) drake_cc_library( name = "direct_transcription", srcs = [ "direct_transcription.cc", ], hdrs = [ "direct_transcription.h", ], deps = [ ":multiple_shooting", "//common/symbolic:polynomial", "//common/trajectories:piecewise_polynomial", "//math:autodiff", "//math:gradient", "//systems/analysis:explicit_euler_integrator", "//systems/analysis:integrator_base", "//systems/framework", "//systems/primitives:linear_system", ], ) drake_cc_library( name = "kinematic_trajectory_optimization", srcs = ["kinematic_trajectory_optimization.cc"], hdrs = ["kinematic_trajectory_optimization.h"], deps = [ "//common", "//common/trajectories:bspline_trajectory", "//math:bspline_basis", "//math:gradient", "//math:matrix_util", "//solvers:mathematical_program", "//solvers:mathematical_program_result", ], ) drake_cc_library( name = "gcs_trajectory_optimization", srcs = ["gcs_trajectory_optimization.cc"], hdrs = ["gcs_trajectory_optimization.h"], deps = [ "//common", "//common/trajectories:bezier_curve", "//common/trajectories:composite_trajectory", "//geometry/optimization:geodesic_convexity", "//geometry/optimization:graph_of_convex_sets", "//multibody/plant", "//solvers:solve", ], ) drake_cc_library( name = "integration_constraint", srcs = ["integration_constraint.cc"], hdrs = ["integration_constraint.h"], deps = [ "//solvers:constraint", ], ) # === test/ === drake_cc_googletest( name = "multiple_shooting_test", deps = [ ":multiple_shooting", "//common/test_utilities:eigen_matrix_compare", "//solvers:osqp_solver", "//solvers:solve", ], ) drake_cc_googletest( name = "direct_collocation_test", deps = [ ":direct_collocation", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//examples/rimless_wheel", "//multibody/benchmarks/pendulum", "//solvers:solve", "//systems/primitives:linear_system", ], ) drake_cc_googletest( name = "direct_transcription_test", data = ["//examples/pendulum:models"], # This test has two duplicated long cases; run them in parallel. shard_count = 4, deps = [ ":direct_transcription", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_throws_message", "//multibody/parsing", "//multibody/plant", "//solvers:snopt_solver", "//solvers:solve", "//systems/primitives:symbolic_vector_system", "//systems/primitives:trajectory_linear_system", ], ) drake_cc_googletest( name = "gcs_trajectory_optimization_test", shard_count = 8, deps = [ ":gcs_trajectory_optimization", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", "//common/test_utilities:expect_throws_message", "//common/trajectories:piecewise_polynomial", "//solvers:gurobi_solver", "//solvers:mosek_solver", "//solvers:snopt_solver", ], ) drake_cc_googletest( name = "kinematic_trajectory_optimization_test", deps = [ ":kinematic_trajectory_optimization", "//common/test_utilities:eigen_matrix_compare", "//solvers:constraint", "//solvers:ipopt_solver", "//solvers:osqp_solver", "//solvers:solve", ], ) drake_cc_googletest( name = "sequential_expression_manager_test", deps = [ ":sequential_expression_manager", "//common/test_utilities:expect_throws_message", "@fmt", ], ) drake_cc_googletest( name = "integration_constraint_test", deps = [ ":integration_constraint", "//common/test_utilities:eigen_matrix_compare", "//math:gradient", ], ) add_lint_tests()
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/kinematic_trajectory_optimization.cc
#include "drake/planning/trajectory_optimization/kinematic_trajectory_optimization.h" #include <algorithm> #include <limits> #include <string> #include <unordered_map> #include <utility> #include "drake/common/pointer_cast.h" #include "drake/common/symbolic/decompose.h" #include "drake/common/text_logging.h" #include "drake/math/autodiff_gradient.h" #include "drake/math/bspline_basis.h" #include "drake/math/matrix_util.h" using Eigen::MatrixXd; using Eigen::VectorXd; using std::nullopt; using std::optional; namespace drake { namespace planning { namespace trajectory_optimization { using math::BsplineBasis; using math::EigenToStdVector; using math::ExtractValue; using math::InitializeAutoDiff; using math::StdVectorToEigen; using solvers::Binding; using solvers::BoundingBoxConstraint; using solvers::Constraint; using solvers::Cost; using solvers::LinearConstraint; using solvers::LinearCost; using solvers::MathematicalProgram; using solvers::MathematicalProgramResult; using solvers::VectorXDecisionVariable; using symbolic::Expression; using symbolic::Variables; using trajectories::BsplineTrajectory; namespace { class PathConstraint : public Constraint { public: PathConstraint(std::shared_ptr<Constraint> wrapped_constraint, std::vector<double> basis_function_values) : Constraint( wrapped_constraint->num_outputs(), basis_function_values.size() * wrapped_constraint->num_vars(), wrapped_constraint->lower_bound(), wrapped_constraint->upper_bound()), wrapped_constraint_(wrapped_constraint), basis_function_values_(std::move(basis_function_values)) {} void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { AutoDiffVecXd y_t; Eval(InitializeAutoDiff(x), &y_t); *y = ExtractValue(y_t); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { AutoDiffVecXd x_sum = basis_function_values_[0] * x.segment(0, wrapped_constraint_->num_vars()); const int num_terms = basis_function_values_.size(); for (int i = 1; i < num_terms; ++i) { x_sum += basis_function_values_[i] * x.segment(i * wrapped_constraint_->num_vars(), wrapped_constraint_->num_vars()); } wrapped_constraint_->Eval(x_sum, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const override { throw std::runtime_error( "PathConstraint does not support evaluation with Expression."); } private: std::shared_ptr<Constraint> wrapped_constraint_; std::vector<double> basis_function_values_; }; /* Implements a constraint of the form wrapped_constraint([q, v]), where duration = x[0] q = M_pos * x[1:num_pos_vars+1] v = M_vel * x[-num_vel_vars:] / duration TODO(russt): M_pos and M_vel are predictably sparse, and we could handle that here if performance demands it. */ class WrappedVelocityConstraint : public Constraint { public: WrappedVelocityConstraint(std::shared_ptr<Constraint> wrapped_constraint, Eigen::MatrixXd M_pos, Eigen::MatrixXd M_vel) : Constraint(wrapped_constraint->num_outputs(), M_pos.cols() + M_vel.cols() + 1, wrapped_constraint->lower_bound(), wrapped_constraint->upper_bound()), wrapped_constraint_(wrapped_constraint), M_pos_{std::move(M_pos)}, M_vel_{std::move(M_vel)} { DRAKE_DEMAND(M_pos_.rows() + M_vel_.rows() == wrapped_constraint_->num_vars()); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { AutoDiffVecXd y_t; Eval(InitializeAutoDiff(x), &y_t); *y = ExtractValue(y_t); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { AutoDiffXd duration = x[0]; VectorX<AutoDiffXd> qv(wrapped_constraint_->num_vars()); qv << M_pos_ * x.segment(1, M_pos_.cols()), M_vel_ * x.tail(M_vel_.cols()) / duration; wrapped_constraint_->Eval(qv, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const override { throw std::runtime_error( "WrappedDerivativeConstraint does not support evaluation with " "Expression."); } private: std::shared_ptr<Constraint> wrapped_constraint_; const Eigen::MatrixXd M_pos_; const Eigen::MatrixXd M_vel_; }; /* Implements a constraint of the form: duration = x[0] lb <= M * x[1:] / duration^order <= ub */ class DerivativeConstraint : public Constraint { public: DerivativeConstraint(const Eigen::MatrixXd& M, int derivative_order, const Eigen::Ref<const VectorXd>& lb, const Eigen::Ref<const VectorXd>& ub) : Constraint(M.rows(), M.cols() + 1, lb, ub), M_{M}, derivative_order_{derivative_order} { DRAKE_DEMAND(derivative_order >= 1); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { AutoDiffVecXd y_t; Eval(InitializeAutoDiff(x), &y_t); *y = ExtractValue(y_t); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { AutoDiffXd duration = x[0]; *y = M_ * x.tail(M_.cols()) / pow(duration, derivative_order_); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const override { throw std::runtime_error( "DerivativeConstraint does not support evaluation with Expression."); } private: const Eigen::MatrixXd M_; const int derivative_order_; }; } // namespace KinematicTrajectoryOptimization::KinematicTrajectoryOptimization( int num_positions, int num_control_points, int spline_order, double duration) : KinematicTrajectoryOptimization(BsplineTrajectory( BsplineBasis<double>(spline_order, num_control_points, math::KnotVectorType::kClampedUniform, 0, duration), std::vector<MatrixXd>(num_control_points, MatrixXd::Zero(num_positions, 1)))) {} KinematicTrajectoryOptimization::KinematicTrajectoryOptimization( const trajectories::BsplineTrajectory<double>& trajectory) : num_positions_(trajectory.rows()), num_control_points_(trajectory.num_control_points()) { // basis_ = trajectory.basis() normalized to s∈[0,1]. const double duration = trajectory.end_time() - trajectory.start_time(); std::vector<double> normalized_knots = trajectory.basis().knots(); for (auto& knot : normalized_knots) { knot /= duration; } basis_ = BsplineBasis<double>(trajectory.basis().order(), normalized_knots); control_points_ = prog_.NewContinuousVariables( num_positions_, num_control_points_, "control_point"); duration_ = prog_.NewContinuousVariables(1, "duration")[0]; // duration >= 0. prog_.AddBoundingBoxConstraint(0, std::numeric_limits<double>::infinity(), duration_); SetInitialGuess(trajectory); // Create symbolic curves to enable creating linear constraints on the // positions and its derivatives. // TODO(russt): Consider computing these only the first time they are used. sym_r_ = std::make_unique<BsplineTrajectory<symbolic::Expression>>( basis_, EigenToStdVector<Expression>(control_points_.cast<Expression>())); sym_rdot_ = dynamic_pointer_cast_or_throw<BsplineTrajectory<symbolic::Expression>>( sym_r_->MakeDerivative()); sym_rddot_ = dynamic_pointer_cast_or_throw<BsplineTrajectory<symbolic::Expression>>( sym_rdot_->MakeDerivative()); sym_rdddot_ = dynamic_pointer_cast_or_throw<BsplineTrajectory<symbolic::Expression>>( sym_rddot_->MakeDerivative()); } void KinematicTrajectoryOptimization::SetInitialGuess( const trajectories::BsplineTrajectory<double>& trajectory) { prog_.SetInitialGuess(control_points_, StdVectorToEigen<double>(trajectory.control_points())); prog_.SetInitialGuess(duration_, trajectory.end_time() - trajectory.start_time()); } BsplineTrajectory<double> KinematicTrajectoryOptimization::ReconstructTrajectory( const MathematicalProgramResult& result) const { const double duration = result.GetSolution(duration_); std::vector<double> scaled_knots = basis_.knots(); for (auto& knot : scaled_knots) { knot *= duration; } return BsplineTrajectory<double>( BsplineBasis<double>(basis_.order(), scaled_knots), EigenToStdVector<double>(result.GetSolution(control_points_))); } Binding<LinearConstraint> KinematicTrajectoryOptimization::AddPathPositionConstraint( const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, double s) { DRAKE_DEMAND(lb.size() == num_positions()); DRAKE_DEMAND(ub.size() == num_positions()); DRAKE_DEMAND(0 <= s && s <= 1); const VectorX<symbolic::Expression> sym_r_value = sym_r_->value(s); auto binding = prog_.AddLinearConstraint(lb <= sym_r_value && sym_r_value <= ub); binding.evaluator()->set_description("path position constraint"); return binding; } Binding<Constraint> KinematicTrajectoryOptimization::AddPathPositionConstraint( const std::shared_ptr<Constraint>& constraint, double s) { DRAKE_DEMAND(constraint->num_vars() == num_positions_); DRAKE_DEMAND(0 <= s && s <= 1); std::vector<double> basis_function_values; basis_function_values.reserve(basis_.order()); std::vector<int> active_control_point_indices = basis_.ComputeActiveBasisFunctionIndices(s); const int num_active_control_points = static_cast<int>(active_control_point_indices.size()); VectorXDecisionVariable var_vector(num_active_control_points * num_positions()); for (int i = 0; i < num_active_control_points; ++i) { const int control_point_index = active_control_point_indices[i]; basis_function_values.push_back( basis_.EvaluateBasisFunctionI(control_point_index, s)); var_vector.segment(i * num_positions(), num_positions()) = control_points_.col(control_point_index); } auto binding = prog_.AddConstraint( std::make_shared<PathConstraint>(constraint, basis_function_values), var_vector); binding.evaluator()->set_description("path position constraint"); return binding; } Binding<LinearConstraint> KinematicTrajectoryOptimization::AddPathVelocityConstraint( const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, double s) { DRAKE_DEMAND(lb.size() == num_positions()); DRAKE_DEMAND(ub.size() == num_positions()); DRAKE_DEMAND(0 <= s && s <= 1); const VectorX<symbolic::Expression> sym_rdot_value = sym_rdot_->value(s); auto binding = prog_.AddLinearConstraint(lb <= sym_rdot_value && sym_rdot_value <= ub); binding.evaluator()->set_description("path velocity constraint"); return binding; } Binding<Constraint> KinematicTrajectoryOptimization::AddVelocityConstraintAtNormalizedTime( const std::shared_ptr<solvers::Constraint>& constraint, double s) { DRAKE_DEMAND(constraint->num_vars() == 2 * num_positions_); DRAKE_DEMAND(0 <= s && s <= 1); VectorX<Expression> r = sym_r_->value(s); VectorX<Expression> rdot = sym_rdot_->value(s); VectorXDecisionVariable vars_pos, vars_vel; std::unordered_map<symbolic::Variable::Id, int> unused_map; std::tie(vars_pos, unused_map) = symbolic::ExtractVariablesFromExpression(r); std::tie(vars_vel, unused_map) = symbolic::ExtractVariablesFromExpression(rdot); Eigen::MatrixXd M_pos(num_positions(), vars_pos.size()); Eigen::MatrixXd M_vel(num_positions(), vars_vel.size()); symbolic::DecomposeLinearExpressions(r, vars_pos, &M_pos); symbolic::DecomposeLinearExpressions(rdot, vars_vel, &M_vel); VectorXDecisionVariable duration_and_vars(1 + vars_pos.size() + vars_vel.size()); duration_and_vars << duration_, vars_pos, vars_vel; auto wrapped_constraint = std::make_shared<WrappedVelocityConstraint>( constraint, std::move(M_pos), std::move(M_vel)); auto binding = prog_.AddConstraint(wrapped_constraint, duration_and_vars); binding.evaluator()->set_description("velocity constraint"); return binding; } Binding<LinearConstraint> KinematicTrajectoryOptimization::AddPathAccelerationConstraint( const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, double s) { DRAKE_DEMAND(lb.size() == num_positions()); DRAKE_DEMAND(ub.size() == num_positions()); DRAKE_DEMAND(0 <= s && s <= 1); const VectorX<symbolic::Expression> sym_rddot_value = sym_rddot_->value(s); auto binding = prog_.AddLinearConstraint(lb <= sym_rddot_value && sym_rddot_value <= ub); binding.evaluator()->set_description("path acceleration constraint"); return binding; } Binding<BoundingBoxConstraint> KinematicTrajectoryOptimization::AddDurationConstraint(optional<double> lb, optional<double> ub) { auto binding = prog_.AddBoundingBoxConstraint( lb.value_or(0), ub.value_or(std::numeric_limits<double>::infinity()), duration_); binding.evaluator()->set_description("duration constraint"); return binding; } std::vector<Binding<BoundingBoxConstraint>> KinematicTrajectoryOptimization::AddPositionBounds( const Eigen::Ref<const VectorXd>& lb, const Eigen::Ref<const VectorXd>& ub) { DRAKE_DEMAND(lb.size() == num_positions()); DRAKE_DEMAND(ub.size() == num_positions()); // This leverages the convex hull property of the B-splines: if all of the // control points satisfy these convex constraints and the curve is inside // the convex hull of these constraints, then the curve satisfies the // constraints for all s (and therefore all t). std::vector<Binding<BoundingBoxConstraint>> binding; for (int i = 0; i < num_control_points(); ++i) { binding.emplace_back( prog_.AddBoundingBoxConstraint(lb, ub, control_points_.col(i))); binding[i].evaluator()->set_description( fmt::format("position bound {}", i)); } return binding; } std::vector<Binding<LinearConstraint>> KinematicTrajectoryOptimization::AddVelocityBounds( const Eigen::Ref<const VectorXd>& lb, const Eigen::Ref<const VectorXd>& ub) { DRAKE_DEMAND(lb.size() == num_positions()); DRAKE_DEMAND(ub.size() == num_positions()); // We have q̇(t) = drds * dsdt = ṙ(s) / duration, and duration >= 0, so we // use duration * lb <= ṙ(s) <= duration * ub. // // This also leverages the convex hull property of the B-splines: if all of // the control points satisfy these convex constraints and the curve is // inside the convex hull of these constraints, then the curve satisfies the // constraints for all t. std::vector<Binding<LinearConstraint>> binding; for (int i = 0; i < sym_rdot_->num_control_points(); ++i) { binding.emplace_back(prog_.AddLinearConstraint( sym_rdot_->control_points()[i] >= duration_ * lb && sym_rdot_->control_points()[i] <= duration_ * ub)); binding[i].evaluator()->set_description( fmt::format("velocity bound {}", i)); } return binding; } std::vector<std::vector<Binding<Constraint>>> KinematicTrajectoryOptimization::AddAccelerationBounds( const Eigen::Ref<const VectorXd>& lb, const Eigen::Ref<const VectorXd>& ub) { DRAKE_DEMAND(lb.size() == num_positions()); DRAKE_DEMAND(ub.size() == num_positions()); // We have t = duration * s. So dsdt = 1/duration, d²sdt² = 0. Then q̈(t) = // r̈(s) * dsdt^2. // This again leverages the convex hull property to enforce the guarantee ∀t // by only constraining the values at the control points. Eigen::RowVectorXd M; VectorXDecisionVariable vars, duration_and_vars; std::unordered_map<symbolic::Variable::Id, int> unused_map; std::vector<std::vector<Binding<Constraint>>> binding( sym_rddot_->num_control_points()); for (int i = 0; i < sym_rddot_->num_control_points(); ++i) { for (int j = 0; j < num_positions(); ++j) { std::tie(vars, unused_map) = symbolic::ExtractVariablesFromExpression( sym_rddot_->control_points()[i](j)); M.resize(vars.size()); // TODO(russt): Avoid symbolic here and throughout. symbolic::DecomposeLinearExpressions( Vector1<Expression>(sym_rddot_->control_points()[i](j)), vars, &M); auto con = std::make_shared<DerivativeConstraint>(M, 2, lb.segment<1>(j), ub.segment<1>(j)); duration_and_vars.resize(vars.size() + 1); duration_and_vars << duration_, vars; binding[i].emplace_back(prog_.AddConstraint(con, duration_and_vars)); binding[i][j].evaluator()->set_description( fmt::format("acceleration bound {}, {}", i, j)); } } return binding; } std::vector<std::vector<Binding<Constraint>>> KinematicTrajectoryOptimization::AddJerkBounds( const Eigen::Ref<const VectorXd>& lb, const Eigen::Ref<const VectorXd>& ub) { DRAKE_DEMAND(lb.size() == num_positions()); DRAKE_DEMAND(ub.size() == num_positions()); // Following the derivations above, we have d³qdt³(t) = d³rds³(s) * dsdt*3. // This again leverages the convex hull property to enforce the guarantee ∀t // by only constraining the values at the control points. Eigen::RowVectorXd M; VectorXDecisionVariable vars, duration_and_vars; std::unordered_map<symbolic::Variable::Id, int> map_var_to_index; std::vector<std::vector<Binding<Constraint>>> binding( sym_rddot_->num_control_points()); for (int i = 0; i < sym_rdddot_->num_control_points(); ++i) { for (int j = 0; j < num_positions(); ++j) { std::tie(vars, map_var_to_index) = symbolic::ExtractVariablesFromExpression( sym_rdddot_->control_points()[i](j)); M.resize(vars.size()); symbolic::DecomposeLinearExpressions( Vector1<Expression>(sym_rdddot_->control_points()[i](j)), vars, &M); auto con = std::make_shared<DerivativeConstraint>(M, 3, lb.segment<1>(j), ub.segment<1>(j)); duration_and_vars.resize(vars.size() + 1); duration_and_vars << duration_, vars; binding[i].emplace_back(prog_.AddConstraint(con, duration_and_vars)); binding[i][j].evaluator()->set_description( fmt::format("jerk bound {}, {}", i, j)); } } return binding; } Binding<LinearCost> KinematicTrajectoryOptimization::AddDurationCost( double weight) { auto binding = prog_.AddLinearCost(weight * duration_); binding.evaluator()->set_description("duration cost"); return binding; } std::vector<Binding<Cost>> KinematicTrajectoryOptimization::AddPathLengthCost( double weight, bool use_conic_constraint) { MatrixXd A(num_positions_, 2 * num_positions_); A.leftCols(num_positions_) = weight * MatrixXd::Identity(num_positions_, num_positions_); A.rightCols(num_positions_) = -weight * MatrixXd::Identity(num_positions_, num_positions_); const VectorXd b = VectorXd::Zero(num_positions_); VectorXDecisionVariable vars(2 * num_positions_); std::vector<Binding<Cost>> binding; for (int i = 1; i < num_control_points(); ++i) { vars.head(num_positions_) = control_points_.col(i); vars.tail(num_positions_) = control_points_.col(i - 1); if (use_conic_constraint) { auto slack_cost_and_constraint_tuple = prog_.AddL2NormCostUsingConicConstraint(A, b, vars); binding.emplace_back(std::get<1>(slack_cost_and_constraint_tuple)); std::get<2>(slack_cost_and_constraint_tuple) .evaluator() ->set_description( fmt::format("path length cost {} conic constraint", i)); } else { binding.emplace_back(prog_.AddL2NormCost(A, b, vars)); } binding[i - 1].evaluator()->set_description( fmt::format("path length cost {}", i)); } return binding; } } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/direct_transcription.h
#pragma once #include <memory> #include <variant> #include "drake/common/drake_copyable.h" #include "drake/common/trajectories/piecewise_polynomial.h" #include "drake/planning/trajectory_optimization/multiple_shooting.h" #include "drake/systems/analysis/integrator_base.h" #include "drake/systems/framework/context.h" #include "drake/systems/framework/system.h" #include "drake/systems/primitives/linear_system.h" namespace drake { namespace planning { namespace trajectory_optimization { // Helper struct holding a time-step value for continuous-time // DirectTranscription. This is currently needed to disambiguate between the // constructors; DirectTranscription(system, context, int, int) could cast the // last int into a fixed_time_step or the input_port_index. struct TimeStep { double value{-1}; explicit TimeStep(double step) : value(step) {} }; /// DirectTranscription is perhaps the simplest implementation of a multiple /// shooting method, where we have decision variables representing the /// control and input at every sample time in the trajectory, and one-step /// of numerical integration provides the dynamic constraints between those /// decision variables. /// @ingroup planning_trajectory class DirectTranscription : public MultipleShooting { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DirectTranscription) /// Constructs the MathematicalProgram and adds the dynamic constraints. /// This version of the constructor is only for simple discrete-time systems /// (with a single periodic time step update). Continuous-time systems /// must call one of the constructors that takes bounds on the time step as /// an argument. /// /// @param system A dynamical system to be used in the dynamic constraints. /// This system must support System::ToAutoDiffXd. /// Note that this is aliased for the lifetime of this object. /// @param context Required to describe any parameters of the system. The /// values of the state in this context do not have any effect. This /// context will also be "cloned" by the optimization; changes to the /// context after calling this method will NOT impact the trajectory /// optimization. /// @param num_time_samples The number of breakpoints in the trajectory. /// @param input_port_index A valid input port index or valid /// InputPortSelection for @p system. All other inputs on the system will be /// left disconnected (if they are disconnected in @p context) or will be set /// to their current values (if they are connected/fixed in @p context). /// @default kUseFirstInputIfItExists. /// /// @throws std::exception if `context.has_only_discrete_state() == false`. DirectTranscription( const systems::System<double>* system, const systems::Context<double>& context, int num_time_samples, const std::variant<systems::InputPortSelection, systems::InputPortIndex>& input_port_index = systems::InputPortSelection::kUseFirstInputIfItExists); // TODO(russt): Generalize the symbolic short-cutting to handle this case, // and remove the special-purpose constructor (unless we want it for // efficiency). /// Constructs the MathematicalProgram and adds the dynamic constraints. This /// version of the constructor is only for *linear time-varying* discrete-time /// systems (with a single periodic time step update). This constructor adds /// value because the symbolic short-cutting does not yet support systems /// that are affine in state/input, but not time. /// /// @param system A linear time-varying system to be used in the dynamic /// constraints. Note that this is aliased for the lifetime of this object. /// @param context Required to describe any parameters of the system. The /// values of the state in this context do not have any effect. This /// context will also be "cloned" by the optimization; changes to the /// context after calling this method will NOT impact the trajectory /// optimization. /// @param num_time_samples The number of breakpoints in the trajectory. /// @param input_port_index A valid input port index or valid /// InputPortSelection for @p system. All other inputs on the system will be /// left disconnected (if they are disconnected in @p context) or will be set /// to their current values (if they are connected/fixed in @p context). /// @default kUseFirstInputIfItExists. /// /// @throws std::exception if `context.has_only_discrete_state() == false`. /// /// @exclude_from_pydrake_mkdoc{This overload is not bound in pydrake. When /// we do bind it, we should probably rename `system` to tv_linear_system` or /// similar, so that kwargs determine which overload is suggested, instead of /// hoping that type checking does the right thing.} DirectTranscription( const systems::TimeVaryingLinearSystem<double>* system, const systems::Context<double>& context, int num_time_samples, const std::variant<systems::InputPortSelection, systems::InputPortIndex>& input_port_index = systems::InputPortSelection::kUseFirstInputIfItExists); // TODO(russt): Support more than just forward Euler integration (by // accepting a SimulatorConfig.) /// Constructs the MathematicalProgram and adds the dynamic constraints. /// This version of the constructor is only for continuous-time systems; /// the dynamics constraints use explicit forward Euler integration. /// /// @param system A dynamical system to be used in the dynamic constraints. /// This system must support System::ToAutoDiffXd. /// Note that this is aliased for the lifetime of this object. /// @param context Required to describe any parameters of the system. The /// values of the state in this context do not have any effect. This /// context will also be "cloned" by the optimization; changes to the /// context after calling this method will NOT impact the trajectory /// optimization. /// @param num_time_samples The number of breakpoints in the trajectory. /// @param fixed_time_step The spacing between sample times. /// @param input_port_index A valid input port index or valid /// InputPortSelection for @p system. All other inputs on the system will be /// left disconnected (if they are disconnected in @p context) or will be set /// to their current values (if they are connected/fixed in @p context). /// @default kUseFirstInputIfItExists. /// /// @throws std::exception if `context.has_only_continuous_state() == false`. DirectTranscription( const systems::System<double>* system, const systems::Context<double>& context, int num_time_samples, TimeStep fixed_time_step, const std::variant<systems::InputPortSelection, systems::InputPortIndex>& input_port_index = systems::InputPortSelection::kUseFirstInputIfItExists); // TODO(russt): Implement constructor for continuous time systems with // time as a decision variable; and perhaps add support for mixed // discrete-/continuous- systems. ~DirectTranscription() override {} /// Get the input trajectory at the solution as a PiecewisePolynomial. The /// order of the trajectory will be determined by the integrator used in /// the dynamic constraints. trajectories::PiecewisePolynomial<double> ReconstructInputTrajectory( const solvers::MathematicalProgramResult& result) const override; /// Get the state trajectory at the solution as a PiecewisePolynomial. The /// order of the trajectory will be determined by the integrator used in /// the dynamic constraints. trajectories::PiecewisePolynomial<double> ReconstructStateTrajectory( const solvers::MathematicalProgramResult& result) const override; private: // Implements a running cost at all time steps. void DoAddRunningCost(const symbolic::Expression& e) override; // Attempts to create a symbolic version of the plant, and to add linear // constraints to impose the dynamics if possible. Returns true iff the // constraints are added. bool AddSymbolicDynamicConstraints( const systems::System<double>* system, const systems::Context<double>& context, const std::variant<systems::InputPortSelection, systems::InputPortIndex>& input_port_index); // Attempts to create an autodiff version of the plant, and to impose // the generic (nonlinear) constraints to impose the dynamics. // Aborts if the conversion ToAutoDiffXd fails. void AddAutodiffDynamicConstraints( const systems::System<double>* system, const systems::Context<double>& context, const std::variant<systems::InputPortSelection, systems::InputPortIndex>& input_port_index); // Constrain the final input to match the penultimate, otherwise the final // input is unconstrained. // (Note that it might be more ideal to have fewer decision variables // allocated, but this is a reasonable work-around). // // TODO(jadecastro) Allow MultipleShooting to take on N-1 inputs, and remove // this constraint. void ConstrainEqualInputAtFinalTwoTimesteps(); // Ensures that the MultipleShooting problem is well-formed and that the // provided @p system and @p context have only one group of discrete states // and only one (possibly multidimensional) input. void ValidateSystem( const systems::System<double>& system, const systems::Context<double>& context, const std::variant<systems::InputPortSelection, systems::InputPortIndex>& input_port_index); // AutoDiff versions of the System components (for the constraints). // These values are allocated iff the dynamic constraints are allocated // as DirectTranscriptionConstraint, otherwise they are nullptr. std::unique_ptr<const systems::System<AutoDiffXd>> system_; std::unique_ptr<systems::Context<AutoDiffXd>> context_; std::unique_ptr<systems::IntegratorBase<AutoDiffXd>> integrator_; const systems::InputPort<AutoDiffXd>* input_port_{nullptr}; // Owned by the context. systems::FixedInputPortValue* input_port_value_{nullptr}; const bool discrete_time_system_{false}; }; } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/gcs_trajectory_optimization.cc
#include "drake/planning/trajectory_optimization/gcs_trajectory_optimization.h" #include <limits> #include <tuple> #include <unordered_map> #include <unordered_set> #include "drake/common/pointer_cast.h" #include "drake/common/scope_exit.h" #include "drake/common/symbolic/decompose.h" #include "drake/geometry/optimization/cartesian_product.h" #include "drake/geometry/optimization/geodesic_convexity.h" #include "drake/geometry/optimization/hpolyhedron.h" #include "drake/geometry/optimization/intersection.h" #include "drake/geometry/optimization/point.h" #include "drake/math/autodiff_gradient.h" #include "drake/math/matrix_util.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/tree/planar_joint.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/solvers/solve.h" namespace drake { namespace planning { namespace trajectory_optimization { using Subgraph = GcsTrajectoryOptimization::Subgraph; using EdgesBetweenSubgraphs = GcsTrajectoryOptimization::EdgesBetweenSubgraphs; using drake::solvers::MathematicalProgram; using drake::solvers::Solve; using drake::solvers::VectorXDecisionVariable; using Eigen::MatrixXd; using Eigen::SparseMatrix; using Eigen::VectorXd; using geometry::optimization::CalcPairwiseIntersections; using geometry::optimization::CartesianProduct; using geometry::optimization::CheckIfSatisfiesConvexityRadius; using geometry::optimization::ConvexSet; using geometry::optimization::ConvexSets; using geometry::optimization::GraphOfConvexSets; using geometry::optimization::GraphOfConvexSetsOptions; using geometry::optimization::HPolyhedron; using geometry::optimization::Intersection; using geometry::optimization::PartitionConvexSet; using geometry::optimization::Point; using geometry::optimization::internal::ComputeOffsetContinuousRevoluteJoints; using geometry::optimization::internal::GetMinimumAndMaximumValueAlongDimension; using geometry::optimization::internal::ThrowsForInvalidContinuousJointsList; using math::ExtractValue; using math::InitializeAutoDiff; using multibody::Joint; using multibody::JointIndex; using multibody::MultibodyPlant; using multibody::PlanarJoint; using multibody::RevoluteJoint; using solvers::Binding; using solvers::ConcatenateVariableRefList; using solvers::Constraint; using solvers::Cost; using solvers::L2NormCost; using solvers::LinearConstraint; using solvers::LinearCost; using solvers::LinearEqualityConstraint; using symbolic::DecomposeLinearExpressions; using symbolic::Expression; using symbolic::MakeMatrixContinuousVariable; using symbolic::MakeVectorContinuousVariable; using trajectories::BezierCurve; using trajectories::CompositeTrajectory; using trajectories::Trajectory; using Vertex = GraphOfConvexSets::Vertex; using Edge = GraphOfConvexSets::Edge; using VertexId = GraphOfConvexSets::VertexId; using EdgeId = GraphOfConvexSets::EdgeId; using Transcription = GraphOfConvexSets::Transcription; const double kInf = std::numeric_limits<double>::infinity(); /* Implements a constraint of the form 0 <= - dᴺr(s) / dsᴺ - hᴺ * lb <= inf, 0 <= - dᴺr(s) / dsᴺ + hᴺ * ub <= inf, where N := derivative order, h = x[num_control_points], dᴺr(s) / dsᴺ = M * x[0:num_control_points]. This constraint is enforced along one dimension of the Bézier curve, hence must be called for each dimension separately. */ class NonlinearDerivativeConstraint : public solvers::Constraint { public: NonlinearDerivativeConstraint(const Eigen::SparseMatrix<double>& M, double lb, double ub, int derivative_order) : Constraint(2 * M.rows(), M.cols() + 1, Eigen::VectorXd::Zero(2 * M.rows()), Eigen::VectorXd::Constant( 2 * M.rows(), std::numeric_limits<double>::infinity())), M_(M), lb_(Eigen::VectorXd::Constant(M.rows(), lb)), ub_(Eigen::VectorXd::Constant(M.rows(), ub)), derivative_order_(derivative_order), num_control_points_(M.cols()) { DRAKE_DEMAND(derivative_order > 1); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const { AutoDiffVecXd y_t; Eval(InitializeAutoDiff(x), &y_t); *y = ExtractValue(y_t); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const { // x is the stack [r_control.row(i); h]. AutoDiffXd pow_h = pow(x[num_control_points_], derivative_order_); // Precompute Matrix Product. AutoDiffVecXd Mx = M_ * x.head(num_control_points_); y->head(M_.rows()) = Mx - pow_h * lb_; y->tail(M_.rows()) = -Mx + pow_h * ub_; } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const { throw std::runtime_error( "NonlinearDerivativeConstraint does not support evaluation with " "Expression."); } private: const Eigen::SparseMatrix<double> M_; const Eigen::VectorXd lb_; const Eigen::VectorXd ub_; const int derivative_order_; const int num_control_points_; }; /* Implements a constraint of the form (dᴺrᵤ(s=1) / dsᴺ) * hᵥᴺ == (dᴺrᵥ(s=0) / dsᴺ) * hᵤᴺ where N := derivative order, hᵤ = x[num_u_control_points], hᵥ = x[num_u_control_points + num_v_control_points + 1], dᴺrᵤ(s) / dsᴺ = Mu * x[0:num_u_control_points]. dᴺrᵥ(s) / dsᴺ = Mv * x[num_u_control_points + 1: -1]. This constraint is enforced along one dimension of the Bézier curve, hence must be called for each dimension separately. */ class NonlinearContinuityConstraint : public solvers::Constraint { public: NonlinearContinuityConstraint(const Eigen::SparseMatrix<double>& Mu, const Eigen::SparseMatrix<double>& Mv, int continuity_order) : Constraint(1, Mu.cols() + 1 + Mv.cols() + 1, Eigen::VectorXd::Zero(1), Eigen::VectorXd::Zero(1)), Mu_(Mu), Mv_(Mv), continuity_order_(continuity_order), num_control_points_u_(Mu.cols()), num_control_points_v_(Mv.cols()) { DRAKE_DEMAND(Mu.rows() == 1); DRAKE_DEMAND(Mv.rows() == 1); DRAKE_DEMAND(continuity_order >= 1); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const { AutoDiffVecXd y_t; Eval(InitializeAutoDiff(x), &y_t); *y = ExtractValue(y_t); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const { // x is the stack [r_control_u.row(i); h_u; r_control_v.row(i); h_v;]. AutoDiffXd pow_h_u = pow(x[num_control_points_u_], continuity_order_); AutoDiffXd pow_h_v = pow(x[num_control_points_u_ + num_control_points_v_ + 1], continuity_order_); // Precompute Matrix Products. AutoDiffXd Mu_x = Mu_.row(0) * x.head(num_control_points_u_); AutoDiffXd Mv_x = Mv_.row(0) * x.segment(num_control_points_u_ + 1, num_control_points_v_); (*y)[0] = Mu_x * pow_h_v - Mv_x * pow_h_u; } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const { throw std::runtime_error( "NonlinearContinuityConstraint does not support evaluation with " "Expression."); } private: const Eigen::SparseMatrix<double> Mu_; const Eigen::SparseMatrix<double> Mv_; const int continuity_order_; const int num_control_points_u_; const int num_control_points_v_; }; Subgraph::Subgraph( const ConvexSets& regions, const std::vector<std::pair<int, int>>& edges_between_regions, int order, double h_min, double h_max, std::string name, GcsTrajectoryOptimization* traj_opt, std::optional<const std::vector<VectorXd>> edge_offsets) : regions_(regions), order_(order), h_min_(h_min), name_(std::move(name)), traj_opt_(*traj_opt) { DRAKE_THROW_UNLESS(order >= 0); DRAKE_THROW_UNLESS(!regions_.empty()); if (edge_offsets.has_value()) { DRAKE_THROW_UNLESS(edge_offsets->size() == edges_between_regions.size()); } // Make sure all regions have the same ambient dimension. for (const std::unique_ptr<ConvexSet>& region : regions_) { DRAKE_THROW_UNLESS(region != nullptr); DRAKE_THROW_UNLESS(region->ambient_dimension() == num_positions()); } // If there are any continuous revolute joints, make sure the convexity radius // is respected. if (continuous_revolute_joints().size() > 0) { ThrowsForInvalidConvexityRadius(); } // Make time scaling set once to avoid many allocations when adding the // vertices to GCS. const HPolyhedron time_scaling_set = HPolyhedron::MakeBox(Vector1d(h_min), Vector1d(h_max)); // Add Regions with time scaling set. Eigen::VectorXd this_edge_offset = Eigen::VectorXd::Zero(num_positions()); for (int i = 0; i < ssize(regions_); ++i) { ConvexSets vertex_set; // Assign each control point to a separate set. const int num_points = order + 1; vertex_set.reserve(num_points + 1); vertex_set.insert(vertex_set.begin(), num_points, ConvexSets::value_type{*regions_[i]}); // Add time scaling set. vertex_set.emplace_back(time_scaling_set); vertices_.emplace_back(traj_opt_.gcs_.AddVertex( CartesianProduct(vertex_set), fmt::format("{}: Region{}", name_, i))); traj_opt->vertex_to_subgraph_[vertices_.back()] = this; } r_trajectory_ = BezierCurve<double>(0, 1, MatrixXd::Zero(num_positions(), order + 1)); // GetControlPoints(u).col(order) - GetControlPoints(v).col(0) = 0, via Ax = // 0, A = [I, -I], x = [u_controls.col(order); v_controls.col(0)]. Eigen::SparseMatrix<double> A(num_positions(), 2 * num_positions()); std::vector<Eigen::Triplet<double>> tripletList; tripletList.reserve(2 * num_positions()); for (int i = 0; i < num_positions(); ++i) { tripletList.push_back(Eigen::Triplet<double>(i, i, 1.0)); tripletList.push_back(Eigen::Triplet<double>(i, num_positions() + i, -1.0)); } A.setFromTriplets(tripletList.begin(), tripletList.end()); for (int idx = 0; idx < ssize(edges_between_regions); ++idx) { // Add edge. Vertex* u = vertices_[edges_between_regions[idx].first]; Vertex* v = vertices_[edges_between_regions[idx].second]; Edge* uv_edge = traj_opt_.AddEdge(u, v); edges_.emplace_back(uv_edge); // Add path continuity constraints. if (edge_offsets.has_value()) { // In this case, we instead enforce the constraint // GetControlPoints(u).col(order) - GetControlPoints(v).col(0) = // -tau_uv.value(), via Ax = -edge_offsets.value()[idx], A = [I, -I], // x = [u_controls.col(order); v_controls.col(0)]. this_edge_offset = -edge_offsets->at(idx); } const auto path_continuity_constraint = std::make_shared<LinearEqualityConstraint>(A, this_edge_offset); uv_edge->AddConstraint(Binding<Constraint>( path_continuity_constraint, {GetControlPoints(*u).col(order), GetControlPoints(*v).col(0)})); } } Subgraph::~Subgraph() = default; void Subgraph::ThrowsForInvalidConvexityRadius() const { for (int i = 0; i < ssize(regions_); ++i) { for (const int& j : continuous_revolute_joints()) { auto [min_value, max_value] = GetMinimumAndMaximumValueAlongDimension(*regions_[i], j); if (max_value - min_value >= M_PI) { throw std::runtime_error(fmt::format( "GcsTrajectoryOptimization: Region at index {} is wider than π " "along dimension {}, so it doesn't respect the convexity radius! " "To add this set, separate it into smaller pieces so that along " "dimensions corresponding to continuous revolute joints, its width " "is strictly smaller than π. This can be done manually, or with " "the helper function PartitionConvexSet.", i, j)); } } } } void Subgraph::AddTimeCost(double weight) { // The time cost is the sum of duration variables ∑ hᵢ auto time_cost = std::make_shared<LinearCost>(weight * Eigen::VectorXd::Ones(1), 0.0); for (Vertex* v : vertices_) { // The duration variable is the last element of the vertex. v->AddCost(Binding<LinearCost>(time_cost, v->x().tail(1))); } } void Subgraph::AddPathLengthCost(const MatrixXd& weight_matrix) { /* We will upper bound the trajectory length by the sum of the distances between the control points. ∑ |weight_matrix * (rᵢ₊₁ − rᵢ)|₂ */ DRAKE_THROW_UNLESS(weight_matrix.rows() == num_positions()); DRAKE_THROW_UNLESS(weight_matrix.cols() == num_positions()); if (order() == 0) { throw std::runtime_error( "Path length cost is not defined for a set of order 0."); } MatrixXd A(num_positions(), 2 * num_positions()); A << weight_matrix, -weight_matrix; const auto path_length_cost = std::make_shared<L2NormCost>(A, VectorXd::Zero(num_positions())); for (Vertex* v : vertices_) { auto control_points = GetControlPoints(*v); for (int i = 0; i < control_points.cols() - 1; ++i) { v->AddCost(Binding<L2NormCost>( path_length_cost, {control_points.col(i + 1), control_points.col(i)})); } } } void Subgraph::AddPathLengthCost(double weight) { const MatrixXd weight_matrix = weight * MatrixXd::Identity(num_positions(), num_positions()); return Subgraph::AddPathLengthCost(weight_matrix); } void Subgraph::AddVelocityBounds(const Eigen::Ref<const VectorXd>& lb, const Eigen::Ref<const VectorXd>& ub) { DRAKE_THROW_UNLESS(lb.size() == num_positions()); DRAKE_THROW_UNLESS(ub.size() == num_positions()); if (order() == 0) { throw std::runtime_error( "Velocity Bounds are not defined for a set of order 0."); } // We have q̇(t) = drds * dsdt = ṙ(s) / h, and h >= 0, so we // use h * lb <= ṙ(s) <= h * ub, formulated as: // 0 <= ṙ(s) - h * lb <= inf, // - inf <= ṙ(s) - h * ub <= 0. // This leverages the convex hull property of the B-splines: if all of the // control points satisfy these convex constraints and the curve is inside // the convex hull of these constraints, then the curve satisfies the // constraints for all t. // The relevant derivatives of the Bezier curve come in the form: // rdot_control.row(i).T = M.T * r_control.row(i).T, so we loop over the // positions, rather than over the control points. const VectorXd kVecInf = VectorXd::Constant(order_, kInf); const VectorXd kVecZero = VectorXd::Zero(order_); solvers::VectorXDecisionVariable vars(order_ + 2); SparseMatrix<double> H_lb( order_ /* number of control points for one row of ṙ(s)*/, order_ + 2 /* number of control points for one row of r(s) + 1*/); H_lb.leftCols(order_ + 1) = r_trajectory_.AsLinearInControlPoints(1).transpose(); SparseMatrix<double> H_ub = H_lb; for (int i = 0; i < num_positions(); ++i) { // Lower bound. 0 <= ṙ(s).row(i) - h * lb <= inf. H_lb.rightCols<1>() = VectorXd::Constant(order_, -lb[i]).sparseView(); const auto lb_constraint = std::make_shared<LinearConstraint>(H_lb, kVecZero, kVecInf); // Upper bound. -inf <= ṙ(s).row(i) - h * ub <= 0. H_ub.rightCols<1>() = VectorXd::Constant(order_, -ub[i]).sparseView(); const auto ub_constraint = std::make_shared<LinearConstraint>(H_ub, -kVecInf, kVecZero); for (Vertex* v : vertices_) { vars << GetControlPoints(*v).row(i).transpose(), GetTimeScaling(*v); v->AddConstraint(Binding<LinearConstraint>(lb_constraint, vars)); v->AddConstraint(Binding<LinearConstraint>(ub_constraint, vars)); } } } void Subgraph::AddNonlinearDerivativeBounds( const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, int derivative_order) { DRAKE_THROW_UNLESS(lb.size() == num_positions()); DRAKE_THROW_UNLESS(ub.size() == num_positions()); if (derivative_order > order()) { throw std::runtime_error( "Derivative order must be less than or equal to the set order."); } if (derivative_order == 1) { throw std::runtime_error( "Use AddVelocityBounds instead of AddNonlinearDerivativeBounds with " "derivative_order=1; velocity bounds are linear."); } if (derivative_order < 1) { throw std::runtime_error("Derivative order must be greater than 1."); } // The nonlinear derivative dᴺq(t) / dtᴺ = dᴺr(s) / dsᴺ / hᴺ, with h >= 0, // can be written as hᴺ * lb <= dᴺr(s) / dsᴺ <= hᴺ * ub, and constrained as: // 0 <= dᴺr(s) / dsᴺ - hᴺ * lb <= inf, // 0 <= - dᴺr(s) / dsᴺ + hᴺ * ub <= inf. // The nonlinear constraint will be enforced in the restriction and MIP // of GCS, while a convex surrogate in the relaxation transcription will // guide the rounding process. // Since hᴺ is the source of nonlinearities, we will replace it with: // h₀ᴺ⁻¹h // Then we will get the following linear constraint: // 0 <= dᴺr(s) / dsᴺ - h₀ᴺ⁻¹h * lb <= inf // 0 <= - dᴺr(s) / dsᴺ + h₀ᴺ⁻¹h * ub <= inf. // For simplicity sake, we will set h₀ to one until we come up with a // reasonable heuristic, e.g. based on the maximum length of the convex set. const double h0 = 1.0; // This leverages the convex hull property of the B-splines: if all of the // control points satisfy these convex constraints and the curve is inside // the convex hull of these constraints, then the curve satisfies the // constraints for all t. // The relevant derivatives of the Bezier curve come in the form: // rdot_control.row(i).T = M.T * r_control.row(i).T, so we loop over the // positions, rather than over the control points. solvers::VectorXDecisionVariable vars(order_ + 2); SparseMatrix<double> M_transpose = r_trajectory_.AsLinearInControlPoints(derivative_order).transpose(); // Lower bound: 0 <= (dᴺr(s) / dsᴺ).row(i) - h₀ᴺ⁻¹h * lb[i] <= inf, // Upper bound: 0 <= - (dᴺr(s) / dsᴺ).row(i) + h₀ᴺ⁻¹h * ub[i] <= inf. int rdot_control_points = order_ + 1 - derivative_order; const VectorXd kVecInf = VectorXd::Constant(2 * rdot_control_points, kInf); const VectorXd kVecZero = VectorXd::Zero(2 * rdot_control_points); Eigen::MatrixXd H( 2 * rdot_control_points, order_ + 2); // number of control points for one row of r(s) + 1 H.block(0, 0, M_transpose.rows(), M_transpose.cols()) = M_transpose; H.block(M_transpose.rows(), 0, M_transpose.rows(), M_transpose.cols()) = -M_transpose; for (int i = 0; i < num_positions(); ++i) { // Update the bounds for each position. H.block(0, order_ + 1, rdot_control_points, 1) = VectorXd::Constant( rdot_control_points, -std::pow(h0, derivative_order - 1) * lb[i]); H.block(rdot_control_points, order_ + 1, rdot_control_points, 1) = VectorXd::Constant(rdot_control_points, std::pow(h0, derivative_order - 1) * ub[i]); const auto normalized_path_derivative_constraint = std::make_shared<LinearConstraint>(H.sparseView(), kVecZero, kVecInf); const auto nonlinear_derivative_constraint = std::make_shared<NonlinearDerivativeConstraint>( M_transpose, lb[i], ub[i], derivative_order); for (Vertex* v : vertices_) { vars << GetControlPoints(*v).row(i).transpose(), GetTimeScaling(*v); // Add convex surrogate. v->AddConstraint(Binding<LinearConstraint>( normalized_path_derivative_constraint, vars), {Transcription::kRelaxation}); // Add nonlinear constraint. v->AddConstraint(Binding<NonlinearDerivativeConstraint>( nonlinear_derivative_constraint, vars), {Transcription::kMIP, Transcription::kRestriction}); } } } void Subgraph::AddPathContinuityConstraints(int continuity_order) { if (continuity_order == 0) { throw std::runtime_error( "Path continuity is enforced by default. Choose a higher order."); } if (continuity_order < 1) { throw std::runtime_error("Order must be greater than or equal to 1."); } if (order_ < continuity_order) { throw std::runtime_error( "Cannot add continuity constraint of order greater than the set " "order."); } // The continuity on derivatives of r(s) will be enforced between the last // control point of the u set and the first control point of the v set in an // edge. urdot_control.col(order-continuity_order) - vrdot_control.col(0) = 0, // The latter can be achieved by getting the control point matrix M. // A = [M.col(order - continuity_order).T, -M.col(0).T], // x = [u_controls.row(i); v_controls.row(i)]. // Ax = 0, SparseMatrix<double> Mu_transpose = r_trajectory_.AsLinearInControlPoints(continuity_order) .col(order_ - continuity_order) .transpose(); SparseMatrix<double> Mv_transpose = r_trajectory_.AsLinearInControlPoints(continuity_order) .col(0) .transpose(); // Concatenate Mu_transpose and Mv_transpose. // A = [Mu.T, - Mv.T] // The A matrix will have one row since sparsity allows us to enforce the // continuity in each dimension. The number of columns matches the number of // control points for one row of r_u(s) and r_v(s). SparseMatrix<double> A(1, 2 * (order_ + 1)); A.leftCols(order_ + 1) = Mu_transpose; A.rightCols(order_ + 1) = -Mv_transpose; const auto continuity_constraint = std::make_shared<LinearEqualityConstraint>(A, VectorXd::Zero(1)); for (int i = 0; i < num_positions(); ++i) { for (Edge* edge : edges_) { // Add continuity constraints. edge->AddConstraint(Binding<LinearEqualityConstraint>( continuity_constraint, {GetControlPoints(edge->u()).row(i), GetControlPoints(edge->v()).row(i)})); } } } void Subgraph::AddContinuityConstraints(int continuity_order) { if (continuity_order == 0) { throw std::runtime_error( "Path continuity is enforced by default. Choose a higher order."); } if (continuity_order < 1) { throw std::runtime_error("Order must be greater than or equal to 1."); } if (continuity_order > order_) { throw std::runtime_error( "Cannot add continuity constraint of order greater than the set " "order."); } // The continuity on derivatives of q(t) will be enforced between the last // control point of the u set and the first control point of the v set in an // edge. // Since the derivative of q(t) appears nonlinear in h, the following // nonlinear constraint will be enforced on the MIP and the restriction: // (dᴺrᵤ(s=1) / dsᴺ) / hᵤᴺ == (dᴺrᵥ(s=0) / dsᴺ) / hᵥᴺ. // Which can be written as: // urdot_control.col(order-N) * hᵥᴺ - vrdot_control.col(0) * hᵤᴺ = 0. SparseMatrix<double> Mu_transpose = r_trajectory_.AsLinearInControlPoints(continuity_order) .col(order_ - continuity_order) .transpose(); SparseMatrix<double> Mv_transpose = r_trajectory_.AsLinearInControlPoints(continuity_order) .col(0) .transpose(); const auto nonlinear_continuity_constraint = std::make_shared<NonlinearContinuityConstraint>( Mu_transpose, Mv_transpose, continuity_order); solvers::VectorXDecisionVariable vars(2 * (order_ + 2)); // Since hᵤᴺ, hᵥᴺ is the source of nonlinearities, we will replace it with // hᵤ₀ᴺ and hᵥ₀ᴺ, which are the characteristic times of the respective sets: // (dᴺrᵤ(s=1) / dsᴺ) / hᵤ₀ᴺ == (dᴺrᵥ(s=0) / dsᴺ) / hᵥ₀ᴺ. // Then we will get the following linear equality constraint as a surrogate: // urdot_control.col(order-N) * hᵥ₀ᴺ - vrdot_control.col(0) * hᵤ₀ᴺ = 0. // For simplicity sake, we will set hᵤ₀ and hᵥ₀ to one until we come up with a // reasonable heuristic, e.g. based on the maximum length of the convex set. const double hu0 = 1.0; const double hv0 = 1.0; // The latter can be achieved by getting the control point matrix M. // A = [Mu.col(order - continuity_order).T * hᵥ₀, -Mv.col(0).T * hᵤ₀], // x = [u_controls.row(i); v_controls.row(i)]. // Ax = 0, // The A matrix will have one row since sparsity allows us to enforce the // continuity in each dimension. The number of columns matches the number of // control points for one row of r_u(s) and r_v(s). SparseMatrix<double> A(1, 2 * (order_ + 1)); A.leftCols(order_ + 1) = Mu_transpose * hv0; A.rightCols(order_ + 1) = -Mv_transpose * hu0; const auto path_continuity_constraint = std::make_shared<LinearEqualityConstraint>(A, VectorXd::Zero(1)); for (int i = 0; i < num_positions(); ++i) { for (Edge* edge : edges_) { // Add convex surrogate. edge->AddConstraint( Binding<LinearEqualityConstraint>( path_continuity_constraint, {GetControlPoints(edge->u()).row(i), GetControlPoints(edge->v()).row(i)}), {Transcription::kRelaxation}); // Add nonlinear constraint. vars << GetControlPoints(edge->u()).row(i).transpose(), GetTimeScaling(edge->u()), GetControlPoints(edge->v()).row(i).transpose(), GetTimeScaling(edge->v()); edge->AddConstraint(Binding<NonlinearContinuityConstraint>( nonlinear_continuity_constraint, vars), {Transcription::kMIP, Transcription::kRestriction}); } } } Eigen::Map<const MatrixX<symbolic::Variable>> Subgraph::GetControlPoints( const geometry::optimization::GraphOfConvexSets::Vertex& v) const { DRAKE_DEMAND(v.x().size() == num_positions() * (order_ + 1) + 1); return Eigen::Map<const MatrixX<symbolic::Variable>>( v.x().data(), num_positions(), order_ + 1); } symbolic::Variable Subgraph::GetTimeScaling( const geometry::optimization::GraphOfConvexSets::Vertex& v) const { DRAKE_DEMAND(v.x().size() == num_positions() * (order_ + 1) + 1); return v.x()(v.x().size() - 1); } EdgesBetweenSubgraphs::EdgesBetweenSubgraphs( const Subgraph& from_subgraph, const Subgraph& to_subgraph, const ConvexSet* subspace, GcsTrajectoryOptimization* traj_opt) : traj_opt_(*traj_opt), from_subgraph_(from_subgraph), to_subgraph_(to_subgraph) { // Formulate edge costs and constraints. if (subspace != nullptr) { if (subspace->ambient_dimension() != num_positions()) { throw std::runtime_error( "Subspace dimension must match the number of positions."); } if (typeid(*subspace) != typeid(Point) && typeid(*subspace) != typeid(HPolyhedron)) { throw std::runtime_error("Subspace must be a Point or HPolyhedron."); } } ur_trajectory_ = BezierCurve<double>( 0, 1, MatrixXd::Zero(num_positions(), from_subgraph_.order() + 1)); vr_trajectory_ = BezierCurve<double>( 0, 1, MatrixXd::Zero(num_positions(), to_subgraph_.order() + 1)); // Zeroth order continuity constraints. // ur_control.col(-1) == vr_control.col(0). SparseMatrix<double> A(num_positions(), 2 * num_positions()); // A = [I, -I]. std::vector<Eigen::Triplet<double>> tripletList; tripletList.reserve(2 * num_positions()); for (int i = 0; i < num_positions(); ++i) { tripletList.push_back(Eigen::Triplet<double>(i, i, 1.0)); tripletList.push_back(Eigen::Triplet<double>(i, num_positions() + i, -1.0)); } A.setFromTriplets(tripletList.begin(), tripletList.end()); std::vector<VectorXd> sets_A_subspace_offset; if (subspace != nullptr) { std::vector<std::pair<double, double>> subspace_revolute_joints_bbox = GetMinimumAndMaximumValueAlongDimension(*subspace, continuous_revolute_joints()); for (const auto& region : from_subgraph.regions()) { std::vector<std::pair<double, double>> set_revolute_joints_bbox = GetMinimumAndMaximumValueAlongDimension(*region, continuous_revolute_joints()); sets_A_subspace_offset.push_back(ComputeOffsetContinuousRevoluteJoints( num_positions(), continuous_revolute_joints(), set_revolute_joints_bbox, subspace_revolute_joints_bbox)); } } const std::vector<std::tuple<int, int, Eigen::VectorXd>> edge_data = CalcPairwiseIntersections(from_subgraph.regions(), to_subgraph.regions(), continuous_revolute_joints()); for (const auto& edge : edge_data) { int i = std::get<0>(edge); int j = std::get<1>(edge); Eigen::VectorXd edge_offset = std::get<2>(edge); // Check if the overlap between the sets is contained in the subspace. if (subspace != nullptr) { Eigen::VectorXd subspace_offset = sets_A_subspace_offset[i]; if (!RegionsConnectThroughSubspace(*from_subgraph.regions()[i], *to_subgraph.regions()[j], *subspace, edge_offset, subspace_offset)) { continue; } } // Add edge. Vertex* u = from_subgraph.vertices_[i]; Vertex* v = to_subgraph.vertices_[j]; Edge* uv_edge = traj_opt_.AddEdge(u, v); edges_.emplace_back(uv_edge); // Add path continuity constraints. We instead enforce the constraint // u - v = -tau_uv, via Ax = -edge_offset, A = [I, -I], // x = [u_controls.col(order); v_controls.col(0)]. const auto path_continuity_constraint = std::make_shared<LinearEqualityConstraint>(A, -edge_offset); uv_edge->AddConstraint(Binding<Constraint>( path_continuity_constraint, ConcatenateVariableRefList( {GetControlPointsU(*uv_edge).col(from_subgraph_.order()), GetControlPointsV(*uv_edge).col(0)}))); if (subspace != nullptr) { // Add subspace constraints to the last control point of the u vertex. const auto vars = GetControlPointsU(*uv_edge).col(from_subgraph_.order()); // subspace will either be a Point or HPolyhedron. We check if it's a // Point via the method ConvexSet::MaybeGetPoint(), which will return a // value for Point, and won't return a value for HPolyhedron. std::optional<VectorXd> subspace_point = subspace->MaybeGetPoint(); if (subspace_point.has_value()) { // Encode u = subspace_point + subspace_offset via the linear equality // constraint [I][u] = [subspace_point + subspace_offset]. const auto subgraph_constraint = std::make_shared<LinearEqualityConstraint>( Eigen::MatrixXd::Identity(num_positions(), num_positions()), subspace_point.value() + sets_A_subspace_offset[i]); uv_edge->AddConstraint(Binding<Constraint>(subgraph_constraint, vars)); } else if (typeid(*subspace) == typeid(HPolyhedron)) { const HPolyhedron* hpoly = dynamic_cast<const HPolyhedron*>(subspace); const Eigen::MatrixXd& hpoly_A = hpoly->A(); const Eigen::VectorXd& hpoly_b = hpoly->b(); solvers::MathematicalProgram prog; const VectorX<symbolic::Variable> x = prog.NewContinuousVariables(num_positions(), "x"); // To translate the HPolyhedron, rewrite A*(x+offset)<=b as // Ax<=b-A*offset. prog.AddLinearConstraint( hpoly_A, Eigen::VectorXd::Constant(hpoly_b.size(), std::numeric_limits<double>::infinity()), hpoly_b - (hpoly_A * sets_A_subspace_offset[i]), x); for (const auto& binding : prog.GetAllConstraints()) { const std::shared_ptr<Constraint>& constraint = binding.evaluator(); uv_edge->AddConstraint(Binding<Constraint>(constraint, vars)); } } } } } EdgesBetweenSubgraphs::~EdgesBetweenSubgraphs() = default; bool EdgesBetweenSubgraphs::RegionsConnectThroughSubspace( const ConvexSet& A, const ConvexSet& B, const ConvexSet& subspace, std::optional<const VectorXd> maybe_set_B_offset, std::optional<const VectorXd> maybe_subspace_offset) { DRAKE_THROW_UNLESS(A.ambient_dimension() > 0); DRAKE_THROW_UNLESS(A.ambient_dimension() == B.ambient_dimension()); DRAKE_THROW_UNLESS(A.ambient_dimension() == subspace.ambient_dimension()); DRAKE_THROW_UNLESS(maybe_set_B_offset.has_value() == maybe_subspace_offset.has_value()); if (maybe_set_B_offset.has_value()) { DRAKE_THROW_UNLESS(maybe_set_B_offset.value().size() == A.ambient_dimension()); DRAKE_THROW_UNLESS(maybe_subspace_offset.value().size() == A.ambient_dimension()); } if (std::optional<VectorXd> subspace_point = subspace.MaybeGetPoint()) { // If the subspace is a point, then the point must be in both A and B. if (maybe_set_B_offset.has_value()) { // Compute the value of the point such that it can be directly checked for // containment in A. We take its given value, and subtract the offset from // the set to the subspace. const VectorXd point_in_A_coords = *subspace_point - maybe_subspace_offset.value(); // Compute the value of the point such that it can be directly checked for // containment in B. We take the value of the point that can be checked // for A, and add the offset form A to B. const VectorXd point_in_B_coords = point_in_A_coords + maybe_set_B_offset.value(); return A.PointInSet(point_in_A_coords) && B.PointInSet(point_in_B_coords); } else { return A.PointInSet(*subspace_point) && B.PointInSet(*subspace_point); } } else if (!maybe_set_B_offset.has_value()) { // Otherwise, we can formulate a problem to check if a point is contained in // A, B and the subspace. Intersection intersection(MakeConvexSets(A, B, subspace)); return !intersection.IsEmpty(); } else { // The program has to be different if there's an offset. const int dimension = A.ambient_dimension(); MathematicalProgram prog; VectorXDecisionVariable x = prog.NewContinuousVariables(dimension); VectorXDecisionVariable y = prog.NewContinuousVariables(dimension); VectorXDecisionVariable z = prog.NewContinuousVariables(dimension); A.AddPointInSetConstraints(&prog, x); B.AddPointInSetConstraints(&prog, y); subspace.AddPointInSetConstraints(&prog, z); MatrixXd equality_constraint_matrix(dimension, 2 * dimension); equality_constraint_matrix.leftCols(dimension) = MatrixXd::Identity(dimension, dimension); equality_constraint_matrix.rightCols(dimension) = -MatrixXd::Identity(dimension, dimension); // y = x + B_offset as [I, -I][y; x] = [B_offset]. prog.AddLinearEqualityConstraint(equality_constraint_matrix, maybe_set_B_offset.value(), {x, y}); // z = x + subspace_offset as [I, -I][z; x] = [subspace_offset] prog.AddLinearEqualityConstraint(equality_constraint_matrix, maybe_subspace_offset.value(), {x, z}); const auto result = Solve(prog); return result.is_success(); } } void EdgesBetweenSubgraphs::AddVelocityBounds( const Eigen::Ref<const VectorXd>& lb, const Eigen::Ref<const VectorXd>& ub) { DRAKE_THROW_UNLESS(lb.size() == num_positions()); DRAKE_THROW_UNLESS(ub.size() == num_positions()); // We have q̇(t) = drds * dsdt = ṙ(s) / h, and h >= 0, so we // use h * lb <= ṙ(s) <= h * ub, formulated as: // 0 <= ṙ(s) - h * lb <= inf, // - inf <= ṙ(s) - h * ub <= 0. // We will enforce the velocity bounds on the last control point of the u set // and on the first control point of the v set unless one of the sets are of // order zero. In the zero order case, velocity doesn't matter since its a // point. const Vector1d kVecInf = Vector1d::Constant(kInf); const Vector1d kVecZero = Vector1d::Zero(); if (from_subgraph_.order() == 0 && to_subgraph_.order() == 0) { throw std::runtime_error( "Cannot add velocity bounds to a subgraph edges where both subgraphs " "have zero order."); } if (from_subgraph_.order() > 0) { // Add velocity bounds to the last control point of the u set. // See BezierCurve::AsLinearInControlPoints(). solvers::VectorXDecisionVariable vars(from_subgraph_.order() + 2); SparseMatrix<double> m = ur_trajectory_.AsLinearInControlPoints(1) .col(from_subgraph_.order() - 1) .transpose(); SparseMatrix<double> H_lb( 1 /* we are only constraining the last point in the u set */, from_subgraph_.order() + 2 /* number of control points for one row of r(s) + 1*/); H_lb.leftCols(from_subgraph_.order() + 1) = m; SparseMatrix<double> H_ub = H_lb; for (int i = 0; i < num_positions(); ++i) { // Lower bound. 0 <= ṙ(s).row(i) - h * lb <= inf. H_lb.coeffRef(0, from_subgraph_.order() + 1) = -lb[i]; const auto lb_constraint = std::make_shared<LinearConstraint>(H_lb, kVecZero, kVecInf); // Upper bound. -inf <= ṙ(s).row(i) - h * ub <= 0. H_ub.coeffRef(0, from_subgraph_.order() + 1) = -ub[i]; const auto ub_constraint = std::make_shared<LinearConstraint>(H_ub, -kVecInf, kVecZero); for (Edge* edge : edges_) { // vars = [control_points.row(i).T; time_scaling] vars << GetControlPointsU(*edge).row(i).transpose(), GetTimeScalingU(*edge); edge->AddConstraint(Binding<LinearConstraint>(lb_constraint, vars)); edge->AddConstraint(Binding<LinearConstraint>(ub_constraint, vars)); } } } if (to_subgraph_.order() > 0) { // Add velocity bounds to the first control point of the v set. // See Subgraph::AddVelocityBounds(). solvers::VectorXDecisionVariable vars(to_subgraph_.order() + 2); SparseMatrix<double> m = vr_trajectory_.AsLinearInControlPoints(1).col(0).transpose(); SparseMatrix<double> H_lb( 1 /* we are only constraining the last point in the u set */, to_subgraph_.order() + 2 /* number of control points for one row of r(s) + 1*/); H_lb.leftCols(to_subgraph_.order() + 1) = m; SparseMatrix<double> H_ub = H_lb; for (int i = 0; i < num_positions(); ++i) { // Lower bound. 0 <= ṙ(s).row(i) - h * lb <= inf. H_lb.coeffRef(0, to_subgraph_.order() + 1) = -lb[i]; const auto lb_constraint = std::make_shared<LinearConstraint>(H_lb, kVecZero, kVecInf); // Upper bound. -inf <= ṙ(s).row(i) - h * ub <= 0. H_ub.coeffRef(0, to_subgraph_.order() + 1) = -ub[i]; const auto ub_constraint = std::make_shared<LinearConstraint>(H_ub, -kVecInf, kVecZero); for (Edge* edge : edges_) { // vars = [control_points.row(i).T; time_scaling] vars << GetControlPointsV(*edge).row(i).transpose(), GetTimeScalingV(*edge); edge->AddConstraint(Binding<LinearConstraint>(lb_constraint, vars)); edge->AddConstraint(Binding<LinearConstraint>(ub_constraint, vars)); } } } } void EdgesBetweenSubgraphs::AddNonlinearDerivativeBounds( const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, int derivative_order) { DRAKE_THROW_UNLESS(lb.size() == num_positions()); DRAKE_THROW_UNLESS(ub.size() == num_positions()); if (derivative_order < 1) { throw std::runtime_error("Derivative order must be greater than 1."); } if (derivative_order == 1) { throw std::runtime_error( "Use AddVelocityBounds instead of AddNonlinearDerivativeBounds with " "derivative_order=1; velocity bounds are linear."); } if (derivative_order > from_subgraph_.order() && derivative_order > to_subgraph_.order()) { throw std::runtime_error(fmt::format( "Cannot add derivative bounds to subgraph edges where both subgraphs " "have less than derivative order.\n From subgraph order: {}\n To " "subgraph order: {}\n Derivative order: {}", from_subgraph_.order(), to_subgraph_.order(), derivative_order)); } // See see Subgraph::AddNonlinearDerivativeBounds for details on how the // nonlinear derivative constraints are formulated. // We will enforce the derivative bounds on the last control point of the u // set and on the first control point of the v set unless one of the sets // order is less than the derivative order. const VectorXd kVecInf = VectorXd::Constant(2, kInf); const VectorXd kVecZero = VectorXd::Zero(2); const double h0 = 1.0; if (from_subgraph_.order() >= derivative_order) { // Add derivative bounds to the last control point of the u set. // See BezierCurve::AsLinearInControlPoints(). solvers::VectorXDecisionVariable vars(from_subgraph_.order() + 2); SparseMatrix<double> M_transpose = ur_trajectory_.AsLinearInControlPoints(derivative_order) .col(from_subgraph_.order() - derivative_order) .transpose(); Eigen::MatrixXd H( 2 /* we are only constraining the last point in the u set */, from_subgraph_.order() + 2 /* number of control points for one row of r(s) + 1*/); H.block(0, 0, 1, from_subgraph_.order() + 1) = M_transpose; H.block(1, 0, 1, from_subgraph_.order() + 1) = -M_transpose; for (int i = 0; i < num_positions(); ++i) { // Lower bound: 0 <= (dᴺr(s=1) / dsᴺ).row(i) - h₀ᴺ⁻¹ h * lb[i] <= inf, // Upper bound: 0 <= - (dᴺr(s=1) / dsᴺ).row(i) + h₀ᴺ⁻¹ h * ub[i] <= inf. H(0, from_subgraph_.order() + 1) = -std::pow(h0, derivative_order - 1) * lb[i]; H(1, from_subgraph_.order() + 1) = std::pow(h0, derivative_order - 1) * ub[i]; const auto convex_derivative_constraint = std::make_shared<LinearConstraint>(H.sparseView(), kVecZero, kVecInf); const auto nonlinear_derivative_constraint = std::make_shared<NonlinearDerivativeConstraint>( M_transpose, lb[i], ub[i], derivative_order); for (Edge* edge : edges_) { vars << GetControlPointsU(*edge).row(i).transpose(), GetTimeScalingU(*edge); // Add convex surrogate. edge->AddConstraint( Binding<LinearConstraint>(convex_derivative_constraint, vars), {Transcription::kRelaxation}); // Add nonlinear constraint. edge->AddConstraint(Binding<NonlinearDerivativeConstraint>( nonlinear_derivative_constraint, vars), {Transcription::kMIP, Transcription::kRestriction}); } } } if (to_subgraph_.order() >= derivative_order) { // Add velocity bounds to the first control point of the v set. // See BezierCurve::AsLinearInControlPoints(). solvers::VectorXDecisionVariable vars(to_subgraph_.order() + 2); SparseMatrix<double> M_transpose = vr_trajectory_.AsLinearInControlPoints(derivative_order) .col(0) .transpose(); Eigen::MatrixXd H( 2 /* we are only constraining the last point in the v set */, to_subgraph_.order() + 2 /* number of control points for one row of r(s) + 1*/); H.block(0, 0, 1, to_subgraph_.order() + 1) = M_transpose; H.block(1, 0, 1, to_subgraph_.order() + 1) = -M_transpose; for (int i = 0; i < num_positions(); ++i) { // Lower bound: 0 <= (dᴺr(s=0) / dsᴺ).row(i) - h₀ᴺ⁻¹h * lb[i] <= inf, // Upper bound: 0 <= - (dᴺr(s=0) / dsᴺ).row(i) + h₀ᴺ⁻¹h * ub[i] <= inf. H(0, to_subgraph_.order() + 1) = -std::pow(h0, derivative_order - 1) * lb[i]; H(1, to_subgraph_.order() + 1) = std::pow(h0, derivative_order - 1) * ub[i]; const auto convex_derivative_constraint = std::make_shared<LinearConstraint>(H.sparseView(), kVecZero, kVecInf); const auto nonlinear_derivative_constraint = std::make_shared<NonlinearDerivativeConstraint>( M_transpose, lb[i], ub[i], derivative_order); for (Edge* edge : edges_) { vars << GetControlPointsV(*edge).row(i).transpose(), GetTimeScalingU(*edge); // Add convex surrogate. edge->AddConstraint( Binding<LinearConstraint>(convex_derivative_constraint, vars), {Transcription::kRelaxation}); // Add nonlinear constraint. edge->AddConstraint(Binding<NonlinearDerivativeConstraint>( nonlinear_derivative_constraint, vars), {Transcription::kMIP, Transcription::kRestriction}); } } } } void EdgesBetweenSubgraphs::AddZeroDerivativeConstraints(int derivative_order) { if (derivative_order < 1) { throw std::runtime_error("Derivative order must be greater than 1."); } if (derivative_order > from_subgraph_.order() && derivative_order > to_subgraph_.order()) { throw std::runtime_error(fmt::format( "Cannot add derivative bounds to subgraph edges where both subgraphs " "have less than derivative order.\n From subgraph order: {}\n To " "subgraph order: {}\n Derivative order: {}", from_subgraph_.order(), to_subgraph_.order(), derivative_order)); } // We have dᴺq(t) / dtᴺ = dᴺr(s)/(dsᴺ * hᴺ) and h >= 0, which is nonlinear. // To constraint zero velocity we can set the numerator to zero, which is // convex: // dᴺr(s) / dsᴺ = 0. const Vector1d kVecZero = Vector1d::Zero(); if (from_subgraph_.order() >= derivative_order) { // Add derivative bounds to the last control point of the u set. // See BezierCurve::AsLinearInControlPoints(). SparseMatrix<double> M_transpose = ur_trajectory_.AsLinearInControlPoints(derivative_order) .col(from_subgraph_.order() - derivative_order) .transpose(); // Equality constraint. // (dᴺr(s) / dsᴺ).row(i) = 0. const auto zero_derivative_constraint = std::make_shared<LinearEqualityConstraint>(M_transpose, kVecZero); for (int i = 0; i < num_positions(); ++i) { for (Edge* edge : edges_) { edge->AddConstraint(Binding<LinearEqualityConstraint>( zero_derivative_constraint, GetControlPointsU(*edge).row(i).transpose())); } } } if (to_subgraph_.order() >= derivative_order) { // Add derivative bounds to the first control point of the v set. // See BezierCurve::AsLinearInControlPoints(). SparseMatrix<double> M_transpose = vr_trajectory_.AsLinearInControlPoints(derivative_order) .col(0) .transpose(); // Equality constraint: // (dᴺr(s) / dsᴺ).row(i) = 0. const auto zero_derivative_constraint = std::make_shared<LinearEqualityConstraint>(M_transpose, kVecZero); for (int i = 0; i < num_positions(); ++i) { for (Edge* edge : edges_) { edge->AddConstraint(Binding<LinearEqualityConstraint>( zero_derivative_constraint, GetControlPointsV(*edge).row(i).transpose())); } } } } void EdgesBetweenSubgraphs::AddPathContinuityConstraints(int continuity_order) { if (continuity_order == 0) { throw std::runtime_error( "Path continuity is enforced by default. Choose a higher order."); } if (continuity_order < 1) { throw std::runtime_error("Order must be greater than or equal to 1."); } if (continuity_order > from_subgraph_.order() || continuity_order > to_subgraph_.order()) { throw std::runtime_error( "Cannot add continuity constraint to a subgraph edge where both " "subgraphs order are not greater than or equal to the requested " "continuity order."); } // The continuity on derivatives of r(s) will be enforced between the last // control point of the u set and the first control point of the v set in an // edge. urdot_control.col(order-continuity_order) - vrdot_control.col(0) = 0, // The latter can be achieved by getting the control point matrix M. // A = [M.col(from_subgraph.order() - continuity_order).T, -M.col(0).T], // x = [u_controls.row(i); v_controls.row(i)]. // Ax = 0, SparseMatrix<double> Mu_transpose = ur_trajectory_.AsLinearInControlPoints(continuity_order) .col(from_subgraph_.order() - continuity_order) .transpose(); SparseMatrix<double> Mv_transpose = vr_trajectory_.AsLinearInControlPoints(continuity_order) .col(0) .transpose(); // Concatenate Mu_transpose and Mv_transpose. // A = [Mu.T, - Mv.T] // The A matrix will have one row since sparsity allows us to enforce the // continuity in each dimension. The number of columns matches the number of // control points for one row of r_u(s) and r_v(s). SparseMatrix<double> A( 1, (from_subgraph_.order() + 1) + (to_subgraph_.order() + 1)); A.leftCols(from_subgraph_.order() + 1) = Mu_transpose; A.rightCols(to_subgraph_.order() + 1) = -Mv_transpose; const auto continuity_constraint = std::make_shared<LinearEqualityConstraint>(A, VectorXd::Zero(1)); for (int i = 0; i < num_positions(); ++i) { for (Edge* edge : edges_) { // Add continuity constraints. edge->AddConstraint(Binding<LinearEqualityConstraint>( continuity_constraint, {GetControlPointsU(*edge).row(i), GetControlPointsV(*edge).row(i)})); } } } void EdgesBetweenSubgraphs::AddContinuityConstraints(int continuity_order) { if (continuity_order == 0) { throw std::runtime_error( "Path continuity is enforced by default. Choose a higher order."); } if (continuity_order < 1) { throw std::runtime_error("Order must be greater than or equal to 1."); } if (continuity_order > from_subgraph_.order() || continuity_order > to_subgraph_.order()) { throw std::runtime_error( "Cannot add continuity constraint to a subgraph edge where both " "subgraphs order are not greater than or equal to the requested " "continuity order."); } // See see Subgraph::AddContinuityConstraints for details on how the // nonlinear derivative constraints are formulated. // The continuity on derivatives of q(s) will be enforced between the last // control point of the u set and the first control point of the v set in an // edge. const double hu0 = 1.0; const double hv0 = 1.0; SparseMatrix<double> Mu_transpose = ur_trajectory_.AsLinearInControlPoints(continuity_order) .col(from_subgraph_.order() - continuity_order) .transpose(); SparseMatrix<double> Mv_transpose = vr_trajectory_.AsLinearInControlPoints(continuity_order) .col(0) .transpose(); const auto nonlinear_continuity_constraint = std::make_shared<NonlinearContinuityConstraint>( Mu_transpose, Mv_transpose, continuity_order); solvers::VectorXDecisionVariable vars(from_subgraph_.order() + 2 + to_subgraph_.order() + 2); // The A matrix will have one row since sparsity allows us to enforce the // continuity in each dimension. The number of columns matches the number of // control points for one row of r_u(s) and r_v(s). SparseMatrix<double> A( 1, (from_subgraph_.order() + 1) + (to_subgraph_.order() + 1)); A.leftCols(from_subgraph_.order() + 1) = Mu_transpose * hv0; A.rightCols(to_subgraph_.order() + 1) = -Mv_transpose * hu0; const auto path_continuity_constraint = std::make_shared<LinearEqualityConstraint>(A, VectorXd::Zero(1)); for (int i = 0; i < num_positions(); ++i) { for (Edge* edge : edges_) { // Add convex surrogate. edge->AddConstraint( Binding<LinearEqualityConstraint>(path_continuity_constraint, {GetControlPointsU(*edge).row(i), GetControlPointsV(*edge).row(i)}), {Transcription::kRelaxation}); // Add nonlinear constraint. vars << GetControlPointsU(*edge).row(i).transpose(), GetTimeScalingU(*edge), GetControlPointsV(*edge).row(i).transpose(), GetTimeScalingV(*edge); edge->AddConstraint(Binding<NonlinearContinuityConstraint>( nonlinear_continuity_constraint, vars), {Transcription::kMIP, Transcription::kRestriction}); } } } Eigen::Map<const MatrixX<symbolic::Variable>> EdgesBetweenSubgraphs::GetControlPointsU( const geometry::optimization::GraphOfConvexSets::Edge& e) const { DRAKE_DEMAND(e.xu().size() == num_positions() * (from_subgraph_.order() + 1) + 1); return Eigen::Map<const MatrixX<symbolic::Variable>>( e.xu().data(), num_positions(), from_subgraph_.order() + 1); } Eigen::Map<const MatrixX<symbolic::Variable>> EdgesBetweenSubgraphs::GetControlPointsV( const geometry::optimization::GraphOfConvexSets::Edge& e) const { DRAKE_DEMAND(e.xv().size() == num_positions() * (to_subgraph_.order() + 1) + 1); return Eigen::Map<const MatrixX<symbolic::Variable>>( e.xv().data(), num_positions(), to_subgraph_.order() + 1); } symbolic::Variable EdgesBetweenSubgraphs::GetTimeScalingU( const geometry::optimization::GraphOfConvexSets::Edge& e) const { DRAKE_DEMAND(e.xu().size() == num_positions() * (from_subgraph_.order() + 1) + 1); return e.xu()(e.xu().size() - 1); } symbolic::Variable EdgesBetweenSubgraphs::GetTimeScalingV( const geometry::optimization::GraphOfConvexSets::Edge& e) const { DRAKE_DEMAND(e.xv().size() == num_positions() * (to_subgraph_.order() + 1) + 1); return e.xv()(e.xv().size() - 1); } GcsTrajectoryOptimization::GcsTrajectoryOptimization( int num_positions, std::vector<int> continuous_revolute_joints) : num_positions_(num_positions), continuous_revolute_joints_(std::move(continuous_revolute_joints)) { DRAKE_THROW_UNLESS(num_positions >= 1); ThrowsForInvalidContinuousJointsList(num_positions, continuous_revolute_joints_); } GcsTrajectoryOptimization::~GcsTrajectoryOptimization() = default; Subgraph& GcsTrajectoryOptimization::AddRegions( const ConvexSets& regions, const std::vector<std::pair<int, int>>& edges_between_regions, int order, double h_min, double h_max, std::string name, std::optional<const std::vector<VectorXd>> edge_offsets) { if (edge_offsets.has_value()) { DRAKE_THROW_UNLESS(edge_offsets->size() == edges_between_regions.size()); } if (name.empty()) { name = fmt::format("Subgraph{}", subgraphs_.size()); } Subgraph* subgraph = new Subgraph(regions, edges_between_regions, order, h_min, h_max, std::move(name), this, edge_offsets); // Add global costs to the subgraph. for (double weight : global_time_costs_) { subgraph->AddTimeCost(weight); } if (order > 0) { // These costs and constraints rely on the derivative of the trajectory. for (const MatrixXd& weight_matrix : global_path_length_costs_) { subgraph->AddPathLengthCost(weight_matrix); } for (const auto& [lb, ub] : global_velocity_bounds_) { subgraph->AddVelocityBounds(lb, ub); } } for (auto& [lb, ub, derivative_order] : global_nonlinear_derivative_bounds_) { if (order >= derivative_order) { subgraph->AddNonlinearDerivativeBounds(lb, ub, derivative_order); } } // Add global continuity constraints to the subgraph. for (int continuity_order : global_path_continuity_constraints_) { if (order >= continuity_order) { subgraph->AddPathContinuityConstraints(continuity_order); } } for (int continuity_order : global_continuity_constraints_) { if (order >= continuity_order) { subgraph->AddContinuityConstraints(continuity_order); } } return *subgraphs_.emplace_back(subgraph); } Subgraph& GcsTrajectoryOptimization::AddRegions(const ConvexSets& regions, int order, double h_min, double h_max, std::string name) { // TODO(wrangelvid): This is O(n^2) and can be improved. DRAKE_DEMAND(regions.size() > 0); const std::vector<std::tuple<int, int, Eigen::VectorXd>> edge_data = CalcPairwiseIntersections(regions, continuous_revolute_joints()); std::vector<std::pair<int, int>> edges_between_regions; std::vector<Eigen::VectorXd> edge_offsets; edges_between_regions.reserve(edge_data.size()); edge_offsets.reserve(edge_data.size()); for (int i = 0; i < ssize(edge_data); ++i) { edges_between_regions.emplace_back(std::get<0>(edge_data[i]), std::get<1>(edge_data[i])); edge_offsets.emplace_back(std::get<2>(edge_data[i])); } return GcsTrajectoryOptimization::AddRegions(regions, edges_between_regions, order, h_min, h_max, std::move(name), edge_offsets); } void GcsTrajectoryOptimization::RemoveSubgraph(const Subgraph& subgraph) { // Check if the subgraph is in the list of subgraphs. if (!std::any_of(subgraphs_.begin(), subgraphs_.end(), [&](const std::unique_ptr<Subgraph>& s) { return s.get() == &subgraph; })) { throw std::runtime_error(fmt::format( "Subgraph {} is not registered with `this`", subgraph.name())); } // Remove the underlying edges between subgraphs from the gcs problem. for (const std::unique_ptr<EdgesBetweenSubgraphs>& subgraph_edge : subgraph_edges_) { if (&subgraph_edge->from_subgraph_ == &subgraph || &subgraph_edge->to_subgraph_ == &subgraph) { for (Edge* edge : subgraph_edge->edges_) { gcs_.RemoveEdge(edge); } } } // Remove the edges between subgraphs objects. subgraph_edges_.erase( std::remove_if(subgraph_edges_.begin(), subgraph_edges_.end(), [&](const std::unique_ptr<EdgesBetweenSubgraphs>& e) { return &e->from_subgraph_ == &subgraph || &e->to_subgraph_ == &subgraph; }), subgraph_edges_.end()); // Remove all vertices in the subgraph. for (Vertex* v : subgraph.vertices_) { // This will also remove all edges connected to the vertex. gcs_.RemoveVertex(v); } // Remove the subgraph from the list of subgraphs. subgraphs_.erase(std::remove_if(subgraphs_.begin(), subgraphs_.end(), [&](const std::unique_ptr<Subgraph>& s) { return s.get() == &subgraph; }), subgraphs_.end()); } EdgesBetweenSubgraphs& GcsTrajectoryOptimization::AddEdges( const Subgraph& from_subgraph, const Subgraph& to_subgraph, const ConvexSet* subspace) { EdgesBetweenSubgraphs* subgraph_edge = new EdgesBetweenSubgraphs(from_subgraph, to_subgraph, subspace, this); // Add global continuity constraints to the edges between subgraphs. for (int continuity_order : global_path_continuity_constraints_) { if (subgraph_edge->from_subgraph_.order() >= continuity_order && subgraph_edge->to_subgraph_.order() >= continuity_order) { subgraph_edge->AddPathContinuityConstraints(continuity_order); } } for (int continuity_order : global_continuity_constraints_) { if (subgraph_edge->from_subgraph_.order() >= continuity_order && subgraph_edge->to_subgraph_.order() >= continuity_order) { subgraph_edge->AddContinuityConstraints(continuity_order); } } return *subgraph_edges_.emplace_back(subgraph_edge); } void GcsTrajectoryOptimization::AddTimeCost(double weight) { // Add time cost to each subgraph. for (std::unique_ptr<Subgraph>& subgraph : subgraphs_) { subgraph->AddTimeCost(weight); } global_time_costs_.push_back(weight); } void GcsTrajectoryOptimization::AddPathLengthCost( const MatrixXd& weight_matrix) { // Add path length cost to each subgraph. for (std::unique_ptr<Subgraph>& subgraph : subgraphs_) { if (subgraph->order() > 0) { subgraph->AddPathLengthCost(weight_matrix); } } global_path_length_costs_.push_back(weight_matrix); } void GcsTrajectoryOptimization::AddPathLengthCost(double weight) { const MatrixXd weight_matrix = weight * MatrixXd::Identity(num_positions(), num_positions()); return GcsTrajectoryOptimization::AddPathLengthCost(weight_matrix); } void GcsTrajectoryOptimization::AddVelocityBounds( const Eigen::Ref<const VectorXd>& lb, const Eigen::Ref<const VectorXd>& ub) { DRAKE_THROW_UNLESS(lb.size() == num_positions()); DRAKE_THROW_UNLESS(ub.size() == num_positions()); // Add path velocity bounds to each subgraph. for (std::unique_ptr<Subgraph>& subgraph : subgraphs_) { if (subgraph->order() > 0) { subgraph->AddVelocityBounds(lb, ub); } } global_velocity_bounds_.push_back({lb, ub}); } void GcsTrajectoryOptimization::AddNonlinearDerivativeBounds( const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, int derivative_order) { DRAKE_THROW_UNLESS(lb.size() == num_positions()); DRAKE_THROW_UNLESS(ub.size() == num_positions()); // Add nonlinear derivative bounds to each subgraph. for (std::unique_ptr<Subgraph>& subgraph : subgraphs_) { if (subgraph->order() >= derivative_order) { subgraph->AddNonlinearDerivativeBounds(lb, ub, derivative_order); } } global_nonlinear_derivative_bounds_.push_back({lb, ub, derivative_order}); } void GcsTrajectoryOptimization::AddPathContinuityConstraints( int continuity_order) { if (continuity_order == 0) { throw std::runtime_error( "Path continuity is enforced by default. Choose a higher order."); } if (continuity_order < 1) { throw std::runtime_error("Order must be greater than or equal to 1."); } // Add continuity constraints to each subgraph. for (std::unique_ptr<Subgraph>& subgraph : subgraphs_) { if (subgraph->order() >= continuity_order) { subgraph->AddPathContinuityConstraints(continuity_order); } } // Add continuity constraints to the edges between subgraphs. for (std::unique_ptr<EdgesBetweenSubgraphs>& subgraph_edge : subgraph_edges_) { if (subgraph_edge->from_subgraph_.order() >= continuity_order && subgraph_edge->to_subgraph_.order() >= continuity_order) { subgraph_edge->AddPathContinuityConstraints(continuity_order); } } global_path_continuity_constraints_.push_back(continuity_order); } void GcsTrajectoryOptimization::AddContinuityConstraints(int continuity_order) { if (continuity_order == 0) { throw std::runtime_error( "Path continuity is enforced by default. Choose a higher order."); } if (continuity_order < 1) { throw std::runtime_error("Order must be greater than or equal to 1."); } // Add continuity constraints to each subgraph. for (std::unique_ptr<Subgraph>& subgraph : subgraphs_) { if (subgraph->order() >= continuity_order) { subgraph->AddContinuityConstraints(continuity_order); } } // Add continuity constraints to the edges between subgraphs. for (std::unique_ptr<EdgesBetweenSubgraphs>& subgraph_edge : subgraph_edges_) { if (subgraph_edge->from_subgraph_.order() >= continuity_order && subgraph_edge->to_subgraph_.order() >= continuity_order) { subgraph_edge->AddContinuityConstraints(continuity_order); } } global_continuity_constraints_.push_back(continuity_order); } std::pair<CompositeTrajectory<double>, solvers::MathematicalProgramResult> GcsTrajectoryOptimization::SolvePath( const Subgraph& source, const Subgraph& target, const GraphOfConvexSetsOptions& specified_options) { // Fill in default options. Note: if these options change, they must also be // updated in the method documentation. GraphOfConvexSetsOptions options = specified_options; if (!options.convex_relaxation) { options.convex_relaxation = true; } if (!options.preprocessing) { options.preprocessing = true; } if (!options.max_rounded_paths) { options.max_rounded_paths = 5; } const VectorXd empty_vector; Vertex* source_vertex = source.vertices_[0]; Vertex* dummy_source = nullptr; Vertex* target_vertex = target.vertices_[0]; Vertex* dummy_target = nullptr; if (source.size() != 1) { // Source subgraph has more than one region. Add a dummy source vertex. dummy_source = gcs_.AddVertex(Point(empty_vector), "Dummy source"); source_vertex = dummy_source; for (Vertex* v : source.vertices_) { AddEdge(dummy_source, v); } } const ScopeExit cleanup_dummy_source_before_returning([&]() { if (dummy_source != nullptr) { gcs_.RemoveVertex(dummy_source); } }); if (target.size() != 1) { // Target subgraph has more than one region. Add a dummy target vertex. dummy_target = gcs_.AddVertex(Point(empty_vector), "Dummy target"); target_vertex = dummy_target; for (Vertex* v : target.vertices_) { AddEdge(v, dummy_target); } } const ScopeExit cleanup_dummy_target_before_returning([&]() { if (dummy_target != nullptr) { gcs_.RemoveVertex(dummy_target); } }); solvers::MathematicalProgramResult result = gcs_.SolveShortestPath(*source_vertex, *target_vertex, options); if (!result.is_success()) { return {CompositeTrajectory<double>({}), result}; } const double kTolerance = 1.0; // take any path we can get. std::vector<const Edge*> path_edges = gcs_.GetSolutionPath(*source_vertex, *target_vertex, result, kTolerance); // Remove the dummy edges from the path. if (dummy_source != nullptr) { DRAKE_DEMAND(!path_edges.empty()); path_edges.erase(path_edges.begin()); } if (dummy_target != nullptr) { DRAKE_DEMAND(!path_edges.empty()); path_edges.erase(path_edges.end() - 1); } return {ReconstructTrajectoryFromSolutionPath(path_edges, result), result}; } std::pair<trajectories::CompositeTrajectory<double>, solvers::MathematicalProgramResult> GcsTrajectoryOptimization::SolveConvexRestriction( const std::vector<const Vertex*>& active_vertices, const GraphOfConvexSetsOptions& options) { DRAKE_DEMAND(active_vertices.size() > 1); std::vector<const Edge*> active_edges; for (size_t i = 0; i < active_vertices.size() - 1; ++i) { bool vertices_connected = false; for (const Edge* e : active_vertices[i]->outgoing_edges()) { if (e->v().id() == active_vertices[i + 1]->id()) { if (vertices_connected) { throw std::runtime_error(fmt::format( "Vertex: {} is connected to vertex: {} through multiple edges.", active_vertices[i]->name(), active_vertices[i + 1]->name())); } active_edges.push_back(e); vertices_connected = true; } } if (!vertices_connected) { throw std::runtime_error(fmt::format( "Vertex: {} is not connected to vertex: {}.", active_vertices[i]->name(), active_vertices[i + 1]->name())); } } solvers::MathematicalProgramResult result = gcs_.SolveConvexRestriction(active_edges, options); if (!result.is_success()) { return {CompositeTrajectory<double>({}), result}; } return {ReconstructTrajectoryFromSolutionPath(active_edges, result), result}; } CompositeTrajectory<double> GcsTrajectoryOptimization::ReconstructTrajectoryFromSolutionPath( std::vector<const Edge*> edges, const solvers::MathematicalProgramResult& result) { // Extract the path from the edges. std::vector<copyable_unique_ptr<Trajectory<double>>> bezier_curves; for (const Edge* e : edges) { // Extract phi from the solution to rescale the control points and duration // in case we get the relaxed solution. const double phi_inv = 1 / result.GetSolution(e->phi()); // Extract the control points from the solution. const int num_control_points = vertex_to_subgraph_[&e->u()]->order() + 1; const MatrixX<double> edge_path_points = phi_inv * Eigen::Map<MatrixX<double>>(result.GetSolution(e->xu()).data(), num_positions(), num_control_points); // Extract the duration from the solution. double h = phi_inv * result.GetSolution(e->xu()).tail<1>().value(); const double start_time = bezier_curves.empty() ? 0 : bezier_curves.back()->end_time(); // Skip edges with a single control point that spend near zero time in the // region, since zero order continuity constraint is sufficient. These edges // would result in a discontinuous trajectory for velocities and higher // derivatives. if (!(num_control_points == 1 && vertex_to_subgraph_[&e->u()]->h_min_ == 0)) { bezier_curves.emplace_back(std::make_unique<BezierCurve<double>>( start_time, start_time + h, edge_path_points)); } } // Get the final control points from the solution. const Edge& last_edge = *edges.back(); const double phi_inv = 1 / result.GetSolution(last_edge.phi()); const int num_control_points = vertex_to_subgraph_[&last_edge.v()]->order() + 1; const MatrixX<double> edge_path_points = phi_inv * Eigen::Map<MatrixX<double>>(result.GetSolution(last_edge.xv()).data(), num_positions(), num_control_points); double h = phi_inv * result.GetSolution(last_edge.xv()).tail<1>().value(); const double start_time = bezier_curves.empty() ? 0 : bezier_curves.back()->end_time(); // Skip edges with a single control point that spend near zero time in the // region, since zero order continuity constraint is sufficient. if (!(num_control_points == 1 && vertex_to_subgraph_[&last_edge.v()]->h_min_ == 0)) { bezier_curves.emplace_back(std::make_unique<BezierCurve<double>>( start_time, start_time + h, edge_path_points)); } return CompositeTrajectory<double>(bezier_curves); } Edge* GcsTrajectoryOptimization::AddEdge(Vertex* u, Vertex* v) { return gcs_.AddEdge(u, v, fmt::format("{} -> {}", u->name(), v->name())); } double GcsTrajectoryOptimization::EstimateComplexity() const { double result = 0; // TODO(ggould) A more correct computation estimate would be: // If each vertex and edge problem were solved only once, the cost would be // | constraint_var_sum = variables per constraint summed over constraints // | cost_vars = total unique variables over all costs // | constraint_vars = total unique variables over all constraints // : constraint_var_sum * cost_vars * constraint_vars^2 // In fact each vertex must be solved at least as many times as it has // edges, so multiply the vertex cost by the vertex's arity. for (const auto* v : gcs_.Vertices()) { for (const auto& c : v->GetCosts()) { result += c.GetNumElements(); } for (const auto& c : v->GetConstraints()) { result += c.GetNumElements(); } } for (const auto* e : gcs_.Edges()) { for (const auto& c : e->GetCosts()) { result += c.GetNumElements(); } for (const auto& c : e->GetConstraints()) { result += c.GetNumElements(); } } return result; } std::vector<Subgraph*> GcsTrajectoryOptimization::GetSubgraphs() const { std::vector<Subgraph*> subgraphs; subgraphs.reserve(subgraphs_.size()); for (const auto& subgraph : subgraphs_) { subgraphs.push_back(subgraph.get()); } return subgraphs; } std::vector<EdgesBetweenSubgraphs*> GcsTrajectoryOptimization::GetEdgesBetweenSubgraphs() const { std::vector<EdgesBetweenSubgraphs*> subgraph_edges; subgraph_edges.reserve(subgraph_edges_.size()); for (const auto& edge : subgraph_edges_) { subgraph_edges.push_back(edge.get()); } return subgraph_edges; } trajectories::CompositeTrajectory<double> GcsTrajectoryOptimization::NormalizeSegmentTimes( const trajectories::CompositeTrajectory<double>& trajectory) { std::vector<copyable_unique_ptr<Trajectory<double>>> normalized_bezier_curves; double start_time = trajectory.start_time(); for (int i = 0; i < trajectory.get_number_of_segments(); ++i) { // Create a new BezierCurve with the same control points, but with a // duration of one second. if (const BezierCurve<double>* gcs_segment = dynamic_cast<const BezierCurve<double>*>(&trajectory.segment(i))) { normalized_bezier_curves.emplace_back( std::make_unique<BezierCurve<double>>(start_time, start_time + 1.0, gcs_segment->control_points())); start_time += 1.0; } else { throw std::runtime_error( "NormalizeSegmentTimes: All segments in the gcs trajectory " "must be of type " "BezierCurve<double>."); } } return CompositeTrajectory<double>(normalized_bezier_curves); } namespace { bool IsMultipleOf2Pi(double value) { // We allow some tolerance for trajectories coming out of GCS. // TODO(sadra): find out what tolerance is appropriate. double kTol = 1e-10; // To match what is provided in the docs. return std::abs(value - 2 * M_PI * std::round(value / (2 * M_PI))) < kTol; } // Unwrap the angle to the range [2π * round, 2π * (round+1)). double UnwrapAngle(const double angle, const int round) { const int twopi_factors_to_remove = static_cast<int>(std::floor(angle / (2 * M_PI))) - round; return angle - 2 * M_PI * twopi_factors_to_remove; } } // namespace trajectories::CompositeTrajectory<double> GcsTrajectoryOptimization::UnwrapToContinousTrajectory( const trajectories::CompositeTrajectory<double>& gcs_trajectory, std::vector<int> continuous_revolute_joints, std::optional<std::vector<int>> starting_rounds) { if (starting_rounds.has_value()) { DRAKE_THROW_UNLESS(starting_rounds->size() == continuous_revolute_joints.size()); } // TODO(@anyone): make this a unique_ptr and use std::move to avoid copying. std::vector<copyable_unique_ptr<Trajectory<double>>> unwrapped_trajectories; int dim = gcs_trajectory.rows(); geometry::optimization::internal::ThrowsForInvalidContinuousJointsList( dim, continuous_revolute_joints); Eigen::VectorXd last_segment_finish; for (int i = 0; i < gcs_trajectory.get_number_of_segments(); ++i) { const auto& traj_segment = gcs_trajectory.segment(i); const auto* bezier_segment = dynamic_cast<const BezierCurve<double>*>(&traj_segment); if (bezier_segment == nullptr) { throw std::runtime_error( "UnwrapToContinuousTrajectory: All segments in the gcs_trajectory " "must be of type " "BezierCurve<double>."); } Eigen::MatrixXd new_control_points = bezier_segment->control_points(); const Eigen::MatrixXd& old_control_points = bezier_segment->control_points(); const Eigen::VectorXd& old_start = old_control_points.col(0); std::vector<double> shift; if (i == 0) { // there is no shift from previous segment. if (starting_rounds.has_value()) { for (int j = 0; j < ssize(continuous_revolute_joints); ++j) { const int joint_index = continuous_revolute_joints.at(j); const int start_round = starting_rounds->at(j); // This value will be subtracted from the old_start to get the // shift. const double joint_shift = old_start(joint_index) - UnwrapAngle(old_start(joint_index), start_round); DRAKE_DEMAND(IsMultipleOf2Pi(joint_shift)); shift.push_back(joint_shift); } } else { shift = std::vector<double>(ssize(continuous_revolute_joints), 0); } } else { DRAKE_DEMAND(last_segment_finish.rows() == gcs_trajectory.rows()); // See how much shift is needed to match the previous new segment. for (const int joint_index : continuous_revolute_joints) { const double joint_shift = old_start(joint_index) - last_segment_finish(joint_index); if (!IsMultipleOf2Pi(joint_shift)) { throw std::runtime_error( fmt::format("UnwrapToContinuousTrajectory: The shift from " "previous segment: {} is not a multiple " "of 2π at segment {}, joint {}.", joint_shift, i, joint_index)); } shift.push_back(joint_shift); } } for (int j = 0; j < ssize(continuous_revolute_joints); ++j) { const int joint_index = continuous_revolute_joints[j]; // Shift all the columns of the control points by the shift. new_control_points.row(joint_index) -= Eigen::VectorXd::Constant(old_control_points.cols(), shift.at(j)); } last_segment_finish = new_control_points.rightCols(1); unwrapped_trajectories.emplace_back(std::make_unique<BezierCurve<double>>( bezier_segment->start_time(), bezier_segment->end_time(), new_control_points)); } return CompositeTrajectory<double>(unwrapped_trajectories); } std::vector<int> GetContinuousRevoluteJointIndices( const multibody::MultibodyPlant<double>& plant) { std::vector<int> indices; for (JointIndex i : plant.GetJointIndices()) { const Joint<double>& joint = plant.get_joint(i); // The first possibility we check for is a revolute joint with no joint // limits. if (joint.type_name() == "revolute") { if (joint.position_lower_limits()[0] == -std::numeric_limits<float>::infinity() && joint.position_upper_limits()[0] == std::numeric_limits<float>::infinity()) { indices.push_back(joint.position_start()); } continue; } // The second possibility we check for is a planar joint. If it is (and // the angle component has no joint limits), we only add the third entry // of the position vector, corresponding to theta. if (joint.type_name() == "planar") { if (joint.position_lower_limits()[2] == -std::numeric_limits<float>::infinity() && joint.position_upper_limits()[2] == std::numeric_limits<float>::infinity()) { indices.push_back(joint.position_start() + 2); } continue; } // TODO(cohnt): Determine if other joint types (e.g. UniversalJoint) can // be handled appropriately with wraparound edges, and if so, return their // indices as well. } return indices; } } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/gcs_trajectory_optimization.h
#pragma once #include <map> #include <memory> #include <optional> #include <string> #include <tuple> #include <utility> #include <vector> #include "drake/common/trajectories/bezier_curve.h" #include "drake/common/trajectories/composite_trajectory.h" #include "drake/geometry/optimization/convex_set.h" #include "drake/geometry/optimization/graph_of_convex_sets.h" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace planning { namespace trajectory_optimization { /** GcsTrajectoryOptimization implements a simplified motion planning optimization problem introduced in the paper ["Motion Planning around Obstacles with Convex Optimization"](https://arxiv.org/abs/2205.04422) by Tobia Marcucci, Mark Petersen, David von Wrangel, Russ Tedrake. Instead of using the full time-scaling curve, this problem uses a single time-scaling variable for each region. This formulation yields continuous trajectories, which are not differentiable at the transition times between the regions since non-convex continuity constraints are not supported yet. However, it supports continuity on the path r(s) for arbitrary degree. The path r(s) can be reconstructed from the gcs solution q(t) with `NormalizeSegmentTimes()` and post-processed with e.g. Toppra to enforce acceleration bounds. The ith piece of the composite trajectory is defined as q(t) = r((t - tᵢ) / hᵢ). r : [0, 1] → ℝⁿ is a the path, parametrized as a Bézier curve with order n. tᵢ and hᵢ are the initial time and duration of the ith sub-trajectory. This class supports the notion of a Subgraph of regions. This has proven useful to facilitate multi-modal motion planning such as: Subgraph A: find a collision-free trajectory for the robot to a grasping posture, Subgraph B: find a collision-free trajectory for the robot with the object in its hand to a placing posture, etc. @anchor continuous_revolute_joints ### Continuous Revolute Joints This class also supports robots with continuous revolute joints (revolute joints that don't have any joint limits) and mobile bases. Adding or subtracting 2π to such a joint's angle leaves it unchanged; this logic is implemented behind the scenes. To use it, one should specify the joint indices that don't have limits, and ensure all sets satisfy the "convexity radius" property -- their width along a dimension corresponding to a continuous revolute joint must be less than π. This can be enforced when constructing the convex sets, or after the fact with `geometry::optimization::PartitionConvexSet`. The `GcsTrajectoryOptimization` methods `AddRegions` and `AddEdges` will handle all of the intersection checks behind the scenes, including applying the appropriate logic to connect sets that "wrap around" 2π. */ class GcsTrajectoryOptimization final { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GcsTrajectoryOptimization); /** Constructs the motion planning problem. @param num_positions is the dimension of the configuration space. @param continuous_revolute_joints is a list of indices corresponding to continuous revolute joints, i.e., revolute joints which don't have any joint limits, and hence "wrap around" at 2π. Each entry in continuous_revolute_joints must be non-negative, less than num_positions, and unique. This feature is currently only supported within a single subgraph: continuous revolute joints won't be taken into account when constructing edges between subgraphs or checking if sets intersect through a subspace. */ explicit GcsTrajectoryOptimization( int num_positions, std::vector<int> continuous_revolute_joints = std::vector<int>()); ~GcsTrajectoryOptimization(); /** A Subgraph is a subset of the larger graph. It is defined by a set of regions and edges between them based on intersection. From an API standpoint, a Subgraph is useful to define a multi-modal motion planning problem. Further, it allows different constraints and objects to be added to different subgraphs. Note that the the GraphOfConvexSets does not differentiate between subgraphs and can't be mixed with other instances of GcsTrajectoryOptimization. */ class Subgraph final { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(Subgraph); ~Subgraph(); /** Returns the name of the subgraph. */ const std::string& name() const { return name_; } /** Returns the order of the Bézier trajectory within the region. */ int order() const { return order_; } /** Returns the number of vertices in the subgraph. */ int size() const { return vertices_.size(); } /** Returns constant reference to a vector of mutable pointers to the vertices stored in the subgraph. The order of the vertices is the same as the order the regions were added.*/ const std::vector<geometry::optimization::GraphOfConvexSets::Vertex*>& Vertices() { return vertices_; } /** Returns pointers to the vertices stored in the subgraph. The order of the vertices is the same as the order the regions were added. @exclude_from_pydrake_mkdoc{This overload is not bound in pydrake.} */ std::vector<const geometry::optimization::GraphOfConvexSets::Vertex*> Vertices() const { std::vector<const geometry::optimization::GraphOfConvexSets::Vertex*> vertices; vertices.reserve(vertices_.size()); for (const auto& v : vertices_) { vertices.push_back(v); } return vertices; } /** Returns the regions associated with this subgraph before the CartesianProduct. */ const geometry::optimization::ConvexSets& regions() const { return regions_; } /** Adds a minimum time cost to all regions in the subgraph. The cost is the sum of the time scaling variables. @param weight is the relative weight of the cost. */ void AddTimeCost(double weight = 1.0); /** Adds multiple L2Norm Costs on the upper bound of the path length. Since we cannot directly compute the path length of a Bézier curve, we minimize the upper bound of the path integral by minimizing the sum of distances between control points. For Bézier curves, this is equivalent to the sum of the L2Norm of the derivative control points of the curve divided by the order. @param weight_matrix is the relative weight of each component for the cost. The diagonal of the matrix is the weight for each dimension. The off-diagonal elements are the weight for the cross terms, which can be used to penalize diagonal movement. @pre weight_matrix must be of size num_positions() x num_positions(). */ void AddPathLengthCost(const Eigen::MatrixXd& weight_matrix); /** Adds multiple L2Norm Costs on the upper bound of the path length. We upper bound the trajectory length by the sum of the distances between control points. For Bézier curves, this is equivalent to the sum of the L2Norm of the derivative control points of the curve divided by the order. @param weight is the relative weight of the cost. */ void AddPathLengthCost(double weight = 1.0); /** Adds a linear velocity constraint to the subgraph `lb` ≤ q̇(t) ≤ `ub`. @param lb is the lower bound of the velocity. @param ub is the upper bound of the velocity. @throws std::exception if subgraph order is zero, since the velocity is defined as the derivative of the Bézier curve. @throws std::exception if lb or ub are not of size num_positions(). */ void AddVelocityBounds(const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub); /** Adds a nonlinear derivative constraints to the subgraph `lb` ≤ dᴺq(t) / dtᴺ ≤ `ub`. This adds a nonlinear constraint to the restriction and MIP GraphOfConvexSets::Transcription, while adding a convex surrogate to the relaxation. For more details, see @ref nonconvex_graph_of_convex_sets "Guiding Non-convex Optimization with the GraphOfConvexSets". The nonlinear constraint involves the derivative dᴺq(t) / dtᴺ which is decomposed as dᴺr(s) / dsᴺ / hᴺ. The convex surrogate replaces the nonlinear component hᴺ with h₀ᴺ⁻¹h, where h₀ is the characteristic time of the set. For now, h₀ is set to 1.0 for all sets. @param lb is the lower bound of the derivative. @param ub is the upper bound of the derivative. @param derivative_order is the order of the derivative to be constrained. @throws std::exception if subgraph order is less than the derivative order. @throws std::exception if the derivative order <= 1, since the linear velocity bounds are preferred. @throws std::exception if lb or ub are not of size num_positions(). */ void AddNonlinearDerivativeBounds( const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, int derivative_order); /** Enforces derivative continuity constraints on the subgraph. Note that the constraints are on the control points of the derivatives of r(s) and not q(t). This may result in discontinuities of the trajectory return by `SolvePath()` since the r(s) will get rescaled by the duration h to yield q(t). `NormalizeSegmentTimes()` will return r(s) with valid continuity. @param continuity_order is the order of the continuity constraint. @throws std::exception if the continuity order is not equal or less than the order the subgraphs. @throws std::exception if the continuity order is less than one since path continuity is enforced by default. */ void AddPathContinuityConstraints(int continuity_order); /** Enforces derivative continuity constraints on the subgraph. This adds a nonlinear constraint to the restriction and MIP GraphOfConvexSets::Transcription, while adding a convex surrogate to the relaxation. For more details, see @ref nonconvex_graph_of_convex_sets "Guiding Non-convex Optimization with the GraphOfConvexSets". The continuity is enforced on the control points of q(t), which appear as nonlinear constraints. <pre> (dᴺrᵤ(s=1) / dsᴺ) / hᵤᴺ == (dᴺrᵥ(s=0) / dsᴺ) / hᵥᴺ </pre> The convex surrogate is simply the path continuity, where hᵤᴺ and hᵥᴺ are replaced by the characteristic times of the respective sets: <pre> (dᴺrᵤ(s=1) / dsᴺ) / hᵤ₀ᴺ == (dᴺrᵥ(s=0) / dsᴺ) / hᵥ₀ᴺ </pre>. For now, these are set to one, but future work may involve scaling them by the size of the sets. @param continuity_order is the order of the continuity constraint. @throws std::exception if the continuity order is not equal or less than the order the subgraphs. @throws std::exception if the continuity order is less than one since path continuity is enforced by default. */ void AddContinuityConstraints(int continuity_order); private: /* Constructs a new subgraph and copies the regions. */ Subgraph(const geometry::optimization::ConvexSets& regions, const std::vector<std::pair<int, int>>& regions_to_connect, int order, double h_min, double h_max, std::string name, GcsTrajectoryOptimization* traj_opt, std::optional<const std::vector<Eigen::VectorXd>> edge_offsets); /* Convenience accessor, for brevity. */ int num_positions() const { return traj_opt_.num_positions(); } /* Convenience accessor, for brevity. */ const std::vector<int>& continuous_revolute_joints() const { return traj_opt_.continuous_revolute_joints(); } /* Throw an error if any convex set in regions violates the convexity radius. */ void ThrowsForInvalidConvexityRadius() const; /* Extracts the control points variables from a vertex. */ Eigen::Map<const MatrixX<symbolic::Variable>> GetControlPoints( const geometry::optimization::GraphOfConvexSets::Vertex& v) const; /* Extracts the time scaling variable from a vertex. */ symbolic::Variable GetTimeScaling( const geometry::optimization::GraphOfConvexSets::Vertex& v) const; const geometry::optimization::ConvexSets regions_; const int order_; const double h_min_; const std::string name_; GcsTrajectoryOptimization& traj_opt_; std::vector<geometry::optimization::GraphOfConvexSets::Vertex*> vertices_; std::vector<geometry::optimization::GraphOfConvexSets::Edge*> edges_; // r(s) is a BezierCurve of the right shape and order, which can be used to // design costs and constraints for the underlying vertices and edges. trajectories::BezierCurve<double> r_trajectory_; friend class GcsTrajectoryOptimization; }; /** EdgesBetweenSubgraphs are defined as the connecting edges between two given subgraphs. These edges are a subset of the many other edges in the larger graph. From an API standpoint, EdgesBetweenSubgraphs enable transitions between Subgraphs, which can enable transitions between modes. Further, it allows different constraints to be added in the transition between subgraphs. Note that the EdgesBetweenSubgraphs can't be separated from the actual edges in the GraphOfConvexSets framework, thus mixing it with other instances of GCSTrajetoryOptimization is not supported. */ class EdgesBetweenSubgraphs final { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(EdgesBetweenSubgraphs); ~EdgesBetweenSubgraphs(); /** Adds a linear velocity constraint to the control point connecting the subgraphs `lb` ≤ q̇(t) ≤ `ub`. @param lb is the lower bound of the velocity. @param ub is the upper bound of the velocity. @throws std::exception if both subgraphs order is zero, since the velocity is defined as the derivative of the Bézier curve. At least one of the subgraphs must have an order of at least 1. @throws std::exception if lb or ub are not of size num_positions(). */ void AddVelocityBounds(const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub); /** Adds a nonlinear derivative constraints to the control point connecting the subgraphs `lb` ≤ dᴺq(t) / dtᴺ ≤ `ub`. This adds a nonlinear constraint to the restriction and MIP GraphOfConvexSets::Transcription, while adding a convex surrogate to the relaxation. For more details, see @ref nonconvex_graph_of_convex_sets "Guiding Non-convex Optimization with the GraphOfConvexSets". The nonlinear constraint involves the derivative dᴺq(t) / dtᴺ which is decomposed as dᴺr(s) / dsᴺ / hᴺ. The convex surrogate replaces the nonlinear component hᴺ with h₀ᴺ⁻¹h, where h₀ is the characteristic time of the set. For now, h₀ is set to 1.0 for all sets. @param lb is the lower bound of the derivative. @param ub is the upper bound of the derivative. @param derivative_order is the order of the derivative to be constrained. @throws std::exception if both subgraphs order is less than the desired derivative order. @throws std::exception if the derivative order <= 1, since the linear velocity bounds are preferred. @throws std::exception if lb or ub are not of size num_positions(). */ void AddNonlinearDerivativeBounds( const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, int derivative_order); /** Enforces zero derivatives on the control point connecting the subgraphs. For velocity, acceleration, jerk, etc. enforcing zero-derivative on the trajectory q(t) is equivalent to enforcing zero-derivative on the trajectory r(s). Hence this constraint is convex. @param derivative_order is the order of the derivative to be constrained. @throws std::exception if the derivative order < 1. @throws std::exception if both subgraphs order is less than the desired derivative order. */ void AddZeroDerivativeConstraints(int derivative_order); /** Enforces derivative continuity constraints on the edges between the subgraphs. Note that the constraints are on the control points of the derivatives of r(s) and not q(t). This may result in discontinuities of the trajectory return by `SolvePath()` since the r(s) will get rescaled by the duration h to yield q(t). `NormalizeSegmentTimes()` will return r(s) with valid continuity. @param continuity_order is the order of the continuity constraint. @throws std::exception if the continuity order is not equal or less than the order of both subgraphs. @throws std::exception if the continuity order is less than one since path continuity is enforced by default. */ void AddPathContinuityConstraints(int continuity_order); /** Enforces derivative continuity constraints on the edges between the subgraphs. This adds a nonlinear constraint to the restriction and MIP GraphOfConvexSets::Transcription, while adding a convex surrogate to the relaxation. For more details, see @ref nonconvex_graph_of_convex_sets "Guiding Non-convex Optimization with the GraphOfConvexSets". The continuity is enforced on the control points of q(t), which appear as nonlinear constraints. <pre> (dᴺrᵤ(s=1) / dsᴺ) / hᵤᴺ == (dᴺrᵥ(s=0) / dsᴺ) / hᵥᴺ </pre> The convex surrogate is simply the path continuity, where hᵤᴺ and hᵥᴺ are replaced by the characteristic times of the respective sets: <pre> (dᴺrᵤ(s=1) / dsᴺ) / hᵤ₀ᴺ == (dᴺrᵥ(s=0) / dsᴺ) / hᵥ₀ᴺ </pre>. For now, these are set to one, but future work may involve scaling them by the size of the sets. @param continuity_order is the order of the continuity constraint. @throws std::exception if the continuity order is not equal or less than the order of both subgraphs. @throws std::exception if the continuity order is less than one since path continuity is enforced by default. */ void AddContinuityConstraints(int continuity_order); private: EdgesBetweenSubgraphs(const Subgraph& from_subgraph, const Subgraph& to_subgraph, const geometry::optimization::ConvexSet* subspace, GcsTrajectoryOptimization* traj_opt); /* Convenience accessor, for brevity. */ int num_positions() const { return traj_opt_.num_positions(); } /* Convenience accessor, for brevity. */ const std::vector<int>& continuous_revolute_joints() const { return traj_opt_.continuous_revolute_joints(); } bool RegionsConnectThroughSubspace( const geometry::optimization::ConvexSet& A, const geometry::optimization::ConvexSet& B, const geometry::optimization::ConvexSet& subspace, std::optional<const Eigen::VectorXd> maybe_set_B_offset = std::nullopt, std::optional<const Eigen::VectorXd> maybe_subspace_offset = std::nullopt); /* Extracts the control points variables from an edge. */ Eigen::Map<const MatrixX<symbolic::Variable>> GetControlPointsU( const geometry::optimization::GraphOfConvexSets::Edge& e) const; /* Extracts the control points variables from an edge. */ Eigen::Map<const MatrixX<symbolic::Variable>> GetControlPointsV( const geometry::optimization::GraphOfConvexSets::Edge& e) const; /* Extracts the time scaling variable from a edge. */ symbolic::Variable GetTimeScalingU( const geometry::optimization::GraphOfConvexSets::Edge& e) const; /* Extracts the time scaling variable from a edge. */ symbolic::Variable GetTimeScalingV( const geometry::optimization::GraphOfConvexSets::Edge& e) const; GcsTrajectoryOptimization& traj_opt_; const Subgraph& from_subgraph_; const Subgraph& to_subgraph_; trajectories::BezierCurve<double> ur_trajectory_; trajectories::BezierCurve<double> vr_trajectory_; std::vector<geometry::optimization::GraphOfConvexSets::Edge*> edges_; friend class GcsTrajectoryOptimization; }; /** Returns the number of position variables. */ int num_positions() const { return num_positions_; } /** Returns a list of indices corresponding to continuous revolute joints. */ const std::vector<int>& continuous_revolute_joints() { return continuous_revolute_joints_; } /** Returns a Graphviz string describing the graph vertices and edges. If `results` is supplied, then the graph will be annotated with the solution values. @param show_slacks determines whether the values of the intermediate (slack) variables are also displayed in the graph. @param precision sets the floating point precision (how many digits are generated) of the annotations. @param scientific sets the floating point formatting to scientific (if true) or fixed (if false). */ std::string GetGraphvizString( const std::optional<solvers::MathematicalProgramResult>& result = std::nullopt, bool show_slack = true, int precision = 3, bool scientific = false) const { return gcs_.GetGraphvizString(result, show_slack, precision, scientific); } /** Creates a Subgraph with the given regions and indices. @param regions represent the valid set a control point can be in. We retain a copy of the regions since other functions may access them. If any of the positions represent revolute joints without limits, each region has a maximum width of strictly less than π along dimensions corresponding to those joints. @param edges_between_regions is a list of pairs of indices into the regions vector. For each pair representing an edge between two regions, an edge is added within the subgraph. Note that the edges are directed so (i,j) will only add an edge from region i to region j. @param order is the order of the Bézier curve. @param h_max is the maximum duration to spend in a region (seconds). Some solvers struggle numerically with large values. @param h_min is the minimum duration to spend in a region (seconds) if that region is visited on the optimal path. Some cost and constraints are only convex for h > 0. For example the perspective quadratic cost of the path energy ||ṙ(s)||² / h becomes non-convex for h = 0. Otherwise h_min can be set to 0. @param name is the name of the subgraph. If the passed name is an empty string, a default name will be provided. @param edge_offsets is an optional list of vectors. If defined, the list must contain the same number of entries as edges_between_regions. In other words, if defined, there must be one edge offset for each specified edge. For each pair of sets listed in edges_between_regions, the first set is translated (in configuration space) by the corresponding vector in edge_offsets before computing the constraints associated to that edge. This is used to add edges between sets that "wrap around" 2π along some dimension, due to, e.g., a continuous revolute joint. This edge offset corresponds to the translation component of the affine map τ_uv in equation (11) of "Non-Euclidean Motion Planning with Graphs of Geodesically-Convex Sets", and per the discussion in Subsection VI A, τ_uv has no rotation component. */ Subgraph& AddRegions( const geometry::optimization::ConvexSets& regions, const std::vector<std::pair<int, int>>& edges_between_regions, int order, double h_min = 0, double h_max = 20, std::string name = "", std::optional<const std::vector<Eigen::VectorXd>> edge_offsets = std::nullopt); /** Creates a Subgraph with the given regions. This function will compute the edges between the regions based on the set intersections. @param regions represent the valid set a control point can be in. We retain a copy of the regions since other functions may access them. If any of the positions represent continuous revolute joints, each region must have a maximum width of strictly less than π along dimensions corresponding to those joints. @param order is the order of the Bézier curve. @param h_min is the minimum duration to spend in a region (seconds) if that region is visited on the optimal path. Some cost and constraints are only convex for h > 0. For example the perspective quadratic cost of the path energy ||ṙ(s)||² / h becomes non-convex for h = 0. Otherwise h_min can be set to 0. @param h_max is the maximum duration to spend in a region (seconds). Some solvers struggle numerically with large values. @param name is the name of the subgraph. A default name will be provided. @throws std::exception if any of the regions has a width of π or greater along dimensions corresponding to continuous revolute joints. */ Subgraph& AddRegions(const geometry::optimization::ConvexSets& regions, int order, double h_min = 0, double h_max = 20, std::string name = ""); /** Remove a subgraph and all associated edges found in the subgraph and to and from other subgraphs. @pre The subgraph must have been created from a call to AddRegions() on this object. */ void RemoveSubgraph(const Subgraph& subgraph); /** Connects two subgraphs with directed edges. @param from_subgraph is the subgraph to connect from. Must have been created from a call to AddRegions() on this object, not some other optimization program. @param to_subgraph is the subgraph to connect to. Must have been created from a call to AddRegions() on this object, not some other optimization program. @param subspace is the subspace that the connecting control points must be in. Subspace is optional. Only edges that connect through the subspace will be added, and the subspace is added as a constraint on the connecting control points. Subspaces of type point or HPolyhedron are supported since other sets require constraints that are not yet supported by the GraphOfConvexSets::Edge constraint, e.g., set containment of a HyperEllipsoid is formulated via LorentzCone constraints. Workaround: Create a subgraph of zero order with the subspace as the region and connect it between the two subgraphs. This works because GraphOfConvexSet::Vertex , supports arbitrary instances of ConvexSets. */ EdgesBetweenSubgraphs& AddEdges( const Subgraph& from_subgraph, const Subgraph& to_subgraph, const geometry::optimization::ConvexSet* subspace = nullptr); /** Adds a minimum time cost to all regions in the whole graph. The cost is the sum of the time scaling variables. This cost will be added to the entire graph. Note that this cost will be applied even to subgraphs added in the future. @param weight is the relative weight of the cost. */ void AddTimeCost(double weight = 1.0); /** Adds multiple L2Norm Costs on the upper bound of the path length. Since we cannot directly compute the path length of a Bézier curve, we minimize the upper bound of the path integral by minimizing the sum of (weighted) distances between control points: ∑ |weight_matrix * (rᵢ₊₁ − rᵢ)|₂. This cost will be added to the entire graph. Since the path length is only defined for Bézier curves that have two or more control points, this cost will only added to all subgraphs with order greater than zero. Note that this cost will be applied even to subgraphs added in the future. @param weight_matrix is the relative weight of each component for the cost. The diagonal of the matrix is the weight for each dimension. The off-diagonal elements are the weight for the cross terms, which can be used to penalize diagonal movement. @pre weight_matrix must be of size num_positions() x num_positions(). */ void AddPathLengthCost(const Eigen::MatrixXd& weight_matrix); /** Adds multiple L2Norm Costs on the upper bound of the path length. Since we cannot directly compute the path length of a Bézier curve, we minimize the upper bound of the path integral by minimizing the sum of distances between control points. For Bézier curves, this is equivalent to the sum of the L2Norm of the derivative control points of the curve divided by the order. This cost will be added to the entire graph. Since the path length is only defined for Bézier curves that have two or more control points, this cost will only added to all subgraphs with order greater than zero. Note that this cost will be applied even to subgraphs added in the future. @param weight is the relative weight of the cost. */ void AddPathLengthCost(double weight = 1.0); /** Adds a linear velocity constraint to the entire graph `lb` ≤ q̇(t) ≤ `ub`. @param lb is the lower bound of the velocity. @param ub is the upper bound of the velocity. This constraint will be added to the entire graph. Since the velocity requires forming the derivative of the Bézier curve, this constraint will only added to all subgraphs with order greater than zero. Note that this constraint will be applied even to subgraphs added in the future. @throws std::exception if lb or ub are not of size num_positions(). */ void AddVelocityBounds(const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub); /** Adds a nonlinear derivative constraints to the entire graph `lb` ≤ dᴺq(t) / dtᴺ ≤ `ub`. This adds a nonlinear constraint to the restriction and MIP GraphOfConvexSets::Transcription, while adding a convex surrogate to the relaxation. For more details, see @ref nonconvex_graph_of_convex_sets "Guiding Non-convex Optimization with the GraphOfConvexSets". The nonlinear constraint involves the derivative dᴺq(t) / dtᴺ which is decomposed as dᴺr(s) / dsᴺ / hᴺ. The convex surrogate replaces the nonlinear component hᴺ with h₀ᴺ⁻¹h, where h₀ is the characteristic time of the set. For now, h₀ is set to 1.0 for all sets. @param lb is the lower bound of the derivative. @param ub is the upper bound of the derivative. @param derivative_order is the order of the derivative to be constrained. @throws std::exception if lb or ub are not of size num_positions(). */ void AddNonlinearDerivativeBounds(const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub, int derivative_order); /** Enforces derivative continuity constraints on the entire graph. Note that the constraints are on the control points of the derivatives of r(s) and not q(t). This may result in discontinuities of the trajectory return by `SolvePath()` since the r(s) will get rescaled by the duration h to yield q(t). `NormalizeSegmentTimes()` will return r(s) with valid continuity. @param continuity_order is the order of the continuity constraint. @throws std::exception if the continuity order is less than one since path continuity is enforced by default. */ void AddPathContinuityConstraints(int continuity_order); /** Enforces derivative continuity constraints on the entire graph. This adds a nonlinear constraint to the restriction and MIP GraphOfConvexSets::Transcription, while adding a convex surrogate to the relaxation. For more details, see @ref nonconvex_graph_of_convex_sets "Guiding Non-convex Optimization with the GraphOfConvexSets". The continuity is enforced on the control points of q(t), which appear as nonlinear constraints. <pre> (dᴺrᵤ(s=1) / dsᴺ) / hᵤᴺ == (dᴺrᵥ(s=0) / dsᴺ) / hᵥᴺ </pre> The convex surrogate is simply the path continuity, where hᵤᴺ and hᵥᴺ are replaced by the characteristic times of the respective sets: <pre> (dᴺrᵤ(s=1) / dsᴺ) / hᵤ₀ᴺ == (dᴺrᵥ(s=0) / dsᴺ) / hᵥ₀ᴺ </pre>. For now, these are set to one, but future work may involve scaling them by the size of the sets. @param continuity_order is the order of the continuity constraint. @throws std::exception if the continuity order is less than one since path continuity is enforced by default. */ void AddContinuityConstraints(int continuity_order); /** Formulates and solves the mixed-integer convex formulation of the shortest path problem on the whole graph. @see `geometry::optimization::GraphOfConvexSets::SolveShortestPath()` for further details. @param source specifies the source subgraph. Must have been created from a call to AddRegions() on this object, not some other optimization program. If the source is a subgraph with more than one region, an empty set will be added and optimizer will choose the best region to start in. To start in a particular point, consider adding a subgraph of order zero with a single region of type Point. @param target specifies the target subgraph. Must have been created from a call to AddRegions() on this object, not some other optimization program. If the target is a subgraph with more than one region, an empty set will be added and optimizer will choose the best region to end in. To end in a particular point, consider adding a subgraph of order zero with a single region of type Point. @param options include all settings for solving the shortest path problem. The following default options will be used if they are not provided in `options`: - `options.convex_relaxation = true`, - `options.max_rounded_paths = 5`, - `options.preprocessing = true`. @see `geometry::optimization::GraphOfConvexSetsOptions` for further details. */ std::pair<trajectories::CompositeTrajectory<double>, solvers::MathematicalProgramResult> SolvePath( const Subgraph& source, const Subgraph& target, const geometry::optimization::GraphOfConvexSetsOptions& options = {}); /** Solves a trajectory optimization problem through specific vertices. This method allows for targeted optimization by considering only selected active vertices, reducing the problem's complexity. See geometry::optimization::GraphOfConvexSets::SolveConvexRestriction(). This API prefers a sequence of vertices over edges, as a user may know which regions the solution should pass through. GcsTrajectoryOptimization::AddRegions() automatically manages edge creation and intersection checks, which makes passing a sequence of edges less convenient. @param active_vertices A sequence of ordered vertices of subgraphs to be included in the problem. @param options include all settings for solving the shortest path problem. @pre There must be at least two vertices in active_vertices. @throws std::exception if the vertices are not connected. @throws std::exception if two vertices are connected by multiple edges. This may happen if one connects two graphs through multiple subspaces, which is currently not supported with this method. @throws std::exception if the program cannot be written as a convex optimization consumable by one of the standard solvers.*/ std::pair<trajectories::CompositeTrajectory<double>, solvers::MathematicalProgramResult> SolveConvexRestriction( const std::vector< const geometry::optimization::GraphOfConvexSets::Vertex*>& active_vertices, const geometry::optimization::GraphOfConvexSetsOptions& options = {}); /** Provide a heuristic estimate of the complexity of the underlying GCS mathematical program, for regression testing purposes. Here we sum the total number of variable appearances in our costs and constraints as a rough approximation of the complexity of the subproblems. */ double EstimateComplexity() const; /** Returns a vector of all subgraphs. */ std::vector<Subgraph*> GetSubgraphs() const; /** Returns a vector of all edges between subgraphs. */ std::vector<EdgesBetweenSubgraphs*> GetEdgesBetweenSubgraphs() const; /** Getter for the underlying GraphOfConvexSets. This is intended primarily for inspecting the resulting programs. */ const geometry::optimization::GraphOfConvexSets& graph_of_convex_sets() const { return gcs_; } /** Normalizes each trajectory segment to one second in duration. Reconstructs the path r(s) from the solution trajectory q(t) of `SolvePath()` s.t. each segment of the resulting trajectory will be one second long. The start time will match the original start time. @param trajectory The solution trajectory returned by `SolvePath()`. @throws std::exception if not all trajectory segments of the CompositeTrajectory are of type BezierCurve<double> */ static trajectories::CompositeTrajectory<double> NormalizeSegmentTimes( const trajectories::CompositeTrajectory<double>& trajectory); /** Unwraps a trajectory with continuous revolute joints into a continuous trajectory in the Euclidean space. Trajectories produced by GcsTrajectoryOptimization for robotic systems with continuous revolute joints may include apparent discontinuities, where a multiple of 2π is instantaneously added to a joint value at the boundary between two adjacent segments of the trajectory. This function removes such discontinuities by adding or subtracting the appropriate multiple of 2π, "unwrapping" the trajectory into a continuous representation suitable for downstream tasks that do not take the joint wraparound into account. @param gcs_trajectory The trajectory to unwrap. @param continuous_revolute_joints The indices of the continuous revolute joints. @param starting_rounds A vector of integers that sets the starting rounds for each continuous revolute joint. Given integer k for the starting_round of a joint, its initial position will be wrapped into [2πk , 2π(k+1)). If the starting rounds are not provided, the initial position of @p trajectory will be unchanged. @returns an unwrapped (continous in Euclidean space) CompositeTrajectory. @throws std::exception if starting_rounds.size()!=continuous_revolute_joints.size(). @throws std::exception if continuous_revolute_joints contain repeated indices and/or indices outside the range [0, gcs_trajectory.rows()). @throws std::exception if the gcs_trajectory is not continuous on the manifold defined by the continuous_revolute_joints, i.e., the shift between two consecutive segments is not an integer multiple of 2π (within a tolerance of 1e-10 radians). @throws std::exception if all the segments are not of type BezierCurve. Other types are not supported yet. Note that currently the output of GcsTrajectoryOptimization::SolvePath() is a CompositeTrajectory of BezierCurves. */ static trajectories::CompositeTrajectory<double> UnwrapToContinousTrajectory( const trajectories::CompositeTrajectory<double>& gcs_trajectory, std::vector<int> continuous_revolute_joints, std::optional<std::vector<int>> starting_rounds = std::nullopt); private: const int num_positions_; const std::vector<int> continuous_revolute_joints_; trajectories::CompositeTrajectory<double> ReconstructTrajectoryFromSolutionPath( std::vector<const geometry::optimization::GraphOfConvexSets::Edge*> edges, const solvers::MathematicalProgramResult& result); // Adds a Edge to gcs_ with the name "{u.name} -> {v.name}". geometry::optimization::GraphOfConvexSets::Edge* AddEdge( geometry::optimization::GraphOfConvexSets::Vertex* u, geometry::optimization::GraphOfConvexSets::Vertex* v); geometry::optimization::GraphOfConvexSets gcs_; // Store the subgraphs by reference. std::vector<std::unique_ptr<Subgraph>> subgraphs_; std::vector<std::unique_ptr<EdgesBetweenSubgraphs>> subgraph_edges_; std::map<const geometry::optimization::GraphOfConvexSets::Vertex*, Subgraph*> vertex_to_subgraph_; std::vector<double> global_time_costs_; std::vector<Eigen::MatrixXd> global_path_length_costs_; std::vector<std::pair<Eigen::VectorXd, Eigen::VectorXd>> global_velocity_bounds_{}; std::vector<std::tuple<Eigen::VectorXd, Eigen::VectorXd, int>> global_nonlinear_derivative_bounds_{}; std::vector<int> global_path_continuity_constraints_{}; std::vector<int> global_continuity_constraints_{}; }; /** Returns a list of indices in the plant's generalized positions which correspond to a continuous revolute joint (a revolute joint with no joint limits). This includes the revolute component of a planar joint */ std::vector<int> GetContinuousRevoluteJointIndices( const multibody::MultibodyPlant<double>& plant); } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/sequential_expression_manager.cc
#include "drake/planning/trajectory_optimization/sequential_expression_manager.h" #include <fmt/format.h> #include "drake/common/unused.h" namespace drake { namespace planning { namespace trajectory_optimization { namespace internal { using std::string; using std::vector; using symbolic::Expression; using symbolic::Substitution; using symbolic::Variable; using symbolic::Variables; SequentialExpressionManager::SequentialExpressionManager(int num_samples) : num_samples_(num_samples) { DRAKE_THROW_UNLESS(num_samples_ > 0); } VectorX<Variable> SequentialExpressionManager::RegisterSequentialExpressions( const Eigen::Ref<const MatrixX<Expression>>& sequential_expressions, const string& name) { const int rows = sequential_expressions.rows(); DRAKE_THROW_UNLESS(sequential_expressions.cols() == num_samples_); const VectorX<Variable> placeholders{ symbolic::MakeVectorContinuousVariable(rows, name)}; RegisterSequentialExpressions(placeholders, sequential_expressions, name); return placeholders; } void SequentialExpressionManager::RegisterSequentialExpressions( const VectorX<Variable>& placeholders, const Eigen::Ref<const MatrixX<Expression>>& sequential_expressions, const string& name) { DRAKE_THROW_UNLESS(sequential_expressions.rows() == placeholders.size()); DRAKE_THROW_UNLESS(sequential_expressions.cols() == num_samples_); name_to_placeholders_.emplace(std::make_pair(name, placeholders)); for (int i = 0; i < placeholders.size(); ++i) { placeholders_to_expressions_.emplace( std::make_pair(placeholders[i], sequential_expressions.row(i))); } } Substitution SequentialExpressionManager::ConstructPlaceholderVariableSubstitution( int index) const { DRAKE_THROW_UNLESS(0 <= index && index < num_samples_); Substitution substitution; for (const auto& [p, e] : placeholders_to_expressions_) { substitution.emplace(p, e(index)); } return substitution; } VectorX<symbolic::Variable> SequentialExpressionManager::GetVariables( const Eigen::Ref<const VectorX<symbolic::Variable>>& vars, int index) const { DRAKE_THROW_UNLESS(0 <= index && index < num_samples_); VectorX<symbolic::Variable> vars_at_index(vars.size()); for (int i = 0; i < vars.size(); ++i) { const auto it = placeholders_to_expressions_.find(vars[i]); if (it == placeholders_to_expressions_.end()) { throw std::runtime_error( vars[i].get_name() + " does not appear to be a placeholder variable in this program."); } if (!symbolic::is_variable(it->second[index])) { throw std::runtime_error( fmt::format("The placeholder variable {} is associated with {} which " "is not a variable.", vars[i].get_name(), it->second[index].to_string())); } vars_at_index[i] = symbolic::get_variable(it->second[index]); } return vars_at_index; } VectorX<Expression> SequentialExpressionManager::GetSequentialExpressionsByName( const string& name, int index) const { DRAKE_THROW_UNLESS(0 <= index && index < num_samples_); const auto it = name_to_placeholders_.find(name); DRAKE_THROW_UNLESS(it != name_to_placeholders_.end()); VectorX<Expression> e(it->second.size()); for (int i = 0; i < it->second.size(); ++i) { const auto e_it = placeholders_to_expressions_.find(it->second[i]); DRAKE_THROW_UNLESS(e_it != placeholders_to_expressions_.end()); e[i] = e_it->second[index]; } return e; } int SequentialExpressionManager::num_rows(const string& name) const { const auto it = name_to_placeholders_.find(name); DRAKE_THROW_UNLESS(it != name_to_placeholders_.end()); return it->second.size(); } vector<string> SequentialExpressionManager::GetSequentialExpressionNames() const { vector<string> ret; for (const auto& [p, e] : placeholders_to_expressions_) { unused(p); for (int i = 0; i < static_cast<int>(e.size()); ++i) { ret.emplace_back(e(i).to_string()); } } return ret; } } // namespace internal } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/multiple_shooting.cc
#include "drake/planning/trajectory_optimization/multiple_shooting.h" #include <algorithm> #include <cmath> #include <limits> #include <stdexcept> #include <string> #include "drake/solvers/ipopt_solver.h" #include "drake/solvers/solve.h" using Eigen::MatrixXd; using Eigen::VectorXd; namespace drake { namespace planning { namespace trajectory_optimization { using internal::SequentialExpressionManager; using symbolic::Expression; using symbolic::Formula; using symbolic::MakeVectorContinuousVariable; using symbolic::Substitution; using symbolic::Variable; using trajectories::PiecewisePolynomial; // For readability of long lines, these single-letter variables names are // sometimes used: // N number of time steps (aka samples) // h time steps (there are N-1 of these) // x state // u control input MultipleShooting::MultipleShooting(int num_inputs, int num_states, int num_time_samples, double fixed_time_step, solvers::MathematicalProgram* prog) : MultipleShooting(num_inputs, num_states, num_time_samples, false /* time_steps_are_decision_variables */, fixed_time_step, fixed_time_step, prog) {} MultipleShooting::MultipleShooting( const solvers::VectorXDecisionVariable& input, const solvers::VectorXDecisionVariable& state, int num_time_samples, double fixed_time_step, solvers::MathematicalProgram* prog) : MultipleShooting(input, state, num_time_samples, std::nullopt, fixed_time_step, fixed_time_step, prog) {} MultipleShooting::MultipleShooting(int num_inputs, int num_states, int num_time_samples, double minimum_time_step, double maximum_time_step, solvers::MathematicalProgram* prog) : MultipleShooting(num_inputs, num_states, num_time_samples, true /* time_steps_are_decision_variables */, minimum_time_step, maximum_time_step, prog) {} MultipleShooting::MultipleShooting( const solvers::VectorXDecisionVariable& input, const solvers::VectorXDecisionVariable& state, const solvers::DecisionVariable& time, int num_time_samples, double minimum_time_step, double maximum_time_step, solvers::MathematicalProgram* prog) : MultipleShooting(input, state, num_time_samples, time, minimum_time_step, maximum_time_step, prog) {} MultipleShooting::MultipleShooting(int num_inputs, int num_states, int num_time_samples, bool time_steps_are_decision_variables, double minimum_time_step, double maximum_time_step, solvers::MathematicalProgram* prog) : MultipleShooting( MakeVectorContinuousVariable(num_inputs, "u"), MakeVectorContinuousVariable(num_states, "x"), num_time_samples, time_steps_are_decision_variables ? std::optional< solvers::DecisionVariable>{solvers::DecisionVariable{"t"}} : std::nullopt, minimum_time_step, maximum_time_step, prog) {} MultipleShooting::MultipleShooting( const solvers::VectorXDecisionVariable& input, const solvers::VectorXDecisionVariable& state, int num_time_samples, const std::optional<solvers::DecisionVariable>& time_var, double minimum_time_step, double maximum_time_step, solvers::MathematicalProgram* prog) : owned_prog_(prog ? nullptr : std::make_unique<solvers::MathematicalProgram>()), prog_(prog ? *prog : *owned_prog_), num_inputs_(input.size()), num_states_(state.size()), N_(num_time_samples), time_steps_are_decision_variables_(time_var), fixed_time_step_(minimum_time_step), x_vars_(prog_.NewContinuousVariables(num_states_ * N_, "x")), u_vars_(prog_.NewContinuousVariables(num_inputs_ * N_, "u")), placeholder_x_vars_(state), placeholder_u_vars_(input), sequential_expression_manager_(N_) { sequential_expression_manager_.RegisterSequentialExpressions( state, Eigen::Map<solvers::MatrixXDecisionVariable>(x_vars_.data(), num_states_, N_) .cast<Expression>(), "x"); sequential_expression_manager_.RegisterSequentialExpressions( input, Eigen::Map<solvers::MatrixXDecisionVariable>(u_vars_.data(), num_inputs_, N_) .cast<Expression>(), "u"); DRAKE_DEMAND(num_time_samples > 1); DRAKE_DEMAND(num_states_ > 0); DRAKE_DEMAND(num_inputs_ >= 0); if (time_steps_are_decision_variables_) { h_vars_ = prog_.NewContinuousVariables(N_ - 1, "h"); DRAKE_DEMAND(minimum_time_step > 0); // == 0 tends to cause numerical issues. DRAKE_DEMAND(maximum_time_step >= minimum_time_step && std::isfinite(maximum_time_step)); prog_.AddBoundingBoxConstraint(minimum_time_step, maximum_time_step, h_vars_); RowVectorX<Expression> t_expressions(N_); t_expressions(0) = 0; for (int i = 1; i < N_; ++i) { t_expressions(i) = t_expressions(i - 1) + h_vars_(i - 1); } placeholder_t_var_(0) = *time_var; sequential_expression_manager_.RegisterSequentialExpressions( placeholder_t_var_, t_expressions, "t"); } else { h_vars_ = solvers::VectorXDecisionVariable(0); DRAKE_DEMAND(fixed_time_step_ > 0); placeholder_t_var_(0) = sequential_expression_manager_.RegisterSequentialExpressions( RowVectorX<Expression>::LinSpaced(N_, 0, (N_ - 1) * fixed_time_step_), "t")(0); } } solvers::VectorXDecisionVariable MultipleShooting::NewSequentialVariable( int rows, const std::string& name) { return sequential_expression_manager_.RegisterSequentialExpressions( prog_.NewContinuousVariables(rows, N_, name).cast<Expression>(), name); } solvers::VectorXDecisionVariable MultipleShooting::GetSequentialVariableAtIndex( const std::string& name, int index) const { return symbolic::GetVariableVector( sequential_expression_manager_.GetSequentialExpressionsByName(name, index)); } std::vector<solvers::Binding<solvers::Constraint>> MultipleShooting::AddConstraintToAllKnotPoints( const Eigen::Ref<const VectorX<symbolic::Formula>>& f) { std::vector<solvers::Binding<solvers::Constraint>> bindings; for (int i = 0; i < f.size(); ++i) { std::vector<solvers::Binding<solvers::Constraint>> b = AddConstraintToAllKnotPoints(f[i]); bindings.insert(bindings.end(), std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())); } return bindings; } solvers::Binding<solvers::BoundingBoxConstraint> MultipleShooting::AddTimeIntervalBounds(double lower_bound, double upper_bound) { DRAKE_THROW_UNLESS(time_steps_are_decision_variables_); return prog_.AddBoundingBoxConstraint(lower_bound, upper_bound, h_vars_); } std::vector<solvers::Binding<solvers::LinearConstraint>> MultipleShooting::AddEqualTimeIntervalsConstraints() { DRAKE_THROW_UNLESS(time_steps_are_decision_variables_); std::vector<solvers::Binding<solvers::LinearConstraint>> constraints; for (int i = 1; i < N_ - 1; i++) { constraints.push_back( prog_.AddLinearConstraint(h_vars_(i - 1) == h_vars_(i))); } return constraints; } solvers::Binding<solvers::LinearConstraint> MultipleShooting::AddDurationBounds( double lower_bound, double upper_bound) { DRAKE_THROW_UNLESS(time_steps_are_decision_variables_); return prog_.AddLinearConstraint(VectorXd::Ones(h_vars_.size()), lower_bound, upper_bound, h_vars_); } solvers::Binding<solvers::VisualizationCallback> MultipleShooting::AddInputTrajectoryCallback( const MultipleShooting::TrajectoryCallback& callback) { return prog_.AddVisualizationCallback( [this, callback](const Eigen::Ref<const Eigen::VectorXd>& x) { const Eigen::VectorXd times = GetSampleTimes(x.head(h_vars_.size())); const Eigen::Map<const Eigen::MatrixXd> inputs( x.data() + h_vars_.size(), num_inputs_, N_); callback(times, inputs); }, {h_vars_, u_vars_}); } solvers::Binding<solvers::VisualizationCallback> MultipleShooting::AddStateTrajectoryCallback( const MultipleShooting::TrajectoryCallback& callback) { return prog_.AddVisualizationCallback( [this, callback](const Eigen::Ref<const Eigen::VectorXd>& x) { const Eigen::VectorXd times = GetSampleTimes(x.head(h_vars_.size())); const Eigen::Map<const Eigen::MatrixXd> states( x.data() + h_vars_.size(), num_states_, N_); callback(times, states); }, {h_vars_, x_vars_}); } solvers::Binding<solvers::VisualizationCallback> MultipleShooting::AddCompleteTrajectoryCallback( const MultipleShooting::CompleteTrajectoryCallback& callback, const std::vector<std::string>& names) { int num_extra_vars = 0; std::vector<int> size_extra_vars; for (size_t ii = 0; ii < names.size(); ii++) { int num_rows = sequential_expression_manager_.num_rows(names[ii]); num_extra_vars += num_rows; size_extra_vars.push_back(num_rows); } solvers::VectorXDecisionVariable extra_vars(num_extra_vars * N_); int row_offset = 0; for (size_t ii = 0; ii < names.size(); ii++) { extra_vars.middleRows(row_offset, size_extra_vars[ii] * N_) = GetSequentialVariable(names[ii]); row_offset += size_extra_vars[ii] * N_; } return prog_.AddVisualizationCallback( [this, callback, size_extra_vars](const Eigen::Ref<const Eigen::VectorXd>& x) { const Eigen::VectorXd times = GetSampleTimes(x.head(h_vars_.size())); const Eigen::Map<const Eigen::MatrixXd> states( x.data() + h_vars_.size(), num_states_, N_); const Eigen::Map<const Eigen::MatrixXd> inputs( x.data() + h_vars_.size() + x_vars_.size(), num_inputs_, N_); int data_offset = h_vars_.size() + u_vars_.size() + x_vars_.size(); std::vector<Eigen::Ref<const Eigen::MatrixXd>> extras_vec; for (size_t ii = 0; ii < size_extra_vars.size(); ii++) { const Eigen::Map<const Eigen::MatrixXd> extras( x.data() + data_offset, size_extra_vars[ii], N_); data_offset += size_extra_vars[ii] * N_; extras_vec.push_back(extras); } callback(times, states, inputs, extras_vec); }, {h_vars_, x_vars_, u_vars_, extra_vars}); } void MultipleShooting::SetInitialTrajectory( const PiecewisePolynomial<double>& traj_init_u, const PiecewisePolynomial<double>& traj_init_x) { double start_time = 0; double h = fixed_time_step_; if (time_steps_are_decision_variables_) { double end_time = fixed_time_step_ * N_; DRAKE_THROW_UNLESS(!traj_init_u.empty() || !traj_init_x.empty()); if (!traj_init_u.empty()) { start_time = traj_init_u.start_time(); end_time = traj_init_u.end_time(); if (!traj_init_x.empty()) { // Note: Consider adding a tolerance here if warranted. DRAKE_THROW_UNLESS(start_time == traj_init_x.start_time()); DRAKE_THROW_UNLESS(end_time == traj_init_x.end_time()); } } else { start_time = traj_init_x.start_time(); end_time = traj_init_x.end_time(); } DRAKE_DEMAND(start_time <= end_time); h = (end_time - start_time) / (N_ - 1); prog_.SetInitialGuess(h_vars_, VectorXd::Constant(h_vars_.size(), h)); } VectorXd guess_u(u_vars_.size()); if (traj_init_u.empty()) { guess_u.fill(0.003); // Start with some small number <= 0.01. } else { for (int i = 0; i < N_; ++i) { guess_u.segment(num_inputs_ * i, num_inputs_) = traj_init_u.value(start_time + i * h); } } prog_.SetInitialGuess(u_vars_, guess_u); VectorXd guess_x(x_vars_.size()); if (traj_init_x.empty()) { guess_x.fill(0.003); // Start with some small number <= 0.01. // TODO(Lucy-tri) Do what DirectTrajectoryOptimization.m does. } else { for (int i = 0; i < N_; ++i) { guess_x.segment(num_states_ * i, num_states_) = traj_init_x.value(start_time + i * h); } } prog_.SetInitialGuess(x_vars_, guess_x); } Eigen::VectorXd MultipleShooting::GetSampleTimes( const Eigen::Ref<const Eigen::VectorXd>& h_var_values) const { Eigen::VectorXd times(N_); if (time_steps_are_decision_variables_) { times[0] = 0.0; for (int i = 1; i < N_; i++) { times[i] = times[i - 1] + h_var_values(i - 1); } } else { for (int i = 0; i < N_; i++) { times[i] = i * fixed_time_step_; } } return times; } Eigen::MatrixXd MultipleShooting::GetInputSamples( const solvers::MathematicalProgramResult& result) const { Eigen::MatrixXd inputs(num_inputs_, N_); for (int i = 0; i < N_; i++) { inputs.col(i) = result.GetSolution(input(i)); } return inputs; } Eigen::MatrixXd MultipleShooting::GetStateSamples( const solvers::MathematicalProgramResult& result) const { Eigen::MatrixXd states(num_states_, N_); for (int i = 0; i < N_; i++) { states.col(i) = result.GetSolution(state(i)); } return states; } Eigen::MatrixXd MultipleShooting::GetSequentialVariableSamples( const solvers::MathematicalProgramResult& result, const std::string& name) const { const int num_sequential_variables = sequential_expression_manager_.num_rows(name); Eigen::MatrixXd sequential_variables(num_sequential_variables, N_); for (int i = 0; i < N_; i++) { sequential_variables.col(i) = result.GetSolution(GetSequentialVariableAtIndex(name, i)); } return sequential_variables; } Substitution MultipleShooting::ConstructPlaceholderVariableSubstitution( int interval_index) const { return sequential_expression_manager_ .ConstructPlaceholderVariableSubstitution(interval_index); } Expression MultipleShooting::SubstitutePlaceholderVariables( const Expression& e, int interval_index) const { return e.Substitute(ConstructPlaceholderVariableSubstitution(interval_index)); } const solvers::VectorXDecisionVariable MultipleShooting::GetSequentialVariable( const std::string& name) const { const int rows = sequential_expression_manager_.num_rows(name); VectorX<Expression> sequential_variable(rows * N_); for (int i = 0; i < N_; i++) { sequential_variable.segment(i * rows, rows) = sequential_expression_manager_.GetSequentialExpressionsByName(name, i); } return symbolic::GetVariableVector(sequential_variable); } Formula MultipleShooting::SubstitutePlaceholderVariables( const Formula& f, int interval_index) const { return f.Substitute(ConstructPlaceholderVariableSubstitution(interval_index)); } solvers::MathematicalProgramResult Solve(const MultipleShooting& trajopt) { const solvers::MathematicalProgram& prog = trajopt.prog(); return Solve(prog); } solvers::MathematicalProgramResult Solve( const MultipleShooting& trajopt, const Eigen::Ref<const Eigen::VectorXd>& initial_guess) { const solvers::MathematicalProgram& prog = trajopt.prog(); return solvers::Solve(prog, initial_guess); } solvers::MathematicalProgramResult Solve( const MultipleShooting& trajopt, const std::optional<Eigen::VectorXd>& initial_guess, const std::optional<solvers::SolverOptions>& solver_options) { const solvers::MathematicalProgram& prog = trajopt.prog(); return Solve(prog, initial_guess, solver_options); } } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/integration_constraint.cc
#include "drake/planning/trajectory_optimization/integration_constraint.h" #include <utility> #include <vector> namespace drake { namespace planning { namespace trajectory_optimization { MidPointIntegrationConstraint::MidPointIntegrationConstraint(int dim) : solvers::Constraint(dim, 4 * dim + 1, Eigen::VectorXd::Zero(dim), Eigen::VectorXd::Zero(dim), "midpoint_integration_constraint"), dim_{dim} { // Set the sparsity pattern of the constraint gradient. The i'th row of the // constraint only depends on variable x_r(i), x_l(i), xdot_r(i), xdot_l(i) // and dt. std::vector<std::pair<int, int>> gradient_sparsity_pattern; gradient_sparsity_pattern.reserve(5 * dim); for (int i = 0; i < dim_; ++i) { gradient_sparsity_pattern.emplace_back(i, i); // x_r(i) gradient_sparsity_pattern.emplace_back(i, i + dim); // x_l(i) gradient_sparsity_pattern.emplace_back(i, i + 2 * dim); // xdot_r(i) gradient_sparsity_pattern.emplace_back(i, i + 3 * dim); // xdot_r(i) gradient_sparsity_pattern.emplace_back(i, 4 * dim); // dt } SetGradientSparsityPattern(gradient_sparsity_pattern); } template <typename T> void MidPointIntegrationConstraint::DoEvalGeneric( const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const { VectorX<T> x_r, x_l, xdot_r, xdot_l; T dt; DecomposeX<T>(x, &x_r, &x_l, &xdot_r, &xdot_l, &dt); *y = x_r - x_l - dt / 2 * (xdot_r + xdot_l); } void MidPointIntegrationConstraint::DoEval( const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const { DoEvalGeneric<double>(x, y); } void MidPointIntegrationConstraint::DoEval( const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const { DoEvalGeneric<AutoDiffXd>(x, y); } void MidPointIntegrationConstraint::DoEval( const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const { DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y); } } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/direct_transcription.cc
#include "drake/planning/trajectory_optimization/direct_transcription.h" #include <algorithm> #include <cstddef> #include <limits> #include <optional> #include <stdexcept> #include <string> #include <utility> #include <vector> #include "drake/common/symbolic/decompose.h" #include "drake/math/autodiff.h" #include "drake/math/autodiff_gradient.h" #include "drake/solvers/constraint.h" #include "drake/systems/analysis/explicit_euler_integrator.h" #include "drake/systems/framework/system_symbolic_inspector.h" namespace drake { namespace planning { namespace trajectory_optimization { using systems::Context; using systems::DiscreteValues; using systems::ExplicitEulerIntegrator; using systems::FixedInputPortValue; using systems::InputPort; using systems::InputPortIndex; using systems::InputPortSelection; using systems::IntegratorBase; using systems::PeriodicEventData; using systems::PortDataType; using systems::System; using systems::SystemSymbolicInspector; using systems::TimeVaryingLinearSystem; using trajectories::PiecewisePolynomial; namespace { // Implements a constraint on the defect between the state variables // advanced for one discrete step or one integration for a fixed time step, // and the decision variable representing the next state. class DirectTranscriptionConstraint : public solvers::Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DirectTranscriptionConstraint) // @param system The system describing the dynamics of the constraint. // The reference must remain valid for the lifetime of this constraint. // @param context A mutable pointer to a context that will be written to in // order to perform the dynamics evaluations. This context must also // stay valid for the lifetime of this constraint. // @param input_port_value A pre-allocated mutable pointer for writing the // input value, which must be assigned as an input to @p context. It must // also remain valid. // @param num_states the integer size of the discrete or continuous // state vector being optimized. // @param num_inputs the integer size of the input vector being optimized. // @param evaluation_time The time along the trajectory at which this // constraint is evaluated. // @param fixed_time_step Defines the explicit Euler integration // time step for systems with continuous state variables. DirectTranscriptionConstraint(IntegratorBase<AutoDiffXd>* integrator, FixedInputPortValue* input_port_value, int num_states, int num_inputs, double evaluation_time, TimeStep fixed_time_step) : Constraint(num_states, num_inputs + 2 * num_states, Eigen::VectorXd::Zero(num_states), Eigen::VectorXd::Zero(num_states)), integrator_(integrator), input_port_value_(input_port_value), num_states_(num_states), num_inputs_(num_inputs), evaluation_time_(evaluation_time), fixed_time_step_(fixed_time_step.value) { DRAKE_DEMAND(evaluation_time >= 0.0); const Context<AutoDiffXd>& context = integrator->get_context(); DRAKE_DEMAND(context.has_only_discrete_state() || context.has_only_continuous_state()); DRAKE_DEMAND(context.num_input_ports() == 0 || input_port_value_ != nullptr); if (context.has_only_discrete_state()) { discrete_state_ = integrator_->get_system().AllocateDiscreteVariables(); } else { DRAKE_DEMAND(fixed_time_step_ > 0.0); } // Makes sure the autodiff vector is properly initialized. evaluation_time_.derivatives().resize(2 * num_states_ + num_inputs_); evaluation_time_.derivatives().setZero(); } ~DirectTranscriptionConstraint() override = default; protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { AutoDiffVecXd y_t; Eval(x.cast<AutoDiffXd>(), &y_t); *y = math::ExtractValue(y_t); } // The format of the input to the eval() function is a vector // containing {input, state, next_state}. void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DRAKE_ASSERT(x.size() == num_inputs_ + (2 * num_states_)); // Extract our input variables: const auto input = x.head(num_inputs_); const auto state = x.segment(num_inputs_, num_states_); const auto next_state = x.tail(num_states_); Context<AutoDiffXd>* context = integrator_->get_mutable_context(); context->SetTime(evaluation_time_); if (context->num_input_ports() > 0) { input_port_value_->GetMutableVectorData<AutoDiffXd>()->SetFromVector( input); } if (context->has_only_continuous_state()) { // Compute the defect between next_state and the explicit Euler // integration. context->SetContinuousState(state); DRAKE_THROW_UNLESS(integrator_->IntegrateWithSingleFixedStepToTime( evaluation_time_ + fixed_time_step_)); *y = next_state - context->get_continuous_state_vector().CopyToVector(); } else { context->SetDiscreteState(0, state); discrete_state_->SetFrom( integrator_->get_system().EvalUniquePeriodicDiscreteUpdate(*context)); *y = next_state - discrete_state_->get_vector(0).get_value(); } } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const override { throw std::logic_error( "DirectTranscriptionConstraint does not support symbolic evaluation."); } private: IntegratorBase<AutoDiffXd>* const integrator_; std::unique_ptr<DiscreteValues<AutoDiffXd>> discrete_state_; FixedInputPortValue* const input_port_value_{nullptr}; const int num_states_{0}; const int num_inputs_{0}; AutoDiffXd evaluation_time_{0}; const double fixed_time_step_{0}; }; double get_period(const System<double>* system, std::string message) { std::optional<PeriodicEventData> periodic_data = system->GetUniquePeriodicDiscreteUpdateAttribute(); if (!periodic_data.has_value()) { throw std::invalid_argument(message); } DRAKE_DEMAND(periodic_data->offset_sec() == 0.0); return periodic_data->period_sec(); } int get_input_port_size( const System<double>* system, std::variant<InputPortSelection, InputPortIndex> input_port_index) { if (system->get_input_port_selection(input_port_index)) { return system->get_input_port_selection(input_port_index)->size(); } else { return 0; } } } // namespace DirectTranscription::DirectTranscription( const System<double>* system, const Context<double>& context, int num_time_samples, const std::variant<InputPortSelection, InputPortIndex>& input_port_index) : MultipleShooting(get_input_port_size(system, input_port_index), context.num_total_states(), num_time_samples, get_period(system, "This constructor is for discrete-time " "systems. For continuous-time " "systems, you must use a different " "constructor that specifies the " "time steps.")), discrete_time_system_(true) { ValidateSystem(*system, context, input_port_index); // First try symbolic dynamics. if (!AddSymbolicDynamicConstraints(system, context, input_port_index)) { AddAutodiffDynamicConstraints(system, context, input_port_index); } ConstrainEqualInputAtFinalTwoTimesteps(); } DirectTranscription::DirectTranscription( const TimeVaryingLinearSystem<double>* system, const Context<double>& context, int num_time_samples, const std::variant<InputPortSelection, InputPortIndex>& input_port_index) : MultipleShooting(get_input_port_size(system, input_port_index), context.num_total_states(), num_time_samples, std::max(system->time_period(), std::numeric_limits<double>::epsilon()) /* N.B. Ensures that MultipleShooting is well-formed */), discrete_time_system_(true) { if (!context.has_only_discrete_state()) { throw std::invalid_argument( "This constructor is for discrete-time systems. For continuous-time " "systems, you must use a different constructor that specifies the " "time steps."); } ValidateSystem(*system, context, input_port_index); for (int i = 0; i < N() - 1; i++) { const double t = system->time_period() * i; prog().AddLinearEqualityConstraint( state(i + 1).cast<symbolic::Expression>() == system->A(t) * state(i).cast<symbolic::Expression>() + system->B(t) * input(i).cast<symbolic::Expression>()); } ConstrainEqualInputAtFinalTwoTimesteps(); } DirectTranscription::DirectTranscription( const System<double>* system, const Context<double>& context, int num_time_samples, TimeStep fixed_time_step, const std::variant<InputPortSelection, InputPortIndex>& input_port_index) : MultipleShooting(get_input_port_size(system, input_port_index), context.num_total_states(), num_time_samples, fixed_time_step.value), discrete_time_system_(false) { if (!context.has_only_continuous_state()) { throw std::invalid_argument( "This constructor is for continuous-time systems. For discrete-time " "systems, you must use a different constructor that doesn't specify " "the time step."); } DRAKE_DEMAND(fixed_time_step.value > 0.0); if (context.num_input_ports() > 0) { DRAKE_DEMAND(num_inputs() == get_input_port_size(system, input_port_index)); } // First try symbolic dynamics. if (!AddSymbolicDynamicConstraints(system, context, input_port_index)) { AddAutodiffDynamicConstraints(system, context, input_port_index); } ConstrainEqualInputAtFinalTwoTimesteps(); } void DirectTranscription::DoAddRunningCost(const symbolic::Expression& g) { // Cost = \sum_n g(n,x[n],u[n]) dt for (int i = 0; i < N() - 1; i++) { prog().AddCost(SubstitutePlaceholderVariables(g * fixed_time_step(), i)); } } PiecewisePolynomial<double> DirectTranscription::ReconstructInputTrajectory( const solvers::MathematicalProgramResult& result) const { Eigen::VectorXd times = GetSampleTimes(result); std::vector<double> times_vec(N()); std::vector<Eigen::MatrixXd> inputs(N()); for (int i = 0; i < N(); i++) { times_vec[i] = times(i); inputs[i] = result.GetSolution(input(i)); } // TODO(russt): Implement DTTrajectories and return one of those instead. return PiecewisePolynomial<double>::ZeroOrderHold(times_vec, inputs); } PiecewisePolynomial<double> DirectTranscription::ReconstructStateTrajectory( const solvers::MathematicalProgramResult& result) const { Eigen::VectorXd times = GetSampleTimes(result); std::vector<double> times_vec(N()); std::vector<Eigen::MatrixXd> states(N()); for (int i = 0; i < N(); i++) { times_vec[i] = times(i); states[i] = result.GetSolution(state(i)); } // TODO(russt): Implement DTTrajectories and return one of those instead. // TODO(russt): For continuous time, this should return a cubic polynomial. return PiecewisePolynomial<double>::ZeroOrderHold(times_vec, states); } bool DirectTranscription::AddSymbolicDynamicConstraints( const System<double>* system, const Context<double>& context, const std::variant<InputPortSelection, InputPortIndex>& input_port_index) { using symbolic::Expression; const auto symbolic_system = system->ToSymbolicMaybe(); if (!symbolic_system) { return false; } auto symbolic_context = symbolic_system->CreateDefaultContext(); if (SystemSymbolicInspector::IsAbstract(*symbolic_system, *symbolic_context)) { return false; } symbolic_context->SetTimeStateAndParametersFrom(context); const InputPort<Expression>* input_port = symbolic_system->get_input_port_selection(input_port_index); ExplicitEulerIntegrator<Expression> integrator( *symbolic_system, fixed_time_step(), symbolic_context.get()); integrator.Initialize(); VectorX<Expression> next_state(num_states()); for (int i = 0; i < N() - 1; i++) { symbolic_context->SetTime(i * fixed_time_step()); if (input_port) { input_port->FixValue(symbolic_context.get(), input(i).cast<Expression>()); } if (discrete_time_system_) { symbolic_context->SetDiscreteState(state(i).cast<Expression>()); const DiscreteValues<Expression>& discrete_state = symbolic_system->EvalUniquePeriodicDiscreteUpdate(*symbolic_context); next_state = discrete_state.get_vector(0).get_value(); } else { symbolic_context->SetContinuousState(state(i).cast<Expression>()); DRAKE_THROW_UNLESS(integrator.IntegrateWithSingleFixedStepToTime( (i + 1) * fixed_time_step())); next_state = symbolic_context->get_continuous_state_vector().CopyToVector(); } if (i == 0 && !IsAffine(next_state, symbolic::Variables(prog().decision_variables()))) { // Note: only check on the first iteration, where we can return false // before adding any constraints to the program. For i>0, the // AddLinearEqualityConstraint call with throw. return false; } prog().AddLinearEqualityConstraint(state(i + 1) == next_state); } return true; } void DirectTranscription::AddAutodiffDynamicConstraints( const System<double>* system, const Context<double>& context, const std::variant<InputPortSelection, InputPortIndex>& input_port_index) { system_ = system->ToAutoDiffXd(); DRAKE_DEMAND(system_ != nullptr); context_ = system_->CreateDefaultContext(); input_port_ = system_->get_input_port_selection(input_port_index); context_->SetTimeStateAndParametersFrom(context); if (input_port_) { // Verify that the input port is not abstract valued. if (input_port_->get_data_type() == PortDataType::kAbstractValued) { throw std::logic_error( "The specified input port is abstract-valued, but " "DirectTranscription only supports vector-valued input ports. Did " "you perhaps forget to pass a non-default `input_port_index` " "argument?"); } // Provide a fixed value for the input port and keep an alias around. input_port_value_ = &input_port_->FixValue( context_.get(), system_->AllocateInputVector(*input_port_)->get_value()); } integrator_ = std::make_unique<ExplicitEulerIntegrator<AutoDiffXd>>( *system_, fixed_time_step(), context_.get()); integrator_->Initialize(); // For N-1 time steps, add a constraint which depends on the breakpoint // along with the state and input vectors at that breakpoint and the // next. for (int i = 0; i < N() - 1; i++) { // Add the dynamic constraints. // Note that these constraints all share a context and inout_port_value, // so should not be evaluated in parallel. auto constraint = std::make_shared<DirectTranscriptionConstraint>( integrator_.get(), input_port_value_, num_states(), num_inputs(), i * fixed_time_step(), TimeStep{fixed_time_step()}); prog().AddConstraint(constraint, {input(i), state(i), state(i + 1)}); } } void DirectTranscription::ConstrainEqualInputAtFinalTwoTimesteps() { if (num_inputs() > 0) { prog().AddLinearEqualityConstraint(input(N() - 2) == input(N() - 1)); } } void DirectTranscription::ValidateSystem( const System<double>& system, const Context<double>& context, const std::variant<InputPortSelection, InputPortIndex>& input_port_index) { DRAKE_DEMAND(system.IsDifferenceEquationSystem()); DRAKE_DEMAND(num_states() == context.get_discrete_state(0).size()); if (context.num_input_ports() > 0) { DRAKE_DEMAND(num_inputs() == get_input_port_size(&system, input_port_index)); } } } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/sequential_expression_manager.h
#pragma once #include <string> #include <unordered_map> #include <utility> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/common/string_unordered_map.h" #include "drake/common/symbolic/expression.h" namespace drake { namespace planning { namespace trajectory_optimization { namespace internal { /* * Represents a collection of sequential expression vectors (expression vectors * that take on different values for each index in {0, ..., `num_samples` - 1}). * Each sequential expression vector is identified by a name and has an * associated vector of placeholder variables. These placeholder variables can * be replaced with the corresponding expressions for a given index by means of * the symbolic::Substitution that ConstructPlaceholderVariableSubstitution() * returns. */ class SequentialExpressionManager { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(SequentialExpressionManager); /* * @pre `num_samples` > 0 */ explicit SequentialExpressionManager(int num_samples); ~SequentialExpressionManager() = default; /* * Registers a sequential expression vector and returns a vector of * placeholder variables. * @param sequential_expressions [num_expressions x num_samples] matrix of * symbolic expressions. sequential_expressions(i, j) is the value of the i-th * expression at the j-th index. * @param name Name for the newly registered sequential expression vector. The * i-th element of the placeholder variable vector will be named name_i. * @pre `sequential_expressions` has num_samples() columns. * @pre `name` must not duplicate the name of any previously registered * sequential expression vector. * @returns placeholder variable vector for use with * ConstructPlaceholderVariableSubstitution(). */ VectorX<symbolic::Variable> RegisterSequentialExpressions( const Eigen::Ref<const MatrixX<symbolic::Expression>>& sequential_expressions, const std::string& name); /* * Registers a placeholder variables and the associated sequential expression * vector. * * @param placeholders Placeholder variables. * @param sequential_expressions [size_of_placeholder_variables x num_samples] * matrix of symbolic expressions. * sequential_expressions(i, j) is the value of * the i-th expression at the j-th index. * @param name Name for the newly registered sequential expression vector. * @throws std::exception unless `sequential_expressions` has * `placeholders.size()` rows. * @throws std::exception unless `sequential_expressions` has num_samples() * columns. * @throws std::exception if it has an existing registration under the * `name`. */ void RegisterSequentialExpressions( const VectorX<symbolic::Variable>& placeholders, const Eigen::Ref<const MatrixX<symbolic::Expression>>& sequential_expressions, const std::string& name); /* * Returns a symbolic::Substitution for replacing all placeholder variables * with their respective `index`-th expression. * @pre 0 <= index < num_samples() */ symbolic::Substitution ConstructPlaceholderVariableSubstitution( int index) const; /* * Returns a vector with each placeholder symbolic::Variable in `vars` * replaced by the symbolic::Variable corresponding to that placeholder at * `index`. @throws std::exception if the placeholder variable at `index` is * an Expression which does not correspond to a single Variable. */ VectorX<symbolic::Variable> GetVariables( const Eigen::Ref<const VectorX<symbolic::Variable>>& vars, int index) const; /* * Returns the `index`-th vector of expressions for `name`. * @pre `name` is associated with a registered sequential expression vector. * @pre 0 <= index < num_samples() **/ VectorX<symbolic::Expression> GetSequentialExpressionsByName( const std::string& name, int index) const; /* Returns all the sequential expression names in this manager. */ std::vector<std::string> GetSequentialExpressionNames() const; /* * Returns the number of samples for the sequential expressions managed by * `this`. */ int num_samples() const { return num_samples_; } /* * Returns the number of rows for the sequential expression vector `name`. * @pre `name` is associated with a registered sequential expression vector. */ int num_rows(const std::string& name) const; private: int num_samples_{}; string_unordered_map<VectorX<symbolic::Variable>> name_to_placeholders_; std::unordered_map<symbolic::Variable, RowVectorX<symbolic::Expression>> placeholders_to_expressions_; }; } // namespace internal } // namespace trajectory_optimization } // namespace planning } // namespace drake
0
/home/johnshepherd/drake/planning
/home/johnshepherd/drake/planning/trajectory_optimization/direct_collocation.h
#pragma once #include <memory> #include <utility> #include <variant> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/planning/trajectory_optimization/multiple_shooting.h" #include "drake/solvers/constraint.h" #include "drake/systems/framework/context.h" #include "drake/systems/framework/system.h" namespace drake { namespace planning { namespace trajectory_optimization { /// DirectCollocation implements the approach to trajectory optimization as /// described in /// C. R. Hargraves and S. W. Paris. Direct trajectory optimization using /// nonlinear programming and collocation. J Guidance, 10(4):338-342, /// July-August 1987. /// It assumes a first-order hold on the input trajectory and a cubic spline /// representation of the state trajectory, and adds dynamic constraints (and /// running costs) to the midpoints as well as the breakpoints in order to /// achieve a 3rd order integration accuracy. /// /// Note: This algorithm only works with the continuous states of a system. /// @ingroup planning_trajectory class DirectCollocation : public MultipleShooting { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DirectCollocation) /// Constructs the %MathematicalProgram% and adds the collocation /// constraints. /// /// @param system A dynamical system to be used in the dynamic constraints. /// This system must support System::ToAutoDiffXd. Note that this is aliased /// for the lifetime of this object. /// @param context Required to describe any parameters of the system. The /// values of the state in this context do not have any effect. This context /// will also be "cloned" by the optimization; changes to the context after /// calling this method will NOT impact the trajectory optimization. /// @param num_time_samples The number of breakpoints in the trajectory. /// @param minimum_time_step Minimum spacing between sample times. /// @param maximum_time_step Maximum spacing between sample times. /// @param input_port_index A valid input port index for @p system or /// InputPortSelection. All other inputs on the system will be left /// disconnected (if they are disconnected in @p context) or will be fixed to /// their current values (if they are connected/fixed in @p context). /// @default kUseFirstInputIfItExists. /// @param assume_non_continuous_states_are_fixed Boolean which, if true, /// allows this algorithm to optimize without considering the dynamics of any /// non-continuous states. This is helpful for optimizing systems that might /// have some additional book-keeping variables in their state. Only use this /// if you are sure that the dynamics of the additional state variables /// cannot impact the dynamics of the continuous states. @default false. /// @param prog (optional). If non-null, then additional decision variables, /// costs, and constraints will be added into the existing /// MathematicalProgram. This can be useful for, e.g., combining multiple /// trajectory optimizations into a single program, coupled by a few /// constraints. If nullptr, then a new MathematicalProgram will be /// allocated. /// @throws std::exception if `system` is not supported by this direct /// collocation method. DirectCollocation( const systems::System<double>* system, const systems::Context<double>& context, int num_time_samples, double minimum_time_step, double maximum_time_step, std::variant<systems::InputPortSelection, systems::InputPortIndex> input_port_index = systems::InputPortSelection::kUseFirstInputIfItExists, bool assume_non_continuous_states_are_fixed = false, solvers::MathematicalProgram* prog = nullptr); // NOTE: The fixed-time-step constructor, which would avoid adding h as // decision variables, has been (temporarily) removed since it complicates // the API and code. ~DirectCollocation() override {} trajectories::PiecewisePolynomial<double> ReconstructInputTrajectory( const solvers::MathematicalProgramResult& result) const override; trajectories::PiecewisePolynomial<double> ReconstructStateTrajectory( const solvers::MathematicalProgramResult& result) const override; private: // Implements a running cost at all time steps using trapezoidal integration. void DoAddRunningCost(const symbolic::Expression& e) override; // Store system-relevant data for e.g. computing the derivatives during // trajectory reconstruction. const systems::System<double>* system_{nullptr}; const std::unique_ptr<systems::Context<double>> context_; const std::variant<systems::InputPortSelection, systems::InputPortIndex> input_port_index_; std::unique_ptr<systems::System<AutoDiffXd>> system_ad_; std::unique_ptr<systems::Context<AutoDiffXd>> context_ad_; std::vector<std::unique_ptr<systems::Context<AutoDiffXd>>> sample_contexts_; }; /// Implements the direct collocation constraints for a first-order hold on /// the input and a cubic polynomial representation of the state trajectories. /// /// Note that the DirectCollocation implementation allocates only ONE of /// these constraints, but binds that constraint multiple times (with /// different decision variables, along the trajectory). /// @ingroup solver_evaluators class DirectCollocationConstraint : public solvers::Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DirectCollocationConstraint) public: /// @see DirectCollocation constructor for a description of the parameters. /// @throws std::exception if `system` is not supported by this direct /// collocation method. /// @pydrake_mkdoc_identifier{double} DirectCollocationConstraint( const systems::System<double>& system, const systems::Context<double>& context, std::variant<systems::InputPortSelection, systems::InputPortIndex> input_port_index = systems::InputPortSelection::kUseFirstInputIfItExists, bool assume_non_continuous_states_are_fixed = false); /// Constructor which supports passing different mutable contexts for the /// different evaluation times. This can be used to facilitate caching (for /// instance, if the `context_segment_start` of one constraint uses the /// `context_segment_end` of the previous constraint). /// /// @see DirectCollocation constructor for a description of the remaining /// parameters. /// /// @throws std::exception if `system` is not supported by this direct /// collocation method. /// @pydrake_mkdoc_identifier{autodiff} DirectCollocationConstraint( const systems::System<AutoDiffXd>& system, systems::Context<AutoDiffXd>* context_sample, systems::Context<AutoDiffXd>* context_next_sample, systems::Context<AutoDiffXd>* context_collocation, std::variant<systems::InputPortSelection, systems::InputPortIndex> input_port_index = systems::InputPortSelection::kUseFirstInputIfItExists, bool assume_non_continuous_states_are_fixed = false); ~DirectCollocationConstraint() override = default; int num_states() const { return num_states_; } int num_inputs() const { return num_inputs_; } protected: DirectCollocationConstraint( std::pair<std::unique_ptr<systems::System<AutoDiffXd>>, std::unique_ptr<systems::Context<AutoDiffXd>>> owned_pair, const systems::System<AutoDiffXd>* system, systems::Context<AutoDiffXd>* context_sample, systems::Context<AutoDiffXd>* context_next_sample, systems::Context<AutoDiffXd>* context_collocation, int num_states, int num_inputs, std::variant<systems::InputPortSelection, systems::InputPortIndex> input_port_index, bool assume_non_continuous_states_are_fixed); void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override; void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override; void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override; private: void CalcDynamics(const AutoDiffVecXd& state, const AutoDiffVecXd& input, systems::Context<AutoDiffXd>* context, AutoDiffVecXd* xdot) const; // Note: owned_system_ and owned_context_ can be nullptr. std::unique_ptr<systems::System<AutoDiffXd>> owned_system_; std::unique_ptr<systems::Context<AutoDiffXd>> owned_context_; const systems::System<AutoDiffXd>& system_; systems::Context<AutoDiffXd>* context_sample_; systems::Context<AutoDiffXd>* context_next_sample_; systems::Context<AutoDiffXd>* context_collocation_; const systems::InputPort<AutoDiffXd>* input_port_; const int num_states_{0}; const int num_inputs_{0}; }; // Note: The order of arguments is a compromise between GSG and the desire to // match the AddConstraint interfaces in MathematicalProgram. /// Helper method to add a DirectCollocationConstraint to the @p prog, /// ensuring that the order of variables in the binding matches the order /// expected by the constraint. solvers::Binding<solvers::Constraint> AddDirectCollocationConstraint( std::shared_ptr<DirectCollocationConstraint> constraint, const Eigen::Ref<const solvers::VectorXDecisionVariable>& time_step, const Eigen::Ref<const solvers::VectorXDecisionVariable>& state, const Eigen::Ref<const solvers::VectorXDecisionVariable>& next_state, const Eigen::Ref<const solvers::VectorXDecisionVariable>& input, const Eigen::Ref<const solvers::VectorXDecisionVariable>& next_input, solvers::MathematicalProgram* prog); } // namespace trajectory_optimization } // namespace planning } // namespace drake
0