repo_id
stringclasses
205 values
file_path
stringlengths
33
141
content
stringlengths
1
307k
__index_level_0__
int64
0
0
/home/johnshepherd/drake/examples/pendulum
/home/johnshepherd/drake/examples/pendulum/test/pendulum_geometry_test.cc
#include "drake/examples/pendulum/pendulum_geometry.h" #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/drake_throw.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/examples/pendulum/pendulum_plant.h" #include "drake/geometry/scene_graph.h" #include "drake/math/rigid_transform.h" #include "drake/math/rotation_matrix.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace examples { namespace pendulum { namespace { using geometry::FramePoseVector; using math::RotationMatrixd; using math::RigidTransformd; math::RigidTransformd ExtractSinglePose( const geometry::FramePoseVector<double>& pose_vector) { DRAKE_THROW_UNLESS(pose_vector.size() == 1); for (const auto& id : pose_vector.ids()) { return pose_vector.value(id); } DRAKE_UNREACHABLE(); } GTEST_TEST(PendulumGeometryTest, AcceptanceTest) { // Specify the diagram. systems::DiagramBuilder<double> builder; auto plant = builder.AddSystem<PendulumPlant>(); auto scene_graph = builder.AddSystem<geometry::SceneGraph>(); auto geom = PendulumGeometry::AddToBuilder( &builder, plant->get_state_output_port(), scene_graph); ASSERT_NE(geom, nullptr); // Finish the diagram and create a context. auto diagram = builder.Build(); auto diagram_context = diagram->CreateDefaultContext(); auto& plant_context = diagram->GetMutableSubsystemContext( *plant, diagram_context.get()); auto& geom_context = diagram->GetMutableSubsystemContext( *geom, diagram_context.get()); // Zero the pendulum input, but set a non-zero initial state. const double theta = 0.2; plant->get_input_port().FixValue(&plant_context, PendulumInput<double>{}); plant->get_mutable_state(&plant_context).set_theta(theta); // Check the frame pose. const double tolerance = 1E-9; // Arbitrary. const auto& geom_output_value = geom->get_output_port(0).Eval<FramePoseVector<double>>(geom_context); EXPECT_TRUE(CompareMatrices( ExtractSinglePose(geom_output_value).GetAsMatrix4(), RigidTransformd(RotationMatrixd::MakeYRotation(theta)).GetAsMatrix4(), tolerance)); // Check other stuff. EXPECT_TRUE(geom->HasAnyDirectFeedthrough()); } } // namespace } // namespace pendulum } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/compass_gait_geometry.cc
#include "drake/examples/compass_gait/compass_gait_geometry.h" #include <memory> #include <fmt/format.h> #include "drake/examples/compass_gait/compass_gait_params.h" #include "drake/geometry/geometry_frame.h" #include "drake/geometry/geometry_ids.h" #include "drake/geometry/geometry_instance.h" #include "drake/geometry/geometry_roles.h" #include "drake/math/rigid_transform.h" #include "drake/math/roll_pitch_yaw.h" #include "drake/math/rotation_matrix.h" namespace drake { namespace examples { namespace compass_gait { using Eigen::Vector3d; using Eigen::Vector4d; using Eigen::VectorXd; using geometry::Box; using geometry::Cylinder; using geometry::GeometryFrame; using geometry::GeometryId; using geometry::GeometryInstance; using geometry::MakePhongIllustrationProperties; using geometry::Sphere; using std::make_unique; const CompassGaitGeometry* CompassGaitGeometry::AddToBuilder( systems::DiagramBuilder<double>* builder, const systems::OutputPort<double>& floating_base_state_port, const CompassGaitParams<double>& compass_gait_params, geometry::SceneGraph<double>* scene_graph) { DRAKE_THROW_UNLESS(builder != nullptr); DRAKE_THROW_UNLESS(scene_graph != nullptr); auto compass_gait_geometry = builder->AddSystem(std::unique_ptr<CompassGaitGeometry>( new CompassGaitGeometry(compass_gait_params, scene_graph))); builder->Connect(floating_base_state_port, compass_gait_geometry->get_input_port(0)); builder->Connect( compass_gait_geometry->get_output_port(0), scene_graph->get_source_pose_port(compass_gait_geometry->source_id_)); return compass_gait_geometry; } CompassGaitGeometry::CompassGaitGeometry( const CompassGaitParams<double>& params, geometry::SceneGraph<double>* scene_graph) { DRAKE_THROW_UNLESS(scene_graph != nullptr); source_id_ = scene_graph->RegisterSource(); // Note: the floating-base state output from CompassGait uses RPY (12 // dims) + 2 for the position/velocity of the right leg. this->DeclareVectorInputPort("floating_base_state", 14); this->DeclareAbstractOutputPort("geometry_pose", &CompassGaitGeometry::OutputGeometryPose); // Add the ramp. // Positioned so that the top center of the box is at x=y=z=0. GeometryId id = scene_graph->RegisterAnchoredGeometry( source_id_, make_unique<GeometryInstance>( math::RigidTransformd( math::RotationMatrixd::MakeYRotation(params.slope())) * math::RigidTransformd(Vector3d(0, 0, -10. / 2.)), make_unique<Box>(100, 1, 10), "ramp")); // Color is "desert sand" according to htmlcsscolor.com. scene_graph->AssignRole( source_id_, id, MakePhongIllustrationProperties(Vector4d(0.9297, 0.7930, 0.6758, 1))); left_leg_frame_id_ = scene_graph->RegisterFrame(source_id_, GeometryFrame("left_leg")); right_leg_frame_id_ = scene_graph->RegisterFrame(source_id_, left_leg_frame_id_, GeometryFrame("right_leg")); // Add the hip. Both legs have the same origin of rotation and the hip // geometry is rotationally symmetric, so we opt to arbitrarily attach it // to the left leg. const double hip_mass_radius = .1; id = scene_graph->RegisterGeometry( source_id_, left_leg_frame_id_, make_unique<GeometryInstance>( math::RigidTransformd(math::RotationMatrixd::MakeXRotation(M_PI_2)), make_unique<Sphere>(hip_mass_radius), "hip")); scene_graph->AssignRole( source_id_, id, MakePhongIllustrationProperties(Vector4d(0, 1, 0, 1))); // Scale the leg mass geometry relative to the hip mass (assuming constant // density). const double leg_mass_radius = std::cbrt( std::pow(hip_mass_radius, 3) * params.mass_leg() / params.mass_hip()); // Add the left leg (which is attached to the hip). id = scene_graph->RegisterGeometry( source_id_, left_leg_frame_id_, make_unique<GeometryInstance>( math::RigidTransformd(Vector3d(0, 0, -params.length_leg() / 2.)), make_unique<Cylinder>(0.0075, params.length_leg()), "left_leg")); scene_graph->AssignRole( source_id_, id, MakePhongIllustrationProperties(Vector4d(1, 0, 0, 1))); id = scene_graph->RegisterGeometry( source_id_, left_leg_frame_id_, make_unique<GeometryInstance>( math::RigidTransformd(Vector3d(0, 0, -params.center_of_mass_leg())), make_unique<Sphere>(leg_mass_radius), "left_leg_mass")); scene_graph->AssignRole( source_id_, id, MakePhongIllustrationProperties(Vector4d(1, 0, 0, 1))); // Add the right leg. id = scene_graph->RegisterGeometry( source_id_, right_leg_frame_id_, make_unique<GeometryInstance>( math::RigidTransformd(Vector3d(0, 0, -params.length_leg() / 2.)), make_unique<Cylinder>(0.0075, params.length_leg()), "right_leg")); scene_graph->AssignRole( source_id_, id, MakePhongIllustrationProperties(Vector4d(0, 0, 1, 1))); id = scene_graph->RegisterGeometry( source_id_, right_leg_frame_id_, make_unique<GeometryInstance>( math::RigidTransformd(Vector3d(0, 0, -params.center_of_mass_leg())), make_unique<Sphere>(leg_mass_radius), "right_leg_mass")); scene_graph->AssignRole( source_id_, id, MakePhongIllustrationProperties(Vector4d(0, 0, 1, 1))); } CompassGaitGeometry::~CompassGaitGeometry() = default; void CompassGaitGeometry::OutputGeometryPose( const systems::Context<double>& context, geometry::FramePoseVector<double>* poses) const { DRAKE_DEMAND(left_leg_frame_id_.is_valid()); DRAKE_DEMAND(right_leg_frame_id_.is_valid()); const VectorXd& input = get_input_port(0).Eval(context); const math::RigidTransformd left_pose( math::RollPitchYawd(input.segment<3>(3)), input.head<3>()); const double hip_angle = input[6]; const math::RigidTransformd right_pose( math::RotationMatrixd::MakeYRotation(hip_angle)); *poses = {{left_leg_frame_id_, left_pose}, {right_leg_frame_id_, right_pose}}; } } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/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", ) package(default_visibility = ["//visibility:private"]) drake_cc_library( name = "compass_gait_vector_types", srcs = [ "compass_gait_continuous_state.cc", "compass_gait_params.cc", ], hdrs = [ "compass_gait_continuous_state.h", "compass_gait_params.h", "gen/compass_gait_continuous_state.h", "gen/compass_gait_params.h", ], visibility = ["//visibility:public"], deps = [ "//common:dummy_value", "//common:essential", "//common:name_value", "//common/symbolic:expression", "//systems/framework:vector", ], ) drake_cc_library( name = "compass_gait", srcs = ["compass_gait.cc"], hdrs = [ "compass_gait.h", ], visibility = ["//visibility:public"], deps = [ ":compass_gait_vector_types", "//common:default_scalars", "//common:essential", "//systems/framework:leaf_system", ], ) drake_cc_library( name = "compass_gait_geometry", srcs = ["compass_gait_geometry.cc"], hdrs = ["compass_gait_geometry.h"], visibility = ["//visibility:public"], deps = [ ":compass_gait", "//geometry:geometry_roles", "//geometry:scene_graph", "//math:geometric_transform", "//systems/framework:diagram_builder", "//systems/framework:leaf_system", ], ) drake_cc_binary( name = "simulate", srcs = ["simulate.cc"], add_test_rule = 1, test_rule_args = ["--target_realtime_rate=0.0"], deps = [ ":compass_gait", ":compass_gait_geometry", "//geometry:drake_visualizer", "//systems/analysis:simulator", "//systems/framework:diagram_builder", "@gflags", ], ) drake_cc_googletest( name = "compass_gait_test", deps = [ ":compass_gait", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:expect_no_throw", "//systems/framework/test_utilities:scalar_conversion", ], ) drake_cc_googletest( name = "compass_gait_geometry_test", deps = [ ":compass_gait", ":compass_gait_geometry", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/compass_gait.h
#pragma once #include <memory> #include <vector> #include "drake/examples/compass_gait/compass_gait_continuous_state.h" #include "drake/examples/compass_gait/compass_gait_params.h" #include "drake/systems/framework/event.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/framework/scalar_conversion_traits.h" #include "drake/systems/framework/witness_function.h" namespace drake { namespace examples { namespace compass_gait { /// Dynamical representation of the idealized hybrid dynamics of a "compass /// gait", as described in /// http://underactuated.mit.edu/underactuated.html?chapter=simple_legs . /// This implementation has two additional state variables that are not /// required in the mathematical model: /// /// - a discrete state for the position of the stance toe along the ramp /// - a Boolean indicator for "left support" (true when the stance leg is /// the left leg). /// /// These are helpful for outputting the floating-base model coordinate, e.g. /// for visualization. /// /// @note This model only supports walking downhill on the ramp, because that /// restriction enables a clean / numerically robust implementation of the foot /// collision witness function that avoids fall detection on the "foot /// scuffing" collision. /// /// @system /// name: CompassGait /// input_ports: /// - hip_torque (optional) /// output_ports: /// - minimal_state /// - floating_base_state /// @endsystem /// /// Continuous States: stance, swing, stancedot, swingdot.<br/> /// Discrete State: stance toe position.<br/> /// Abstract State: left support indicator.<br/> /// /// Note: If the hip_torque input port is not connected, then the torque is /// taken to be zero. /// /// @tparam_default_scalar template <typename T> class CompassGait final : public systems::LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(CompassGait); /// Constructs the plant. CompassGait(); /// Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit CompassGait(const CompassGait<U>&) : CompassGait<T>() {} /// Returns reference to the output port that publishes only /// [theta_stance, theta_swing, thetatdot_stance, thetadot_swing]. const systems::OutputPort<T>& get_minimal_state_output_port() const { return this->get_output_port(0); } /// Returns reference to the output port that provides the state in the /// floating-base coordinates (described via left leg xyz & rpy + hip angle + /// derivatives). const systems::OutputPort<T>& get_floating_base_state_output_port() const { return this->get_output_port(1); } /// Returns the CompassGaitContinuousState. static const CompassGaitContinuousState<T>& get_continuous_state( const systems::Context<T>& context) { return get_continuous_state(context.get_continuous_state()); } /// Returns the mutable CompassGaitContinuousState. static CompassGaitContinuousState<T>& get_mutable_continuous_state( systems::Context<T>* context) { return get_mutable_continuous_state( &context->get_mutable_continuous_state()); } static const T& get_toe_position(const systems::Context<T>& context) { return context.get_discrete_state(0).GetAtIndex(0); } static void set_toe_position(const T& value, systems::State<T>* state) { state->get_mutable_discrete_state().get_mutable_vector(0).SetAtIndex(0, value); } static bool left_leg_is_stance(const systems::Context<T> &context) { return context.template get_abstract_state<bool>(0); } static void set_left_leg_is_stance(bool value, systems::State<T>* state) { state->template get_mutable_abstract_state<bool>(0) = value; } /// Access the CompassGaitParams. const CompassGaitParams<T>& get_parameters( const systems::Context<T>& context) const { return this->template GetNumericParameter<CompassGaitParams>(context, 0); } ///@{ /// Manipulator equation of CompassGait: M(q)v̇ + bias(q,v) = 0. /// /// - M is the 2x2 mass matrix. /// - bias is a 2x1 vector that includes the Coriolis term and gravity term, /// i.e. bias = C(q,v)*v - τ_g(q). Vector2<T> DynamicsBiasTerm(const systems::Context<T> &context) const; Matrix2<T> MassMatrix(const systems::Context<T> &context) const; ///@} private: static const CompassGaitContinuousState<T>& get_continuous_state( const systems::ContinuousState<T>& cstate) { return dynamic_cast<const CompassGaitContinuousState<T>&>( cstate.get_vector()); } static CompassGaitContinuousState<T>& get_mutable_continuous_state( systems::ContinuousState<T>* cstate) { return dynamic_cast<CompassGaitContinuousState<T>&>( cstate->get_mutable_vector()); } // Calculate the kinetic and potential energy (in the world frame attached to // the stance toe). T DoCalcKineticEnergy(const systems::Context<T>& context) const final; T DoCalcPotentialEnergy(const systems::Context<T>& context) const final; // WitnessFunction to check when the foot hits the ramp (with a sufficiently // large step length). T FootCollision(const systems::Context<T>& context) const; // Handles the impact dynamics, including resetting the stance and swing legs. void CollisionDynamics(const systems::Context<T> &context, const systems::UnrestrictedUpdateEvent<T> &, systems::State<T> *state) const; void MinimalStateOut(const systems::Context<T>& context, CompassGaitContinuousState<T>* output) const; void FloatingBaseStateOut(const systems::Context<T>& context, systems::BasicVector<T>* output) const; // Implements the simple double pendulum dynamics during stance. void DoCalcTimeDerivatives( const systems::Context<T>& context, systems::ContinuousState<T>* derivatives) const final; void DoGetWitnessFunctions(const systems::Context<T>&, std::vector<const systems::WitnessFunction<T>*>* witnesses) const final; // The system stores its witness function internally. std::unique_ptr<systems::WitnessFunction<T>> foot_collision_; }; } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/compass_gait.cc
#include "drake/examples/compass_gait/compass_gait.h" #include <algorithm> #include "drake/common/default_scalars.h" namespace drake { namespace examples { namespace compass_gait { template <typename T> CompassGait<T>::CompassGait() : systems::LeafSystem<T>(systems::SystemTypeTag<CompassGait>{}) { this->DeclareContinuousState(CompassGaitContinuousState<T>(), 2, 2, 0); // Discrete state for stance toe distance along the ramp. this->DeclareDiscreteState(1); // Abstract state for indicating that the left foot is the stance foot. This // is only used for the visualization output. const bool left_stance = true; this->DeclareAbstractState(Value<bool>(left_stance)); // Hip torque input. this->DeclareVectorInputPort("hip_torque", 1); // The minimal state of the system. this->DeclareVectorOutputPort( "minimal_state", CompassGaitContinuousState<T>(), &CompassGait::MinimalStateOut, {this->all_state_ticket()}); // The floating-base (RPY) state of the system (useful for visualization). this->DeclareVectorOutputPort( "floating_base_state", 14, &CompassGait::FloatingBaseStateOut, {this->all_state_ticket(), this->all_parameters_ticket()}); this->DeclareNumericParameter(CompassGaitParams<T>()); // Create the witness function. foot_collision_ = this->MakeWitnessFunction( "foot collision", systems::WitnessFunctionDirection::kPositiveThenNonPositive, &CompassGait::FootCollision, &CompassGait::CollisionDynamics); } template <typename T> T CompassGait<T>::DoCalcKineticEnergy( const systems::Context<T>& context) const { const CompassGaitContinuousState<T>& cg_state = get_continuous_state(context); const CompassGaitParams<T>& params = get_parameters(context); const T m = params.mass_leg(); const T mh = params.mass_hip(); const T l = params.length_leg(); const T a = params.length_leg() - params.center_of_mass_leg(); const T b = params.center_of_mass_leg(); const T vst = cg_state.stancedot(); const T vsw = cg_state.swingdot(); // Sum 1/2 m*v^2 for each of the point masses. return .5 * (mh * l * l + m * a * a) * vst * vst + .5 * m * (l * l * vst * vst + b * b * vsw * vsw) - m * l * b * vst * vsw * cos(cg_state.swing() - cg_state.stance()); } template <typename T> T CompassGait<T>::DoCalcPotentialEnergy( const systems::Context<T>& context) const { const CompassGaitContinuousState<T>& cg_state = get_continuous_state(context); const CompassGaitParams<T>& params = get_parameters(context); const T m = params.mass_leg(); const T mh = params.mass_hip(); const T l = params.length_leg(); const T a = params.length_leg() - params.center_of_mass_leg(); const T b = params.center_of_mass_leg(); const T g = params.gravity(); const T y_toe = -get_toe_position(context) * sin(params.slope()); const T y_hip = y_toe + l * cos(cg_state.stance()); return m * g * (y_toe + a * cos(cg_state.stance())) + mh * g * y_hip + m * g * (y_hip - b * cos(cg_state.swing())); } template <typename T> T CompassGait<T>::FootCollision(const systems::Context<T>& context) const { const CompassGaitContinuousState<T>& cg_state = get_continuous_state(context); const CompassGaitParams<T>& params = get_parameters(context); // Dimensionless position of the swing foot along the ramp normal // (the true height scaled by 1/length_leg) is // cos(stance - slope) - cos(swing - slope) // This is greater than zero when cos(stance - slope) > cos(swing - slope). // Since we know we are walking forward/downhill, we have stance - slope > 0, // and swing - slope < 0. Taking acos of both sides gives that the swing foot // is above the ground iff stance - slope < -(swing - slope). // Geometrically, the intuition is that at collision then biped is forming an // isosceles triangle with the ramp. const T collision = 2. * params.slope() - cg_state.stance() - cg_state.swing(); // Only trigger when swing < stance (e.g. stepping forward/downhill), by // taking max with swing()-stance(). // // Note: This is a mathematically clean way to avoid the "foot scuffing" // collision that is inevitable because both legs have the same length. A // tempting alternative is to require some minimum step length, the foot // scuffing is surprisingly hard to avoid with that mechanism. using std::max; return max(collision, cg_state.swing() - cg_state.stance()); } template <typename T> void CompassGait<T>::CollisionDynamics( const systems::Context<T>& context, const systems::UnrestrictedUpdateEvent<T>&, systems::State<T>* state) const { const CompassGaitContinuousState<T>& cg_state = get_continuous_state(context); CompassGaitContinuousState<T>& next_state = get_mutable_continuous_state(&(state->get_mutable_continuous_state())); const CompassGaitParams<T>& params = get_parameters(context); using std::cos; using std::sin; // Shorthand used in the textbook. const T m = params.mass_leg(); const T mh = params.mass_hip(); const T a = params.length_leg() - params.center_of_mass_leg(); const T b = params.center_of_mass_leg(); const T l = params.length_leg(); const T cst = cos(cg_state.stance()); const T csw = cos(cg_state.swing()); const T hip_angle = cg_state.swing() - cg_state.stance(); const T c = cos(hip_angle); const T sst = sin(cg_state.stance()); const T ssw = sin(cg_state.swing()); // The collision update is performed by using the minimal state and the // knowledge that the stance foot is on the ground to set the state of a // (planar) floating-base model of the biped (with the origin at the // pre-collision stance toe), implementing the collision, and then extracting // the new minimal coordinates. Mathematica derivation is here: // https://www.wolframcloud.com/objects/60e3d6c1-156f-4604-bf70-1e374f47140 Matrix4<T> M_floating_base; // The kinematic Jacobian for the location of the pre-collision swing toe // about the origin (at the pre-collision stance toe). Eigen::Matrix<T, 2, 4> J; // clang-format off M_floating_base << 2 * m + mh, 0, (m * a + m * l + mh * l) * cst, -m * b * csw, 0, 2 * m + mh, -(m * a + m * l + mh * l) * sst, m * b * ssw, (m * a + m * l + mh * l) * cst, -(m * a + m * l + mh * l) * sst, m * a * a + (m + mh) * l * l, -m * l * b * c, -m * b * csw, m * b * ssw, -m * l * b * c, m * b * b; J << 1, 0, l * cst, -l * csw, 0, 1, -l * sst, l * ssw; // clang-format on // Floating-base velocity before contact. Vector4<T> v_pre; v_pre << 0, 0, cg_state.stancedot(), cg_state.swingdot(); const Matrix4<T> Minv = M_floating_base.inverse(); // Floating-base velocity after contact. Vector4<T> v_post = v_pre - Minv * J.transpose() * (J * Minv * J.transpose()).inverse() * J * v_pre; // Also switch stance and swing legs: next_state.set_stance(cg_state.swing()); next_state.set_swing(cg_state.stance()); next_state.set_stancedot(v_post(3)); next_state.set_swingdot(v_post(2)); // toe += step length. set_toe_position(get_toe_position(context) - 2. * params.length_leg() * sin(hip_angle / 2.), state); // Switch stance foot from left to right (or back). set_left_leg_is_stance(!left_leg_is_stance(context), state); } template <typename T> void CompassGait<T>::MinimalStateOut( const systems::Context<T>& context, CompassGaitContinuousState<T>* output) const { output->SetFromVector(get_continuous_state(context).CopyToVector()); } template <typename T> void CompassGait<T>::FloatingBaseStateOut( const systems::Context<T>& context, systems::BasicVector<T>* output) const { const CompassGaitContinuousState<T>& cg_state = get_continuous_state(context); const CompassGaitParams<T>& params = get_parameters(context); const T toe = get_toe_position(context); const bool left_stance = left_leg_is_stance(context); // x, y, z. output->SetAtIndex(0, toe * cos(params.slope()) + params.length_leg() * sin(cg_state.stance())); output->SetAtIndex(1, 0.); output->SetAtIndex(2, -toe * sin(params.slope()) + params.length_leg() * cos(cg_state.stance())); const T left = left_stance ? cg_state.stance() : cg_state.swing(); const T right = left_stance ? cg_state.swing() : cg_state.stance(); // roll, pitch, yaw. output->SetAtIndex(3, 0.); // Left leg is attached to the floating base. output->SetAtIndex(4, left); output->SetAtIndex(5, 0.); // Hip angle (right angle - left_angle). output->SetAtIndex(6, right - left); // x, y, z derivatives. output->SetAtIndex( 7, cg_state.stancedot() * params.length_leg() * cos(cg_state.stance())); output->SetAtIndex(8, 0.); output->SetAtIndex( 9, -cg_state.stancedot() * params.length_leg() * sin(cg_state.stance())); const T leftdot = left_stance ? cg_state.stancedot() : cg_state.swingdot(); const T rightdot = left_stance ? cg_state.swingdot() : cg_state.stancedot(); // roll, pitch, yaw derivatives. output->SetAtIndex(10, 0.); output->SetAtIndex(11, leftdot); output->SetAtIndex(12, 0.); // Hip angle derivative. output->SetAtIndex(13, rightdot - leftdot); } template <typename T> Vector2<T> CompassGait<T>::DynamicsBiasTerm( const systems::Context<T>& context) const { const CompassGaitContinuousState<T>& cg_state = get_continuous_state(context); const CompassGaitParams<T>& params = get_parameters(context); using std::sin; // Shorthand used in the textbook. const T m = params.mass_leg(); const T mh = params.mass_hip(); const T a = params.length_leg() - params.center_of_mass_leg(); const T b = params.center_of_mass_leg(); const T l = params.length_leg(); const T g = params.gravity(); const T s = sin(cg_state.stance() - cg_state.swing()); const T vst = cg_state.stancedot(); const T vsw = cg_state.swingdot(); Vector2<T> bias{ -m * l * b * vsw * vsw * s - (mh * l + m * (a + l)) * g * sin(cg_state.stance()), m * l * b * vst * vst * s + m * b * g * sin(cg_state.swing())}; return bias; } template <typename T> Matrix2<T> CompassGait<T>::MassMatrix( const systems::Context<T>& context) const { const CompassGaitContinuousState<T>& cg_state = get_continuous_state(context); const CompassGaitParams<T>& params = get_parameters(context); using std::cos; // Shorthand used in the textbook. const T m = params.mass_leg(); const T mh = params.mass_hip(); const T a = params.length_leg() - params.center_of_mass_leg(); const T b = params.center_of_mass_leg(); const T l = params.length_leg(); const T c = cos(cg_state.swing() - cg_state.stance()); Matrix2<T> M; // clang-format off M << mh * l * l + m * (l * l + a * a), -m * l * b * c, -m * l * b * c, m * b * b; // clang-format on return M; } template <typename T> void CompassGait<T>::DoCalcTimeDerivatives( const systems::Context<T>& context, systems::ContinuousState<T>* derivatives) const { const CompassGaitContinuousState<T>& cg_state = get_continuous_state(context); const Matrix2<T> M = MassMatrix(context); const Vector2<T> bias = DynamicsBiasTerm(context); const Vector2<T> B(-1, 1); const systems::BasicVector<T>* u_vec = this->EvalVectorInput(context, 0); const Vector1<T> u = u_vec ? u_vec->value() : Vector1<T>::Zero(); Vector4<T> xdot; // clang-format off xdot << cg_state.stancedot(), cg_state.swingdot(), M.inverse() * (B*u - bias); // clang-format on derivatives->SetFromVector(xdot); } template <typename T> void CompassGait<T>::DoGetWitnessFunctions( const systems::Context<T>&, std::vector<const systems::WitnessFunction<T>*>* witnesses) const { witnesses->push_back(foot_collision_.get()); } } // namespace compass_gait } // namespace examples } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::examples::compass_gait::CompassGait)
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/compass_gait_continuous_state.cc
#include "drake/examples/compass_gait/compass_gait_continuous_state.h" namespace drake { namespace examples { namespace compass_gait { const int CompassGaitContinuousStateIndices::kNumCoordinates; const int CompassGaitContinuousStateIndices::kStance; const int CompassGaitContinuousStateIndices::kSwing; const int CompassGaitContinuousStateIndices::kStancedot; const int CompassGaitContinuousStateIndices::kSwingdot; const std::vector<std::string>& CompassGaitContinuousStateIndices::GetCoordinateNames() { static const drake::never_destroyed<std::vector<std::string>> coordinates( std::vector<std::string>{ "stance", "swing", "stancedot", "swingdot", }); return coordinates.access(); } } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/compass_gait_continuous_state.h
#pragma once // This file was previously auto-generated, but now is just a normal source // file in git. However, it still retains some historical oddities from its // heritage. In general, we do recommend against subclassing BasicVector in // new code. #include <cmath> #include <limits> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <Eigen/Core> #include "drake/common/drake_bool.h" #include "drake/common/dummy_value.h" #include "drake/common/name_value.h" #include "drake/common/never_destroyed.h" #include "drake/common/symbolic/expression.h" #include "drake/systems/framework/basic_vector.h" namespace drake { namespace examples { namespace compass_gait { /// Describes the row indices of a CompassGaitContinuousState. struct CompassGaitContinuousStateIndices { /// The total number of rows (coordinates). static const int kNumCoordinates = 4; // The index of each individual coordinate. static const int kStance = 0; static const int kSwing = 1; static const int kStancedot = 2; static const int kSwingdot = 3; /// Returns a vector containing the names of each coordinate within this /// class. The indices within the returned vector matches that of this class. /// In other words, /// `CompassGaitContinuousStateIndices::GetCoordinateNames()[i]` is the name /// for `BasicVector::GetAtIndex(i)`. static const std::vector<std::string>& GetCoordinateNames(); }; /// Specializes BasicVector with specific getters and setters. template <typename T> class CompassGaitContinuousState final : public drake::systems::BasicVector<T> { public: /// An abbreviation for our row index constants. typedef CompassGaitContinuousStateIndices K; /// Default constructor. Sets all rows to their default value: /// @arg @c stance defaults to 0.0 radians. /// @arg @c swing defaults to 0.0 radians. /// @arg @c stancedot defaults to 0.0 rad/sec. /// @arg @c swingdot defaults to 0.0 rad/sec. CompassGaitContinuousState() : drake::systems::BasicVector<T>(K::kNumCoordinates) { this->set_stance(0.0); this->set_swing(0.0); this->set_stancedot(0.0); this->set_swingdot(0.0); } // Note: It's safe to implement copy and move because this class is final. /// @name Implements CopyConstructible, CopyAssignable, MoveConstructible, /// MoveAssignable //@{ CompassGaitContinuousState(const CompassGaitContinuousState& other) : drake::systems::BasicVector<T>(other.values()) {} CompassGaitContinuousState(CompassGaitContinuousState&& other) noexcept : drake::systems::BasicVector<T>(std::move(other.values())) {} CompassGaitContinuousState& operator=( const CompassGaitContinuousState& other) { this->values() = other.values(); return *this; } CompassGaitContinuousState& operator=( CompassGaitContinuousState&& other) noexcept { this->values() = std::move(other.values()); other.values().resize(0); return *this; } //@} /// Create a symbolic::Variable for each element with the known variable /// name. This is only available for T == symbolic::Expression. template <typename U = T> typename std::enable_if_t<std::is_same_v<U, symbolic::Expression>> SetToNamedVariables() { this->set_stance(symbolic::Variable("stance")); this->set_swing(symbolic::Variable("swing")); this->set_stancedot(symbolic::Variable("stancedot")); this->set_swingdot(symbolic::Variable("swingdot")); } [[nodiscard]] CompassGaitContinuousState<T>* DoClone() const final { return new CompassGaitContinuousState; } /// @name Getters and Setters //@{ /// The orientation of the stance leg, measured clockwise from the vertical /// axis. /// @note @c stance is expressed in units of radians. const T& stance() const { ThrowIfEmpty(); return this->GetAtIndex(K::kStance); } /// Setter that matches stance(). void set_stance(const T& stance) { ThrowIfEmpty(); this->SetAtIndex(K::kStance, stance); } /// Fluent setter that matches stance(). /// Returns a copy of `this` with stance set to a new value. [[nodiscard]] CompassGaitContinuousState<T> with_stance( const T& stance) const { CompassGaitContinuousState<T> result(*this); result.set_stance(stance); return result; } /// The orientation of the swing leg, measured clockwise from the vertical /// axis. /// @note @c swing is expressed in units of radians. const T& swing() const { ThrowIfEmpty(); return this->GetAtIndex(K::kSwing); } /// Setter that matches swing(). void set_swing(const T& swing) { ThrowIfEmpty(); this->SetAtIndex(K::kSwing, swing); } /// Fluent setter that matches swing(). /// Returns a copy of `this` with swing set to a new value. [[nodiscard]] CompassGaitContinuousState<T> with_swing(const T& swing) const { CompassGaitContinuousState<T> result(*this); result.set_swing(swing); return result; } /// The angular velocity of the stance leg. /// @note @c stancedot is expressed in units of rad/sec. const T& stancedot() const { ThrowIfEmpty(); return this->GetAtIndex(K::kStancedot); } /// Setter that matches stancedot(). void set_stancedot(const T& stancedot) { ThrowIfEmpty(); this->SetAtIndex(K::kStancedot, stancedot); } /// Fluent setter that matches stancedot(). /// Returns a copy of `this` with stancedot set to a new value. [[nodiscard]] CompassGaitContinuousState<T> with_stancedot( const T& stancedot) const { CompassGaitContinuousState<T> result(*this); result.set_stancedot(stancedot); return result; } /// The angular velocity of the swing leg. /// @note @c swingdot is expressed in units of rad/sec. const T& swingdot() const { ThrowIfEmpty(); return this->GetAtIndex(K::kSwingdot); } /// Setter that matches swingdot(). void set_swingdot(const T& swingdot) { ThrowIfEmpty(); this->SetAtIndex(K::kSwingdot, swingdot); } /// Fluent setter that matches swingdot(). /// Returns a copy of `this` with swingdot set to a new value. [[nodiscard]] CompassGaitContinuousState<T> with_swingdot( const T& swingdot) const { CompassGaitContinuousState<T> result(*this); result.set_swingdot(swingdot); return result; } //@} /// Visit each field of this named vector, passing them (in order) to the /// given Archive. The archive can read and/or write to the vector values. /// One common use of Serialize is the //common/yaml tools. template <typename Archive> void Serialize(Archive* a) { T& stance_ref = this->GetAtIndex(K::kStance); a->Visit(drake::MakeNameValue("stance", &stance_ref)); T& swing_ref = this->GetAtIndex(K::kSwing); a->Visit(drake::MakeNameValue("swing", &swing_ref)); T& stancedot_ref = this->GetAtIndex(K::kStancedot); a->Visit(drake::MakeNameValue("stancedot", &stancedot_ref)); T& swingdot_ref = this->GetAtIndex(K::kSwingdot); a->Visit(drake::MakeNameValue("swingdot", &swingdot_ref)); } /// See CompassGaitContinuousStateIndices::GetCoordinateNames(). static const std::vector<std::string>& GetCoordinateNames() { return CompassGaitContinuousStateIndices::GetCoordinateNames(); } /// Returns whether the current values of this vector are well-formed. drake::boolean<T> IsValid() const { using std::isnan; drake::boolean<T> result{true}; result = result && !isnan(stance()); result = result && !isnan(swing()); result = result && !isnan(stancedot()); result = result && !isnan(swingdot()); return result; } private: void ThrowIfEmpty() const { if (this->values().size() == 0) { throw std::out_of_range( "The CompassGaitContinuousState vector has been moved-from; " "accessor methods may no longer be used"); } } }; } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/simulate.cc
#include <memory> #include <gflags/gflags.h> #include "drake/common/find_resource.h" #include "drake/examples/compass_gait/compass_gait.h" #include "drake/examples/compass_gait/compass_gait_geometry.h" #include "drake/geometry/drake_visualizer.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace examples { namespace compass_gait { namespace { DEFINE_double(target_realtime_rate, 1.0, "Playback speed. See documentation for " "Simulator::set_target_realtime_rate() for details."); /// Simulates the compass gait from various initial velocities (accepted as /// command-line arguments. Run meldis to watch the results. int DoMain() { systems::DiagramBuilder<double> builder; auto compass_gait = builder.AddSystem<CompassGait>(); compass_gait->set_name("compass_gait"); auto scene_graph = builder.AddSystem<geometry::SceneGraph>(); CompassGaitGeometry::AddToBuilder(&builder, compass_gait->get_floating_base_state_output_port(), scene_graph); geometry::DrakeVisualizerd::AddToBuilder(&builder, *scene_graph); auto diagram = builder.Build(); systems::Simulator<double> simulator(*diagram); systems::Context<double>& cg_context = diagram->GetMutableSubsystemContext( *compass_gait, &simulator.get_mutable_context()); CompassGaitContinuousState<double>& state = compass_gait->get_mutable_continuous_state(&cg_context); state.set_stance(0.0); state.set_swing(0.0); state.set_stancedot(0.4); state.set_swingdot(-2.0); compass_gait->get_input_port(0).FixValue(&cg_context, Vector1d(0.0)); simulator.set_target_realtime_rate(FLAGS_target_realtime_rate); simulator.get_mutable_context().SetAccuracy(1e-4); simulator.AdvanceTo(10); return 0; } } // namespace } // namespace compass_gait } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::compass_gait::DoMain(); }
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/compass_gait_geometry.h
#pragma once #include "drake/examples/compass_gait/compass_gait_params.h" #include "drake/geometry/scene_graph.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace examples { namespace compass_gait { /// Expresses a CompassGait's geometry to a SceneGraph. /// /// @system /// name: CompassGaitGeometry /// input_ports: /// - floating_base_state /// output_ports: /// - geometry_pose /// @endsystem /// /// This class has no public constructor; instead use the AddToBuilder() static /// method to create and add it to a DiagramBuilder directly. class CompassGaitGeometry final : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(CompassGaitGeometry); ~CompassGaitGeometry() final; /// Creates, adds, and connects a CompassGaitGeometry system into the given /// `builder`. Both the `floating_base_state_port.get_system()` /// and `scene_graph` systems must have been added to the given `builder` /// already. The `compass_gait_params` sets the parameters of the /// geometry registered with `scene_graph`; the visualization changes /// based on the leg length and the ration of leg mass to hip mass (the leg /// mass sphere is scaled assuming a constant density). /// /// The `scene_graph` pointer is not retained by the %CompassGaitGeometry /// system. The return value pointer is an alias of the new /// %CompassGaitGeometry system that is owned by the `builder`. static const CompassGaitGeometry* AddToBuilder( systems::DiagramBuilder<double>* builder, const systems::OutputPort<double>& floating_base_state_port, const CompassGaitParams<double>& compass_gait_params, geometry::SceneGraph<double>* scene_graph); /// Creates, adds, and connects a CompassGaitGeometry system into the given /// `builder`. Both the `floating_base_state_port.get_system()` and /// `scene_graph` systems must have been added to the given `builder` already. /// CompassGaitParams are set to their default values. /// /// The `scene_graph` pointer is not retained by the %CompassGaitGeometry /// system. The return value pointer is an alias of the new /// %CompassGaitGeometry system that is owned by the `builder`. static const CompassGaitGeometry* AddToBuilder( systems::DiagramBuilder<double>* builder, const systems::OutputPort<double>& floating_base_state_port, geometry::SceneGraph<double>* scene_graph) { return AddToBuilder(builder, floating_base_state_port, CompassGaitParams<double>(), scene_graph); } private: CompassGaitGeometry(const CompassGaitParams<double>& compass_gait_params, geometry::SceneGraph<double>*); void OutputGeometryPose(const systems::Context<double>&, geometry::FramePoseVector<double>*) const; // Geometry source identifier for this system to interact with SceneGraph. geometry::SourceId source_id_{}; geometry::FrameId left_leg_frame_id_{}; geometry::FrameId right_leg_frame_id_{}; }; } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/compass_gait_params.h
#pragma once // This file was previously auto-generated, but now is just a normal source // file in git. However, it still retains some historical oddities from its // heritage. In general, we do recommend against subclassing BasicVector in // new code. #include <cmath> #include <limits> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <Eigen/Core> #include "drake/common/drake_bool.h" #include "drake/common/dummy_value.h" #include "drake/common/name_value.h" #include "drake/common/never_destroyed.h" #include "drake/common/symbolic/expression.h" #include "drake/systems/framework/basic_vector.h" namespace drake { namespace examples { namespace compass_gait { /// Describes the row indices of a CompassGaitParams. struct CompassGaitParamsIndices { /// The total number of rows (coordinates). static const int kNumCoordinates = 6; // The index of each individual coordinate. static const int kMassHip = 0; static const int kMassLeg = 1; static const int kLengthLeg = 2; static const int kCenterOfMassLeg = 3; static const int kGravity = 4; static const int kSlope = 5; /// Returns a vector containing the names of each coordinate within this /// class. The indices within the returned vector matches that of this class. /// In other words, `CompassGaitParamsIndices::GetCoordinateNames()[i]` /// is the name for `BasicVector::GetAtIndex(i)`. static const std::vector<std::string>& GetCoordinateNames(); }; /// Specializes BasicVector with specific getters and setters. template <typename T> class CompassGaitParams final : public drake::systems::BasicVector<T> { public: /// An abbreviation for our row index constants. typedef CompassGaitParamsIndices K; /// Default constructor. Sets all rows to their default value: /// @arg @c mass_hip defaults to 10.0 kg. /// @arg @c mass_leg defaults to 5.0 kg. /// @arg @c length_leg defaults to 1.0 m. /// @arg @c center_of_mass_leg defaults to 0.5 m. /// @arg @c gravity defaults to 9.81 m/s^2. /// @arg @c slope defaults to 0.0525 radians. CompassGaitParams() : drake::systems::BasicVector<T>(K::kNumCoordinates) { this->set_mass_hip(10.0); this->set_mass_leg(5.0); this->set_length_leg(1.0); this->set_center_of_mass_leg(0.5); this->set_gravity(9.81); this->set_slope(0.0525); } // Note: It's safe to implement copy and move because this class is final. /// @name Implements CopyConstructible, CopyAssignable, MoveConstructible, /// MoveAssignable //@{ CompassGaitParams(const CompassGaitParams& other) : drake::systems::BasicVector<T>(other.values()) {} CompassGaitParams(CompassGaitParams&& other) noexcept : drake::systems::BasicVector<T>(std::move(other.values())) {} CompassGaitParams& operator=(const CompassGaitParams& other) { this->values() = other.values(); return *this; } CompassGaitParams& operator=(CompassGaitParams&& other) noexcept { this->values() = std::move(other.values()); other.values().resize(0); return *this; } //@} /// Create a symbolic::Variable for each element with the known variable /// name. This is only available for T == symbolic::Expression. template <typename U = T> typename std::enable_if_t<std::is_same_v<U, symbolic::Expression>> SetToNamedVariables() { this->set_mass_hip(symbolic::Variable("mass_hip")); this->set_mass_leg(symbolic::Variable("mass_leg")); this->set_length_leg(symbolic::Variable("length_leg")); this->set_center_of_mass_leg(symbolic::Variable("center_of_mass_leg")); this->set_gravity(symbolic::Variable("gravity")); this->set_slope(symbolic::Variable("slope")); } [[nodiscard]] CompassGaitParams<T>* DoClone() const final { return new CompassGaitParams; } /// @name Getters and Setters //@{ /// Point mass at the hip. /// @note @c mass_hip is expressed in units of kg. /// @note @c mass_hip has a limited domain of [0.0, +Inf]. const T& mass_hip() const { ThrowIfEmpty(); return this->GetAtIndex(K::kMassHip); } /// Setter that matches mass_hip(). void set_mass_hip(const T& mass_hip) { ThrowIfEmpty(); this->SetAtIndex(K::kMassHip, mass_hip); } /// Fluent setter that matches mass_hip(). /// Returns a copy of `this` with mass_hip set to a new value. [[nodiscard]] CompassGaitParams<T> with_mass_hip(const T& mass_hip) const { CompassGaitParams<T> result(*this); result.set_mass_hip(mass_hip); return result; } /// Mass of each leg (modeled as a point mass at the center of mass). /// @note @c mass_leg is expressed in units of kg. /// @note @c mass_leg has a limited domain of [0.0, +Inf]. const T& mass_leg() const { ThrowIfEmpty(); return this->GetAtIndex(K::kMassLeg); } /// Setter that matches mass_leg(). void set_mass_leg(const T& mass_leg) { ThrowIfEmpty(); this->SetAtIndex(K::kMassLeg, mass_leg); } /// Fluent setter that matches mass_leg(). /// Returns a copy of `this` with mass_leg set to a new value. [[nodiscard]] CompassGaitParams<T> with_mass_leg(const T& mass_leg) const { CompassGaitParams<T> result(*this); result.set_mass_leg(mass_leg); return result; } /// The length of each leg. /// @note @c length_leg is expressed in units of m. /// @note @c length_leg has a limited domain of [0.0, +Inf]. const T& length_leg() const { ThrowIfEmpty(); return this->GetAtIndex(K::kLengthLeg); } /// Setter that matches length_leg(). void set_length_leg(const T& length_leg) { ThrowIfEmpty(); this->SetAtIndex(K::kLengthLeg, length_leg); } /// Fluent setter that matches length_leg(). /// Returns a copy of `this` with length_leg set to a new value. [[nodiscard]] CompassGaitParams<T> with_length_leg( const T& length_leg) const { CompassGaitParams<T> result(*this); result.set_length_leg(length_leg); return result; } /// Distance from the hip to the center of mass of each leg. /// @note @c center_of_mass_leg is expressed in units of m. /// @note @c center_of_mass_leg has a limited domain of [0.0, +Inf]. const T& center_of_mass_leg() const { ThrowIfEmpty(); return this->GetAtIndex(K::kCenterOfMassLeg); } /// Setter that matches center_of_mass_leg(). void set_center_of_mass_leg(const T& center_of_mass_leg) { ThrowIfEmpty(); this->SetAtIndex(K::kCenterOfMassLeg, center_of_mass_leg); } /// Fluent setter that matches center_of_mass_leg(). /// Returns a copy of `this` with center_of_mass_leg set to a new value. [[nodiscard]] CompassGaitParams<T> with_center_of_mass_leg( const T& center_of_mass_leg) const { CompassGaitParams<T> result(*this); result.set_center_of_mass_leg(center_of_mass_leg); return result; } /// An approximate value for gravitational acceleration. /// @note @c gravity is expressed in units of m/s^2. /// @note @c gravity has a limited domain of [0.0, +Inf]. const T& gravity() const { ThrowIfEmpty(); return this->GetAtIndex(K::kGravity); } /// Setter that matches gravity(). void set_gravity(const T& gravity) { ThrowIfEmpty(); this->SetAtIndex(K::kGravity, gravity); } /// Fluent setter that matches gravity(). /// Returns a copy of `this` with gravity set to a new value. [[nodiscard]] CompassGaitParams<T> with_gravity(const T& gravity) const { CompassGaitParams<T> result(*this); result.set_gravity(gravity); return result; } /// The angle of the ramp on which the compass gait is walking. Must have 0 /// <= slope < PI/2 so that forward == downhill (an assumption used in the /// foot collision witness function). /// @note @c slope is expressed in units of radians. /// @note @c slope has a limited domain of [0.0, 1.5707]. const T& slope() const { ThrowIfEmpty(); return this->GetAtIndex(K::kSlope); } /// Setter that matches slope(). void set_slope(const T& slope) { ThrowIfEmpty(); this->SetAtIndex(K::kSlope, slope); } /// Fluent setter that matches slope(). /// Returns a copy of `this` with slope set to a new value. [[nodiscard]] CompassGaitParams<T> with_slope(const T& slope) const { CompassGaitParams<T> result(*this); result.set_slope(slope); return result; } //@} /// Visit each field of this named vector, passing them (in order) to the /// given Archive. The archive can read and/or write to the vector values. /// One common use of Serialize is the //common/yaml tools. template <typename Archive> void Serialize(Archive* a) { T& mass_hip_ref = this->GetAtIndex(K::kMassHip); a->Visit(drake::MakeNameValue("mass_hip", &mass_hip_ref)); T& mass_leg_ref = this->GetAtIndex(K::kMassLeg); a->Visit(drake::MakeNameValue("mass_leg", &mass_leg_ref)); T& length_leg_ref = this->GetAtIndex(K::kLengthLeg); a->Visit(drake::MakeNameValue("length_leg", &length_leg_ref)); T& center_of_mass_leg_ref = this->GetAtIndex(K::kCenterOfMassLeg); a->Visit( drake::MakeNameValue("center_of_mass_leg", &center_of_mass_leg_ref)); T& gravity_ref = this->GetAtIndex(K::kGravity); a->Visit(drake::MakeNameValue("gravity", &gravity_ref)); T& slope_ref = this->GetAtIndex(K::kSlope); a->Visit(drake::MakeNameValue("slope", &slope_ref)); } /// See CompassGaitParamsIndices::GetCoordinateNames(). static const std::vector<std::string>& GetCoordinateNames() { return CompassGaitParamsIndices::GetCoordinateNames(); } /// Returns whether the current values of this vector are well-formed. drake::boolean<T> IsValid() const { using std::isnan; drake::boolean<T> result{true}; result = result && !isnan(mass_hip()); result = result && (mass_hip() >= T(0.0)); result = result && !isnan(mass_leg()); result = result && (mass_leg() >= T(0.0)); result = result && !isnan(length_leg()); result = result && (length_leg() >= T(0.0)); result = result && !isnan(center_of_mass_leg()); result = result && (center_of_mass_leg() >= T(0.0)); result = result && !isnan(gravity()); result = result && (gravity() >= T(0.0)); result = result && !isnan(slope()); result = result && (slope() >= T(0.0)); result = result && (slope() <= T(1.5707)); return result; } void GetElementBounds(Eigen::VectorXd* lower, Eigen::VectorXd* upper) const final { const double kInf = std::numeric_limits<double>::infinity(); *lower = Eigen::Matrix<double, 6, 1>::Constant(-kInf); *upper = Eigen::Matrix<double, 6, 1>::Constant(kInf); (*lower)(K::kMassHip) = 0.0; (*lower)(K::kMassLeg) = 0.0; (*lower)(K::kLengthLeg) = 0.0; (*lower)(K::kCenterOfMassLeg) = 0.0; (*lower)(K::kGravity) = 0.0; (*lower)(K::kSlope) = 0.0; (*upper)(K::kSlope) = 1.5707; } private: void ThrowIfEmpty() const { if (this->values().size() == 0) { throw std::out_of_range( "The CompassGaitParams vector has been moved-from; " "accessor methods may no longer be used"); } } }; } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/compass_gait/compass_gait_params.cc
#include "drake/examples/compass_gait/compass_gait_params.h" namespace drake { namespace examples { namespace compass_gait { const int CompassGaitParamsIndices::kNumCoordinates; const int CompassGaitParamsIndices::kMassHip; const int CompassGaitParamsIndices::kMassLeg; const int CompassGaitParamsIndices::kLengthLeg; const int CompassGaitParamsIndices::kCenterOfMassLeg; const int CompassGaitParamsIndices::kGravity; const int CompassGaitParamsIndices::kSlope; const std::vector<std::string>& CompassGaitParamsIndices::GetCoordinateNames() { static const drake::never_destroyed<std::vector<std::string>> coordinates( std::vector<std::string>{ "mass_hip", "mass_leg", "length_leg", "center_of_mass_leg", "gravity", "slope", }); return coordinates.access(); } } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/compass_gait
/home/johnshepherd/drake/examples/compass_gait/gen/compass_gait_continuous_state.h
#pragma once #include "drake/examples/compass_gait/compass_gait_continuous_state.h" // clang-format off // NOLINTNEXTLINE #warning "DRAKE_DEPRECATED: This include path is deprecated and will be removed on or after 2024-09-01. Remove the /gen/ part of your code's include statement." // clang-format on
0
/home/johnshepherd/drake/examples/compass_gait
/home/johnshepherd/drake/examples/compass_gait/gen/compass_gait_params.h
#pragma once #include "drake/examples/compass_gait/compass_gait_params.h" // clang-format off // NOLINTNEXTLINE #warning "DRAKE_DEPRECATED: This include path is deprecated and will be removed on or after 2024-09-01. Remove the /gen/ part of your code's include statement." // clang-format on
0
/home/johnshepherd/drake/examples/compass_gait
/home/johnshepherd/drake/examples/compass_gait/test/compass_gait_test.cc
#include "drake/examples/compass_gait/compass_gait.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" namespace drake { namespace examples { namespace compass_gait { using std::cos; using std::sin; using std::sqrt; using symbolic::Expression; using symbolic::Variable; namespace { GTEST_TEST(CompassGaitTest, ScalarTypeTests) { CompassGait<double> cg; EXPECT_TRUE(is_autodiffxd_convertible(cg)); EXPECT_TRUE(is_symbolic_convertible(cg)); } GTEST_TEST(CompassGaitTest, TestEnergyConservedInSwing) { CompassGait<Expression> cg; auto context = cg.CreateDefaultContext(); cg.get_input_port(0).FixValue(context.get(), Vector1<Expression>(0.0)); CompassGaitContinuousState<Expression>& state = cg.get_mutable_continuous_state(context.get()); // Set the state vector to be symbolic variables. state.SetToNamedVariables(); // Compute the time-derivative of the energy symbolically. const Expression energy = cg.EvalKineticEnergy(*context) + cg.EvalPotentialEnergy(*context); const VectorX<Expression> derivatives = cg.EvalTimeDerivatives(*context).CopyToVector(); const Expression energy_dot = energy.Jacobian(GetVariableVector(state.CopyToVector())) * derivatives; // Evaluate the time-derivative of energy at a few arbitrary states, it // should be zero. for (int i = 0; i < 4; i++) { symbolic::Environment e; e.insert(get_variable(state.stance()), i + 1.); e.insert(get_variable(state.swing()), i + 2.); e.insert(get_variable(state.stancedot()), i + 3.); e.insert(get_variable(state.swingdot()), i + 4.); EXPECT_NEAR(energy_dot.Evaluate(e), 0.0, 2e-13); } } GTEST_TEST(CompassGaitTest, TestHipTorque) { // Position the compass gait with the swing leg horizontal (straight // forward), and the center of mass over the foot. This should be a fixed // point with the torque balancing the swing leg: // hip_torque = mass_leg * gravity * center_of_mass_leg. // x position of the center of mass = 0 => // sin(stance) * (mass_leg * center_of_mass_leg // + (mass_leg + mass_hip) * length_leg) = mass_leg * center_of_mass_leg CompassGait<double> cg; auto context = cg.CreateDefaultContext(); const CompassGaitParams<double>& params = cg.get_parameters(*context); cg.get_input_port(0).FixValue( context.get(), Vector1<double>(params.mass_leg() * params.gravity() * params.center_of_mass_leg())); CompassGaitContinuousState<double>& state = cg.get_mutable_continuous_state(context.get()); state.set_stance(std::asin( params.mass_leg() * params.center_of_mass_leg() / (params.mass_leg() * params.center_of_mass_leg() + (params.mass_leg() + params.mass_hip()) * params.length_leg()))); state.set_swing(M_PI_2); state.set_stancedot(0.0); state.set_swingdot(0.0); const VectorX<double> derivatives = cg.EvalTimeDerivatives(*context).CopyToVector(); EXPECT_TRUE(CompareMatrices(derivatives, Eigen::Vector4d::Zero(), 1e-15)); } GTEST_TEST(CompassGaitTest, TestCollisionGuard) { const CompassGait<double> cg; auto context = cg.CreateDefaultContext(); CompassGaitContinuousState<double>& state = cg.get_mutable_continuous_state(context.get()); const CompassGaitParams<double>& params = cg.get_parameters(*context); const systems::WitnessFunction<double>* foot_collision; { std::vector<const systems::WitnessFunction<double>*> witness_functions; cg.GetWitnessFunctions(*context, &witness_functions); EXPECT_EQ(witness_functions.size(), 1); foot_collision = witness_functions[0]; } // Foot is above the ground. state.set_stance(.1); state.set_swing(-.1); EXPECT_GT(cg.CalcWitnessValue(*context, *foot_collision), 0.); // Foot is below the ground, but stepping backward. state.set_stance(-.1); state.set_swing(.1); EXPECT_GT(cg.CalcWitnessValue(*context, *foot_collision), 0.); // Foot is exactly touching the ground. state.set_stance(.1 + params.slope()); state.set_swing(-.1 + params.slope()); EXPECT_NEAR(cg.CalcWitnessValue(*context, *foot_collision), 0., 1e-16); } double CalcAngularMomentum(const CompassGait<double>& cg, const systems::Context<double>& context, bool about_stance_foot) { const CompassGaitContinuousState<double>& state = cg.get_continuous_state(context); const CompassGaitParams<double>& params = cg.get_parameters(context); const double m = params.mass_leg(); const double mh = params.mass_hip(); const double a = params.length_leg() - params.center_of_mass_leg(); const double b = params.center_of_mass_leg(); const double l = params.length_leg(); const double cst = cos(state.stance()); const double csw = cos(state.swing()); const double sst = sin(state.stance()); const double ssw = sin(state.swing()); const double vst = state.stancedot(); const double vsw = state.swingdot(); // Position and velocity of the mass in the stance leg. const Eigen::Vector2d p_m_stance{a * sst, a * cst}; const Eigen::Vector2d v_m_stance{a * cst * vst, -a * sst * vst}; // Position and velocity of the mass in the hip. const Eigen::Vector2d p_mh{l * sst, l * cst}; const Eigen::Vector2d v_mh{l * cst * vst, -l * sst * vst}; // Position and velocity of the mass in the stance leg. const Eigen::Vector2d p_m_swing = p_mh - Eigen::Vector2d{b * ssw, b * csw}; const Eigen::Vector2d v_m_swing = v_mh - Eigen::Vector2d{b * csw * vsw, -b * ssw * vsw}; Eigen::Vector2d origin = Eigen::Vector2d::Zero(); if (!about_stance_foot) { origin = p_mh - Eigen::Vector2d{l * ssw, l * csw}; } // Compute the out-of-plane component of the cross product of these planar // vectors. (inputs are in x and z, output is y axis). const auto my_cross = [](const Eigen::Vector2d& u, const Eigen::Vector2d& v) { return u(1) * v(0) - u(0) * v(1); }; // ∑ r × mv. return my_cross(p_m_stance - origin, m * v_m_stance) + my_cross(p_mh - origin, mh * v_mh) + my_cross(p_m_swing - origin, m * v_m_swing); } GTEST_TEST(CompassGaitTest, TestCollisionDynamics) { // Check that angular momentum is conserved about the impact. // (This fact was not used explicitly in the derivation). const CompassGait<double> cg; auto context = cg.CreateDefaultContext(); CompassGaitContinuousState<double>& state = cg.get_mutable_continuous_state(context.get()); const CompassGaitParams<double>& params = cg.get_parameters(*context); const systems::WitnessFunction<double>* foot_collision; { std::vector<const systems::WitnessFunction<double>*> witness_functions; cg.GetWitnessFunctions(*context, &witness_functions); EXPECT_EQ(witness_functions.size(), 1); foot_collision = witness_functions[0]; } // Foot is touching the ground. // Note: Stance can be any value > than slope that keeps the hip above ground. // Swing is set to put the swing toe in collision. Velocities are arbitrary. const double kStanceRelativeToRamp = .2; state.set_stance(kStanceRelativeToRamp + params.slope()); state.set_swing(-kStanceRelativeToRamp + params.slope()); state.set_stancedot(2.); state.set_swingdot(-1.); const double angular_momentum_before = CalcAngularMomentum(cg, *context, false); // Evaluate collision dynamics. auto next_context = cg.CreateDefaultContext(); dynamic_cast<const systems::UnrestrictedUpdateEvent<double>*>( foot_collision->get_event()) ->handle(cg, *context, &next_context->get_mutable_state()); const double angular_momentum_after = CalcAngularMomentum(cg, *next_context, true); EXPECT_NEAR(angular_momentum_before, angular_momentum_after, 3e-14); // Ensure that the toe moved forward. EXPECT_GT(cg.get_toe_position(*next_context), cg.get_toe_position(*context)); } GTEST_TEST(CompassGaitTest, TestMinimalStateOutput) { const CompassGait<double> cg; auto context = cg.CreateDefaultContext(); CompassGaitContinuousState<double>& state = cg.get_mutable_continuous_state(context.get()); auto output = cg.get_minimal_state_output_port().Allocate(); DRAKE_EXPECT_NO_THROW(output->get_value<systems::BasicVector<double>>()); const systems::BasicVector<double>& minimal_state = output->get_value<systems::BasicVector<double>>(); state.set_stance(1.); state.set_swing(2.); state.set_stancedot(3.); state.set_swingdot(4.); cg.get_minimal_state_output_port().Calc(*context, output.get()); EXPECT_TRUE(CompareMatrices(minimal_state.CopyToVector(), state.CopyToVector(), 1e-14)); EXPECT_FALSE( cg.HasDirectFeedthrough(cg.get_minimal_state_output_port().get_index())); } GTEST_TEST(CompassGaitTest, TestFloatBaseOutput) { const CompassGait<double> cg; auto context = cg.CreateDefaultContext(); CompassGaitContinuousState<double>& state = cg.get_mutable_continuous_state(context.get()); const CompassGaitParams<double>& params = cg.get_parameters(*context); auto output = cg.get_floating_base_state_output_port().Allocate(); DRAKE_EXPECT_NO_THROW(output->get_value<systems::BasicVector<double>>()); const systems::BasicVector<double>& floating_base_state = output->get_value<systems::BasicVector<double>>(); // Standing on the left with the hip straight above the toe. cg.set_left_leg_is_stance(true, &context->get_mutable_state()); state.set_stance(0.); state.set_swing(1.); state.set_stancedot(2.); state.set_swingdot(3.); cg.set_toe_position(0., &context->get_mutable_state()); Eigen::VectorXd expected(14); // clang-format off expected << 0., 0., params.length_leg(), // x, y, z 0., 0., 0., // roll, pitch, yaw (of left) state.swing() - state.stance(), // hip angle params.length_leg()*state.stancedot(), 0., 0., // velocities 0., state.stancedot(), 0., state.swingdot() - state.stancedot(); // clang-format on cg.get_floating_base_state_output_port().Calc(*context, output.get()); EXPECT_TRUE( CompareMatrices(floating_base_state.CopyToVector(), expected, 1e-14)); // Now standing on the right with the hip straight above the toe. cg.set_left_leg_is_stance(false, &context->get_mutable_state()); // clang-format off expected << 0., 0., params.length_leg(), // x, y, z 0., state.swing(), 0., // roll, pitch, yaw (of left) state.stance() - state.swing(), // -hip angle params.length_leg()*state.stancedot(), 0., 0., // velocities 0., state.swingdot(), 0., state.stancedot() - state.swingdot(); // clang-format on cg.get_floating_base_state_output_port().Calc(*context, output.get()); EXPECT_TRUE( CompareMatrices(floating_base_state.CopyToVector(), expected, 1e-14)); EXPECT_FALSE(cg.HasDirectFeedthrough( cg.get_floating_base_state_output_port().get_index())); } // Ensure that DoCalcTimeDerivatives succeeds even if the input port is // disconnected. GTEST_TEST(CompassGaitTest, NoInput) { const CompassGait<double> plant; auto context = plant.CreateDefaultContext(); DRAKE_EXPECT_NO_THROW(plant.EvalTimeDerivatives(*context)); } } // namespace } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/compass_gait
/home/johnshepherd/drake/examples/compass_gait/test/compass_gait_geometry_test.cc
#include "drake/examples/compass_gait/compass_gait_geometry.h" #include <gtest/gtest.h> #include "drake/examples/compass_gait/compass_gait.h" #include "drake/geometry/scene_graph.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace examples { namespace compass_gait { namespace { GTEST_TEST(CompassGaitGeometryTest, AcceptanceTest) { // Just make sure nothing faults out. systems::DiagramBuilder<double> builder; auto plant = builder.AddSystem<CompassGait>(); auto scene_graph = builder.AddSystem<geometry::SceneGraph>(); auto geom = CompassGaitGeometry::AddToBuilder( &builder, plant->get_floating_base_state_output_port(), scene_graph); auto diagram = builder.Build(); ASSERT_NE(geom, nullptr); } } // namespace } // namespace compass_gait } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kinova_jaco_arm/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", ) package(default_visibility = ["//visibility:private"]) drake_cc_binary( name = "jaco_controller", srcs = ["jaco_controller.cc"], add_test_rule = 1, data = [ "@drake_models//:jaco_description", ], test_rule_args = ["--build_only"], deps = [ "//common:add_text_logging_gflags", "//lcm", "//manipulation/kinova_jaco", "//manipulation/util:robot_plan_interpolator", "//systems/analysis:simulator", "//systems/controllers:pid_controller", "//systems/lcm:lcm_pubsub_system", "//systems/primitives:adder", "//systems/primitives:demultiplexer", "//systems/primitives:multiplexer", "@gflags", ], ) drake_cc_binary( name = "jaco_simulation", srcs = ["jaco_simulation.cc"], add_test_rule = 1, data = [ "@drake_models//:jaco_description", ], test_rule_args = ["--simulation_sec=0.1"], deps = [ "//common:add_text_logging_gflags", "//geometry:drake_visualizer", "//geometry:scene_graph", "//manipulation/kinova_jaco", "//multibody/parsing", "//multibody/plant", "//systems/analysis:simulator", "//systems/controllers:inverse_dynamics_controller", "//systems/primitives:demultiplexer", "//systems/primitives:multiplexer", "//visualization:visualization_config_functions", "@gflags", ], ) drake_cc_binary( name = "move_jaco_ee", srcs = ["move_jaco_ee.cc"], data = [ "@drake_models//:jaco_description", ], deps = [ "//common:add_text_logging_gflags", "//lcmtypes:jaco", "//manipulation/kinova_jaco:jaco_constants", "//manipulation/util:move_ik_demo_base", "//math:geometric_transform", "@lcm", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kinova_jaco_arm/jaco_simulation.cc
/// @file /// /// This demo sets up a gravity compensated JACO arm within a MultibodyPlant /// simulation controlled via LCM. #include <limits> #include <memory> #include <gflags/gflags.h> #include "drake/geometry/drake_visualizer.h" #include "drake/geometry/scene_graph.h" #include "drake/manipulation/kinova_jaco/jaco_command_receiver.h" #include "drake/manipulation/kinova_jaco/jaco_constants.h" #include "drake/manipulation/kinova_jaco/jaco_status_sender.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/controllers/inverse_dynamics_controller.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_interface_system.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/multiplexer.h" #include "drake/visualization/visualization_config_functions.h" DEFINE_double(simulation_sec, std::numeric_limits<double>::infinity(), "Number of seconds to simulate."); DEFINE_double(realtime_rate, 1.0, ""); DEFINE_double(time_step, 3e-3, "The time step to use for MultibodyPlant model " "discretization. 0 uses the continuous version of the plant."); using Eigen::VectorXd; using drake::geometry::SceneGraph; using drake::lcm::DrakeLcm; using drake::manipulation::kinova_jaco::JacoCommandReceiver; using drake::manipulation::kinova_jaco::JacoStatusSender; using drake::manipulation::kinova_jaco::kJacoDefaultArmNumJoints; using drake::manipulation::kinova_jaco::kJacoDefaultArmNumFingers; using drake::manipulation::kinova_jaco::kJacoLcmStatusPeriod; using drake::multibody::MultibodyPlant; using drake::multibody::Parser; using drake::multibody::RigidBody; using drake::systems::controllers::InverseDynamicsController; using drake::systems::Demultiplexer; using drake::visualization::AddDefaultVisualization; namespace drake { namespace examples { namespace kinova_jaco_arm { namespace { const char kUrdfUrl[] = "package://drake_models/jaco_description/urdf/" "j2s7s300_sphere_collision.urdf"; int DoMain() { systems::DiagramBuilder<double> builder; auto [jaco_plant, scene_graph] = multibody::AddMultibodyPlantSceneGraph(&builder, FLAGS_time_step); const multibody::ModelInstanceIndex jaco_id = Parser(&jaco_plant).AddModelsFromUrl(kUrdfUrl).at(0); jaco_plant.WeldFrames(jaco_plant.world_frame(), jaco_plant.GetFrameByName("base")); jaco_plant.Finalize(); // These gains are really just a guess. Velocity limits are not enforced, // allowing much faster simulated movement than the actual robot. const int num_positions = jaco_plant.num_positions(); VectorXd kp = VectorXd::Constant(num_positions, 100); VectorXd kd = 2.0 * kp.array().sqrt(); VectorXd ki = VectorXd::Zero(num_positions); auto jaco_controller = builder.AddSystem<InverseDynamicsController>( jaco_plant, kp, ki, kd, false); builder.Connect(jaco_plant.get_state_output_port(jaco_id), jaco_controller->get_input_port_estimated_state()); AddDefaultVisualization(&builder); systems::lcm::LcmInterfaceSystem* lcm = builder.AddSystem<systems::lcm::LcmInterfaceSystem>(); auto command_sub = builder.AddSystem( systems::lcm::LcmSubscriberSystem::Make<drake::lcmt_jaco_command>( "KINOVA_JACO_COMMAND", lcm)); auto command_receiver = builder.AddSystem<JacoCommandReceiver>(); builder.Connect(command_sub->get_output_port(), command_receiver->get_message_input_port()); auto mux = builder.AddSystem<systems::Multiplexer>( std::vector<int>({kJacoDefaultArmNumJoints + kJacoDefaultArmNumFingers, kJacoDefaultArmNumJoints + kJacoDefaultArmNumFingers})); builder.Connect(command_receiver->get_commanded_position_output_port(), mux->get_input_port(0)); builder.Connect(command_receiver->get_commanded_velocity_output_port(), mux->get_input_port(1)); builder.Connect(mux->get_output_port(), jaco_controller->get_input_port_desired_state()); builder.Connect(jaco_controller->get_output_port_control(), jaco_plant.get_actuation_input_port(jaco_id)); auto status_pub = builder.AddSystem( systems::lcm::LcmPublisherSystem::Make<drake::lcmt_jaco_status>( "KINOVA_JACO_STATUS", lcm, kJacoLcmStatusPeriod)); // TODO(sammy-tri) populate joint torque (and external torques). External // torques might want to wait until after #12631 is fixed or it could slow // down the simulation significantly. auto status_sender = builder.AddSystem<JacoStatusSender>(); auto demux = builder.AddSystem<systems::Demultiplexer>( std::vector<int>({kJacoDefaultArmNumJoints + kJacoDefaultArmNumFingers, kJacoDefaultArmNumJoints + kJacoDefaultArmNumFingers})); builder.Connect(jaco_plant.get_state_output_port(jaco_id), demux->get_input_port()); builder.Connect(demux->get_output_port(0), status_sender->get_position_input_port()); builder.Connect(demux->get_output_port(0), command_receiver->get_position_measured_input_port()); builder.Connect(demux->get_output_port(1), status_sender->get_velocity_input_port()); builder.Connect(status_sender->get_output_port(), status_pub->get_input_port()); std::unique_ptr<systems::Diagram<double>> diagram = builder.Build(); systems::Simulator<double> simulator(*diagram); systems::Context<double>& root_context = simulator.get_mutable_context(); // Set the initial position to something similar to where the jaco moves to // when starting teleop. VectorXd initial_position = VectorXd::Zero(num_positions); initial_position(0) = 1.80; initial_position(1) = 3.44; initial_position(2) = 3.14; initial_position(3) = 0.76; initial_position(4) = 4.63; initial_position(5) = 4.49; initial_position(6) = 5.03; jaco_plant.SetPositions( &diagram->GetMutableSubsystemContext(jaco_plant, &root_context), initial_position); simulator.Initialize(); simulator.set_publish_every_time_step(false); simulator.set_target_realtime_rate(FLAGS_realtime_rate); simulator.AdvanceTo(FLAGS_simulation_sec); return 0; } } // namespace } // namespace kinova_jaco_arm } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::kinova_jaco_arm::DoMain(); }
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kinova_jaco_arm/README.md
# Jaco Arm Examples This directory contains several examples of drake simulating or interacting with a Kinova Jaco arm. ## Simulation ### Prerequisites All instructions assume that you are launching from the `drake` workspace directory. ``` cd drake ``` Open a visualizer window ``` bazel run //tools:meldis -- --open-window & ``` Build the examples in this directory: ``` bazel build //examples/kinova_jaco_arm/... ``` ### Examples The following examples of a simulated jaco are present: ``` bazel-bin/examples/kinova_jaco_arm/jaco_simulation ``` Simulates a Jaco arm with an inverse dynamics controller, communicating via LCM. ## Control ``` bazel-bin/examples/kinova_jaco_arm/jaco_controller ``` Controls a Jaco arm over LCM using joint velocities. Requires a suitable LCM based simulator (such as the example in this directory) or driver listening for ```lcmt_jaco_command``` messages and publishing ```lcmt_jaco_status```, along with a planner sending robot plan messages. ``` bazel-bin/examples/kinova_jaco_arm/move_jaco_ee ``` Calculates a motion plan for the Jaco arm, to the end effector position specified on the command line (with a reachable default position for testing) and sends the resulting plan over LCM. Requires `jaco_controller` to execute the resulting plan.
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kinova_jaco_arm/move_jaco_ee.cc
/// @file /// /// Demo of moving the jaco's end effector in cartesian space. This program /// creates a plan to move the end effector from the current position to the /// location specified on the command line. The current calculated position /// of the end effector is printed before, during, and after the commanded /// motion. #include "lcm/lcm-cpp.hpp" #include <gflags/gflags.h> #include "drake/lcmt_jaco_status.hpp" #include "drake/manipulation/kinova_jaco/jaco_constants.h" #include "drake/manipulation/util/move_ik_demo_base.h" #include "drake/math/rigid_transform.h" #include "drake/math/roll_pitch_yaw.h" #include "drake/multibody/parsing/package_map.h" DEFINE_string(urdf, "", "Name of urdf to load"); DEFINE_string(lcm_status_channel, "KINOVA_JACO_STATUS", "Channel on which to listen for lcmt_jaco_status messages."); DEFINE_string(lcm_plan_channel, "COMMITTED_ROBOT_PLAN", "Channel on which to send lcmt_robot_plan messages."); DEFINE_double(x, 0.3, "x coordinate (meters) to move to"); DEFINE_double(y, -0.26, "y coordinate (meters) to move to"); DEFINE_double(z, 0.5, "z coordinate (meters) to move to"); DEFINE_double(roll, -1.7, "target roll (radians) about world x axis for end effector"); DEFINE_double(pitch, -1.3, "target pitch (radians) about world y axis for end effector"); DEFINE_double(yaw, -1.8, "target yaw (radians) about world z axis for end effector"); DEFINE_string(ee_name, "j2s7s300_end_effector", "Name of the end effector link"); namespace drake { namespace examples { namespace kinova_jaco_arm { namespace { using manipulation::kinova_jaco::kFingerSdkToUrdf; using manipulation::util::MoveIkDemoBase; using multibody::PackageMap; const char kUrdfUrl[] = "package://drake_models/jaco_description/urdf/" "j2s7s300_sphere_collision.urdf"; int DoMain() { math::RigidTransformd pose( math::RollPitchYawd(FLAGS_roll, FLAGS_pitch, FLAGS_yaw), Eigen::Vector3d(FLAGS_x, FLAGS_y, FLAGS_z)); MoveIkDemoBase demo( !FLAGS_urdf.empty() ? FLAGS_urdf : PackageMap{}.ResolveUrl(kUrdfUrl), "base", FLAGS_ee_name, 100); ::lcm::LCM lc; lc.subscribe<lcmt_jaco_status>( FLAGS_lcm_status_channel, [&](const ::lcm::ReceiveBuffer*, const std::string&, const lcmt_jaco_status* status) { Eigen::VectorXd jaco_q(status->num_joints + status->num_fingers); for (int i = 0; i < status->num_joints; i++) { jaco_q[i] = status->joint_position[i]; } for (int i = 0; i < status->num_fingers; i++) { jaco_q[status->num_joints + i] = status->finger_position[i] * kFingerSdkToUrdf; } demo.HandleStatus(jaco_q); if (demo.status_count() == 1) { std::optional<lcmt_robot_plan> plan = demo.Plan(pose); if (plan.has_value()) { lc.publish(FLAGS_lcm_plan_channel, &plan.value()); } } }); while (lc.handle() >= 0) { } return 0; } } // namespace } // namespace kinova_jaco_arm } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::kinova_jaco_arm::DoMain(); }
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kinova_jaco_arm/jaco_controller.cc
/// @file /// /// Implements a controller for a Kinova Jaco arm. #include <memory> #include <gflags/gflags.h> #include "drake/common/drake_assert.h" #include "drake/common/text_logging.h" #include "drake/lcm/drake_lcm.h" #include "drake/lcmt_jaco_command.hpp" #include "drake/lcmt_jaco_status.hpp" #include "drake/lcmt_robot_plan.hpp" #include "drake/manipulation/kinova_jaco/jaco_command_sender.h" #include "drake/manipulation/kinova_jaco/jaco_constants.h" #include "drake/manipulation/kinova_jaco/jaco_status_receiver.h" #include "drake/manipulation/util/robot_plan_interpolator.h" #include "drake/multibody/parsing/package_map.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/controllers/pid_controller.h" #include "drake/systems/framework/context.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_publisher_system.h" #include "drake/systems/lcm/lcm_subscriber_system.h" #include "drake/systems/primitives/adder.h" #include "drake/systems/primitives/demultiplexer.h" #include "drake/systems/primitives/multiplexer.h" DEFINE_string(urdf, "", "Name of urdf to load"); DEFINE_int32(num_joints, drake::manipulation::kinova_jaco::kJacoDefaultArmNumJoints, "Number of joints in the arm (not including fingers)"); DEFINE_int32(num_fingers, drake::manipulation::kinova_jaco::kJacoDefaultArmNumFingers, "Number of fingers on the arm"); DEFINE_bool(build_only, false, "Build the diagram, but exit before processing messages."); namespace drake { namespace examples { namespace kinova_jaco_arm { namespace { using manipulation::kinova_jaco::JacoCommandSender; using manipulation::kinova_jaco::kJacoDefaultArmNumJoints; using manipulation::kinova_jaco::kJacoDefaultArmNumFingers; using manipulation::kinova_jaco::JacoStatusReceiver; using manipulation::util::RobotPlanInterpolator; using multibody::PackageMap; const char* const kJacoUrdfUrl = "package://drake_models/jaco_description/urdf/" "j2s7s300_sphere_collision.urdf"; const char* const kLcmStatusChannel = "KINOVA_JACO_STATUS"; const char* const kLcmCommandChannel = "KINOVA_JACO_COMMAND"; const char* const kLcmPlanChannel = "COMMITTED_ROBOT_PLAN"; int DoMain() { lcm::DrakeLcm lcm; systems::DiagramBuilder<double> builder; auto plan_sub = builder.AddSystem( systems::lcm::LcmSubscriberSystem::Make<lcmt_robot_plan>( kLcmPlanChannel, &lcm)); const std::string urdf = (!FLAGS_urdf.empty() ? FLAGS_urdf : PackageMap{}.ResolveUrl(kJacoUrdfUrl)); auto plan_source = builder.AddSystem<RobotPlanInterpolator>(urdf); builder.Connect(plan_sub->get_output_port(), plan_source->get_plan_input_port()); const int num_joints = FLAGS_num_joints; const int num_fingers = FLAGS_num_fingers; DRAKE_DEMAND(plan_source->plant().num_positions() == num_joints + num_fingers); DRAKE_DEMAND(plan_source->plant().num_velocities() == num_joints + num_fingers); // The driver is operating in joint velocity mode, so that's the // meaningful part of the command message we'll eventually // construct. We create a pid controller which calculates // // y = kp * (q_desired - q) + kd * (v_desired - v) // // (feedback term) which we'll add to v_desired from the plan source // (feed forward term). Eigen::VectorXd jaco_kp = Eigen::VectorXd::Zero(num_joints + num_fingers); Eigen::VectorXd jaco_ki = Eigen::VectorXd::Zero(num_joints + num_fingers); Eigen::VectorXd jaco_kd = Eigen::VectorXd::Zero(num_joints + num_fingers); // The Jaco shows some tracking error if we're just sending open-loop // velocities, so use a small P term to correct for that. jaco_kp.fill(1); auto pid_controller = builder.AddSystem<systems::controllers::PidController>( jaco_kp, jaco_ki, jaco_kd); // We'll directly fix the input to the status receiver later from our lcm // subscriber. auto status_receiver = builder.AddSystem<JacoStatusReceiver>( num_joints, num_fingers); auto status_mux = builder.AddSystem<systems::Multiplexer>( std::vector<int>({kJacoDefaultArmNumJoints + kJacoDefaultArmNumFingers, kJacoDefaultArmNumJoints + kJacoDefaultArmNumFingers})); builder.Connect(status_receiver->get_position_measured_output_port(), status_mux->get_input_port(0)); builder.Connect(status_receiver->get_velocity_measured_output_port(), status_mux->get_input_port(1)); builder.Connect(status_mux->get_output_port(), pid_controller->get_input_port_estimated_state()); builder.Connect(plan_source->get_output_port(0), pid_controller->get_input_port_desired_state()); // Split the plan source into q_d (sent in the command message for // informational purposes) and v_d (feed forward term for control). auto target_demux = builder.AddSystem<systems::Demultiplexer>( (num_joints + num_fingers) * 2, num_joints + num_fingers); builder.Connect(plan_source->get_output_port(0), target_demux->get_input_port()); // Sum the outputs of the pid controller and v_d. auto adder = builder.AddSystem<systems::Adder>(2, num_joints + num_fingers); builder.Connect(pid_controller->get_output_port_control(), adder->get_input_port(0)); builder.Connect(target_demux->get_output_port(1), adder->get_input_port(1)); auto command_pub = builder.AddSystem( systems::lcm::LcmPublisherSystem::Make<lcmt_jaco_command>( kLcmCommandChannel, &lcm, {systems::TriggerType::kForced})); auto command_sender = builder.AddSystem<JacoCommandSender>(num_joints); builder.Connect(target_demux->get_output_port(0), command_sender->get_position_input_port()); builder.Connect(adder->get_output_port(), command_sender->get_velocity_input_port()); builder.Connect(command_sender->get_output_port(), command_pub->get_input_port()); auto owned_diagram = builder.Build(); const systems::Diagram<double>* diagram = owned_diagram.get(); systems::Simulator<double> simulator(std::move(owned_diagram)); // If we're just testing diagram creation, exit here. if (FLAGS_build_only) { return EXIT_SUCCESS; } // Wait for the first message. drake::log()->info("Waiting for first lcmt_jaco_status"); lcm::Subscriber<lcmt_jaco_status> status_sub(&lcm, kLcmStatusChannel); LcmHandleSubscriptionsUntil(&lcm, [&]() { return status_sub.count() > 0; }); const lcmt_jaco_status& first_status = status_sub.message(); DRAKE_DEMAND(first_status.num_joints == 0 || first_status.num_joints == num_joints); DRAKE_DEMAND(first_status.num_fingers == 0 || first_status.num_fingers == num_fingers); systems::Context<double>& diagram_context = simulator.get_mutable_context(); const double t0 = first_status.utime * 1e-6; diagram_context.SetTime(t0); systems::Context<double>& status_context = diagram->GetMutableSubsystemContext(*status_receiver, &diagram_context); auto& status_value = status_receiver->get_input_port().FixValue( &status_context, first_status); auto& plan_source_context = diagram->GetMutableSubsystemContext(*plan_source, &diagram_context); plan_source->Initialize( t0, status_receiver->get_position_measured_output_port().Eval(status_context), &plan_source_context.get_mutable_state()); // Run forever, using the lcmt_jaco_status message to dictate when simulation // time advances. The lcmt_robot_plan message is handled whenever the next // lcmt_jaco_status occurs. drake::log()->info("Controller started"); while (true) { // Wait for an lcmt_jaco_status message. status_sub.clear(); LcmHandleSubscriptionsUntil(&lcm, [&]() { return status_sub.count() > 0; }); // Write the lcmt_jaco_status message into the context and advance. status_value.GetMutableData()->set_value(status_sub.message()); const double time = status_sub.message().utime * 1e-6; simulator.AdvanceTo(time); // Force-publish the lcmt_jaco_command (via the command_pub system within // the diagram). diagram->ForcedPublish(diagram_context); } // We should never reach here. return EXIT_FAILURE; } } // namespace } // namespace kinova_jaco_arm } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::kinova_jaco_arm::DoMain(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/four_bar/passive_simulation.cc
/* @file A four bar linkage demo demonstrating the use of a linear bushing as a way to model a kinematic loop. It shows: - How to model a four bar linkage in SDF. - Use the `multibody::Parser` to load a model from an SDF file into a MultibodyPlant. - Model a revolute joint with a `multibody::LinearBushingRollPitchYaw` to model a closed kinematic chain. Refer to README.md for more details. */ #include <gflags/gflags.h> #include "drake/multibody/parsing/parser.h" #include "drake/multibody/tree/linear_bushing_roll_pitch_yaw.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/analysis/simulator_gflags.h" #include "drake/systems/analysis/simulator_print_stats.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/visualization/visualization_config_functions.h" namespace drake { using Eigen::Vector3d; using geometry::SceneGraph; using multibody::Frame; using multibody::LinearBushingRollPitchYaw; using multibody::MultibodyPlant; using multibody::Parser; using multibody::RevoluteJoint; using systems::Context; using systems::DiagramBuilder; using systems::Simulator; namespace examples { namespace multibody { namespace four_bar { namespace { DEFINE_double(simulation_time, 10.0, "Duration of the simulation in seconds."); DEFINE_double( force_stiffness, 30000, "Force (translational) stiffness value for kx, ky, kz in N/m of the " "LinearBushingRollPitchYaw ForceElement."); DEFINE_double( force_damping, 1500, "Force (translational) damping value for dx, dy, dz in N·s/m of the " "LinearBushingRollPitchYaw ForceElement."); DEFINE_double(torque_stiffness, 30000, "Torque (rotational) stiffness value for k₀, k₁, k₂ in N·m/rad " "of the LinearBushingRollPitchYaw ForceElement."); DEFINE_double( torque_damping, 1500, "Torque (rotational) damping value for d₀, d₁, and d₂ in N·m·s/rad of " "the LinearBushingRollPitchYaw ForceElement."); DEFINE_double(applied_torque, 0.0, "Constant torque applied to joint_WA, denoted Tᴀ in the README."); DEFINE_double( initial_velocity, 3.0, "Initial velocity, q̇A, of joint_WA. Default set to 3 radians/second ≈ " "171.88 degrees/second so that the model has some motion."); int do_main() { // Build a generic MultibodyPlant and SceneGraph. DiagramBuilder<double> builder; auto [four_bar, scene_graph] = AddMultibodyPlantSceneGraph( &builder, std::make_unique<MultibodyPlant<double>>(0.0)); // Make and add the four_bar model from an SDF model. const std::string sdf_url = "package://drake/examples/multibody/four_bar/four_bar.sdf"; Parser parser(&four_bar); parser.AddModelsFromUrl(sdf_url); // Get the two frames that define the bushing, namely frame Bc that is // welded to the end of link B and frame Cb that is welded to the end of // link C. Although the bushing allows 6 degrees-of-freedom between frames // Bc and Cb, the stiffness and damping constants are chosen to approximate // the connection between frames Bc and Cb as having only one rotational // degree of freedom along the bushing's z-axis. const Frame<double>& bc_bushing = four_bar.GetFrameByName("Bc_bushing"); const Frame<double>& cb_bushing = four_bar.GetFrameByName("Cb_bushing"); // See the README for a discussion of how these parameters were selected // for this particular example. const double k_xyz = FLAGS_force_stiffness; const double d_xyz = FLAGS_force_damping; const double k_012 = FLAGS_torque_stiffness; const double d_012 = FLAGS_torque_damping; // See the documentation for LinearBushingRollPitchYaw. // This particular choice of parameters models a z-axis revolute joint. // Note: since each link is constrained to rigid motion in the world X-Z // plane (X-Y plane of the bushing) by the revolute joints specified in the // SDF, it is unnecessary for the bushing to have non-zero values for: k_z, // d_z, k_0, d_0, k_1, d_1. They are left here as an example of how to // parameterize a general z-axis revolute joint without other constraints. const Vector3d force_stiffness_constants{k_xyz, k_xyz, k_xyz}; // N/m const Vector3d force_damping_constants{d_xyz, d_xyz, d_xyz}; // N·s/m const Vector3d torque_stiffness_constants{k_012, k_012, 0}; // N·m/rad const Vector3d torque_damping_constants{d_012, d_012, 0}; // N·m·s/rad // Add a bushing force element where the joint between link B and link C // should be in an ideal 4-bar linkage. four_bar.AddForceElement<LinearBushingRollPitchYaw>( bc_bushing, cb_bushing, torque_stiffness_constants, torque_damping_constants, force_stiffness_constants, force_damping_constants); // We are done defining the model. Finalize and build the diagram. four_bar.Finalize(); visualization::AddDefaultVisualization(&builder); auto diagram = builder.Build(); // Create a context for this system and sub-context for the four bar system. std::unique_ptr<Context<double>> diagram_context = diagram->CreateDefaultContext(); Context<double>& four_bar_context = four_bar.GetMyMutableContextFromRoot(diagram_context.get()); // A constant source for applied torque (Tᴀ) at joint_WA. four_bar.get_actuation_input_port().FixValue(&four_bar_context, FLAGS_applied_torque); // Set initial conditions so the model will have some motion const RevoluteJoint<double>& joint_WA = four_bar.GetJointByName<RevoluteJoint>("joint_WA"); const RevoluteJoint<double>& joint_WC = four_bar.GetJointByName<RevoluteJoint>("joint_WC"); const RevoluteJoint<double>& joint_AB = four_bar.GetJointByName<RevoluteJoint>("joint_AB"); // See the README for an explanation of these angles. const double qA = atan2(sqrt(15.0), 1.0); // about 75.52° const double qB = M_PI - qA; // about 104.48° const double qC = qB; // about 104.48° joint_WA.set_angle(&four_bar_context, qA); joint_AB.set_angle(&four_bar_context, qB); joint_WC.set_angle(&four_bar_context, qC); // Set q̇A,the rate of change in radians/second of the angle qA. joint_WA.set_angular_rate(&four_bar_context, FLAGS_initial_velocity); // Create a simulator and run the simulation std::unique_ptr<Simulator<double>> simulator = MakeSimulatorFromGflags(*diagram, std::move(diagram_context)); simulator->AdvanceTo(FLAGS_simulation_time); // Print some useful statistics PrintSimulatorStatistics(*simulator); return 0; } } // namespace } // namespace four_bar } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A four bar linkage demo demonstrating the use of a linear bushing as " "a way to model a kinematic loop. Launch meldis before running this " "example."); // Changes the default realtime rate to 1.0, so the visualization looks // realistic. Otherwise, it finishes so fast that we can't appreciate the // motion. Users can still change it on command-line, e.g. " // --simulator_target_realtime_rate=0.5" to slow it down. FLAGS_simulator_target_realtime_rate = 1.0; gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::four_bar::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/four_bar/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_binary", ) package(default_visibility = ["//visibility:private"]) filegroup( name = "models", srcs = glob([ "**/*.sdf", ]), visibility = [ "//:__pkg__", "//bindings/pydrake/multibody:__pkg__", ], ) drake_cc_binary( name = "passive_simulation", srcs = ["passive_simulation.cc"], add_test_rule = 1, data = [":models"], test_rule_args = [ "--simulation_time=0.1", ], deps = [ "//multibody/parsing", "//multibody/plant", "//multibody/tree", "//systems/analysis:simulator", "//systems/analysis:simulator_gflags", "//systems/analysis:simulator_print_stats", "//systems/framework:diagram", "//visualization:visualization_config_functions", "@gflags", ], ) add_lint_tests()
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/four_bar/README.md
# Four-Bar Linkage Example This planar four-bar linkage demonstrates how to use a bushing to approximate a closed kinematic chain. It loads an SDF model from the file "four_bar.sdf" into MultiBodyPlant. It handles the closed kinematic chain by replacing one of the four-bar's revolute (pin) joints with a bushing ([drake::multibody::LinearBushingRollPitchYaw](https://drake.mit.edu/doxygen_cxx/classdrake_1_1multibody_1_1_linear_bushing_roll_pitch_yaw.html)) whose force stiffness and damping values were approximated as discussed below. An alternative way to close this four-bar's kinematic chain is to "cut" one of the four-bar's rigid links in half and join those halves with a bushing that has both force and torque stiffness/damping. Note: the links in this example are constrained to rigid motion in the world X-Z plane (bushing X-Y plane) by the 3 revolute joints specified in the SDF. Therefore it is not necessary for the bushing to have force stiffness/damping along the joint axis. To run with default flags: ``` bazel run //examples/multibody/four_bar:passive_simulation ``` You should see the four-bar model oscillating passively with a small initial velocity. To change the initial velocity of `joint_WA`, q̇A in radians/second : ``` bazel run //examples/multibody/four_bar:passive_simulation -- --initial_velocity=<desired_velocity> ``` You can also apply a constant torque, 𝐓ᴀ, to `joint_WA` with a command line argument: ``` bazel run //examples/multibody/four_bar:passive_simulation -- --applied_torque=<desired_torque> ``` The torque is applied constantly to the joint actuator with no feedback. Thus, if set high enough, you will see the system become unstable. You can change the bushing parameters from the command line to observe their effect on the modeled joint. For instance, change `force_stiffness` to 300: ``` bazel run //examples/multibody/four_bar:passive_simulation -- --force_stiffness=300 ``` And observe a gradual displacement between link *B* and link *C*. Change `force_damping` to 0: ``` bazel run //examples/multibody/four_bar:passive_simulation -- --force_damping=0 ``` And observe the joint oscillating. Try setting `applied_torque` to 1000 and watch how the large forces interact with the bushing stiffness. ## Four-bar linkage model The figure below shows a planar four-bar linkage consisting of frictionless-pin-connected uniform rigid links *A, B, C* and ground-link *W*. - Link *A* connects to *W* and *B* at points *A*ₒ and *B*ₒ - Link *B* connects to *A* and *C* at points *B*ₒ and *B*c - Link *C* connects to *W* and *B* at points *C*ₒ and *C*ʙ Right-handed orthogonal unit vectors **Âᵢ B̂ᵢ Ĉᵢ Ŵᵢ** (*i = x,y,z*) are fixed in *A, B, C, W,* with: - **Â**𝐱 directed from *A*ₒ to *B*ₒ - **B̂**𝐱 directed from *B*ₒ to *B*c - **Ĉ**𝐱 directed from *C*ₒ to *C*ʙ - **Ŵ**𝐳 vertically-upward. - **Â**𝐲 = **B̂**𝐲 = **Ĉ**𝐲 = **Ŵ**𝐲 parallel to pin axes | Diagram of the four bar model described above. | | :---: | | ![FourBarLinkageSchematic](images/FourBarLinkageSchematic.png) | | | | Quantity | Symbol | Value | |--------------------------------------------|-------------------|-----------| | Distance between *W*ₒ and *C*ₒ | 𝐋ᴡ | 2 m | | Lengths of links *A, B, C* | *L* | 4 m | | Masses of *A, B, C* | *m* | 20 kg | | Earth’s gravitational acceleration | *g* | 9.8 m/s² | | | | | | **Ŵ**𝐲 measure of motor torque on *A* | 𝐓ᴀ | Specified | | Angle from **Ŵ**𝐱 to **Â**𝐱 with a +**Ŵ**𝐲 sense | 𝐪ᴀ | Variable | | Angle from **Â**𝐱 to **B̂**𝐱 with a +**Â**𝐲 sense | 𝐪ʙ | Variable | | Angle from **Ŵ**𝐱 to **Ĉ**𝐱 with a +**Ŵ**𝐲 sense | 𝐪ᴄ | Variable | | | | | | "Coupler-point" *P*'s position from *B*ₒ | 2 **B̂**𝐱 - 2 **B̂**𝐳 | With 𝐓ᴀ = 0, the equilibrium values for the angles are: 𝐪ᴀ ≈ 75.52°, 𝐪ʙ ≈ 104.48°, 𝐪ᴄ ≈ 104.48°. ## Starting Configuration The SDF defines all of the links with their x axes parallel to the world x axis for convenience of measuring the angles in the state of the system with respect to a fixed axis. Below we derive a valid initial configuration of the three angles 𝐪ᴀ, 𝐪ʙ, and 𝐪ᴄ. | Derivation of starting configuration | | :---: | | ![FourBarLinkageSchematic](images/FourBarLinkageGeometry.png) | | | Due to equal link lengths, the initial condition (static equilibrium) forms an isosceles trapezoid and initial values can be determined from trigonometry. 𝐪ᴀ is one angle of a right triangle with its adjacent side measuring 1 m and its hypotenuse measuring 4 m. Hence, initially 𝐪ᴀ = tan⁻¹(√15) ≈ 1.318 radians ≈ 75.52°. Because link *B* is parallel to **Ŵ**𝐱, 𝐪ᴀ and 𝐪ʙ are supplementary, hence the initial value is 𝐪ʙ = π - 𝐪ᴀ ≈ 1.823 radians ≈ 104.48°. Similarly, 𝐪ᴀ and 𝐪ᴄ are supplementary, so initially 𝐪ᴄ = 𝐪ʙ. # Modeling the revolute joint between links B and C with a bushing In this example, we replace the pin joint at point **Bc** (see diagram) that connects links *B* and *C* with a [drake::multibody::LinearBushingRollPitchYaw](https://drake.mit.edu/doxygen_cxx/classdrake_1_1multibody_1_1_linear_bushing_roll_pitch_yaw.html) (there are many other uses of a bushing). We model a z-axis revolute joint by setting torque stiffness constant k₂ = 0 and torque damping constant d₂ = 0. We chose the z-axis (Yaw) to avoid a singularity associated with "gimbal lock". Two frames (one attached to *B* called `Bc_Bushing` with origin at point **Bc** and one attached to *C* called `Cb_Bushing` with origin at point **Cb**) are oriented so their z-axes are perpedicular to the planar four-bar linkage. ## Estimating bushing parameters Joints are normally modeled with hard constraints except in their motion direction, and three of the four revolute joints here are indeed modeled that way. However, in order to close the kinematic loop we have to use a bushing as a "penalty method" substitute for hard constraints. That is, because the bushing is compliant it will violate the constraint to some degree. The stiffer we make it, the more precisely it will enforce the constraint but the more difficult the problem will be to solve numerically. We want to choose stiffness k and damping d for the bushing to balance those considerations. First, consider your tolerance for constraint errors -- if the joint allows deviations of 1mm (say) would that be OK for your application? Similarly, would angular errors of 1 degree (say) be tolerable? We will give a procedure below for estimating a reasonable value of k to achieve a specified translational and rotational tolerance. Also, we need to choose d to damp out oscillations caused by the stiff spring in a "reasonable" time. Consider a time scale you would consider negligible. Perhaps a settling time of 1ms (say) would be ignorable for your robot arm, which presumably has much larger time constants for important behaviors. We will give a procedure here for obtaining a reasonable d from k and your settling time tolerance. For a more detailed discussion on choosing bushing parameters for a variety of its uses, see [drake::multibody::LinearBushingRollPitchYaw](https://drake.mit.edu/doxygen_cxx/classdrake_1_1multibody_1_1_linear_bushing_roll_pitch_yaw.html). ### Estimate force stiffness [kx ky kz] from loading/displacement The bushing's force stiffness constants [kx ky kz] can be approximated via various methods (or a combination thereof). For example, one could specify a maximum bushing displacement in a direction (e.g., xₘₐₓ), estimate a maximum directional load (Fx) that combines gravity forces, applied forces, inertia forces (centripetal, Coriolus, gyroscopic), and then calculate kx ≈ Fx / xₘₐₓ. ### Estimate force stiffness [kx ky kz] constants from mass and ωₙ The bushing's force stiffness constants [kx ky kz] can be approximated via a related linear constant-coefficient 2ⁿᵈ-order ODE: | | | | ----- | ---- | | m ẍ + dₓ ẋ + kₓ x = 0 | or alternatively as | | ẍ + 2 ζ ωₙ ẋ + ωₙ² x = 0 | where ωₙ = √(kₓ/m), ζ = dx / (2 √(m kₓ)) | Values for kₓ can be determined by choosing a characteristic mass m (which may be directionally dependent) and then choosing ωₙ > 0 (speed of response). Rearranging ωₙ = √(kₓ/m) produces kₓ = m ωₙ². One way to choose ωₙ is to choose a settling time tₛ which approximates the desired time for stretch x to settle to within 1% (0.01) of an equilibrium solution, and choose a damping ratio ζ (e.g., ζ = 1, critical damping), then calculate ωₙ = -ln(0.01) / (ζ tₛ) ≈ 4.6 / (ζ tₛ). For the included example code, a characteristic mass m = 20 kg was chosen with tₛ = 0.12 and ζ = 1 (critical damping). Thus ωₙ = -ln(0.01) / 0.12 ≈ 38.38 and kₓ = (20)*(38.38)² ≈ 30000. ### Estimate force damping [dx dy dz] from mass and stiffness Once m and kₓ have been chosen, damping dₓ can be estimated by picking a damping ratio ζ (e.g., ζ ≈ 1, critical damping), then dₓ ≈ 2 ζ √(m kx). For our example dₓ ≈ 2·√(20·30000) ≈ 1500. ### Estimating torque stiffness [k₀ k₁ k₂] and damping [d₀ d₁ d₂] The bushing in this planar example replaces a revolute joint. The links are constrained to planar motion by the existing joints, hence no torque stiffness nor torque damping is needed. An alternative way to deal with this four-bar's closed kinematic loop is to "cut" one of the four-bar's rigid links in half and join those halves with a bushing that has both force and torque stiffness/damping. If this technique is used, torque stiffness is needed. One way to approximate torque stiffness is with concepts similar to the force stiffness above. For example, the bushing's torque stiffness k₀ could be calculated by specifying a maximum bushing angular displacement θₘₐₓ, estimating a maximum moment load Mx and calculating k₀ = Mx / θₘₐₓ. Alternatively, a value for k₀ can be determined by choosing a characteristic moment of inertia I₀ (which is directionally dependent) and then choosing ωₙ (e.g., from setting time), then using k₀ ≈ I₀ ωₙ². With k₀ available and a damping ratio ζ chosen, d₀ ≈ 2 ζ √(I₀ k₀).
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/four_bar/four_bar.sdf
<?xml version="1.0"?> <sdf version="1.7"> <model name="four_bar"> <!-- This sdf file produces a model of a planar four bar linkage. See the README for more details on the modelling done in this file. We replace one of the 4 revolute joints with a model revolute joint implemented with a LinearBushingRollPitchYaw ForceElement in the code. This SDF provides the frames at which to place the above mentioned bushing. Links A, B, C, and (the implicit) World link complete the closed kinematic chain. Links A, B, C have length 4 m and mass 20 kg and in 3D are modeled by boxes with dimensions (4.2 m, 0.1 m, 0.2 m). For each link we define a frame: A, B, C, and W. Wz ^ | Wx <- - - · Frame W is the implicit world link with Wo its origin, Wz pointing up, Wx pointing left, and Wy pointing out of the page. Gravity points in the -Wz direction. In the zero configuration, frame A is coincident with frame W. In other words X_WA is the identity. The Ax axis points along the link. Frame B is defined relative to A. The origin of the B frame measured in A, p_AB, is (-4, 0, 0) In the zero configuration, frame B's orientation measured in A, R_AB, is the identity. The Bx axis points along the link. Frame C is defined relative to W. The origin of the C frame measured in the world, p_WC, is (-2, 0, 0). In the zero configuration, frame C's orientation measured in the world, R_WC, is the identity. The Cx axis points along the link. In pseudo code, the frames in the zero configuration can be written: X_WA = RigidTransformd::Identity(); X_AB = RigidTransformd(Vector3d(4, 0, 0)); X_WC = RigidTransformd(Vector3d(-2, 0, 0)); For each link, we also define a revolute joint, located at the origin of that link's frame, oriented along the world's y-axis. joint_WA is the y-axis revolute joint between the parent world and the child A. joint_WA's joint angle is denoted q_WA. joint_AB is the y-axis revolute joint between the parent A and the child B. joint_AB's joint angle is denoted q_AB. joint_WC is the y-axis revolute joint between the parent world and the child B. joint_WC's joint angle is denoted q_WC. There is no joint connecting link B to link C. We will model a revolute joint between them with a LinearBushingRollPitchYaw ForceElement in the code. For this we define two frames: Bc_bushing is a frame attached to link B. Cb_bushing is a frame attached to link C. See their definition below for the details of how they are defined. In the default configuration (i.e. q_WA = q_AB = q_WC = 0) all of the links lie flat along the Wx axis. Note this is not a valid configuration that satisfies loop closure. However, they are defined in such a way to make this SDF readable and so at least q_WA and q_WC are measured relative to a fixed axis of the world frame. Please see the README for a detailed diagram with configuration angles that satisfy the loop closure equation. --> <link name="A"> <!-- The frame A measured in the world frame, X_WA is the identity. This link is also called 'Crank' in the diagram in README.md --> <inertial> <!-- Acm (A's center of mass) is located at the midpoint of the 4 meter long link. --> <pose>2 0 0 0 0 0</pose> <mass>20</mass> <inertia> <!-- Inertia tensor for a solid cuboid of dimensions (l, w, h) = (4.2 m, 0.1 m, 0.2 m) and mass 20 kg--> <ixx>0.08333333333333334</ixx> <iyy>29.46666666666666</iyy> <izz>29.416666666666668</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> <!-- A skinny red box along the Ax axis --> <visual name="A_visual"> <pose>2 0 0 0 0 0</pose> <geometry> <box> <size>4.2 0.1 0.2</size> </box> </geometry> <material> <diffuse>1 0 0 1</diffuse> </material> </visual> <!-- A visual representing the revolute joint between the world and link A. --> <visual name="A_pivot_visual"> <!-- Rotation around Ax by 90° = π/2 radians ≈ 1.57079632679 --> <pose>0 0 0 1.57079632679 0 0</pose> <geometry> <cylinder> <radius>0.01</radius> <length>0.15</length> </cylinder> </geometry> <material> <diffuse>0 1 0 1</diffuse> </material> </visual> </link> <link name="B"> <!-- The frame B measured in A, X_AB, is a translation along the Ax axis, and a small translation along the Ay (revolute) axis for visual purposes. This link is also called 'Coupler' in the diagram in README.md --> <pose relative_to="A">4 0.1 0 0 0 0</pose> <inertial> <!-- Bcm (B's center of mass) is located at the midpoint of the 4 meter long link. --> <pose>2 0 0 0 0 0</pose> <mass>20</mass> <inertia> <!-- Inertia tensor for a solid cuboid of dimensions (l, w, h) = (4.2 m, 0.1 m, 0.2 m) and mass 20 kg--> <ixx>0.08333333333333334</ixx> <iyy>29.46666666666666</iyy> <izz>29.416666666666668</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> <!-- A skinny blue box along the Bx axis --> <visual name="B_visual"> <pose>2 0 0 0 0 0</pose> <geometry> <box> <size>4.2 0.1 0.2</size> </box> </geometry> <material> <diffuse>0 0 1 1</diffuse> </material> </visual> <!-- A visual representing the revolute joint between link A and link B. --> <visual name="B_pivot_visual"> <!-- Rotation around Bx by 90° = π/2 radians ≈ 1.57079632679 --> <pose>0 -0.05 0 1.57079632679 0 0</pose> <geometry> <cylinder> <radius>0.01</radius> <length>0.25</length> </cylinder> </geometry> <material> <diffuse>0 1 0 1</diffuse> </material> </visual> <!-- A visual representing the 'Coupler-Point' P --> <visual name="CouplerPoint"> <!-- Translation down Bx by 2 and down Bz by -2 --> <pose relative_to="B">2 0 -2 0 0 0</pose> <geometry> <sphere> <radius>0.1</radius> </sphere> </geometry> <material> <diffuse>0 0 1 1</diffuse> </material> </visual> </link> <link name="C"> <!-- The frame C measured in W, X_WC, is a translation along the Wx axis, and a small translation along the Wy (revolute) axis for visual purposes. This link is also called 'Rocker' in the diagram in README.md --> <pose>-2 0.2 0 0 0 0</pose> <inertial> <!-- Ccm (C's center of mass) is located at the midpoint of the 4 meter long link. --> <pose>2 0 0 0 0 0</pose> <mass>20</mass> <inertia> <!-- Inertia tensor for a solid cuboid of dimensions (l, w, h) = (4.2 m, 0.1 m, 0.2 m) and mass 20 kg--> <ixx>0.08333333333333334</ixx> <iyy>29.46666666666666</iyy> <izz>29.416666666666668</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> <!-- A skinny yellow box along the Bx axis --> <visual name="C_visual"> <pose>2 0 0 0 0 0</pose> <geometry> <box> <size>4.2 0.1 0.2</size> </box> </geometry> <material> <diffuse>1 1 0 1</diffuse> </material> </visual> <!-- A visual representing the revolute joint between the world and link C. --> <visual name="C_pivot_visual"> <!-- Rotation around Cx by 90° = π/2 radians ≈ 1.57079632679 --> <pose>0 0 0 1.57079632679 0 0</pose> <geometry> <cylinder> <radius>0.01</radius> <length>0.15</length> </cylinder> </geometry> <material> <diffuse>0 1 0 1</diffuse> </material> </visual> </link> <joint name="joint_WA" type="revolute"> <child>A</child> <parent>world</parent> <axis> <xyz expressed_in="__model__">0 1 0</xyz> <limit> <!-- No limit provided. sdformat defaults to -1, which we parse as an actuated joint. --> </limit> <dynamics> <damping>0.0</damping> </dynamics> </axis> </joint> <joint name="joint_AB" type="revolute"> <child>B</child> <parent>A</parent> <axis> <xyz expressed_in="__model__">0 1 0</xyz> <limit> <!-- An effort of 0 is parsed as an unactuated joint. --> <effort>0</effort> </limit> <dynamics> <damping>0.0</damping> </dynamics> </axis> </joint> <joint name="joint_WC" type="revolute"> <child>C</child> <parent>world</parent> <axis> <xyz expressed_in="__model__">0 1 0</xyz> <limit> <!-- An effort of 0 is parsed as an unactuated joint. --> <effort>0</effort> </limit> <dynamics> <damping>0.0</damping> </dynamics> </axis> </joint> <!-- A frame at the end of the B link, down the Bx axis. The frame is rotated so that the z of Bc_bushing is aligned with the By axis. This is done so the LinearBushingRollPitchYaw ForceElement freely rotates around its z axis (Yaw) to avoid gimbal lock on the y axis (Pitch). --> <frame name="Bc_bushing" attached_to="B"> <!-- This frame is rotated relative from link B, around Bx, by -90° = -π/2 radians ≈ -1.57079632679 --> <pose relative_to="B">4 0 0 -1.57079632679 0 0</pose> </frame> <!-- A frame at the end of the C link, down the Cx axis. The frame is rotated so that the z of Cb_bushing is aligned with the Cy axis. This is done so the LinearBushingRollPitchYaw ForceElement freely rotates around its z axis (Yaw) to avoid gimbal lock on the y axis (Pitch). --> <frame name="Cb_bushing" attached_to="C"> <!-- This frame is rotated relative from link C, around Cx, by -90° = -π/2 radians ≈ -1.57079632679 --> <pose relative_to="C">4 0 0 -1.57079632679 0 0</pose> </frame> </model> </sdf>
0
/home/johnshepherd/drake/examples/multibody/four_bar
/home/johnshepherd/drake/examples/multibody/four_bar/dev/four_bar_weld.sdf
<?xml version="1.0"?> <sdf version="1.7"> <model name="four_bar_weld"> <!-- TODO(sherm1) This is aspirational as of 3/2023. As compared to the 4-bar linkage in four_bar_loop.sdf (see it for info), this sdf is different. It explicitly defines a model consisting of a spanning tree (rooted at world) plus a loop-closing constraint. To break the loop, it splits the coupler link C into two pieces, each with the same dimensions but half the density. The coupler is the "main" link and the other piece is called the "shadow" link S. A weld constraint is then added to reconnect the pieces and recover the original mass properties. We also have to ensure that the parent->child ordering forms a valid spanning tree. As compared to four_bar_loop.sdf, the Dc-Co (driver-coupler) revolute joint is still present, but the Cr-Rc (coupler-rocker) revolute joint is gone. Instead we use an Rs-Sr (rocker-shadow) revolute joint whose ordering rocker-shadow (not shadow-rocker) is reversed to define a tree branch world-rocker-shadow. (When automated we will preserve the user's parent->child ordering but model using a reverse mobilizer.) The other tree branch is world-driver-coupler. * Rs shadow S 4.8m 0.5kg Scm | So *------------------------x--------------------|--------* Sr | Co *------------------------x------------------------------ coupler C 4.8m 0.5kg Ccm | Dc * | | rocker R | 2m | | 2kg 1m | driver D | 1kg | | Wy | | | * Do Ro * | +----- Wx *====================== Wo ===================* / Wd 2m world W 2m Wr Wz The weld constraint connects the centers of mass of the split coupler and shadow links, at the points marked with an "x" above. --> <!-- Define links & their attached frames. --> <frame name="Wd" attached_to="world"> <pose relative_to="world">-2 0 0 0 0 0</pose> </frame> <frame name="Wr" attached_to="world"> <pose relative_to="world">2 0 0 0 0 0</pose> </frame> <link name="driver"> <inertial> <pose>0 0.5 0 0 0 0</pose> <mass>1</mass> <inertia> <ixx>0.0833333333333333</ixx> <iyy>0</iyy> <izz>0.0833333333333333</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> </link> <frame name="Dc" attached_to="driver"> <pose relative_to="driver">0 1 0 0 0 0</pose> </frame> <link name="rocker"> <inertial> <pose>0 1 0 0 0 0</pose> <mass>2</mass> <inertia> <ixx>0.6666666666666667</ixx> <iyy>0</iyy> <izz>0.6666666666666667</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> </link> <frame name="Rs" attached_to="rocker"> <pose relative_to="rocker">0 2 0 0 0 0</pose> </frame> <!-- Since we split the coupler into two half-density links, the mass and inertia are 50% of the original coupler. Welding the pieces together recovers the full mass properties. --> <link name="coupler"> <inertial> <pose>2.4 0 0 0 0 0</pose> <mass>0.5</mass> <inertia> <ixx>0</ixx> <iyy>0.96</iyy> <izz>0.96</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> </link> <frame name="Ccm" attached_to="coupler"> <pose relative_to="coupler">2.4 0 0 0 0 0</pose> </frame> <link name="shadow"> <inertial> <pose>2.4 0 0 0 0 0</pose> <mass>0.5</mass> <inertia> <ixx>0</ixx> <iyy>0.96</iyy> <izz>0.96</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> </link> <frame name="Scm" attached_to="shadow"> <pose relative_to="shadow">2.4 0 0 0 0 0</pose> </frame> <frame name="Sr" attached_to="shadow"> <pose relative_to="shadow">4.8 0 0 0 0 0</pose> </frame> <!-- Define the four joints --> <joint name="world_driver" type="revolute"> <parent>Wd</parent> <child>driver</child> <axis> <xyz expressed_in="__model__">0 0 1</xyz> </axis> </joint> <joint name="world_rocker" type="revolute"> <parent>Wr</parent> <child>rocker</child> <axis> <xyz expressed_in="__model__">0 0 1</xyz> </axis> </joint> <joint name="driver_coupler" type="revolute"> <parent>Dc</parent> <child>coupler</child> <axis> <xyz expressed_in="__model__">0 0 1</xyz> </axis> </joint> <!-- As compared to the coupler-rocker revolute joint in four_bar_loop.sdf, we form a world-rocker-shadow tree branch that requires an Rs-Sr (rocker-shadow) revolute joint. --> <joint name="rocker_shadow" type="revolute"> <parent>Rs</parent> <child>Sr</child> <axis> <xyz expressed_in="__model__">0 0 1</xyz> </axis> </joint> <!-- Add a weld constraint to join the half-density coupler and shadow links. Note that a weld constraint looks exactly like a weld joint. The parent/child ordering is arbitrary here. --> <drake:weld_constraint> <parent>Ccm</parent> <child>Scm</child> </drake:weld_constraint> </model> </sdf>
0
/home/johnshepherd/drake/examples/multibody/four_bar
/home/johnshepherd/drake/examples/multibody/four_bar/dev/four_bar_loop.sdf
<?xml version="1.0"?> <sdf version="1.7"> <model name="four_bar_loop"> <!-- TODO(sherm1) This is aspirational as of 3/2023. A straightforward description of a planar 4-bar linkage, with no attempt to specify a spanning tree. This is ideally what we would like Drake to be able to work with, with no fuss. There are three links (driver, coupler, rocker) plus world and four revolute joints. The mechanism moves in the x-y plane; revolute axes all point in the +z direction (towards you). In the figure below, the links are shown as we are going to define them below, unassembled and conveniently lined up with the World frame axes. "*" marks the connection points and the frames are named. In sdf the frame at the link origin is indicated by the link name (say "driver") rather than the monogram-named origin frame ("Do"). The additional frame's names start with a capital letter matching the link to which they are fixed and a lower case letter for the connected link. All frame axes are aligned with World in the description here. * Rc | | coupler C | Co *------------------------------------------------------* Cr 4.8m 1kg | * Dc | | rocker R | 2m | | 2kg 1m | driver D | 1kg | | Wy | | | * Do Ro * | +----- Wx *====================== Wo ===================* / Wd 2m world W 2m Wr Wz In parent-child order, the joints will connect Wd-Do Wr-Ro Dc-Co Cr-Rc. Link mass centers are at their midpoints. Lengths and masses are shown; inertias are of thin rods (ML²/12). --> <!-- Define links & their attached frames. --> <frame name="Wd" attached_to="world"> <pose relative_to="world">-2 0 0 0 0 0</pose> </frame> <frame name="Wr" attached_to="world"> <pose relative_to="world">2 0 0 0 0 0</pose> </frame> <link name="driver"> <inertial> <pose>0 0.5 0 0 0 0</pose> <mass>1</mass> <inertia> <ixx>0.0833333333333333</ixx> <iyy>0</iyy> <izz>0.0833333333333333</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> </link> <frame name="Dc" attached_to="driver"> <pose relative_to="driver">0 1 0 0 0 0</pose> </frame> <link name="rocker"> <inertial> <pose>0 1 0 0 0 0</pose> <mass>2</mass> <inertia> <ixx>0.6666666666666667</ixx> <iyy>0</iyy> <izz>0.6666666666666667</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> </link> <frame name="Rc" attached_to="rocker"> <pose relative_to="rocker">0 2 0 0 0 0</pose> </frame> <link name="coupler"> <inertial> <pose>2.4 0 0 0 0 0</pose> <mass>1</mass> <inertia> <ixx>0</ixx> <iyy>1.92</iyy> <izz>1.92</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> </link> <frame name="Cr" attached_to="coupler"> <pose relative_to="coupler">4.8 0 0 0 0 0</pose> </frame> <!-- Define the four joints --> <joint name="world_driver" type="revolute"> <parent>Wd</parent> <child>driver</child> <axis> <xyz expressed_in="__model__">0 0 1</xyz> </axis> </joint> <joint name="world_rocker" type="revolute"> <parent>Wr</parent> <child>rocker</child> <axis> <xyz expressed_in="__model__">0 0 1</xyz> </axis> </joint> <joint name="driver_coupler" type="revolute"> <parent>Dc</parent> <child>coupler</child> <axis> <xyz expressed_in="__model__">0 0 1</xyz> </axis> </joint> <joint name="coupler_rocker" type="revolute"> <parent>Cr</parent> <child>Rc</child> <axis> <xyz expressed_in="__model__">0 0 1</xyz> </axis> </joint> </model> </sdf>
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/acrobot/passive_simulation.cc
#include <memory> #include <gflags/gflags.h> #include "drake/common/drake_assert.h" #include "drake/geometry/drake_visualizer.h" #include "drake/geometry/scene_graph.h" #include "drake/lcm/drake_lcm.h" #include "drake/multibody/benchmarks/acrobot/make_acrobot_plant.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/systems/analysis/implicit_euler_integrator.h" #include "drake/systems/analysis/runge_kutta3_integrator.h" #include "drake/systems/analysis/semi_explicit_euler_integrator.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/constant_vector_source.h" namespace drake { using geometry::SceneGraph; using geometry::SourceId; using lcm::DrakeLcm; using multibody::benchmarks::acrobot::AcrobotParameters; using multibody::benchmarks::acrobot::MakeAcrobotPlant; using multibody::MultibodyPlant; using multibody::RevoluteJoint; using systems::ImplicitEulerIntegrator; using systems::RungeKutta3Integrator; using systems::SemiExplicitEulerIntegrator; namespace examples { namespace multibody { namespace acrobot { namespace { DEFINE_double(target_realtime_rate, 1.0, "Desired rate relative to real time. See documentation for " "Simulator::set_target_realtime_rate() for details."); DEFINE_string(integration_scheme, "runge_kutta3", "Integration scheme to be used. Available options are:" "'runge_kutta3','implicit_euler','semi_explicit_euler'"); DEFINE_double(simulation_time, 10.0, "Desired duration of the simulation in seconds."); int do_main() { systems::DiagramBuilder<double> builder; SceneGraph<double>& scene_graph = *builder.AddSystem<SceneGraph>(); scene_graph.set_name("scene_graph"); const double simulation_time = FLAGS_simulation_time; // Make the desired maximum time step a fraction of the simulation time. const double max_time_step = simulation_time / 1000.0; // The target accuracy determines the size of the actual time steps taken // whenever a variable time step integrator is used. const double target_accuracy = 0.001; // Make and add the acrobot model. const AcrobotParameters acrobot_parameters; const MultibodyPlant<double>& acrobot = *builder.AddSystem(MakeAcrobotPlant( acrobot_parameters, true /* Finalize the plant */, &scene_graph)); const RevoluteJoint<double>& shoulder = acrobot.GetJointByName<RevoluteJoint>( acrobot_parameters.shoulder_joint_name()); const RevoluteJoint<double>& elbow = acrobot.GetJointByName<RevoluteJoint>( acrobot_parameters.elbow_joint_name()); // A constant source for a zero applied torque at the elbow joint. double applied_torque(0.0); auto torque_source = builder.AddSystem<systems::ConstantVectorSource>(applied_torque); torque_source->set_name("Applied Torque"); builder.Connect(torque_source->get_output_port(), acrobot.get_actuation_input_port()); // Sanity check on the availability of the optional source id before using it. DRAKE_DEMAND(acrobot.get_source_id().has_value()); builder.Connect( acrobot.get_geometry_poses_output_port(), scene_graph.get_source_pose_port(acrobot.get_source_id().value())); geometry::DrakeVisualizerd::AddToBuilder(&builder, scene_graph); auto diagram = builder.Build(); // Create a context for this system: std::unique_ptr<systems::Context<double>> diagram_context = diagram->CreateDefaultContext(); diagram->SetDefaultContext(diagram_context.get()); systems::Context<double>& acrobot_context = diagram->GetMutableSubsystemContext(acrobot, diagram_context.get()); // Set initial angles. Velocities are left to the default zero values. shoulder.set_angle(&acrobot_context, 1.0); elbow.set_angle(&acrobot_context, 1.0); systems::Simulator<double> simulator(*diagram, std::move(diagram_context)); systems::IntegratorBase<double>* integrator{nullptr}; if (FLAGS_integration_scheme == "implicit_euler") { integrator = &simulator.reset_integrator<ImplicitEulerIntegrator<double>>(); } else if (FLAGS_integration_scheme == "runge_kutta3") { integrator = &simulator.reset_integrator<RungeKutta3Integrator<double>>(); } else if (FLAGS_integration_scheme == "semi_explicit_euler") { integrator = &simulator.reset_integrator<SemiExplicitEulerIntegrator<double>>( max_time_step); } else { throw std::runtime_error( "Integration scheme '" + FLAGS_integration_scheme + "' not supported for this example."); } integrator->set_maximum_step_size(max_time_step); // Error control is only supported for variable time step integrators. if (!integrator->get_fixed_step_mode()) integrator->set_target_accuracy(target_accuracy); simulator.set_publish_every_time_step(false); simulator.set_target_realtime_rate(FLAGS_target_realtime_rate); simulator.Initialize(); simulator.AdvanceTo(simulation_time); // Some sanity checks: if (FLAGS_integration_scheme == "semi_explicit_euler") { DRAKE_DEMAND(integrator->get_fixed_step_mode() == true); } // Checks for variable time step integrators. if (!integrator->get_fixed_step_mode()) { // From IntegratorBase::set_maximum_step_size(): // "The integrator may stretch the maximum step size by as much as 1% to // reach discrete event." Thus the 1.01 factor in this DRAKE_DEMAND. DRAKE_DEMAND( integrator->get_largest_step_size_taken() <= 1.01 * max_time_step); DRAKE_DEMAND(integrator->get_smallest_adapted_step_size_taken() <= integrator->get_largest_step_size_taken()); DRAKE_DEMAND( integrator->get_num_steps_taken() >= simulation_time / max_time_step); } // Checks for fixed time step integrators. if (integrator->get_fixed_step_mode()) { DRAKE_DEMAND(integrator->get_num_derivative_evaluations() == integrator->get_num_steps_taken()); DRAKE_DEMAND( integrator->get_num_step_shrinkages_from_error_control() == 0); } // We made a good guess for max_time_step and therefore we expect no // failures when taking a time step. DRAKE_DEMAND(integrator->get_num_substep_failures() == 0); DRAKE_DEMAND( integrator->get_num_step_shrinkages_from_substep_failures() == 0); return 0; } } // namespace } // namespace acrobot } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A simple acrobot demo using Drake's MultibodyPlant," "with SceneGraph visualization. " "Launch meldis before running this example."); gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::acrobot::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/acrobot/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", ) package(default_visibility = ["//visibility:private"]) drake_cc_binary( name = "passive_simulation", srcs = ["passive_simulation.cc"], add_test_rule = 1, test_rule_args = [ "--simulation_time=0.1", "--target_realtime_rate=0.0", ], deps = [ "//common:add_text_logging_gflags", "//geometry:drake_visualizer", "//lcm", "//multibody/benchmarks/acrobot:make_acrobot_plant", "//systems/analysis:implicit_euler_integrator", "//systems/analysis:runge_kutta3_integrator", "//systems/analysis:semi_explicit_euler_integrator", "//systems/analysis:simulator", "//systems/framework:diagram", "//systems/primitives:constant_vector_source", "@gflags", ], ) drake_cc_binary( name = "run_lqr", srcs = ["run_lqr.cc"], add_test_rule = 1, data = ["//multibody/benchmarks/acrobot:models"], test_rule_args = [ "--simulation_time=0.1", "--target_realtime_rate=0.0", ], deps = [ "//common:add_text_logging_gflags", "//lcm", "//multibody/benchmarks/acrobot:make_acrobot_plant", "//multibody/parsing", "//systems/analysis:simulator", "//systems/controllers:linear_quadratic_regulator", "//systems/framework:diagram", "//systems/primitives:affine_system", "//visualization:visualization_config_functions", "@gflags", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/acrobot/run_lqr.cc
#include <memory> #include <gflags/gflags.h> #include "drake/common/drake_assert.h" #include "drake/geometry/scene_graph.h" #include "drake/multibody/benchmarks/acrobot/make_acrobot_plant.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/controllers/linear_quadratic_regulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/affine_system.h" #include "drake/visualization/visualization_config_functions.h" namespace drake { using geometry::SceneGraph; using multibody::benchmarks::acrobot::AcrobotParameters; using multibody::benchmarks::acrobot::MakeAcrobotPlant; using multibody::AddMultibodyPlantSceneGraph; using multibody::MultibodyPlant; using multibody::Parser; using multibody::JointActuator; using multibody::RevoluteJoint; using systems::Context; using systems::InputPort; using Eigen::Vector2d; namespace examples { namespace multibody { namespace acrobot { namespace { DEFINE_double(target_realtime_rate, 1.0, "Desired rate relative to real time. See documentation for " "Simulator::set_target_realtime_rate() for details."); DEFINE_double(simulation_time, 3.0, "Desired duration of the simulation in seconds."); DEFINE_bool(time_stepping, true, "If 'true', the plant is modeled as a " "discrete system with periodic updates. " "If 'false', the plant is modeled as a continuous system."); // This helper method makes an LQR controller to balance an acrobot model // specified in the SDF file `file_name`. std::unique_ptr<systems::AffineSystem<double>> MakeBalancingLQRController( const std::string& acrobot_url) { // LinearQuadraticRegulator() below requires the controller's model of the // plant to only have a single input port corresponding to the actuation. // Therefore we create a new model that meets this requirement. (a model // created along with a SceneGraph for simulation would also have input ports // to interact with that SceneGraph). MultibodyPlant<double> acrobot(0.0); Parser parser(&acrobot); parser.AddModelsFromUrl(acrobot_url); // We are done defining the model. acrobot.Finalize(); const RevoluteJoint<double>& shoulder = acrobot.GetJointByName<RevoluteJoint>("ShoulderJoint"); const RevoluteJoint<double>& elbow = acrobot.GetJointByName<RevoluteJoint>("ElbowJoint"); std::unique_ptr<Context<double>> context = acrobot.CreateDefaultContext(); // Set nominal actuation torque to zero. const InputPort<double>& actuation_port = acrobot.get_actuation_input_port(); actuation_port.FixValue(context.get(), 0.0); acrobot.get_applied_generalized_force_input_port().FixValue( context.get(), Vector2d::Constant(0.0)); shoulder.set_angle(context.get(), M_PI); shoulder.set_angular_rate(context.get(), 0.0); elbow.set_angle(context.get(), 0.0); elbow.set_angular_rate(context.get(), 0.0); // Setup LQR Cost matrices (penalize position error 10x more than velocity // to roughly address difference in units, using sqrt(g/l) as the time // constant. Eigen::Matrix4d Q = Eigen::Matrix4d::Identity(); Q(0, 0) = 10; Q(1, 1) = 10; Vector1d R = Vector1d::Constant(1); return systems::controllers::LinearQuadraticRegulator( acrobot, *context, Q, R, Eigen::Matrix<double, 0, 0>::Zero() /* No cross state/control costs */, actuation_port.get_index()); } int do_main() { systems::DiagramBuilder<double> builder; const double time_step = FLAGS_time_stepping ? 1.0e-3 : 0.0; auto [acrobot, scene_graph] = AddMultibodyPlantSceneGraph(&builder, time_step); // Make and add the acrobot model. const std::string acrobot_url = "package://drake/multibody/benchmarks/acrobot/acrobot.sdf"; Parser parser(&acrobot); parser.AddModelsFromUrl(acrobot_url); // We are done defining the model. acrobot.Finalize(); DRAKE_DEMAND(acrobot.num_actuators() == 1); DRAKE_DEMAND(acrobot.num_actuated_dofs() == 1); RevoluteJoint<double>& shoulder = acrobot.GetMutableJointByName<RevoluteJoint>("ShoulderJoint"); RevoluteJoint<double>& elbow = acrobot.GetMutableJointByName<RevoluteJoint>("ElbowJoint"); // Drake's parser will default the name of the actuator to match the name of // the joint it actuates. const JointActuator<double>& actuator = acrobot.GetJointActuatorByName("ElbowJoint"); DRAKE_DEMAND(actuator.joint().name() == "ElbowJoint"); // For this example the controller's model of the plant exactly matches the // plant to be controlled (in reality there would always be a mismatch). auto controller = builder.AddSystem( MakeBalancingLQRController(acrobot_url)); controller->set_name("controller"); builder.Connect(acrobot.get_state_output_port(), controller->get_input_port()); builder.Connect(controller->get_output_port(), acrobot.get_actuation_input_port()); visualization::AddDefaultVisualization(&builder); auto diagram = builder.Build(); systems::Simulator<double> simulator(*diagram); simulator.set_target_realtime_rate(FLAGS_target_realtime_rate); RandomGenerator generator; // Setup distribution for random initial conditions. std::normal_distribution<symbolic::Expression> gaussian; shoulder.set_random_angle_distribution(M_PI + 0.02*gaussian(generator)); elbow.set_random_angle_distribution(0.05*gaussian(generator)); for (int i = 0; i < 5; i++) { simulator.get_mutable_context().SetTime(0.0); simulator.get_system().SetRandomContext(&simulator.get_mutable_context(), &generator); simulator.Initialize(); simulator.AdvanceTo(FLAGS_simulation_time); } return 0; } } // namespace } // namespace acrobot } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A simple acrobot demo using Drake's MultibodyPlant with " "LQR stabilization. " "Launch meldis before running this example."); gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::acrobot::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/point_source_force_field.h
#pragma once #include <memory> #include "drake/multibody/plant/force_density_field.h" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace examples { namespace deformable { /* A custom external force density field that applies external force to deformable bodies. The force density points towards a point C affixed to a rigid body. The magnitude of the force density decays linearly with the distance to the point C and floors at 0. The maximum force density is read from a double-valued input port (see maximum_force_density_input_port()). If the port is unconnected, it reads as zero. */ class PointSourceForceField final : public multibody::ForceDensityField<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PointSourceForceField) /* Constructs a new PointSourceForceField object @param plant The MultibodyPlant that owns this force field. @param body The body to which the source of the force field C is affixed to. @param p_BC The fixed offset from the body origin to the point source of the force field. @param falloff_distance The force density decays linearly. `falloff_distance` in meters is the distance from the point source beyond which the force density is zero. Must be positive and finite. */ PointSourceForceField(const multibody::MultibodyPlant<double>& plant, const multibody::RigidBody<double>& body, const Vector3<double>& p_BC, double falloff_distance); /* Input port for desired maximum force density with units of N/m³. The port belongs to the MultibodyPlant that owns this density field. */ const systems::InputPort<double>& maximum_force_density_input_port() const { return parent_system_or_throw().get_input_port( maximum_force_density_port_index_); } private: /* Computes the world frame position of the center of the point source force field. */ Vector3<double> CalcPointSourceLocation( const systems::Context<double>& context) const { return plant_->EvalBodyPoseInWorld(context, plant_->get_body(body_)) * p_BC_; } /* Eval version of `CalcPointSourceLocation()`. */ const Vector3<double>& EvalPointSourceLocation( const systems::Context<double>& context) const { return parent_system_or_throw() .get_cache_entry(point_source_position_cache_index_) .template Eval<Vector3<double>>(context); } Vector3<double> DoEvaluateAt(const systems::Context<double>& context, const Vector3<double>& p_WQ) const final; std::unique_ptr<ForceDensityField<double>> DoClone() const final; void DoDeclareCacheEntries(multibody::MultibodyPlant<double>* plant) final; void DoDeclareInputPorts(multibody::MultibodyPlant<double>* plant) final; const multibody::MultibodyPlant<double>* plant_{}; const multibody::BodyIndex body_; Vector3<double> p_BC_; double falloff_distance_{}; systems::CacheIndex point_source_position_cache_index_; systems::InputPortIndex maximum_force_density_port_index_; }; } // namespace deformable } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/parallel_gripper_controller.h
#pragma once #include "drake/systems/framework/leaf_system.h" namespace drake { namespace examples { namespace deformable { /* We create a leaf system that outputs the desired state of a parallel jaw gripper to follow a close-lift-open motion sequence. The desired position is 2-dimensional with the first element corresponding to the wrist degree of freedom and the second element corresponding to the left finger degree of freedom. This control is a time-based state machine, where desired state changes based on the context time. There are four states, executed in the following order: 0. The fingers are open in the initial state. 1. The fingers are closed to secure a grasp. 2. The gripper is lifted to a prescribed final height. 3. The fingers are open to loosen the grasp. The desired state is interpolated between these states. */ class ParallelGripperController : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ParallelGripperController); /* Constructs a ParallelGripperController system with the given parameters. @param[in] open_width The width between fingers in the open state. (meters) @param[in] closed_width The width between fingers in the closed state. (meters) @param[in] height The height of the gripper in the lifted state. (meters) */ ParallelGripperController(double open_width, double closed_width, double height); private: /* Computes the output desired state of the parallel gripper. */ void CalcDesiredState(const systems::Context<double>& context, systems::BasicVector<double>* output) const; /* The time at which the fingers reach the desired closed state. */ const double fingers_closed_time_{1.5}; /* The time at which the gripper reaches the desired "lifted" state. */ const double gripper_lifted_time_{3.0}; const double hold_time_{5.5}; /* The time at which the fingers reach the desired open state. */ const double fingers_open_time_{7.0}; Eigen::Vector2d initial_configuration_; Eigen::Vector2d closed_configuration_; Eigen::Vector2d lifted_configuration_; Eigen::Vector2d open_configuration_; }; } // namespace deformable } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/suction_cup_controller.cc
#include "drake/examples/multibody/deformable/suction_cup_controller.h" namespace drake { namespace examples { namespace deformable { using Eigen::Vector2d; using systems::BasicVector; using systems::Context; SuctionCupController::SuctionCupController(double initial_height, double object_height, double approach_time, double start_suction_time, double retrieve_time, double release_suction_time) : initial_height_(initial_height), object_height_(object_height), approach_time_(approach_time), start_suction_time_(start_suction_time), retrieve_time_(retrieve_time), release_suction_time_(release_suction_time) { desired_state_port_index_ = DeclareVectorOutputPort("desired state", BasicVector<double>(2), &SuctionCupController::CalcDesiredState) .get_index(); maximum_force_density_port_index_ = DeclareVectorOutputPort("maximum suction force density [N/m³]", BasicVector<double>(1), &SuctionCupController::CalcMaxForceDensity) .get_index(); } void SuctionCupController::CalcDesiredState( const Context<double>& context, BasicVector<double>* desired_state) const { const double t = context.get_time(); /* Time to move from the initial height to the object height. */ const double travel_time = start_suction_time_ - approach_time_; Vector2d state_value; if (t < approach_time_) { state_value << initial_height_, 0; } else if (t < start_suction_time_) { const double v = (object_height_ - initial_height_) / travel_time; const double dt = t - approach_time_; state_value << initial_height_ + dt * v, v; } else if (t < retrieve_time_) { state_value << object_height_, 0; } else if (t < retrieve_time_ + travel_time) { const double v = (initial_height_ - object_height_) / travel_time; const double dt = t - retrieve_time_; state_value << object_height_ + dt * v, v; } else { state_value << initial_height_, 0; } desired_state->set_value(state_value); } void SuctionCupController::CalcMaxForceDensity( const Context<double>& context, BasicVector<double>* max_force_density) const { const double time = context.get_time(); if (time >= start_suction_time_ && time <= release_suction_time_) { // An arbitrary value that's reasonable for picking up the deformable torus // in the example with density comparable to water. (*max_force_density)[0] = 2.0e5; } else { (*max_force_density)[0] = 0.0; } } } // namespace deformable } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/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", ) package(default_visibility = ["//visibility:private"]) filegroup( name = "torus_tet_mesh", data = ["models/torus.vtk"], visibility = ["//geometry:__pkg__"], ) filegroup( name = "models", srcs = glob(["models/**"]) + [ "@drake_models//:wsg_50_description", ], visibility = ["//:__pkg__"], ) drake_cc_library( name = "parallel_gripper_controller", srcs = [ "parallel_gripper_controller.cc", ], hdrs = [ "parallel_gripper_controller.h", ], deps = [ "//multibody/plant", ], ) drake_cc_library( name = "point_source_force_field", srcs = [ "point_source_force_field.cc", ], hdrs = [ "point_source_force_field.h", ], deps = [ "//multibody/plant", ], ) drake_cc_library( name = "suction_cup_controller", srcs = [ "suction_cup_controller.cc", ], hdrs = [ "suction_cup_controller.h", ], deps = [ "//multibody/plant", ], ) drake_cc_binary( name = "deformable_torus", srcs = [ "deformable_torus.cc", ], add_test_rule = 1, data = [ ":models", ], test_rule_args = [ "-simulation_time=0.1", "-realtime_rate=0.0", ], deps = [ ":parallel_gripper_controller", ":point_source_force_field", ":suction_cup_controller", "//geometry:drake_visualizer", "//geometry:scene_graph", "//multibody/parsing", "//multibody/plant", "//systems/analysis:simulator", "//systems/framework:diagram", "@gflags", ], ) drake_cc_binary( name = "bubble_gripper", srcs = [ "bubble_gripper.cc", ], add_test_rule = 1, data = [ ":models", ], test_rule_args = [ "-simulation_time=0.1", "-realtime_rate=0.0", "-render_bubble=false", ], deps = [ ":parallel_gripper_controller", "//geometry", "//geometry/proximity", "//geometry/render_gl", "//multibody/parsing", "//multibody/plant", "//systems/analysis:simulator", "//systems/framework:diagram", "//systems/sensors:camera_config_functions", "@gflags", ], ) drake_cc_googletest( name = "point_source_force_field_test", deps = [ ":point_source_force_field", "//common/test_utilities:eigen_matrix_compare", ], ) add_lint_tests()
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/deformable_torus.cc
#include <memory> #include <gflags/gflags.h> #include "drake/common/find_resource.h" #include "drake/examples/multibody/deformable/parallel_gripper_controller.h" #include "drake/examples/multibody/deformable/point_source_force_field.h" #include "drake/examples/multibody/deformable/suction_cup_controller.h" #include "drake/geometry/drake_visualizer.h" #include "drake/geometry/proximity_properties.h" #include "drake/geometry/scene_graph.h" #include "drake/math/rigid_transform.h" #include "drake/multibody/fem/deformable_body_config.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/deformable_model.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/plant/multibody_plant_config_functions.h" #include "drake/multibody/tree/prismatic_joint.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" DEFINE_double(simulation_time, 12.0, "Desired duration of the simulation [s]."); DEFINE_double(realtime_rate, 1.0, "Desired real time rate."); DEFINE_double(time_step, 1e-2, "Discrete time step for the system [s]. Must be positive."); DEFINE_double(E, 3e4, "Young's modulus of the deformable body [Pa]."); DEFINE_double(nu, 0.4, "Poisson's ratio of the deformable body, unitless."); DEFINE_double(density, 1e3, "Mass density of the deformable body [kg/m³]. We observe that " "density above 2400 kg/m³ makes the torus too heavy to be picked " "up by the suction gripper."); DEFINE_double(beta, 0.01, "Stiffness damping coefficient for the deformable body [1/s]."); DEFINE_string(gripper, "parallel", "Type of gripper used to pick up the deformable torus. Options " "are: 'parallel' and 'suction'."); DEFINE_string(contact_approximation, "lagged", "Type of convex contact approximation. See " "multibody::DiscreteContactApproximation for details. Options " "are: 'sap', 'lagged', and 'similar'."); DEFINE_double( contact_damping, 10.0, "Hunt and Crossley damping for the deformable body, only used when " "'contact_approximation' is set to 'lagged' or 'similar' [s/m]."); using drake::examples::deformable::ParallelGripperController; using drake::examples::deformable::PointSourceForceField; using drake::examples::deformable::SuctionCupController; using drake::geometry::AddContactMaterial; using drake::geometry::Box; using drake::geometry::Capsule; using drake::geometry::Ellipsoid; using drake::geometry::GeometryInstance; using drake::geometry::IllustrationProperties; using drake::geometry::Mesh; using drake::geometry::ProximityProperties; using drake::geometry::Sphere; using drake::math::RigidTransformd; using drake::multibody::AddMultibodyPlant; using drake::multibody::CoulombFriction; using drake::multibody::DeformableBodyId; using drake::multibody::DeformableModel; using drake::multibody::ModelInstanceIndex; using drake::multibody::MultibodyPlant; using drake::multibody::MultibodyPlantConfig; using drake::multibody::Parser; using drake::multibody::PrismaticJoint; using drake::multibody::RigidBody; using drake::multibody::SpatialInertia; using drake::multibody::fem::DeformableBodyConfig; using drake::systems::BasicVector; using drake::systems::Context; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::Vector4d; using Eigen::VectorXd; namespace drake { namespace examples { namespace { /* Adds a suction gripper to the given MultibodyPlant and assign `proximity_props` to all the registered collision geometries. Returns the ModelInstanceIndex of the gripper model. */ ModelInstanceIndex AddSuctionGripper( MultibodyPlant<double>* plant, const ProximityProperties& proximity_props) { const double radius = 0.02; const double length = 0.1; const auto M = SpatialInertia<double>::SolidCapsuleWithMass( 0.1, radius, length, Vector3d::UnitZ()); ModelInstanceIndex model_instance = plant->AddModelInstance("instance"); const auto& body = plant->AddRigidBody("cup_body", model_instance, M); const Capsule capsule{radius, length}; IllustrationProperties cup_illustration_props; cup_illustration_props.AddProperty("phong", "diffuse", Vector4d(0.9, 0.1, 0.1, 0.8)); plant->RegisterVisualGeometry(body, RigidTransformd::Identity(), capsule, "cup_visual", cup_illustration_props); /* Add a visual hint for the center of the suction force source. */ const Sphere sphere{0.0075}; IllustrationProperties source_illustration_props; source_illustration_props.AddProperty("phong", "diffuse", Vector4d(0.1, 0.9, 0.1, 0.8)); plant->RegisterVisualGeometry(body, RigidTransformd(Vector3d(0, 0, -0.07)), sphere, "source_visual", source_illustration_props); plant->RegisterCollisionGeometry(body, RigidTransformd::Identity(), capsule, "cup_collision", proximity_props); /* Adds an actuated joint between the suction cup body and the world. */ const RigidTransformd X_WF(Vector3d(0.04, 0, -0.05)); const auto& prismatic_joint = plant->AddJoint<PrismaticJoint>( "translate_z_joint", plant->world_body(), X_WF, body, std::nullopt, Vector3d::UnitZ()); plant->GetMutableJointByName<PrismaticJoint>("translate_z_joint") .set_default_translation(0.5); const auto actuator_index = plant->AddJointActuator("prismatic joint actuator", prismatic_joint) .index(); plant->get_mutable_joint_actuator(actuator_index) .set_controller_gains({1e4, 1}); return model_instance; } /* Adds a parallel gripper to the given MultibodyPlant and assign `proximity_props` to all the registered collision geometries. Returns the ModelInstanceIndex of the gripper model. */ ModelInstanceIndex AddParallelGripper( MultibodyPlant<double>* plant, const ProximityProperties& proximity_props) { // TODO(xuchenhan-tri): Consider using a schunk gripper from the manipulation // station instead. Parser parser(plant); ModelInstanceIndex model_instance = parser.AddModelsFromUrl( "package://drake/examples/multibody/deformable/models/simple_gripper.sdf") [0]; /* Add collision geometries. */ const RigidTransformd X_BG = RigidTransformd(math::RollPitchYawd(M_PI_2, 0, 0), Vector3d::Zero()); const RigidBody<double>& left_finger = plant->GetBodyByName("left_finger"); const RigidBody<double>& right_finger = plant->GetBodyByName("right_finger"); /* The size of the fingers is set to match the visual geometries in simple_gripper.sdf. */ Capsule capsule(0.01, 0.08); plant->RegisterCollisionGeometry(left_finger, X_BG, capsule, "left_finger_collision", proximity_props); plant->RegisterCollisionGeometry(right_finger, X_BG, capsule, "right_finger_collision", proximity_props); /* Get joints so that we can set initial conditions. */ PrismaticJoint<double>& left_slider = plant->GetMutableJointByName<PrismaticJoint>("left_slider"); PrismaticJoint<double>& right_slider = plant->GetMutableJointByName<PrismaticJoint>("right_slider"); /* Initialize the gripper in an "open" position. */ const double kInitialWidth = 0.085; left_slider.set_default_translation(-kInitialWidth / 2.0); right_slider.set_default_translation(kInitialWidth / 2.0); return model_instance; } int do_main() { systems::DiagramBuilder<double> builder; MultibodyPlantConfig plant_config; plant_config.time_step = FLAGS_time_step; plant_config.discrete_contact_approximation = FLAGS_contact_approximation; auto [plant, scene_graph] = AddMultibodyPlant(plant_config, &builder); /* Minimum required proximity properties for rigid bodies to interact with deformable bodies. 1. A valid Coulomb friction coefficient, and 2. A resolution hint. (Rigid bodies need to be tessellated so that collision queries can be performed against deformable geometries.) The value dictates how fine the mesh used to represent the rigid collision geometry is. */ ProximityProperties rigid_proximity_props; /* Set the friction coefficient close to that of rubber against rubber. */ const CoulombFriction<double> surface_friction(1.15, 1.15); AddContactMaterial({}, {}, surface_friction, &rigid_proximity_props); rigid_proximity_props.AddProperty(geometry::internal::kHydroGroup, geometry::internal::kRezHint, 0.01); /* Set up a ground. */ Box ground{4, 4, 4}; const RigidTransformd X_WG(Eigen::Vector3d{0, 0, -2}); plant.RegisterCollisionGeometry(plant.world_body(), X_WG, ground, "ground_collision", rigid_proximity_props); IllustrationProperties illustration_props; illustration_props.AddProperty("phong", "diffuse", Vector4d(0.7, 0.5, 0.4, 0.8)); plant.RegisterVisualGeometry(plant.world_body(), X_WG, ground, "ground_visual", std::move(illustration_props)); /* Add a parallel gripper or a suction gripper depending on the runtime flag. */ const bool use_suction = FLAGS_gripper == "suction"; ModelInstanceIndex gripper_instance = use_suction ? AddSuctionGripper(&plant, rigid_proximity_props) : AddParallelGripper(&plant, rigid_proximity_props); /* Set up a deformable torus. */ auto owned_deformable_model = std::make_unique<DeformableModel<double>>(&plant); DeformableBodyConfig<double> deformable_config; deformable_config.set_youngs_modulus(FLAGS_E); deformable_config.set_poissons_ratio(FLAGS_nu); deformable_config.set_mass_density(FLAGS_density); deformable_config.set_stiffness_damping_coefficient(FLAGS_beta); const std::string torus_vtk = FindResourceOrThrow( "drake/examples/multibody/deformable/models/torus.vtk"); /* Load the geometry and scale it down to 65% (to showcase the scaling capability and to make the torus suitable for grasping by the gripper). */ const double scale = 0.65; auto torus_mesh = std::make_unique<Mesh>(torus_vtk, scale); /* Minor diameter of the torus inferred from the vtk file. */ const double kL = 0.09 * scale; /* Set the initial pose of the torus such that its bottom face is touching the ground. */ const RigidTransformd X_WB(Vector3<double>(0.0, 0.0, kL / 2.0)); auto torus_instance = std::make_unique<GeometryInstance>( X_WB, std::move(torus_mesh), "deformable_torus"); /* Minimally required proximity properties for deformable bodies: A valid Coulomb friction coefficient. */ ProximityProperties deformable_proximity_props; AddContactMaterial(FLAGS_contact_damping, {}, surface_friction, &deformable_proximity_props); torus_instance->set_proximity_properties(deformable_proximity_props); /* Registration of all deformable geometries ostensibly requires a resolution hint parameter that dictates how the shape is tessellated. In the case of a `Mesh` shape, the resolution hint is unused because the shape is already tessellated. */ // TODO(xuchenhan-tri): Though unused, we still asserts the resolution hint is // positive. Remove the requirement of a resolution hint for meshed shapes. const double unused_resolution_hint = 1.0; owned_deformable_model->RegisterDeformableBody( std::move(torus_instance), deformable_config, unused_resolution_hint); /* Add an external suction force if using a suction gripper. */ const PointSourceForceField* suction_force_ptr{nullptr}; if (use_suction) { auto suction_force = std::make_unique<PointSourceForceField>( plant, plant.GetBodyByName("cup_body"), Vector3d(0, 0, -0.07), 0.1); suction_force_ptr = suction_force.get(); owned_deformable_model->AddExternalForce(std::move(suction_force)); } plant.AddPhysicalModel(std::move(owned_deformable_model)); /* All rigid and deformable models have been added. Finalize the plant. */ plant.Finalize(); /* It's essential to connect the vertex position port in DeformableModel to the source configuration port in SceneGraph when deformable bodies are present in the plant. */ builder.Connect( plant.get_deformable_body_configuration_output_port(), scene_graph.get_source_configuration_port(plant.get_source_id().value())); /* Add a visualizer that emits LCM messages for visualization. */ geometry::DrakeVisualizerParams params; geometry::DrakeVisualizerd::AddToBuilder(&builder, scene_graph, nullptr, params); /* Add a controller appropriate for the type of gripper. */ if (use_suction) { const double kInitialHeight = 0.5; const double kStartSuctionHeight = 0.15; // The height at which to turn on suction. const double kApproachTime = 3.0; // Time to start the action const double kStartSuctionTime = 4.0; // Time to turn on suction const double kRetrieveTime = 6.0; // Time to retrieve the gripper const double kDropTime = 9.0; // Time to turn off suction const auto& suction = *builder.AddSystem<SuctionCupController>( kInitialHeight, kStartSuctionHeight, kApproachTime, kStartSuctionTime, kRetrieveTime, kDropTime); builder.Connect(suction.maximum_force_density_port(), suction_force_ptr->maximum_force_density_input_port()); builder.Connect(suction.desired_state_output_port(), plant.get_desired_state_input_port(gripper_instance)); } else { /* Set the width between the fingers for open and closed states as well as the height to which the gripper lifts the deformable torus. */ const double kOpenWidth = kL * 1.5; const double kClosedWidth = kL * 0.4; const double kLiftedHeight = 0.18; const auto& control = *builder.AddSystem<ParallelGripperController>( kOpenWidth, kClosedWidth, kLiftedHeight); builder.Connect(control.get_output_port(), plant.get_desired_state_input_port(gripper_instance)); } auto diagram = builder.Build(); std::unique_ptr<Context<double>> diagram_context = diagram->CreateDefaultContext(); /* Build the simulator and run! */ systems::Simulator<double> simulator(*diagram, std::move(diagram_context)); simulator.Initialize(); simulator.set_target_realtime_rate(FLAGS_realtime_rate); simulator.AdvanceTo(FLAGS_simulation_time); return 0; } } // namespace } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "This is a demo used to showcase deformable body simulations in Drake. " "A parallel (or suction) gripper grasps a deformable torus on the " "ground, lifts it up, and then drops it back on the ground. " "Launch meldis before running this example. " "Refer to README for instructions on meldis as well as optional flags."); gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/README.md
# Deformable torus This is an example of a basic deformable body simulation in Drake. The example poses a deformable torus on the ground and uses a PD controlled gripper that follows a prescribed kinematics to pick up the torus, lift it up in the air, and then drop it back on the ground. Users can switch between a parallel jaw gripper model and a suction cup gripper model with the `--gripper` flag. This demonstrates the dynamics of deformable bodies and showcases the SAP solver in handling contact between deformable and rigid bodies. In the source code, this example shows how to set up deformable bodies in a Drake simulation and highlights the difference between deformable and rigid bodies. # Bubble gripper This example simulates the [bubble gripper designed at Toyota Research Institute (TRI)](https://www.tri.global/news/sensing-believing-more-capable-robot-hands-soft-bubble-gripper) using deformable bodies. This example is also described in the paper [A Convex Formulation of Frictional Contact between Rigid and Deformable Bodies](https://arxiv.org/abs/2303.08912). The example poses a deformable teddy bear on the ground and uses PD control to pick it up with the bubble gripper. A camera is mounted inside the bubble gripper to show how a dense dot pattern inside the latex membrane is moving and distorting during the grasp. This example demonstrates the following capabilities of deformable body simulation in Drake: 1. frictional contact resolution among deformable bodies; 2. deformable geometry rendering; 3. fixed constraints between rigid bodies and deformable bodies. In the source code, this example shows how to set up use these functionalities by calling C++ APIs. Note that currently (April 2024), this example doesn't run on macOS. We are working on supporting this on all platforms supported by Drake. ## Run visualizer ``` bazel run //tools:meldis -- --open-window & ``` ## Run the example ``` bazel run //examples/multibody/deformable:deformable_torus ``` or ``` bazel run //examples/multibody/deformable:bubble_gripper ``` ## Options There are a few command-line options that you can use to adjust the physical properties of the deformable body. Use `--help` to see the list. ``` bazel run //examples/multibody/deformable:deformable_torus -- --help ``` or ``` bazel run //examples/multibody/deformable:bubble_gripper -- --help ```
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/parallel_gripper_controller.cc
#include "drake/examples/multibody/deformable/parallel_gripper_controller.h" namespace drake { namespace examples { namespace deformable { using drake::systems::BasicVector; using drake::systems::Context; using Eigen::Vector2d; using Eigen::VectorXd; ParallelGripperController::ParallelGripperController(double open_width, double closed_width, double height) : initial_configuration_(0, -open_width / 2), closed_configuration_(0, -closed_width / 2), lifted_configuration_(height, -closed_width / 2), open_configuration_(height, -open_width / 2) { this->DeclareVectorOutputPort("desired state", BasicVector<double>(4), &ParallelGripperController::CalcDesiredState); } void ParallelGripperController::CalcDesiredState( const Context<double>& context, BasicVector<double>* output) const { const Vector2d desired_velocities = Vector2d::Zero(); Vector2d desired_positions; const double t = context.get_time(); if (t < fingers_closed_time_) { const double end_time = fingers_closed_time_; const double theta = t / end_time; desired_positions = theta * closed_configuration_ + (1.0 - theta) * initial_configuration_; } else if (t < gripper_lifted_time_) { const double end_time = gripper_lifted_time_ - fingers_closed_time_; const double theta = (t - fingers_closed_time_) / end_time; desired_positions = theta * lifted_configuration_ + (1.0 - theta) * closed_configuration_; } else if (t < hold_time_) { desired_positions = lifted_configuration_; } else if (t < fingers_open_time_) { const double end_time = fingers_open_time_ - hold_time_; const double theta = (t - hold_time_) / end_time; desired_positions = theta * open_configuration_ + (1.0 - theta) * lifted_configuration_; } else { desired_positions = open_configuration_; } output->get_mutable_value() << desired_positions, desired_velocities; } } // namespace deformable } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/bubble_gripper.cc
#include <memory> #include <gflags/gflags.h> #include "drake/common/find_resource.h" #include "drake/examples/multibody/deformable/parallel_gripper_controller.h" #include "drake/geometry/drake_visualizer.h" #include "drake/geometry/proximity_properties.h" #include "drake/geometry/render_gl/factory.h" #include "drake/math/rigid_transform.h" #include "drake/multibody/fem/deformable_body_config.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/deformable_model.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/plant/multibody_plant_config_functions.h" #include "drake/multibody/tree/prismatic_joint.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/sensors/camera_config.h" #include "drake/systems/sensors/camera_config_functions.h" DEFINE_double(simulation_time, 15.0, "Desired duration of the simulation [s]."); DEFINE_double(realtime_rate, 0.0, "Desired real time rate."); DEFINE_double(discrete_time_step, 2.5e-2, "Discrete time step for the system [s]."); DEFINE_bool(render_bubble, true, "Renders the dot pattern inside the bubble gripper if true."); using drake::examples::deformable::ParallelGripperController; using drake::geometry::AddContactMaterial; using drake::geometry::Box; using drake::geometry::GeometryInstance; using drake::geometry::IllustrationProperties; using drake::geometry::Mesh; using drake::geometry::PerceptionProperties; using drake::geometry::ProximityProperties; using drake::geometry::RenderEngineGlParams; using drake::geometry::Rgba; using drake::math::RigidTransformd; using drake::math::RollPitchYawd; using drake::math::RotationMatrixd; using drake::multibody::AddMultibodyPlant; using drake::multibody::Body; using drake::multibody::CoulombFriction; using drake::multibody::DeformableBodyId; using drake::multibody::DeformableModel; using drake::multibody::ModelInstanceIndex; using drake::multibody::MultibodyPlantConfig; using drake::multibody::PackageMap; using drake::multibody::Parser; using drake::multibody::PrismaticJoint; using drake::multibody::fem::DeformableBodyConfig; using drake::schema::Transform; using drake::systems::Context; using drake::systems::sensors::ApplyCameraConfig; using drake::systems::sensors::CameraConfig; using Eigen::Vector3d; using Eigen::Vector4d; namespace drake { namespace examples { namespace multibody { namespace bubble_gripper { namespace { int do_main() { if (!drake::geometry::kHasRenderEngineGl && FLAGS_render_bubble) { drake::log()->error( "This example can only be run on Linux when the bubble gripper is " "rendered."); return 0; } systems::DiagramBuilder<double> builder; MultibodyPlantConfig plant_config; DRAKE_DEMAND(FLAGS_discrete_time_step > 0.0); plant_config.time_step = FLAGS_discrete_time_step; /* Deformable simulation only works with SAP solver. */ plant_config.discrete_contact_approximation = "sap"; auto [plant, scene_graph] = AddMultibodyPlant(plant_config, &builder); if (FLAGS_render_bubble) { /* Add a renderer to render the inside dot pattern of the bubble gripper. Currently (April 2024), deformable rendering is only supported by RenderEngineGl. */ scene_graph.AddRenderer( "gl_renderer", geometry::MakeRenderEngineGl(RenderEngineGlParams{})); } /* Minimum required proximity properties for rigid bodies to interact with deformable bodies. 1. A valid Coulomb friction coefficient, and 2. A resolution hint. (Rigid bodies need to be tessellated so that collision queries can be performed against deformable geometries.) */ ProximityProperties rigid_proximity_props; const CoulombFriction<double> surface_friction(1.0, 1.0); const double resolution_hint = 0.01; AddContactMaterial({}, {}, surface_friction, &rigid_proximity_props); rigid_proximity_props.AddProperty(geometry::internal::kHydroGroup, geometry::internal::kRezHint, resolution_hint); /* Set up a ground. */ Box ground{1, 1, 1}; const RigidTransformd X_WG(Eigen::Vector3d{0, 0, -0.505}); plant.RegisterCollisionGeometry(plant.world_body(), X_WG, ground, "ground_collision", rigid_proximity_props); IllustrationProperties illustration_props; illustration_props.AddProperty("phong", "diffuse", Vector4d(0.95, 0.80, 0.65, 0.9)); /* Avoid rendering the ground as it clutters the background. Currently, all visual geometries added through MultibodyPlant are automatically assigned perception properties. When that automatic assignment is no longer done, we can remove this and simply not assign a perception property. */ illustration_props.AddProperty("renderer", "accepting", std::set<std::string>{"nothing"}); plant.RegisterVisualGeometry(plant.world_body(), X_WG, ground, "ground_visual", illustration_props); /* Parse the gripper model (without the bubbles). */ Parser parser(&plant, &scene_graph); ModelInstanceIndex gripper_instance = parser.AddModelsFromUrl( "package://drake_models/wsg_50_description/sdf/" "schunk_wsg_50_deformable_bubble.sdf")[0]; /* Add in the bubbles. */ auto owned_deformable_model = std::make_unique<DeformableModel<double>>(&plant); DeformableModel<double>* deformable_model = owned_deformable_model.get(); DeformableBodyConfig<double> bubble_config; bubble_config.set_youngs_modulus(1e4); // [Pa] bubble_config.set_poissons_ratio(0.45); // unitless bubble_config.set_mass_density(10); // [kg/m³] bubble_config.set_stiffness_damping_coefficient(0.05); // [1/s] /* Minimally required proximity properties for deformable bodies: A valid Coulomb friction coefficient. */ ProximityProperties deformable_proximity_props; AddContactMaterial({}, {}, surface_friction, &deformable_proximity_props); /* The mesh we render in the camera sim. */ PerceptionProperties perception_properties; const std::string textured_bubble_obj = PackageMap{}.ResolveUrl( "package://drake_models/wsg_50_description/meshes/textured_bubble.obj"); /* Assign the mesh to be rendered. If this property is not specified, the untextured surface mesh of the simulated volume mesh is rendered. */ perception_properties.AddProperty("deformable", "embedded_mesh", textured_bubble_obj); /* Add in the left bubble. */ const std::string bubble_vtk = PackageMap{}.ResolveUrl( "package://drake_models/wsg_50_description/meshes/bubble.vtk"); auto left_bubble_mesh = std::make_unique<Mesh>(bubble_vtk); /* Pose of the left bubble (at initialization) in the world frame. */ const RigidTransformd X_WBl(RollPitchYawd(M_PI_2, M_PI, 0), Vector3d(-0.185, -0.09, 0.06)); auto left_bubble_instance = std::make_unique<GeometryInstance>( X_WBl, std::move(left_bubble_mesh), "left bubble"); left_bubble_instance->set_proximity_properties(deformable_proximity_props); left_bubble_instance->set_perception_properties(perception_properties); /* Since the deformable geometry is specified through Shape::Mesh, the resolution hint is unused. */ const double unused_resolution_hint = 1.0; const DeformableBodyId left_bubble_id = deformable_model->RegisterDeformableBody(std::move(left_bubble_instance), bubble_config, unused_resolution_hint); /* Now we attach the bubble to the WSG finger using a fixed constraint. To do that, we specify a box geometry and put all vertices of the bubble geometry under fixed constraint with the rigid finger if they fall inside the box. Refer to DeformableModel::AddFixedConstraint for details. */ const Body<double>& left_finger = plant.GetBodyByName("left_finger"); /* Pose of the bubble in the left finger body frame. */ const RigidTransformd X_FlBl = RigidTransformd( math::RollPitchYawd(M_PI_2, M_PI_2, 0), Vector3d(0.0, -0.03, -0.1125)); /* All vertices of the deformable bubble mesh inside this box will be subject to fixed constraints. */ const Box box(0.1, 0.004, 0.15); deformable_model->AddFixedConstraint( left_bubble_id, left_finger, X_FlBl, box, /* The pose of the box in the left finger's frame. */ RigidTransformd(Vector3d(0.0, -0.03, -0.1))); /* Add in the right bubble and attach it to the right finger. */ auto right_bubble_mesh = std::make_unique<Mesh>(bubble_vtk); /* Pose of the right bubble (at initialization) in the world frame. */ const RigidTransformd X_WBr(RollPitchYawd(-M_PI_2, M_PI, 0), Vector3d(-0.185, 0.09, 0.06)); auto right_bubble_instance = std::make_unique<GeometryInstance>( X_WBr, std::move(right_bubble_mesh), "right bubble"); right_bubble_instance->set_proximity_properties(deformable_proximity_props); right_bubble_instance->set_perception_properties(perception_properties); const DeformableBodyId right_bubble_id = deformable_model->RegisterDeformableBody(std::move(right_bubble_instance), bubble_config, unused_resolution_hint); const Body<double>& right_finger = plant.GetBodyByName("right_finger"); /* Pose of the right finger body (at initialization) in the world frame. */ const RigidTransformd X_FrBr = RigidTransformd( math::RollPitchYawd(-M_PI_2, M_PI_2, 0), Vector3d(0.0, 0.03, -0.1125)); deformable_model->AddFixedConstraint( right_bubble_id, right_finger, X_FrBr, box, /* The pose of the box in the right finger's frame. */ RigidTransformd(Vector3d(0.0, 0.03, -0.1))); /* Add in a deformable manipuland. */ DeformableBodyConfig<double> teddy_config; teddy_config.set_youngs_modulus(5e4); // [Pa] teddy_config.set_poissons_ratio(0.45); // unitless teddy_config.set_mass_density(1000); // [kg/m³] teddy_config.set_stiffness_damping_coefficient(0.05); // [1/s] const std::string teddy_vtk = FindResourceOrThrow( "drake/examples/multibody/deformable/models/teddy.vtk"); auto teddy_mesh = std::make_unique<Mesh>(teddy_vtk, /* scale */ 0.15); auto teddy_instance = std::make_unique<GeometryInstance>( RigidTransformd(math::RollPitchYawd(M_PI / 2.0, 0, -M_PI / 2.0), Vector3d(-0.17, 0, 0)), std::move(teddy_mesh), "teddy"); teddy_instance->set_proximity_properties(deformable_proximity_props); /* Give the teddy bear a brown color for illustration to better distinguish it from the bubble gripper in the visualizer. */ IllustrationProperties teddy_illustration_props; teddy_illustration_props.AddProperty("phong", "diffuse", Rgba(0.82, 0.71, 0.55, 1.0)); teddy_instance->set_illustration_properties(teddy_illustration_props); deformable_model->RegisterDeformableBody(std::move(teddy_instance), teddy_config, 1.0); plant.AddPhysicalModel(std::move(owned_deformable_model)); /* All rigid and deformable models have been added. Finalize the plant. */ plant.Finalize(); /* It's essential to connect the vertex position port in DeformableModel to the source configuration port in SceneGraph when deformable bodies are present in the plant. */ builder.Connect( plant.get_deformable_body_configuration_output_port(), scene_graph.get_source_configuration_port(plant.get_source_id().value())); /* Set the width between the fingers for open and closed states as well as the height to which the gripper lifts the manipuland. */ const double open_width = 0.12; const double closed_width = 0.04; const double lifted_height = 0.12; const auto& control = *builder.AddSystem<ParallelGripperController>( open_width, closed_width, lifted_height); builder.Connect(control.get_output_port(), plant.get_desired_state_input_port(gripper_instance)); /* Add a visualizer that emits LCM messages for visualization. */ geometry::DrakeVisualizerParams params; params.role = geometry::Role::kIllustration; geometry::DrakeVisualizerd::AddToBuilder(&builder, scene_graph, nullptr, params); /* We want to look in the -Py direction so we line up Bz with -Py.*/ const Vector3d Bz_P = -Vector3d::UnitY(); const Vector3d Bx_P = Vector3d::UnitZ(); const Vector3d By_P = Bz_P.cross(Bx_P); // Already a unit vector. const Vector3d p_PB(0, 0.06, -0.11); const RotationMatrixd R_PB = RotationMatrixd::MakeFromOrthonormalColumns(Bx_P, By_P, Bz_P); Transform schema_X_PB(RigidTransformd(R_PB, p_PB)); schema_X_PB.base_frame = "right_finger"; /* Create the camera if rendering is requested. */ if (FLAGS_render_bubble) { const CameraConfig camera_config{.width = 1280, .height = 720, .focal{CameraConfig::FovDegrees{.y = 90}}, .clipping_near = 0.001, .X_PB = schema_X_PB, .renderer_name = "gl_renderer", .show_rgb = true}; ApplyCameraConfig(camera_config, &builder); } auto diagram = builder.Build(); std::unique_ptr<Context<double>> diagram_context = diagram->CreateDefaultContext(); /* Build the simulator and run! */ systems::Simulator<double> simulator(*diagram, std::move(diagram_context)); /* Set the initial conditions for the spatula pose and the gripper finger positions. */ Context<double>& mutable_root_context = simulator.get_mutable_context(); Context<double>& plant_context = diagram->GetMutableSubsystemContext(plant, &mutable_root_context); /* Set initial finger joint positions to the "open" state. */ const PrismaticJoint<double>& right_joint = plant.GetMutableJointByName<PrismaticJoint>("right_finger_sliding_joint"); const PrismaticJoint<double>& left_joint = plant.GetMutableJointByName<PrismaticJoint>("left_finger_sliding_joint"); left_joint.set_translation(&plant_context, -open_width / 2.0); right_joint.set_translation(&plant_context, open_width / 2.0); simulator.Initialize(); simulator.set_target_realtime_rate(FLAGS_realtime_rate); simulator.AdvanceTo(FLAGS_simulation_time); return 0; } } // namespace } // namespace bubble_gripper } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "This is a demo used to showcase the following features in deformable " "body simulation in Drake:\n" " 1. frictional contact resolution among deformable bodies;\n" " 2. deformable geometry rendering;\n" " 3. fixed constraints between rigid bodies and deformable bodies.\n" "Note that this example only runs on Linux systems."); gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::bubble_gripper::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/suction_cup_controller.h
#pragma once #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace examples { namespace deformable { /* We create a leaf system that outputs the desire state of a suction cup gripper mounted on a prismatic joint to the world. This control is a time-based state machine, where the desired state changes based on the context time. The desired state is described through two output ports, one containing the desired position and velocity of the prismatic joint to the world, the other containing the maximum suction force density. The suction cup is first lowered to approach the object, then the suction force is turned on to pick up the object. Then the suction cup is raised to the initial height and the suction force is turned off to release the object. This is strictly for demo purposes and is not intended as a generalized model for suction grippers. */ class SuctionCupController : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SuctionCupController); /* Constructs a SuctionCupController system with the given parameters. The trajectory is characterized by 4 key time stamps and 2 key positions. The 4 key time stamps are `approach_time`, `start_suction_time`, `retrieve_time`, and `release_suction_time`. They must be in increasing order. The 2 key positions are `initial_height` and `object_height`. @param[in] initial_height Initial height of the gripper. @param[in] object_height The estimated height of the object. We turn suction on when the gripper first reach this height. @param[in] approach_time The time at which the gripper starts to approach the manipuland. @param[in] start_suction_time The time at which suction force turns on. @param[in] retrieve_time The time at which to start lifting the gripper. @param[in] release_suction_time The time at which suction turns off. */ SuctionCupController(double initial_height, double object_height, double approach_time, double start_suction_time, double retrieve_time, double release_suction_time); const systems::OutputPort<double>& desired_state_output_port() const { return get_output_port(desired_state_port_index_); } const systems::OutputPort<double>& maximum_force_density_port() const { return get_output_port(maximum_force_density_port_index_); } private: /* Computes the output desired state of the suction cup. */ void CalcDesiredState(const systems::Context<double>& context, systems::BasicVector<double>* desired_state) const; /* Computes the maximum suction force in Newtons based on time. */ void CalcMaxForceDensity( const systems::Context<double>& context, systems::BasicVector<double>* max_force_density) const; double initial_height_{}; double object_height_{}; double approach_time_{}; double start_suction_time_{}; double retrieve_time_{}; double release_suction_time_{}; int desired_state_port_index_{}; int maximum_force_density_port_index_{}; }; } // namespace deformable } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/deformable/point_source_force_field.cc
#include "drake/examples/multibody/deformable/point_source_force_field.h" namespace drake { namespace examples { namespace deformable { using multibody::ForceDensityField; using multibody::MultibodyPlant; using multibody::RigidBody; using systems::BasicVector; using systems::Context; PointSourceForceField::PointSourceForceField( const MultibodyPlant<double>& plant, const RigidBody<double>& body, const Vector3<double>& p_BC, double falloff_distance) : plant_(&plant), body_(body.index()), p_BC_(p_BC), falloff_distance_(falloff_distance) { DRAKE_THROW_UNLESS(falloff_distance_ > 0); } Vector3<double> PointSourceForceField::DoEvaluateAt( const Context<double>& context, const Vector3<double>& p_WQ) const { const Vector3<double>& p_WC = EvalPointSourceLocation(context); Vector3<double> p_QC_W = p_WC - p_WQ; const double dist = p_QC_W.norm(); if (dist == 0 || dist > falloff_distance_) { return Vector3<double>::Zero(); } const double max_value = maximum_force_density_input_port().HasValue(context) ? maximum_force_density_input_port() .Eval<systems::BasicVector<double>>(context)[0] : 0.0; const double magnitude = (falloff_distance_ - dist) * max_value / falloff_distance_; return magnitude * p_QC_W / p_QC_W.norm(); } std::unique_ptr<ForceDensityField<double>> PointSourceForceField::DoClone() const { return std::make_unique<PointSourceForceField>( *plant_, plant_->get_body(body_), p_BC_, falloff_distance_); } void PointSourceForceField::DoDeclareCacheEntries( MultibodyPlant<double>* plant) { /* We store the location of the point source C in the world frame as a cache entry so we don't need to repeatedly compute it. */ point_source_position_cache_index_ = this->DeclareCacheEntry( plant, "point source of the force field", systems::ValueProducer( this, &PointSourceForceField::CalcPointSourceLocation), {systems::System<double>::xd_ticket()}) .cache_index(); } void PointSourceForceField::DoDeclareInputPorts(MultibodyPlant<double>* plant) { maximum_force_density_port_index_ = this->DeclareVectorInputPort(plant, "maximum force density magnitude in N/m³", BasicVector<double>(1)) .get_index(); } } // namespace deformable } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody/deformable
/home/johnshepherd/drake/examples/multibody/deformable/models/teddy.vtk
# vtk DataFile Version 3.0 Fixed teddy mesh ASCII DATASET UNSTRUCTURED_GRID POINTS 410 double -0.35110059 0.18137895 0.43459845 -0.34532255 0.12186533 0.34743726 -0.34216294 0.20965686 0.35381222 -0.33242810 0.08019476 0.42254895 -0.33124948 0.52337724 0.14307070 -0.32834080 0.11259806 0.25533178 -0.32529825 0.53656691 0.24372268 -0.32516119 0.17134389 0.18050072 -0.32502949 0.18451397 0.26960620 -0.32438967 0.45743698 0.30780899 -0.32420093 0.28570479 0.40315944 -0.32394385 0.42832381 0.20169498 -0.32363328 0.53165615 0.03371000 -0.32106325 0.42689469 0.08054148 -0.31821147 0.14800470 0.09890267 -0.31726819 0.23110309 0.09885550 -0.30484384 0.44022229 -0.04342172 -0.30445671 0.04632862 0.33916572 -0.30437389 0.27038434 0.45805052 -0.30261955 0.16382439 0.00437081 -0.30175155 0.25682950 0.19604222 -0.29846466 0.07311782 0.16562328 -0.29541519 0.53693610 0.33836079 -0.29470068 0.28418884 0.02159709 -0.29096403 0.51564211 -0.07496607 -0.29008406 0.23038116 -0.06171644 -0.28201947 0.59362525 0.00203236 -0.27992463 0.19932663 0.46594170 -0.27877057 0.31070465 0.10641132 -0.27638832 0.03190494 0.25568146 -0.27637315 0.06813670 0.05777087 -0.27538565 0.40034920 0.27613360 -0.27303731 0.27630880 0.29510593 -0.27196536 0.39338312 0.16689962 -0.27006725 0.36542976 -0.10882288 -0.26975363 0.29849049 -0.06199601 -0.26941276 0.14499223 -0.10481401 -0.26929438 0.44811681 0.38048226 -0.26918903 0.59648848 0.10973718 -0.26318893 0.25450230 -0.15851420 -0.25640733 0.43878937 -0.14860024 -0.25272229 0.58914697 0.19928604 -0.25232977 0.58016664 0.27032083 -0.24814108 0.06305392 -0.03511329 -0.24556583 0.12747556 0.46074337 -0.24428125 0.35289520 0.00386479 -0.24420056 0.02659164 0.42919651 -0.23881620 0.77191961 -0.02227929 -0.23798916 0.31107315 0.19916889 -0.23789817 0.02794865 0.12111899 -0.23786226 0.59044075 -0.09591210 -0.23737478 0.82674360 0.03487985 -0.23606875 0.35674453 -0.20418498 -0.22932841 0.61271113 0.08491389 -0.22634044 0.69869638 -0.04456071 -0.22363636 0.70752913 0.07314210 -0.22180554 0.30966300 0.46155518 -0.21935140 0.93206263 0.02434384 -0.21762872 0.52276093 -0.16870093 -0.21649188 0.01750460 0.31343082 -0.21606350 0.01235798 0.20908462 -0.21408138 0.86626285 -0.07051197 -0.21296729 0.30199760 0.36630613 -0.21210571 0.15543020 -0.19899355 -0.20952454 0.36463916 0.09980165 -0.20938915 0.75926191 -0.11485562 -0.20760661 0.88787174 0.08681473 -0.20435306 0.22835603 0.47590426 -0.20067307 0.80735129 0.13507773 -0.20022188 0.39615172 0.20993485 -0.19910693 0.06829590 -0.13366431 -0.19908913 0.63043123 -0.00364365 -0.19812949 0.48892891 0.39616418 -0.19724391 1.02371609 0.02783165 -0.19421314 0.55399525 0.32351273 -0.19267696 0.95782417 -0.04152877 -0.18714349 0.26302645 -0.24945922 -0.18441281 0.44774929 -0.23175421 -0.17844468 0.72102773 0.16580567 -0.17756887 0.01303235 0.04324571 -0.17284448 0.26113468 0.28310180 -0.17235279 0.57541764 0.17221849 -0.17125651 0.63860214 -0.11602370 -0.17045541 0.56184405 0.25366616 -0.16910545 0.41801125 0.30843661 -0.16753492 0.97215265 0.03291892 -0.16497144 0.01791905 -0.05501836 -0.17331646 0.58195341 -0.16189200 -0.16270716 0.85168022 -0.16301182 -0.15678571 0.27880815 0.41123664 -0.15378919 0.61004829 0.08908074 -0.14654040 0.73482186 -0.18907289 -0.14485483 0.09018269 0.44956613 -0.14462979 0.36172083 -0.27797037 -0.14334582 0.94506782 -0.11453281 -0.14264736 0.50634271 0.32185480 -0.14220487 0.31491709 0.18955778 -0.14194270 0.05527275 0.36649579 -0.14125454 0.42900443 0.18460479 -0.13806018 0.16275480 0.46529290 -0.13768671 0.66770107 0.16357398 -0.13636151 0.88251942 0.16299278 -0.13571902 0.24413632 0.36433658 -0.13519989 0.02190280 0.15160468 -0.13496260 0.17110895 -0.27252564 -0.13401374 0.08430851 -0.21429218 -0.13217729 0.80130374 0.17976368 -0.13168861 0.23091480 0.45043078 -0.13062498 0.50460166 0.24332395 -0.12874690 1.01771092 -0.04891741 -0.12808816 0.56400812 0.12906291 -0.12201357 0.53920943 -0.23439877 -0.12083284 0.96138245 0.12545922 -0.11419679 0.21463771 0.30923805 -0.11161558 0.50293767 0.17750640 -0.10984896 0.05513612 0.25433832 -0.10758029 1.03159881 0.03897561 -0.10399138 0.10297663 0.31691858 -0.10263206 0.14903599 0.37834820 -0.10162380 0.76146096 0.21973528 -0.09817304 0.26859921 -0.30092701 -0.09698907 0.02201335 -0.12873823 -0.08898129 0.02695428 0.08927463 -0.08775511 0.24365574 0.22553465 -0.08270462 0.00517616 -0.01048632 -0.08270178 0.63637805 -0.19224545 -0.08024055 0.92992794 -0.17900716 -0.07387844 0.15803596 0.26825169 -0.07026795 0.45010176 -0.29211402 -0.06898358 0.82341683 -0.22951409 -0.06522833 0.68277937 0.23816094 -0.06076218 0.72173870 -0.22552341 -0.05989092 0.09432399 0.15738562 -0.05986021 0.08328651 -0.28847173 -0.05616292 0.18274729 -0.32078516 -0.05504362 0.99875915 -0.10837173 -0.05438370 0.35636098 -0.31226885 -0.05298236 0.60198009 0.13942853 -0.05289081 0.36681125 0.21771742 -0.05102389 0.92079675 0.19424194 -0.04626364 0.53118616 0.17216951 -0.04396029 0.45582384 0.20528461 -0.03886473 1.00066508 0.10445729 -0.03417745 0.27115861 0.21899119 -0.03407675 0.04755354 -0.21011163 -0.03106447 0.18479320 0.19491778 -0.02593170 0.84336877 0.21145241 -0.02407789 0.52983695 -0.26327619 -0.02097661 1.02607989 -0.02835067 -0.01736744 0.60406899 -0.22052389 -0.00532536 0.97194958 0.16015656 -0.00381372 0.11224608 -0.34034568 -0.00375437 0.90589488 -0.20783919 -0.00276656 0.76631939 0.29364493 0.00076059 0.03045164 0.06094060 0.00107854 1.01852250 0.04864684 0.00227219 0.97526521 -0.15847585 0.00294779 0.01726855 -0.06355026 0.00353942 0.62402963 0.22061599 0.00497415 0.27667552 -0.32462958 0.00789632 0.75366628 -0.23838814 0.00574169 0.03106544 -0.14695833 0.02052816 0.67290216 -0.21797825 0.02435172 0.68605644 0.26677030 0.02463659 0.55286586 0.15678057 0.02842448 0.06534106 -0.28009075 0.03019546 0.11076291 0.14584507 0.03299904 0.18003967 -0.33882543 0.03300501 0.39038789 -0.31190821 0.03841430 0.49485981 0.19122972 0.03853517 0.41269317 0.21556449 0.04327698 0.82846475 -0.23386855 0.04362600 0.32483262 0.21941230 0.04731900 0.48472309 -0.28696975 0.05180018 0.15346503 0.19699791 0.05743967 0.56092836 -0.24278908 0.05980262 1.00359809 -0.09701750 0.06054753 0.60338479 0.13694872 0.06451030 0.23453441 0.21586014 0.06483254 0.92235273 0.19249004 0.06665078 0.81630808 0.20967598 0.07079045 0.99032253 0.11273744 0.07560588 0.66405410 0.21440031 0.07618937 0.05246901 -0.20335116 0.08153360 0.00773968 0.00426557 0.08243924 0.18297751 0.27601206 0.08536267 0.92557961 -0.18142280 0.08614835 0.75762731 0.23311588 0.08754341 1.03094828 0.00959960 0.09075733 0.09972367 0.29437912 0.09093594 0.63749200 -0.19578464 0.09345848 0.06073485 0.19982991 0.09547583 0.32329071 -0.30182621 0.09591699 0.03213674 0.11088477 0.09909815 0.23095703 -0.29879427 0.10069478 0.11369835 -0.27473023 0.10482243 0.73948050 -0.20925105 0.10606980 0.18857683 0.36857232 0.10928533 0.01806946 -0.10996628 0.11181195 0.37051278 0.19854297 0.11827923 0.53293937 0.15661553 0.11889732 0.09298767 0.38160312 0.12659274 0.44896173 0.18924156 0.12776928 0.51771208 0.23328634 0.12867819 0.11913995 0.44687754 0.13057205 0.82558507 -0.19819799 0.13236238 0.29659241 0.20120917 0.13471368 0.97982174 0.06238679 0.13651282 0.94176650 0.12690890 0.13832809 0.67709696 0.16896227 0.13983089 0.21714672 0.46112624 0.14028183 0.58491778 -0.18948486 0.14040601 0.50979328 -0.23825362 0.14209250 0.26286504 0.40845376 0.14346549 0.94858646 -0.10705598 0.14376785 0.24958923 0.29082915 0.14572231 0.40788457 -0.26808789 0.14621083 1.00560296 -0.05159708 0.14786291 0.43296707 0.27225357 0.15905082 0.54099381 0.31574455 0.16063133 0.60527068 0.08514957 0.16193868 0.01204153 0.06142562 0.16330165 0.69501299 -0.15816152 0.16564839 0.86054140 0.14662668 0.16754623 0.63300651 -0.11064965 0.16774114 0.01667817 -0.03715062 0.16891873 0.76476157 0.17549239 0.17043027 0.01833643 0.25013959 0.17332256 0.01917760 0.16104123 0.17446454 0.08955133 -0.18902817 0.17485686 0.29540008 -0.26245645 0.17565408 0.87727904 -0.13689722 0.17713839 0.28311824 0.36465108 0.17786719 0.03146996 0.34980378 0.18035559 0.57362539 0.20516643 0.18124893 0.18690085 -0.24035636 0.18158950 0.46165666 0.38880080 0.18495074 0.77747816 -0.15156639 0.18978031 0.05503849 0.44754675 0.18994083 0.30000234 0.45858476 0.19246275 0.15141244 0.46840966 0.19154021 1.02196968 0.01884173 0.19679028 0.91958284 0.07871633 0.19742376 0.36118847 0.12040165 0.19905281 0.29619932 0.21956946 0.20245494 0.63710773 -0.01148693 0.20915425 0.55595428 -0.15760922 0.21310376 0.69210392 0.09634430 0.21391350 0.93031037 0.02821433 0.21474758 0.91595858 -0.03890446 0.21504253 0.71428901 -0.09137840 0.22233966 0.38605851 0.19040041 0.22354662 0.45613518 -0.19126563 0.22312247 0.07099955 -0.10321580 0.22474617 0.80181181 0.08830397 0.22500803 0.81548488 -0.06761241 0.22755285 0.34301090 0.05392435 0.22927715 0.22866714 0.47229344 0.23072198 0.40422615 0.29653314 0.23387997 0.84788036 0.02372269 0.23561855 0.04031217 0.00270530 0.23651093 0.25920641 -0.20201105 0.23990186 0.74341404 -0.00236458 0.24028884 0.35989019 -0.19728327 0.24502517 0.01609801 0.29902646 0.24589163 0.37347850 0.02228044 0.24758963 0.59270334 0.16075660 0.24811330 0.03230071 0.10503380 0.25295723 0.32312396 -0.00815968 0.25561234 0.57868624 0.27183032 0.25566465 0.61168915 0.05916899 0.26059017 0.30858198 0.19288471 0.26237535 0.17774811 -0.14509329 0.26452184 0.50382692 -0.11894893 0.26650181 0.53543085 0.36822724 0.26792234 0.58178878 -0.06147948 0.26892024 0.27825904 0.28987363 0.27042455 0.29538602 0.46606266 0.27043927 0.15043387 0.45631745 0.27100176 0.29622111 -0.10933342 0.27109763 0.42670775 0.36372435 0.27703128 0.03593869 0.20987645 0.27983347 0.41130358 -0.09103383 0.28449282 0.03076038 0.39821914 0.28464499 0.13286297 -0.04446962 0.28534550 0.31068474 0.39623478 0.28894138 0.40215790 0.10158344 0.29183579 0.24059525 -0.05499291 0.29396355 0.10444659 0.05068687 0.29597548 0.40901795 0.26214868 0.29926366 0.29352734 0.10355659 0.30459511 0.24364424 0.20781080 0.30667037 0.09725498 0.14123268 0.30869353 0.07628424 0.43759289 0.30929372 0.49146008 -0.05055042 0.31232622 0.22282943 0.02663628 0.31510651 0.42450303 0.01355668 0.31977799 0.53982776 0.21711597 0.32044429 0.53489286 0.02553023 0.32167738 0.55108158 0.12237054 0.32397217 0.18631904 0.11903737 0.32698074 0.08396317 0.30321997 0.32716912 0.45444050 0.08846076 0.32753170 0.15034397 0.21584916 0.33152640 0.44365794 0.17570475 0.33389396 0.49476922 0.31383330 0.33478475 0.18265481 0.29840201 0.33643323 0.24750023 0.44817692 0.33751013 0.47602422 0.24196565 0.34588614 0.09875478 0.38436696 0.34705788 0.21578920 0.37078422 0.35318014 0.15171756 0.42672068 0.24738937 0.49934717 0.16134599 -0.22906954 0.14805423 0.32039985 -0.20298350 0.20804063 0.40779156 -0.19421257 0.50208463 0.02279631 -0.19445234 0.19226507 0.10379330 -0.12900080 0.31686037 -0.12906909 0.03346147 0.16750510 -0.18038014 -0.12031151 0.56667510 -0.06990040 -0.04109076 0.80922189 0.05575147 -0.06032955 0.12819809 -0.02734008 -0.01786472 0.27223175 0.10025147 0.02898362 0.59404827 -0.08468796 -0.02506170 0.47388067 0.06322293 0.05179429 0.35235168 -0.17099566 0.10214334 0.37247653 0.06565354 0.15586811 0.19017118 0.00342103 0.20577805 0.17175001 0.20442157 0.17755169 0.50121460 -0.01795389 0.04484206 0.78025736 -0.11093819 0.11220177 0.88918729 0.02694218 0.16299442 0.10137386 0.11370429 0.22367697 0.17868145 0.38065731 0.17457217 0.37176282 -0.09790500 -0.30160741 0.45838018 0.15498516 -0.27038701 0.44400820 0.12143618 -0.25180113 0.54939744 0.15764459 -0.30034195 0.46845806 0.25992814 -0.29863180 0.46497501 0.20531115 -0.24900284 0.21623929 0.23180126 -0.24893699 0.22282433 0.27635400 -0.30206278 0.24251571 0.43455057 -0.26657891 0.44814765 0.06675582 -0.25718419 0.40243073 0.02818997 -0.23729802 0.25898209 0.23957201 -0.28540042 0.46864265 0.30724719 -0.26405397 0.49474809 0.23770982 -0.26385771 0.49025792 0.27322722 -0.23479939 0.47717223 0.29982317 -0.22292053 0.48109663 0.26489988 -0.20901650 0.45334595 0.29899420 -0.20832010 0.41467682 0.23036920 -0.20300531 0.45247543 0.25972877 -0.26234382 0.49126504 0.18309283 -0.22215907 0.48440038 0.16955905 -0.22121038 0.47761358 0.21028289 -0.20660995 0.41119377 0.17575221 -0.20129517 0.44899239 0.20511179 -0.23175376 0.50105603 0.35199749 -0.20597087 0.47722976 0.35116853 -0.19375426 0.09137416 0.41361958 -0.17387357 0.04154239 0.18772866 -0.14889454 0.06113632 0.13925230 -0.21084400 0.87706730 0.00815138 -0.19080815 0.91920775 -0.01879652 -0.19093867 0.47002840 0.13601007 -0.18010594 0.96498841 -0.00430492 -0.11872989 0.05367817 0.10031566 -0.12336146 0.20958532 0.27567674 -0.15680367 0.50221103 0.17841164 -0.15544037 0.95861024 -0.04080694 -0.14814091 0.99493179 -0.00799924 -0.01748651 0.78888452 0.21470563 -0.00773772 0.75954413 0.22642558 0.00518878 0.67341673 0.22628062 0.01046001 0.72020334 0.23563841 -0.01386922 0.12404417 -0.30043796 0.02146761 0.20685216 -0.30978972 0.02226593 0.14822282 -0.29775770 0.15785149 0.44706392 0.13850859 0.17030944 0.45949894 0.17350797 0.17505447 0.45188529 0.21184337 0.21187238 0.46336501 0.24771751 0.17995761 0.31980166 0.12756676 0.21581302 0.29505987 0.15238288 0.14046226 0.99271235 0.00539485 0.17431359 0.95506606 0.04530056 0.18423676 0.88203567 -0.08733419 0.18867273 0.89823341 -0.04166664 0.18006217 0.96795666 -0.01169138 0.22191919 0.42099251 0.26720113 0.19488640 0.47260998 0.30613884 0.22751315 0.47500588 0.28894661 0.25242396 0.05771657 0.32651188 0.25632597 0.10706239 0.32410289 0.26187667 0.06511237 0.36708537 0.20134763 0.47984195 0.19778342 0.23816554 0.49132167 0.23365755 0.24915823 0.29486333 0.16156302 0.25182396 0.26992178 0.21369013 0.26993953 0.28292017 0.04028031 0.27576251 0.26466497 0.08648086 0.24861190 0.46982850 0.33238019 0.25520673 0.43865271 -0.04833424 0.27759267 0.43246929 -0.01413499 0.27579391 0.49385209 0.26698950 0.28123865 0.47222440 0.31518796 0.30469283 0.46852538 0.06355683 0.30530938 0.47661974 0.11197699 CELLS 1207 6035 4 0 1 2 313 4 0 313 3 1 4 0 2 10 313 4 62 10 313 314 4 148 331 188 155 4 226 331 254 247 4 5 313 7 8 4 245 320 323 220 4 365 371 94 367 4 327 384 256 326 4 36 43 70 321 4 154 332 327 166 4 1 313 8 2 4 266 270 312 220 4 45 64 322 324 4 1 3 17 313 4 163 182 375 187 4 1 5 8 313 4 46 97 313 361 4 1 313 17 5 4 153 180 187 373 4 113 127 313 369 4 322 328 327 206 4 392 403 274 236 4 385 399 290 243 4 172 326 170 199 4 2 8 32 313 4 230 235 261 318 4 2 313 32 10 4 98 366 370 315 4 335 354 41 339 4 356 350 108 83 4 359 74 95 349 4 190 211 224 323 4 3 44 46 313 4 380 329 243 326 4 108 98 355 370 4 41 335 81 354 4 202 243 380 251 4 200 329 220 312 4 27 342 18 314 4 5 7 313 21 4 5 29 21 313 4 338 9 11 31 4 338 31 346 9 4 200 326 324 329 4 338 348 42 346 4 338 41 42 347 4 243 326 329 265 4 296 329 408 298 4 265 286 329 243 4 296 265 286 329 4 7 14 15 316 4 7 316 21 14 4 294 329 405 296 4 7 15 20 316 4 341 345 32 80 4 341 80 340 345 4 34 315 45 317 4 341 313 80 32 4 9 346 37 31 4 380 243 329 312 4 243 312 286 329 4 316 132 321 322 4 299 408 329 298 4 10 32 62 313 4 312 270 299 329 4 11 335 33 13 4 11 33 338 31 4 11 33 335 339 4 323 245 330 320 4 289 406 312 398 4 258 289 251 391 4 305 289 406 312 4 13 64 45 344 4 305 297 312 269 4 312 269 266 234 4 13 344 343 64 4 13 64 335 33 4 234 266 312 220 4 297 266 299 312 4 297 312 269 266 4 13 343 336 64 4 14 316 19 15 4 14 316 30 19 4 312 299 409 329 4 30 21 49 316 4 304 299 409 312 4 14 316 21 30 4 15 19 23 316 4 15 316 28 20 4 15 23 28 316 4 16 24 12 315 4 16 315 40 24 4 344 45 315 64 4 17 313 59 29 4 17 29 5 313 4 17 46 59 313 4 17 313 3 46 4 289 312 251 397 4 18 56 67 314 4 393 406 407 289 4 19 316 36 25 4 19 30 43 316 4 19 316 43 36 4 20 28 48 316 4 345 80 48 32 4 345 80 316 48 4 345 340 316 80 4 398 406 393 289 4 21 313 316 7 4 407 289 305 280 4 21 29 60 313 4 21 316 60 49 4 22 359 74 72 4 346 42 74 348 4 23 25 35 316 4 23 25 316 19 4 23 316 45 28 4 23 35 45 316 4 304 297 312 308 4 24 315 50 26 4 24 26 12 315 4 24 315 58 50 4 304 297 299 312 4 25 317 39 35 4 25 316 317 35 4 25 36 39 317 4 26 50 71 315 4 26 315 71 53 4 26 38 12 315 4 27 314 67 44 4 202 218 251 382 4 27 314 18 67 4 397 312 251 381 4 28 45 64 316 4 28 316 64 48 4 29 59 60 313 4 341 313 340 80 4 30 43 316 79 4 30 79 316 49 4 32 313 80 62 4 62 56 10 314 4 304 312 289 308 4 357 98 69 64 4 355 366 370 98 4 357 69 98 352 4 355 81 366 335 4 34 35 39 317 4 34 35 317 45 4 34 39 52 317 4 392 258 391 289 4 16 34 40 315 4 35 316 317 45 4 36 317 316 321 4 36 317 321 70 4 36 316 317 25 4 346 349 74 359 4 360 72 84 95 4 38 41 337 81 4 38 315 26 53 4 38 81 315 53 4 38 315 4 12 4 38 337 315 81 4 354 347 41 338 4 39 317 76 52 4 39 63 76 317 4 308 289 305 312 4 305 308 312 297 4 41 347 83 42 4 108 98 352 357 4 42 348 83 74 4 392 236 218 258 4 43 79 86 321 4 361 92 97 314 4 46 92 97 361 4 44 67 99 314 4 44 314 99 92 4 407 289 280 403 4 316 317 45 322 4 46 313 97 59 4 361 97 313 314 4 47 51 55 320 4 47 320 61 51 4 47 320 55 54 4 47 54 65 320 4 47 320 65 61 4 48 64 96 316 4 48 80 316 96 4 50 319 87 82 4 50 71 319 82 4 50 319 58 87 4 50 315 319 71 4 50 58 319 315 4 51 55 320 68 4 51 66 364 57 4 51 364 66 320 4 52 76 93 317 4 52 77 317 93 4 52 77 40 317 4 53 90 315 71 4 54 55 71 320 4 54 71 82 320 4 54 65 320 82 4 55 68 78 320 4 55 90 320 100 4 55 100 320 78 4 56 62 89 314 4 56 314 18 10 4 57 364 85 66 4 364 320 85 66 4 57 85 367 73 4 57 365 367 85 4 77 40 317 58 4 59 313 115 60 4 61 65 88 320 4 94 320 109 371 4 61 88 94 320 4 62 314 102 89 4 62 314 313 102 4 0 27 313 342 4 63 317 105 104 4 316 45 64 322 4 66 85 112 320 4 66 320 112 101 4 66 101 68 320 4 66 320 68 51 4 67 56 107 314 4 67 314 107 99 4 68 320 106 78 4 360 95 84 351 4 72 74 95 359 4 73 109 372 367 4 73 372 109 116 4 74 83 95 349 4 367 94 109 371 4 365 320 94 371 4 76 93 317 120 4 76 120 317 104 4 368 103 122 132 4 368 132 363 103 4 80 96 123 316 4 80 313 113 102 4 369 127 123 113 4 369 123 127 316 4 41 354 81 83 4 82 87 125 319 4 82 330 125 91 4 82 91 65 330 4 82 330 319 125 4 82 320 71 319 4 82 330 320 319 4 82 330 65 320 4 83 350 108 95 4 84 95 108 351 4 84 352 108 98 4 372 109 116 320 4 85 320 116 112 4 121 321 86 124 4 87 111 319 58 4 88 94 320 126 4 88 126 330 129 4 89 102 107 314 4 90 137 320 100 4 91 125 131 330 4 91 330 131 129 4 91 129 88 330 4 91 330 88 65 4 92 314 118 97 4 92 99 118 314 4 93 317 136 128 4 93 317 120 136 4 93 77 317 128 4 94 320 135 109 4 94 320 126 135 4 96 98 322 64 4 322 324 64 98 4 96 322 143 123 4 96 123 316 322 4 96 138 143 322 4 96 138 322 98 4 96 316 64 322 4 138 324 322 98 4 97 117 313 118 4 97 313 314 118 4 98 108 114 370 4 98 114 141 324 4 98 315 114 324 4 98 324 141 138 4 98 315 370 114 4 99 107 118 314 4 101 320 146 106 4 101 106 68 320 4 101 112 139 320 4 101 139 146 320 4 102 314 118 107 4 102 118 313 113 4 102 118 314 313 4 103 362 60 115 4 103 115 132 362 4 104 105 133 318 4 317 321 70 105 4 104 133 134 318 4 104 120 318 134 4 104 318 317 105 4 104 318 120 317 4 105 318 144 133 4 105 318 121 144 4 105 70 121 321 4 106 119 78 320 4 78 100 320 119 4 109 320 148 116 4 109 135 148 320 4 128 77 317 111 4 112 116 142 320 4 112 320 150 139 4 112 142 150 320 4 113 313 127 118 4 114 140 141 324 4 114 140 324 110 4 41 354 83 347 4 114 110 324 315 4 115 127 313 117 4 116 320 155 142 4 116 148 155 320 4 117 118 127 313 4 373 180 320 146 4 121 124 157 321 4 122 321 154 124 4 122 124 79 321 4 122 154 321 132 4 122 368 132 321 4 123 143 145 322 4 123 145 127 316 4 123 145 316 322 4 124 157 321 154 4 124 86 79 321 4 125 330 162 131 4 125 149 162 323 4 125 330 323 162 4 125 323 330 319 4 128 325 317 136 4 128 111 317 147 4 128 147 325 173 4 128 317 325 147 4 129 131 160 330 4 129 152 126 330 4 129 160 171 330 4 130 320 158 137 4 130 137 100 320 4 153 180 373 146 4 376 320 374 187 4 153 376 187 163 4 130 100 119 320 4 131 330 162 160 4 133 318 165 377 4 133 165 318 144 4 133 377 165 151 4 135 320 176 148 4 135 156 176 320 4 135 156 320 126 4 136 159 168 325 4 136 325 317 120 4 136 120 159 325 4 137 324 164 140 4 137 140 110 324 4 137 324 177 164 4 143 172 322 138 4 139 320 179 146 4 139 150 179 320 4 140 324 169 141 4 140 164 169 324 4 141 169 170 324 4 141 170 138 324 4 142 155 181 320 4 143 322 178 145 4 143 172 178 322 4 144 161 183 318 4 144 318 121 161 4 144 318 183 165 4 145 322 178 174 4 145 174 166 322 4 145 127 316 132 4 145 322 132 316 4 145 132 322 166 4 146 179 180 320 4 148 331 320 176 4 148 188 331 176 4 149 323 190 162 4 149 175 190 323 4 149 323 147 175 4 149 323 125 111 4 149 111 147 323 4 150 179 320 181 4 150 181 320 142 4 151 165 195 377 4 151 379 195 167 4 152 171 186 330 4 152 186 156 330 4 152 126 330 156 4 375 320 182 158 4 376 187 374 153 4 373 180 187 320 4 184 332 154 193 4 181 331 320 155 4 181 331 155 188 4 156 330 186 176 4 157 161 121 321 4 157 161 321 198 4 157 184 321 154 4 161 121 321 318 4 161 318 321 198 4 157 184 198 321 4 375 182 163 158 4 158 320 182 177 4 159 194 378 167 4 160 330 196 171 4 161 183 318 198 4 162 190 196 330 4 162 330 323 190 4 375 182 320 187 4 164 324 200 169 4 164 177 200 324 4 165 183 195 318 4 165 195 377 318 4 193 191 332 166 4 167 194 378 195 4 168 325 216 173 4 168 192 216 325 4 168 192 325 159 4 169 326 202 170 4 169 170 324 326 4 169 200 202 326 4 169 200 326 324 4 170 326 202 199 4 322 172 206 326 4 171 330 205 186 4 171 196 205 330 4 172 199 206 326 4 170 322 324 326 4 172 322 138 170 4 322 326 170 172 4 173 325 216 212 4 173 175 325 212 4 173 147 325 175 4 174 328 322 178 4 190 323 175 211 4 176 186 214 330 4 176 330 320 156 4 177 182 209 320 4 177 200 324 220 4 177 209 220 320 4 177 220 324 323 4 177 220 323 320 4 177 137 320 323 4 177 323 324 137 4 178 328 215 185 4 178 206 215 328 4 399 271 291 290 4 326 243 384 256 4 178 328 185 174 4 179 320 223 180 4 179 181 208 320 4 179 208 223 320 4 180 320 226 187 4 180 226 320 223 4 181 188 207 331 4 181 207 208 331 4 181 208 320 331 4 182 187 209 320 4 184 221 225 332 4 154 332 166 193 4 184 225 327 332 4 154 327 184 321 4 185 333 197 189 4 186 205 231 330 4 186 330 231 214 4 188 386 217 241 4 188 331 217 386 4 188 331 176 217 4 148 320 331 155 4 189 233 333 201 4 189 227 328 233 4 189 185 333 328 4 189 233 328 333 4 190 330 222 196 4 190 330 224 222 4 190 330 323 224 4 192 216 325 230 4 193 332 228 221 4 193 221 184 332 4 193 228 332 191 4 194 325 318 230 4 195 235 194 318 4 195 378 318 194 4 196 330 237 205 4 196 222 237 330 4 197 333 204 201 4 197 333 210 204 4 197 333 213 210 4 197 333 232 213 4 197 215 232 333 4 198 225 253 327 4 198 327 184 225 4 229 318 198 253 4 253 198 327 318 4 199 243 326 202 4 199 206 326 243 4 202 380 243 326 4 251 397 382 289 4 200 329 324 220 4 201 204 238 333 4 201 238 233 333 4 251 391 289 382 4 243 251 286 312 4 381 397 382 251 4 383 289 393 391 4 381 202 251 382 4 204 210 240 333 4 204 333 240 238 4 205 330 237 231 4 206 328 244 215 4 399 271 290 243 4 178 328 322 206 4 207 331 242 208 4 386 390 241 248 4 386 390 248 331 4 387 331 248 242 4 208 331 242 223 4 208 223 320 331 4 209 320 247 220 4 210 213 239 333 4 210 239 257 333 4 210 333 257 240 4 211 329 175 212 4 211 329 246 224 4 246 329 212 252 4 213 232 239 333 4 215 333 276 232 4 215 276 328 244 4 215 333 328 276 4 390 241 248 249 4 390 331 249 248 4 217 214 331 176 4 236 274 280 403 4 221 225 332 260 4 221 228 267 332 4 221 267 260 332 4 222 224 250 330 4 222 330 250 237 4 224 246 275 329 4 225 327 260 253 4 225 327 332 260 4 247 331 262 320 4 227 332 281 228 4 227 228 191 332 4 227 264 281 328 4 227 264 328 233 4 227 281 332 328 4 189 174 185 328 4 227 189 332 191 4 228 332 281 267 4 229 253 272 318 4 194 318 235 230 4 230 261 263 325 4 230 216 325 263 4 230 325 192 194 4 231 237 255 330 4 231 388 255 249 4 231 388 330 255 4 232 333 285 239 4 232 276 285 333 4 261 272 325 318 4 235 272 261 318 4 230 318 261 325 4 392 289 407 403 4 237 250 255 330 4 238 240 278 333 4 238 278 293 333 4 238 333 293 283 4 238 283 233 333 4 239 333 277 257 4 239 333 285 277 4 242 248 259 331 4 242 331 259 254 4 242 254 223 331 4 243 256 326 265 4 234 312 200 220 4 400 276 291 271 4 290 256 328 384 4 245 247 262 320 4 245 262 250 330 4 245 262 330 320 4 299 329 270 298 4 245 329 224 275 4 270 298 329 275 4 245 329 220 323 4 211 212 246 329 4 273 334 329 252 4 246 273 275 329 4 246 273 329 252 4 247 254 262 331 4 248 249 259 331 4 217 331 214 249 4 249 255 259 388 4 249 331 389 259 4 250 330 262 255 4 250 330 224 245 4 252 334 216 263 4 252 334 212 216 4 252 334 329 212 4 253 260 284 327 4 253 327 284 272 4 253 272 318 327 4 254 259 262 331 4 226 223 331 320 4 254 223 331 226 4 255 330 262 259 4 255 388 330 259 4 256 268 326 265 4 257 277 307 333 4 257 333 307 278 4 257 278 240 333 4 259 331 330 262 4 259 330 331 389 4 261 263 325 334 4 261 334 272 279 4 261 325 272 334 4 262 331 330 320 4 263 334 216 325 4 264 328 301 281 4 264 283 301 394 4 264 301 328 394 4 312 266 299 270 4 312 270 329 220 4 267 281 292 332 4 267 332 292 288 4 267 288 260 332 4 268 290 401 295 4 295 327 401 268 4 245 270 329 275 4 245 270 220 329 4 399 290 291 328 4 290 256 384 243 4 400 276 328 291 4 272 284 287 327 4 273 329 294 275 4 273 282 294 404 4 273 404 334 282 4 273 329 404 294 4 273 334 404 329 4 407 406 305 289 4 275 294 298 329 4 276 291 306 328 4 276 306 310 333 4 277 285 307 333 4 278 293 333 311 4 278 307 311 333 4 293 311 309 333 4 279 282 334 268 4 279 327 272 287 4 279 268 327 287 4 279 272 327 334 4 279 268 334 327 4 281 328 303 292 4 281 292 332 328 4 282 405 296 294 4 282 265 334 268 4 283 309 333 293 4 283 301 394 309 4 283 396 333 309 4 284 327 295 287 4 284 295 327 288 4 284 288 327 260 4 287 268 327 295 4 288 292 300 328 4 288 328 332 292 4 290 328 402 300 4 290 295 300 401 4 385 399 328 290 4 291 300 303 328 4 292 328 303 300 4 295 401 327 300 4 300 327 328 402 4 295 300 327 288 4 294 298 329 296 4 298 408 302 299 4 298 408 296 302 4 299 302 304 409 4 300 291 290 328 4 301 328 306 303 4 301 306 394 309 4 301 306 328 394 4 304 312 251 289 4 304 312 286 251 4 306 333 309 310 4 306 328 333 276 4 306 333 395 309 4 307 310 311 333 4 310 333 309 311 4 21 316 313 60 4 340 313 316 80 4 369 313 316 127 4 343 336 64 315 4 343 315 64 344 4 336 366 315 81 4 81 355 108 83 4 362 115 316 60 4 60 115 316 313 4 362 115 132 316 4 313 316 127 115 4 363 132 368 316 4 316 115 132 127 4 86 321 70 43 4 16 45 34 315 4 34 40 315 317 4 45 315 324 317 4 40 58 24 315 4 40 315 317 58 4 45 315 64 324 4 315 58 319 317 4 317 324 319 315 4 315 110 324 90 4 315 324 319 90 4 43 321 316 79 4 86 70 321 121 4 36 43 321 316 4 368 321 316 132 4 105 321 318 317 4 105 121 318 321 4 317 321 318 325 4 317 318 120 325 4 316 322 321 317 4 114 110 315 81 4 317 45 322 324 4 77 58 317 111 4 58 111 319 317 4 317 324 111 319 4 315 71 90 319 4 98 64 315 324 4 71 319 320 90 4 90 137 323 320 4 90 137 110 324 4 90 324 323 137 4 65 330 88 320 4 88 320 330 126 4 132 166 321 322 4 132 154 321 166 4 120 325 318 159 4 120 159 318 134 4 321 322 325 317 4 322 138 170 324 4 322 326 325 324 4 317 322 325 324 4 317 147 111 324 4 317 324 325 147 4 324 111 319 323 4 324 325 147 323 4 324 319 90 323 4 324 323 147 111 4 319 323 320 90 4 319 330 320 323 4 106 146 119 320 4 126 330 156 320 4 154 166 327 321 4 229 318 183 198 4 378 194 159 318 4 318 159 325 194 4 159 325 194 192 4 324 325 323 329 4 325 175 147 323 4 325 326 329 324 4 320 176 331 330 4 198 327 321 184 4 184 332 327 154 4 198 318 321 327 4 321 166 327 322 4 166 322 174 327 4 166 174 332 327 4 166 191 332 174 4 321 318 325 327 4 327 328 256 384 4 178 322 172 206 4 327 328 174 332 4 322 206 327 326 4 325 329 175 323 4 325 326 334 329 4 325 329 212 175 4 325 212 334 216 4 325 334 212 329 4 175 323 329 211 4 324 220 329 323 4 211 323 329 224 4 323 245 224 330 4 323 329 224 245 4 330 214 176 331 4 191 174 189 332 4 227 328 332 189 4 318 325 327 272 4 321 322 327 325 4 327 328 322 174 4 327 332 260 288 4 332 327 328 288 4 327 328 288 300 4 174 189 332 328 4 185 333 328 215 4 327 325 334 272 4 322 327 325 326 4 326 334 327 325 4 326 327 334 268 4 326 268 256 327 4 329 326 334 265 4 326 268 334 265 4 395 306 328 333 4 380 243 312 251 4 3 313 0 44 4 34 40 317 52 4 55 71 320 90 4 62 102 313 80 4 76 104 317 63 4 84 69 352 98 4 317 105 70 63 4 128 173 325 168 4 129 152 330 171 4 137 177 320 158 4 162 160 330 196 4 185 197 333 215 4 189 201 333 197 4 209 226 320 187 4 209 247 320 226 4 220 245 320 247 4 229 235 318 272 4 261 263 334 279 4 276 285 333 310 4 279 263 334 282 4 281 303 328 301 4 285 307 333 310 4 291 306 328 303 4 56 314 89 107 4 387 242 248 241 4 0 18 27 342 4 313 27 44 314 4 27 313 342 314 4 53 110 315 90 4 125 87 111 319 4 125 319 111 323 4 0 44 313 27 4 110 315 81 53 4 36 317 70 63 4 36 39 317 63 4 252 282 334 263 4 252 273 334 282 4 97 313 117 115 4 97 59 313 115 4 168 128 136 325 4 195 183 229 318 4 195 235 318 229 4 398 289 393 383 4 226 320 331 247 4 4 335 41 6 4 41 337 81 335 4 11 4 335 13 4 11 335 4 6 4 13 64 336 335 4 335 81 366 336 4 13 12 4 336 4 12 4 336 315 4 337 336 315 81 4 13 336 4 335 4 335 81 336 337 4 38 41 4 337 4 38 4 315 337 4 41 4 337 335 4 4 336 315 337 4 335 337 336 4 4 6 9 11 338 4 6 338 22 9 4 6 338 42 22 4 6 41 42 338 4 11 33 339 338 4 354 338 41 339 4 335 339 41 6 4 11 339 335 6 4 11 339 6 338 4 339 338 41 6 4 8 340 7 20 4 20 7 316 340 4 8 313 7 340 4 7 313 316 340 4 8 20 32 341 4 8 341 340 20 4 8 313 341 32 4 8 313 340 341 4 342 10 18 314 4 0 342 313 10 4 0 18 342 10 4 342 313 10 314 4 13 16 12 343 4 13 12 336 343 4 12 336 343 315 4 12 315 343 16 4 13 344 45 16 4 13 16 343 344 4 16 45 315 344 4 343 315 344 16 4 341 20 32 345 4 341 345 340 20 4 20 345 48 32 4 20 345 316 48 4 20 340 316 345 4 338 346 22 9 4 338 346 42 22 4 9 22 37 346 4 22 42 74 346 4 22 346 74 359 4 338 347 42 348 4 33 31 347 338 4 347 348 83 42 4 347 356 83 350 4 338 31 348 346 4 346 348 74 349 4 348 349 83 74 4 338 347 348 31 4 347 350 83 348 4 360 349 95 351 4 346 31 349 37 4 349 83 95 350 4 346 348 349 31 4 348 350 83 349 4 358 353 108 350 4 350 351 108 95 4 347 33 350 31 4 347 31 350 348 4 349 350 95 351 4 348 31 350 349 4 37 351 84 31 4 84 351 108 353 4 37 349 351 31 4 350 353 108 351 4 349 350 351 31 4 33 69 352 31 4 108 352 353 358 4 84 353 108 352 4 84 69 31 352 4 33 31 353 350 4 84 351 353 31 4 350 31 353 351 4 353 352 31 33 4 84 31 353 352 4 335 33 354 339 4 354 335 81 355 4 33 347 354 338 4 354 355 81 83 4 354 356 83 347 4 33 338 354 339 4 108 98 357 355 4 357 64 355 98 4 33 355 64 335 4 355 356 108 83 4 354 335 355 33 4 354 356 355 83 4 358 350 108 356 4 347 33 356 350 4 354 33 356 347 4 355 358 108 356 4 354 33 355 356 4 33 357 69 64 4 33 69 357 352 4 108 357 352 358 4 108 357 358 355 4 33 64 355 357 4 33 353 358 350 4 358 352 353 33 4 33 350 358 356 4 355 33 358 356 4 358 357 352 33 4 358 357 33 355 4 360 359 95 349 4 22 37 359 72 4 346 349 359 37 4 72 359 95 360 4 22 346 359 37 4 37 72 84 360 4 37 360 84 351 4 37 349 360 351 4 37 359 360 349 4 72 359 360 37 4 46 361 313 44 4 44 92 361 314 4 46 92 361 44 4 44 361 313 314 4 103 49 60 362 4 103 362 132 363 4 49 362 316 60 4 363 362 132 316 4 79 363 49 103 4 49 363 79 316 4 103 362 363 49 4 49 362 363 316 4 51 364 61 57 4 51 61 364 320 4 57 365 85 364 4 365 320 85 364 4 61 365 94 75 4 57 61 75 365 4 61 320 94 365 4 57 61 365 364 4 61 320 365 364 4 98 64 366 315 4 355 64 366 98 4 355 366 64 335 4 336 64 315 366 4 335 366 64 336 4 365 367 94 75 4 57 367 75 73 4 57 365 75 367 4 73 109 367 75 4 75 94 109 367 4 79 103 122 368 4 79 368 363 103 4 122 79 368 321 4 363 368 79 316 4 79 321 316 368 4 113 369 313 80 4 80 369 123 113 4 80 123 369 316 4 80 313 316 369 4 370 366 81 315 4 108 370 355 81 4 355 366 81 370 4 370 108 114 81 4 370 315 81 114 4 365 85 371 367 4 371 320 109 372 4 367 371 109 372 4 365 320 371 85 4 73 372 85 367 4 73 85 372 116 4 85 372 116 320 4 371 320 372 85 4 367 371 372 85 4 153 373 187 374 4 119 373 320 146 4 153 373 119 146 4 374 373 187 320 4 130 320 119 374 4 130 374 119 153 4 153 373 374 119 4 119 373 374 320 4 163 375 376 187 4 130 320 375 158 4 130 375 163 158 4 376 375 320 187 4 130 320 374 376 4 153 130 376 163 4 130 376 374 153 4 163 375 130 376 4 130 375 320 376 4 133 318 377 134 4 133 134 377 151 4 151 377 195 379 4 377 195 379 318 4 159 378 134 167 4 167 378 379 195 4 195 379 318 378 4 134 378 159 318 4 151 134 379 167 4 151 377 379 134 4 377 379 134 318 4 167 378 134 379 4 379 134 318 378 4 200 329 380 326 4 202 380 381 251 4 200 380 329 312 4 202 200 380 326 4 381 380 312 251 4 234 312 381 200 4 200 234 203 381 4 200 202 381 203 4 202 380 200 381 4 200 380 312 381 4 202 218 382 203 4 382 398 383 289 4 382 391 289 383 4 381 234 203 382 4 381 202 382 203 4 203 383 219 218 4 234 383 219 203 4 382 234 203 383 4 382 218 383 203 4 327 206 384 326 4 326 243 206 384 4 290 384 328 385 4 290 384 385 243 4 327 328 384 206 4 206 244 385 243 4 206 244 328 385 4 385 384 328 206 4 385 384 206 243 4 188 207 386 241 4 188 331 386 207 4 387 386 241 248 4 387 386 248 331 4 207 331 387 242 4 207 242 387 241 4 207 386 241 387 4 207 386 387 331 4 231 214 388 249 4 231 214 330 388 4 249 388 259 389 4 388 389 330 259 4 249 331 214 389 4 389 330 331 214 4 249 388 389 214 4 388 214 330 389 4 386 217 241 390 4 386 217 390 331 4 217 241 390 249 4 217 331 249 390 4 258 391 251 218 4 392 258 218 391 4 251 218 391 382 4 383 391 219 218 4 382 218 391 383 4 219 392 274 236 4 393 392 391 289 4 219 236 218 392 4 393 289 407 392 4 219 392 218 391 4 219 269 274 393 4 234 269 219 393 4 383 393 219 391 4 234 393 219 383 4 219 392 391 393 4 219 393 274 392 4 264 283 394 233 4 264 394 328 233 4 283 394 396 309 4 394 306 395 309 4 394 306 328 395 4 395 333 396 309 4 233 395 328 333 4 394 395 396 309 4 394 395 328 233 4 283 233 333 396 4 283 394 233 396 4 395 333 233 396 4 394 395 233 396 4 289 312 397 398 4 234 312 397 381 4 397 398 382 289 4 381 234 382 397 4 398 269 312 234 4 234 269 393 398 4 234 398 393 383 4 382 234 383 398 4 398 312 397 234 4 397 234 382 398 4 385 244 399 243 4 400 271 291 399 4 244 271 399 243 4 400 399 291 328 4 385 244 328 399 4 244 276 400 271 4 244 276 328 400 4 244 271 400 399 4 244 399 400 328 4 268 290 256 401 4 401 327 256 268 4 290 401 300 402 4 401 402 327 300 4 290 328 256 402 4 402 327 328 256 4 290 401 402 256 4 401 256 327 402 4 392 258 403 236 4 403 289 280 258 4 236 403 280 258 4 392 289 403 258 4 404 282 294 405 4 404 265 334 282 4 404 329 405 294 4 404 334 265 329 4 405 329 265 296 4 282 265 296 405 4 404 282 405 265 4 404 329 265 405 4 406 269 312 398 4 305 406 269 312 4 393 269 274 406 4 398 269 393 406 4 274 269 305 406 4 393 406 274 407 4 274 407 305 280 4 274 407 280 403 4 392 407 274 403 4 274 406 305 407 4 393 407 274 392 4 296 329 286 408 4 299 409 329 408 4 408 409 302 299 4 408 286 296 302 4 312 409 286 329 4 304 409 286 312 4 409 302 304 286 4 409 286 329 408 4 408 286 302 409 CELL_TYPES 1207 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
0
/home/johnshepherd/drake/examples/multibody/deformable
/home/johnshepherd/drake/examples/multibody/deformable/models/simple_gripper.sdf
<?xml version="1.0"?> <sdf version="1.7"> <!-- Note: This is the accompanying SDF file for the example demo in deformable_torus.cc and therefore these files must be kept in sync. This file defines the model for a simple gripper having two fingers on prismatic joints. Only the left finger is actuated and the right finger coupler constrained to the left finger. The frame of the gripper, G, has its x-axis pointing to the right of the gripper, its y-axis pointing "forward" (towards the fingers side) and, the z-axis pointing upwards. This file only defines visual geometry but not contact geometry. --> <model name="simple_gripper"> <pose>0 0.06 0.08 -1.57 0 1.57</pose> <joint name="translate_joint" type="prismatic"> <parent>world</parent> <child>body</child> <axis> <xyz expressed_in="__model__">0 -1 0</xyz> </axis> <drake:controller_gains p='10000.0' d='1.0' /> </joint> <link name="body"> <pose>0 -0.049133 0 0 0 0</pose> <inertial> <mass>0.988882</mass> <inertia> <ixx>0.162992</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.162992</iyy> <iyz>0</iyz> <izz>0.164814</izz> </inertia> </inertial> <visual name="visual"> <geometry> <box> <size>0.146 0.0725 0.049521</size> </box> </geometry> <material> <diffuse>0.3 0.3 0.3 0.9</diffuse> </material> </visual> </link> <link name="left_finger"> <!-- Each finger is positioned along the x-axis such that at q=0 the pads of each finger barely touch each other. See notes at the top of this file. --> <pose>-0.0105 0.029 0 0 0 0</pose> <inertial> <mass>0.05</mass> <inertia> <ixx>0.16</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.16</iyy> <iyz>0</iyz> <izz>0.16</izz> </inertia> </inertial> <visual name="visual"> <pose>0 0.0 0.0 1.57 0 0</pose> <geometry> <capsule> <radius>0.01</radius> <length>0.08</length> </capsule> </geometry> <material> <diffuse>0.3 0.3 0.3 0.9</diffuse> </material> </visual> </link> <link name="right_finger"> <!-- Each finger is positioned along the x-axis such that at q=0 the pads of each finger barely touch each other. See notes at the top of this file. --> <pose>0.0105 0.029 0 0 0 0</pose> <inertial> <mass>0.05</mass> <inertia> <ixx>0.16</ixx> <ixy>0</ixy> <ixz>0</ixz> <iyy>0.16</iyy> <iyz>0</iyz> <izz>0.16</izz> </inertia> </inertial> <visual name="visual"> <pose>0 0.0 0.0 1.57 0 0</pose> <geometry> <capsule> <radius>0.01</radius> <length>0.08</length> </capsule> </geometry> <material> <diffuse>0.3 0.3 0.3 0.9</diffuse> </material> </visual> </link> <joint name="left_slider" type="prismatic"> <parent>body</parent> <child>left_finger</child> <axis> <xyz>1 0 0</xyz> </axis> <drake:controller_gains p='10000.0' d='1.0' /> </joint> <joint name="right_slider" type="prismatic"> <parent>body</parent> <child>right_finger</child> <drake:mimic joint='left_slider' multiplier='-1' offset='0.0'/> <axis> <xyz>1 0 0</xyz> <!-- Drake attaches an actuator to all joints if the effort limit isn't explicitly set to zero. We do NOT want an actuator for this joint due to the existence of the mimic tag. --> <limit> <effort>0</effort> </limit> </axis> </joint> </model> </sdf>
0
/home/johnshepherd/drake/examples/multibody/deformable
/home/johnshepherd/drake/examples/multibody/deformable/models/torus.vtk
# vtk DataFile Version 2.0 torus_fine, Created by Gmsh ASCII DATASET UNSTRUCTURED_GRID POINTS 115 double -0.129531562 -0.0380338728 -3.93402511e-09 -0.129531547 0.038033925 -3.93402511e-09 -0.11943002 -0.035067793 -0.0289254505 -0.119430006 -0.0350677893 0.028925471 -0.119430006 0.0350678414 -0.0289254505 -0.119429991 0.0350678377 0.028925471 -0.09385202080000001 -0.0275574196 -0.0443163514 -0.09385200589999999 0.0275574569 -0.0443163514 -0.093851991 -0.0275574122 0.0443163551 -0.0938519761 0.0275574494 0.0443163551 -0.0884062201 -0.102026179 -3.93402511e-09 -0.08840617539999999 0.102026224 -3.93402511e-09 -0.0815118402 -0.0940696448 -0.0289254505 -0.0815118328 -0.0940696374 0.028925471 -0.08151180299999999 0.0940696821 -0.0289254505 -0.0815117955 0.0940696746 0.028925471 -0.0647657886 -0.0190169383 -0.0389711484 -0.0647657812 0.0190169644 -0.0389711484 -0.0647657588 -0.0190169308 0.0389711335 -0.0647657514 0.0190169569 0.0389711335 -0.0640546754 -0.0739230067 -0.0443163514 -0.064054653 -0.07392298429999999 0.0443163551 -0.0640546456 0.0739230365 -0.0443163514 -0.06405462319999999 0.0739230141 0.0443163551 -0.0457810946 -0.0134425331 -0.0153909167 -0.0457810909 0.0134425517 -0.0153909167 -0.0457810871 -0.0134425303 0.0153908916 -0.0457810797 0.0134425489 0.0153908916 -0.0442031138 -0.0510130972 -0.0389711484 -0.0442030951 -0.0510130748 0.0389711335 -0.0442030951 0.0510131158 -0.0389711484 -0.0442030765 0.0510130934 0.0389711335 -0.0312459245 -0.0360597074 -0.0153909167 -0.0312459171 -0.0360597 0.0153908916 -0.0312459115 0.0360597223 -0.0153909167 -0.031245904 0.0360597149 0.0153908916 -0.0192125197 -0.133625895 -3.93402511e-09 -0.0192124639 0.13362591 -3.93402511e-09 -0.0177142266 -0.123205051 -0.0289254505 -0.0177142248 -0.123205036 0.028925471 -0.0177141745 0.123205058 -0.0289254505 -0.0177141726 0.123205043 0.028925471 -0.0139204198 -0.09681856630000001 -0.0443163514 -0.0139204152 -0.0968185365 0.0443163551 -0.0139203789 0.0968185738 -0.0443163514 -0.0139203742 0.09681854400000001 0.0443163551 -0.00960626081 -0.0668129548 -0.0389711484 -0.00960623287 0.0668129623 -0.0389711484 -0.00960622821 0.06681293250000001 0.0389711335 -0.00679039303 -0.0472281799 -0.0153909167 -0.00679039117 -0.0472281687 0.0153908916 -0.00679037301 0.0472281836 -0.0153909167 -0.00679037115 0.0472281724 0.0153908916 0.0198210385 -0.0434020273 0.0153908916 0.0198210422 -0.0434020348 -0.0153909167 0.0198210441 0.0434020236 0.0153908916 0.0198210496 0.0434020311 -0.0153909167 0.0280405022 -0.0614001453 0.0389711335 0.0280405115 0.0614001416 0.0389711335 0.0280405134 -0.0614001714 -0.0389711484 0.0280405246 0.0614001676 -0.0389711484 0.0401394218 0.0257960465 0.0153908916 0.0401394255 -0.0257960428 0.0153908916 0.040139433 -0.0257960502 -0.0153909167 0.040139433 0.0257960521 -0.0153909167 0.0406334586 -0.0889748782 0.0443163551 0.0406334698 -0.0889749005 -0.0443163514 0.0406334735 0.0889748707 0.0443163551 0.0406334847 0.0889749005 -0.0443163514 0.0477138273 1.44091752e-08 0.0153908916 0.0477138385 1.44091787e-08 -0.0153909167 0.0517075248 -0.113223702 0.028925471 0.0517075323 -0.113223717 -0.0289254505 0.0517075434 0.113223694 0.028925471 0.0517075509 0.113223709 -0.0289254505 0.0560810231 -0.122800328 -3.93402511e-09 0.0560810417 0.12280032 -3.93402511e-09 0.0567845926 0.0364932492 0.0389711335 0.0567845963 -0.0364932455 0.0389711335 0.0567846186 0.0364932641 -0.0389711484 0.0567846224 -0.0364932604 -0.0389711484 0.0674999803 2.03844266e-08 0.0389711335 0.06750001009999999 2.03844372e-08 -0.0389711484 0.08228648450000001 0.0528823249 0.0443163551 0.082286492 -0.0528823212 0.0443163551 0.0822865143 -0.0528823361 -0.0443163514 0.0822865143 0.0528823398 -0.0443163514 0.0978141427 2.95390503e-08 0.0443163551 0.0978141725 2.95390592e-08 -0.0443163514 0.104712486 0.0672946423 0.028925471 0.104712494 -0.0672946349 0.028925471 0.104712501 0.06729464979999999 -0.0289254505 0.104712509 -0.0672946423 -0.0289254505 0.113569222 0.0729865208 -3.93402511e-09 0.11356923 -0.07298651339999999 -3.93402511e-09 0.124471985 3.75894942e-08 0.028925471 0.124472 3.75894977e-08 -0.0289254505 0.135000005 4.07688674e-08 -3.93402511e-09 0.001309323762966374 -0.08202817996158156 -0.001401698167332298 -0.07994430419930573 -0.005381544591651364 -0.001060044448672946 -0.05385358959010374 0.06023333469961908 0.007105593886719179 -0.01186805483199698 0.07036530341629597 -0.00494755411376495 0.0241931399541693 0.08710703252058923 0.001885043222294985 0.0656030771348768 -0.05104244425080109 -0.00024179232534678 0.07306613931916686 0.04305121233841768 0.0002434266578320423 -0.009606257500432952 -0.0668129256145773 0.03897113275553142 0.0550633179399562 -0.07647136733632959 -0.0443163514 0.08552311858057855 -0.08402209430652588 0.02870956028666506 0.1132449877930372 0.0382356949181648 -0.0289254505 0.01765965581742358 -0.1283244814702912 -3.93402511e-09 0.08077634121586827 -0.08803545017567102 -0.0289254505 0.07852553683632962 -0.1033520462333847 -3.93402511e-09 0.07205880135292875 0.09558922604541201 0.02892547085444466 0.1228244713695885 -0.04146603989554602 -3.93402511e-09 0.1217565721643647 0.04510299133309743 -3.93402511e-09 CELLS 286 1430 4 49 98 59 54 4 79 88 104 82 4 44 101 102 40 4 55 102 58 104 4 13 43 98 21 4 36 13 98 10 4 1 5 99 100 4 65 43 98 39 4 35 34 100 101 4 34 30 100 101 4 103 69 62 78 4 59 98 103 54 4 81 87 84 113 4 10 2 0 28 4 19 8 9 99 4 2 0 28 99 4 88 113 103 92 4 11 40 100 14 4 7 2 6 99 4 51 101 56 60 4 28 49 98 46 4 29 28 33 98 4 98 103 53 57 4 105 29 33 98 4 19 9 100 99 4 21 98 28 29 4 21 29 28 8 4 22 100 30 40 4 24 99 33 26 4 52 35 100 101 4 100 48 52 101 4 24 32 33 99 4 98 42 46 66 4 11 100 41 15 4 28 46 98 42 4 25 27 34 100 4 25 100 17 99 4 48 45 101 100 4 98 38 42 66 4 33 32 28 99 4 34 35 51 101 4 35 101 52 51 4 35 27 100 34 4 43 57 98 105 4 109 75 65 71 4 57 65 98 103 4 33 50 105 98 4 51 56 101 52 4 71 65 109 39 4 58 102 48 45 4 58 48 102 55 4 62 63 70 103 4 62 103 70 69 4 100 22 17 99 4 64 69 79 104 4 70 69 103 82 4 72 98 75 110 4 73 112 102 76 4 74 76 102 104 4 76 102 104 112 4 79 104 69 82 4 78 81 103 69 4 85 80 106 103 4 87 113 95 84 4 81 113 103 69 4 87 104 113 81 4 82 88 104 69 4 92 113 103 94 4 94 103 107 90 4 94 90 113 103 4 96 97 108 113 4 28 3 99 0 4 3 28 99 8 4 28 98 10 12 4 6 16 99 28 4 8 29 28 99 4 99 100 19 27 4 10 98 28 13 4 28 13 98 21 4 28 33 99 29 4 30 101 40 100 4 98 43 13 39 4 28 49 33 98 4 32 33 28 49 4 33 49 50 98 4 105 57 98 50 4 50 53 57 98 4 52 101 48 55 4 52 55 56 101 4 109 75 98 65 4 51 60 47 101 4 101 45 48 102 4 47 102 101 60 4 53 78 103 62 4 56 60 101 55 4 48 101 102 55 4 60 55 102 101 4 98 65 75 103 4 64 104 55 61 4 64 61 69 104 4 64 104 79 55 4 61 77 104 55 4 60 86 104 79 4 77 104 58 83 4 103 78 84 81 4 61 81 104 77 4 61 69 104 81 4 103 107 90 84 4 103 90 113 84 4 84 90 113 95 4 84 103 81 113 4 103 88 82 69 4 69 104 81 113 4 86 108 91 104 4 97 113 104 108 4 1 99 5 0 4 24 32 99 16 4 25 17 100 34 4 30 22 17 100 4 31 9 23 100 4 36 12 98 38 4 37 41 100 101 4 38 42 12 98 4 47 51 101 34 4 64 79 69 70 4 71 75 65 107 4 72 38 109 98 4 74 40 102 76 4 91 93 104 108 4 92 94 103 110 4 93 104 89 76 4 94 103 110 111 4 19 99 18 8 4 11 40 37 100 4 31 100 27 19 4 77 104 55 58 4 9 100 99 5 4 99 7 17 16 4 11 14 100 1 4 21 13 8 28 4 99 17 25 24 4 26 27 99 19 4 14 100 99 22 4 14 40 100 22 4 9 23 100 15 4 99 24 25 27 4 99 29 33 26 4 26 18 99 29 4 101 34 30 47 4 9 31 19 100 4 109 98 38 36 4 39 36 98 109 4 30 44 40 101 4 45 101 100 41 4 48 45 100 23 4 62 54 103 53 4 46 49 98 59 4 54 103 53 98 4 60 104 55 79 4 63 62 54 103 4 57 78 65 103 4 103 63 80 54 4 55 56 79 64 4 46 59 98 66 4 73 67 102 112 4 73 41 102 67 4 83 112 104 102 4 74 68 102 40 4 109 72 98 75 4 106 110 98 72 4 106 72 98 66 4 68 74 102 104 4 104 88 79 86 4 63 82 103 80 4 82 88 103 80 4 88 104 113 108 4 70 103 63 82 4 83 87 81 104 4 110 85 103 92 4 88 96 113 92 4 2 12 20 28 4 2 12 28 10 4 2 28 20 6 4 100 15 5 9 4 14 1 99 100 4 15 11 100 1 4 2 99 28 6 4 99 25 100 27 4 26 24 99 27 4 42 12 98 28 4 52 35 31 100 4 31 48 52 100 4 47 44 102 68 4 102 44 40 68 4 45 102 101 41 4 40 101 102 37 4 101 41 102 37 4 76 41 102 73 4 106 98 110 103 4 98 59 103 106 4 106 59 103 80 4 68 102 60 104 4 60 102 55 104 4 75 110 98 103 4 84 107 65 103 4 75 107 103 65 4 106 85 103 110 4 83 67 102 58 4 88 69 113 104 4 95 104 89 114 4 4 0 99 1 4 7 6 16 99 4 7 4 2 99 4 16 24 17 99 4 29 18 99 8 4 18 26 99 19 4 44 40 22 30 4 28 16 99 32 4 30 34 100 17 4 27 31 35 100 4 23 100 48 31 4 47 101 102 44 4 98 43 105 21 4 41 23 100 45 4 30 44 101 47 4 50 54 98 49 4 50 54 53 98 4 80 103 54 59 4 112 67 102 83 4 104 86 60 68 4 104 68 91 86 4 111 107 103 75 4 111 75 103 110 4 58 102 83 104 4 83 104 81 77 4 70 69 82 79 4 88 103 113 69 4 76 93 104 91 4 111 94 103 107 4 88 108 113 96 4 10 3 28 0 4 0 2 4 99 4 14 99 1 4 4 14 4 7 99 4 15 5 1 100 4 3 8 99 9 4 22 99 14 7 4 22 17 99 7 4 15 100 41 23 4 11 100 37 41 4 12 36 98 10 4 36 98 13 39 4 20 28 12 42 4 29 21 98 105 4 37 100 40 101 4 39 65 109 98 4 65 43 57 98 4 68 47 60 102 4 58 67 102 45 4 67 41 102 45 4 76 37 40 102 4 37 41 102 76 4 106 66 98 59 4 57 103 53 78 4 65 103 78 84 4 85 88 80 103 4 88 92 103 85 4 86 108 104 88 4 89 83 112 104 4 112 76 89 104 4 95 113 104 97 4 95 104 114 97 4 95 104 83 89 4 87 104 83 95 4 87 95 113 104 4 114 104 108 97 4 93 104 108 114 4 93 89 104 114 4 3 5 99 0 4 3 9 99 5 4 98 72 38 66 4 8 13 3 28 4 13 28 10 3 4 79 60 56 55 4 74 104 68 91 4 74 76 104 91 CELL_TYPES 286 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
0
/home/johnshepherd/drake/examples/multibody/deformable
/home/johnshepherd/drake/examples/multibody/deformable/test/point_source_force_field_test.cc
#include "drake/examples/multibody/deformable/point_source_force_field.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace examples { namespace deformable { namespace { using drake::math::RigidTransformd; using drake::math::RollPitchYawd; using drake::multibody::MultibodyPlant; using drake::multibody::RigidBody; using drake::multibody::SpatialInertia; using drake::systems::Context; using Eigen::Vector3d; GTEST_TEST(PointSourceForceFieldTest, EvaluateAt) { MultibodyPlant<double> plant(0.01); const RigidBody<double>& box = plant.AddRigidBody( "box", SpatialInertia<double>::SolidCubeWithMass(1.0, 0.1)); /* The fixed offset from the body origin B to the point source of the force field C. */ const Vector3d p_BC(0, 0, 0.123); const double max_distance = 0.2; PointSourceForceField force_field(plant, box, p_BC, max_distance); force_field.DeclareSystemResources(&plant); plant.Finalize(); auto context = plant.CreateDefaultContext(); const RigidTransformd X_WB(RollPitchYawd(1, 2, 3), Vector3d(3, 4, 5)); plant.SetFreeBodyPose(context.get(), box, X_WB); const double max_force_density = 42.0; /* Turn the force on. */ force_field.maximum_force_density_input_port().FixValue(context.get(), max_force_density); const Vector3d p_WC = X_WB * p_BC; /* Inside the non-zero range. */ const Vector3d p_CQ1_W = Vector3d(0, 0, 0.1); const Vector3d p_WQ1 = p_WC + p_CQ1_W; Vector3d expected_force = -0.1 / max_distance * max_force_density * p_CQ1_W.normalized(); EXPECT_TRUE(CompareMatrices(force_field.EvaluateAt(*context, p_WQ1), expected_force, 1e-13)); /* Outside the non-zero range. */ const Vector3d p_CQ2_W = Vector3d(0, 0, 0.3); const Vector3d p_WQ2 = p_WC + p_CQ2_W; EXPECT_TRUE(CompareMatrices(force_field.EvaluateAt(*context, p_WQ2), Vector3d::Zero())); /* Turn the force off. */ force_field.maximum_force_density_input_port().FixValue(context.get(), 0.0); EXPECT_TRUE(CompareMatrices(force_field.EvaluateAt(*context, p_WQ1), Vector3d::Zero())); } } // namespace } // namespace deformable } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/rolling_sphere/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", ) package(default_visibility = ["//visibility:private"]) drake_cc_library( name = "populate_ball_plant", srcs = [ "populate_ball_plant.cc", ], hdrs = [ "populate_ball_plant.h", ], visibility = ["//multibody/plant:__pkg__"], deps = [ "//common:default_scalars", "//geometry:geometry_ids", "//geometry:scene_graph", "//math:geometric_transform", "//multibody/plant", ], ) drake_cc_binary( name = "rolling_sphere_run_dynamics", srcs = ["rolling_sphere_run_dynamics.cc"], add_test_rule = 1, test_rule_args = [ "--simulation_time=0.1", "--simulator_target_realtime_rate=0.0", ], deps = [ ":populate_ball_plant", "//common:add_text_logging_gflags", "//lcm", "//multibody/plant:contact_results_to_lcm", "//systems/analysis:simulator", "//systems/analysis:simulator_gflags", "//systems/analysis:simulator_print_stats", "//systems/framework:diagram", "//visualization", "@gflags", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/rolling_sphere/populate_ball_plant.h
#pragma once #include <memory> #include "drake/geometry/scene_graph.h" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace examples { namespace multibody { namespace bouncing_ball { /// This function populates the given MultibodyPlant with a model of a ball /// falling onto a plane. /// MultibodyPlant models the contact of the ball with the ground as a perfectly /// inelastic collision (zero coefficient of restitution), i.e. energy is lost /// due to the collision. /// /// The hydroelastic compliance type of the ground and ball can be independently /// configured. Not every compliance configuration is compatible with every /// contact model; contact between strict hydroelastic contact will fail for /// two contacting objects with the same compliance type. So, it is important to /// use the resulting plant with a contact model consistent with the /// configuration of the ball and ground. /// /// @param[in] radius /// The radius of the ball. /// @param[in] mass /// The mass of the ball. /// @param[in] hydroelastic_modulus /// The modulus of elasticity for the ball. Only used when modeled with the /// hydroelastic model. See @ref mbp_hydroelastic_materials_properties /// "Hydroelastic contact" documentation for details. /// @param[in] dissipation /// The Hunt & Crossley dissipation constant for the ball. Only used with the /// hydroelastic model. See @ref mbp_hydroelastic_materials_properties /// "Hydroelastic contact" documentation for details. /// @param[in] surface_friction /// The Coulomb's law coefficients of friction. /// @param[in] gravity_W /// The acceleration of gravity vector, expressed in the world frame W. /// @param[in] rigid_sphere /// If `true`, the sphere will have a _rigid_ hydroelastic representation /// (soft otherwise). /// @param[in] compliant_ground /// If 'true', the ground will have a _soft_ hydroelastic representation /// (rigid otherwise). /// @param[in,out] plant /// A valid pointer to a MultibodyPlant. This function will register /// geometry for contact modeling. /// @pre `plant` is not null, unfinalized, and is registered with a SceneGraph. /// @note The given plant is not finalized. You must call Finalize() on the new /// model once you are done populating it. void PopulateBallPlant( double radius, double mass, double hydroelastic_modulus, double dissipation, const drake::multibody::CoulombFriction<double>& surface_friction, const Vector3<double>& gravity_W, bool rigid_sphere, bool compliant_ground, drake::multibody::MultibodyPlant<double>* plant); } // namespace bouncing_ball } // namespace multibody } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/rolling_sphere/populate_ball_plant.cc
#include "drake/examples/multibody/rolling_sphere/populate_ball_plant.h" #include <utility> #include "drake/geometry/proximity_properties.h" #include "drake/multibody/tree/uniform_gravity_field_element.h" namespace drake { namespace examples { namespace multibody { namespace bouncing_ball { using drake::geometry::AddContactMaterial; using drake::geometry::AddRigidHydroelasticProperties; using drake::geometry::AddCompliantHydroelasticProperties; using drake::geometry::AddCompliantHydroelasticPropertiesForHalfSpace; using drake::geometry::ProximityProperties; using drake::geometry::Sphere; using drake::multibody::CoulombFriction; using drake::multibody::MultibodyPlant; using drake::multibody::RigidBody; using drake::multibody::SpatialInertia; using drake::multibody::UnitInertia; using drake::math::RigidTransformd; void PopulateBallPlant( double radius, double mass, double hydroelastic_modulus, double dissipation, const CoulombFriction<double>& surface_friction, const Vector3<double>& gravity_W, bool rigid_sphere, bool compliant_ground, MultibodyPlant<double>* plant) { SpatialInertia<double> M_BBcm = SpatialInertia<double>::SolidSphereWithMass(mass, radius); const RigidBody<double>& ball = plant->AddRigidBody("Ball", M_BBcm); const RigidTransformd X_WG; // identity. ProximityProperties ground_props; if (compliant_ground) { AddCompliantHydroelasticPropertiesForHalfSpace(1.0, hydroelastic_modulus, &ground_props); } else { AddRigidHydroelasticProperties(&ground_props); } AddContactMaterial(dissipation, {} /* point stiffness */, surface_friction, &ground_props); plant->RegisterCollisionGeometry(plant->world_body(), X_WG, geometry::HalfSpace{}, "collision", std::move(ground_props)); // Add visual for the ground. plant->RegisterVisualGeometry(plant->world_body(), X_WG, geometry::HalfSpace{}, "visual"); // Add sphere geometry for the ball. // Pose of sphere geometry S in body frame B. const RigidTransformd X_BS = RigidTransformd::Identity(); // Set material properties for hydroelastics. ProximityProperties ball_props; AddContactMaterial(dissipation, {} /* point stiffness */, surface_friction, &ball_props); if (rigid_sphere) { AddRigidHydroelasticProperties(radius, &ball_props); } else { AddCompliantHydroelasticProperties(radius, hydroelastic_modulus, &ball_props); } plant->RegisterCollisionGeometry(ball, X_BS, Sphere(radius), "collision", std::move(ball_props)); // Add visual for the ball. const Vector4<double> orange(1.0, 0.55, 0.0, 1.0); plant->RegisterVisualGeometry(ball, X_BS, Sphere(radius), "visual", orange); // We add a few purple spots so that we can appreciate the sphere's // rotation. const Vector4<double> red(1.0, 0.0, 0.0, 1.0); const Vector4<double> green(0.0, 1.0, 0.0, 1.0); const Vector4<double> blue(0.0, 0.0, 1.0, 1.0); const double visual_radius = 0.2 * radius; const geometry::Cylinder spot(visual_radius, visual_radius); // N.B. We do not place the cylinder's cap exactly on the sphere surface to // avoid visualization artifacts when the surfaces are kissing. const double radial_offset = radius - 0.45 * visual_radius; auto spot_pose = [](const Vector3<double>& position) { // The cylinder's z-axis is defined as the normalized vector from the // sphere's origin to the cylinder's center `position`. const Vector3<double> axis = position.normalized(); return RigidTransformd( Eigen::Quaterniond::FromTwoVectors(Vector3<double>::UnitZ(), axis), position); }; plant->RegisterVisualGeometry(ball, spot_pose({radial_offset, 0., 0.}), spot, "sphere_x+", red); plant->RegisterVisualGeometry(ball, spot_pose({-radial_offset, 0., 0.}), spot, "sphere_x-", red); plant->RegisterVisualGeometry(ball, spot_pose({0., radial_offset, 0.}), spot, "sphere_y+", green); plant->RegisterVisualGeometry(ball, spot_pose({0., -radial_offset, 0.}), spot, "sphere_y-", green); plant->RegisterVisualGeometry(ball, spot_pose({0., 0., radial_offset}), spot, "sphere_z+", blue); plant->RegisterVisualGeometry(ball, spot_pose({0., 0., -radial_offset}), spot, "sphere_z-", blue); // Gravity acting in the -z direction. plant->mutable_gravity_field().set_gravity_vector(gravity_W); } } // namespace bouncing_ball } // namespace multibody } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/rolling_sphere/rolling_sphere_run_dynamics.cc
#include <chrono> #include <memory> #include <gflags/gflags.h> #include "drake/common/drake_assert.h" #include "drake/examples/multibody/rolling_sphere/populate_ball_plant.h" #include "drake/geometry/geometry_instance.h" #include "drake/geometry/proximity_properties.h" #include "drake/geometry/scene_graph.h" #include "drake/lcm/drake_lcm.h" #include "drake/math/random_rotation.h" #include "drake/multibody/math/spatial_algebra.h" #include "drake/multibody/plant/contact_results_to_lcm.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/analysis/simulator_gflags.h" #include "drake/systems/analysis/simulator_print_stats.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/visualization/visualization_config_functions.h" // Integration parameters. DEFINE_double(simulation_time, 2.0, "Desired duration of the simulation in seconds."); // Contact model parameters. DEFINE_string(contact_model, "point", "Contact model. Options are: 'point', 'hydroelastic', 'hybrid'."); DEFINE_string(hydro_rep, "tri", "Contact-surface representation for hydroelastics. " "Options are: 'tri' for triangles, 'poly' for polygons. " "Default is 'tri'. It has no effect on point contact."); DEFINE_double(hydroelastic_modulus, 5.0e4, "For hydroelastic (and hybrid) contact, " "hydroelastic modulus, [Pa]."); DEFINE_double(dissipation, 5.0, "For hydroelastic (and hybrid) contact, Hunt & Crossley " "dissipation, [s/m]."); DEFINE_double(friction_coefficient, 0.3, "friction coefficient."); DEFINE_bool(rigid_ball, false, "If true, the ball is given a rigid hydroelastic representation " "(instead of being compliant by the default). Make sure " "you have the right contact model to support this representation."); DEFINE_bool( compliant_ground, false, "If true, the ground is given a compliant hydroelastic representation " "(instead of the default rigid value). Make sure you have the " "right contact model to support this representation."); DEFINE_bool(add_wall, false, "If true, adds a wall with compliant hydroelastic representation " "in the path of the default ball trajectory. This will cause the " "simulation to throw when the compliant ball hits the wall with " "the 'hydroelastic' model; use the 'hybrid' or 'point' contact" " model to simulate beyond this contact."); DEFINE_double( mbp_dt, 0.0, "The fixed time step period (in seconds) of discrete updates for the " "multibody plant modeled as a discrete system. Strictly positive. " "Set to zero for a continuous plant model."); DEFINE_bool(visualize, true, "If true, the simulation will publish messages for Drake " "visualizer. Useful to turn off during profiling sessions."); // Sphere's spatial velocity. DEFINE_double(vx, 1.5, "Sphere's initial translational velocity in the x-axis in m/s."); DEFINE_double(vy, 0.0, "Sphere's initial translational velocity in the y-axis in m/s."); DEFINE_double(vz, 0.0, "Sphere's initial translational velocity in the z-axis in m/s."); DEFINE_double(wx, 0.0, "Sphere's initial angular velocity in the y-axis in degrees/s."); DEFINE_double(wy, -360.0, "Sphere's initial angular velocity in the y-axis in degrees/s."); DEFINE_double(wz, 0.0, "Sphere's initial angular velocity in the y-axis in degrees/s."); // Sphere's pose. DEFINE_double(roll, 0.0, "Sphere's initial roll in degrees."); DEFINE_double(pitch, 0.0, "Sphere's initial pitch in degrees."); DEFINE_double(yaw, 0.0, "Sphere's initial yaw in degrees."); DEFINE_double(z0, 0.05, "Sphere's initial position in the z-axis."); namespace drake { namespace examples { namespace multibody { namespace bouncing_ball { namespace { using Eigen::AngleAxisd; using Eigen::Matrix3d; using Eigen::Vector3d; using Eigen::Vector4d; using drake::geometry::SceneGraph; using drake::geometry::SourceId; using drake::lcm::DrakeLcm; using drake::math::RigidTransformd; using drake::multibody::AddMultibodyPlantSceneGraph; using drake::multibody::ContactModel; using drake::multibody::CoulombFriction; using drake::multibody::SpatialVelocity; int do_main() { systems::DiagramBuilder<double> builder; auto [plant, scene_graph] = AddMultibodyPlantSceneGraph(&builder, FLAGS_mbp_dt); // Plant's parameters. const double radius = 0.05; // m const double mass = 0.1; // kg const double g = 9.81; // m/s^2 const double z0 = FLAGS_z0; // Initial height. const CoulombFriction<double> coulomb_friction( FLAGS_friction_coefficient /* static friction */, FLAGS_friction_coefficient /* dynamic friction */); PopulateBallPlant(radius, mass, FLAGS_hydroelastic_modulus, FLAGS_dissipation, coulomb_friction, -g * Vector3d::UnitZ(), FLAGS_rigid_ball, FLAGS_compliant_ground, &plant); if (FLAGS_add_wall) { geometry::Box wall{0.2, 4, 0.4}; const RigidTransformd X_WB(Vector3d{-0.5, 0, 0}); geometry::ProximityProperties prox_prop; geometry::AddContactMaterial({} /* dissipation */, {} /* point stiffness */, CoulombFriction<double>(), &prox_prop); geometry::AddCompliantHydroelasticProperties(0.1, 1e8, &prox_prop); plant.RegisterCollisionGeometry(plant.world_body(), X_WB, wall, "wall_collision", std::move(prox_prop)); geometry::IllustrationProperties illus_prop; illus_prop.AddProperty("phong", "diffuse", Vector4d(0.7, 0.5, 0.4, 0.5)); plant.RegisterVisualGeometry(plant.world_body(), X_WB, wall, "wall_visual", std::move(illus_prop)); } if (FLAGS_hydro_rep == "tri") { plant.set_contact_surface_representation( geometry::HydroelasticContactRepresentation::kTriangle); } else if (FLAGS_hydro_rep == "poly") { plant.set_contact_surface_representation( geometry::HydroelasticContactRepresentation::kPolygon); } else { throw std::runtime_error("Invalid choice of contact-surface representation " "for hydroelastics '" + FLAGS_hydro_rep + "'."); } // Set contact model and parameters. if (FLAGS_contact_model == "hydroelastic") { plant.set_contact_model(ContactModel::kHydroelastic); plant.Finalize(); } else if (FLAGS_contact_model == "point") { // Plant must be finalized before setting the penetration allowance. plant.Finalize(); // Set how much penetration (in meters) we are willing to accept. plant.set_penetration_allowance(0.001); } else if (FLAGS_contact_model == "hybrid") { plant.set_contact_model(ContactModel::kHydroelasticWithFallback); plant.Finalize(); plant.set_penetration_allowance(0.001); } else { throw std::runtime_error("Invalid contact model '" + FLAGS_contact_model + "'."); } DRAKE_DEMAND(plant.num_velocities() == 6); DRAKE_DEMAND(plant.num_positions() == 7); // Provide visualization. if (FLAGS_visualize) { visualization::AddDefaultVisualization(&builder); } auto diagram = builder.Build(); // Create a context for this system: std::unique_ptr<systems::Context<double>> diagram_context = diagram->CreateDefaultContext(); systems::Context<double>& plant_context = diagram->GetMutableSubsystemContext(plant, diagram_context.get()); // Set the sphere's initial pose. math::RotationMatrixd R_WB(math::RollPitchYawd( M_PI / 180.0 * Vector3<double>(FLAGS_roll, FLAGS_pitch, FLAGS_yaw))); math::RigidTransformd X_WB(R_WB, Vector3d(0.0, 0.0, z0)); plant.SetFreeBodyPose( &plant_context, plant.GetBodyByName("Ball"), X_WB); const SpatialVelocity<double> V_WB(Vector3d(FLAGS_wx, FLAGS_wy, FLAGS_wz), Vector3d(FLAGS_vx, FLAGS_vy, FLAGS_vz)); plant.SetFreeBodySpatialVelocity( &plant_context, plant.GetBodyByName("Ball"), V_WB); auto simulator = MakeSimulatorFromGflags(*diagram, std::move(diagram_context)); using clock = std::chrono::steady_clock; const clock::time_point start = clock::now(); simulator->AdvanceTo(FLAGS_simulation_time); const clock::time_point end = clock::now(); const double wall_clock_time = std::chrono::duration<double>(end - start).count(); fmt::print("Simulator::AdvanceTo() wall clock time: {:.4g} seconds.\n", wall_clock_time); systems::PrintSimulatorStatistics(*simulator); return 0; } } // namespace } // namespace bouncing_ball } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A rolling sphere demo using Drake's MultibodyPlant, " "with SceneGraph visualization. This demo allows to switch between " "different contact models and integrators to evaluate performance." "Launch meldis before running this example."); // We slow down the default realtime rate to 0.2, so that we can appreciate // the motion. Users can still change it on command-line, e.g. // --simulator_target_realtime_rate=0.5. FLAGS_simulator_target_realtime_rate = 0.2; // Simulator default parameters for this demo. FLAGS_simulator_accuracy = 1.0e-3; FLAGS_simulator_max_time_step = 1.0e-3; gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::bouncing_ball::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/rolling_sphere/README.md
# Rolling Sphere Example This directory contains an example for illustrating the difference between contact models. It consists of a rolling sphere on a horizontal ground surface. ``` <─── ωy ooooooo o o o vx o o ──> o o o o o ooooooo ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Ground ``` __Figure 1, Default configuration:__ The example creates a sphere with initial translational velocity in the +Wx direction and an angular velocity around the -Wy axis (illustrated by the two vectors labeled with the application's corresponding parameters vx and ωy, respectively). The ball will begin sliding in the +Wx direction but eventually friction will cause the ball to slow and then accelerate in the -Wx direction. Both the ground and the sphere can be modeled as being compliant or rigid in the hydroelastic model. However, choice of compliance type (more particularly contact between objects of particular compliance) will constrain your choice of contact model. See details below. __Contact models__ There are three contact models that can be exercised (via the `--contact_model` parameter). They differ in how they model the contact between two penetrating objects: - "point": modeled as a point pair. The compliance type of the objects do not matter; contact will always be reported and resolved. - "hydroelastic": modeled as a contact surface (where supported). If contact between a pair of objects is detected, but hydroelastic cannot evaluate a contact surface between them, the simulation will throw. See below for circumstances under which a contact surface cannot be computed. - "hybrid": modeled as a contact surface where possible, and as a point. pair otherwise. More formally known as "hydroelastic callback with fallback". The "hydroelastic" model doesn't support all combinations of geometries and compliance types. There are some types of geometries that cannot yet be given a hydroelastic representation and some types of contact which aren't modeled yet. - Contact between a rigid shape and compliant shape is supported. - Contact between two rigid or two compliant objects isn't supported. - Drake `Mesh` shapes can only be modeled with _rigid_ hydroelastic representation. __Solvers__ When the system is modeled as continuous, the multibody system's dynamics is described by an ODE of the form `ẋ = f(t,x)`. Drake's simulator then uses error-controlled integration to advance this dynamics forward in time. When the system is modeled as discrete, the multibody system's dynamics is described by an algebraic equation of the form `x[n+1] = f(t[n],x[n])`. This algebraic relation involves a complex computation performed by Drake's contact solver which solves the system's dynamics subject to contact constraints. This example allows us to choose between a continuous or discrete modeling of the system's dynamics for both point and hydroelastic contact. To enable the discrete model using an update period of one millisecond, supply the additional command line flag `--mbp_dt=1.0e-3`. The continuous approximation is the default (with `--mbp_dt=0`). __Changing the configuration__ This example allows you to experiment with the contact models by changing the configuration in various ways: - Add in an optional compliant wall (as shown below). When using "hybrid" or "hydroelastic" contact models, the wall will have a _soft_ hydroelastic representation. - Change the compliance type of the sphere from compliant (default) to rigid for the "hybrid" and "hydroelastic" models. - Change the compliance type of the ground from rigid (default) to compliant for the "hybrid" and "hydroelastic" models. ``` ▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒ w ▒▒▒▒▒ Wz a ▒▒▒▒▒ <─── ωy l ▒▒▒▒▒ ooooooo │ Wy l ▒▒▒▒▒ o o │ ╱ ▒▒▒▒▒ o vx o │ ╱ ▒▒▒▒▒ o ──> o │╱ ▒▒▒▒▒ o o └─────── Wx ▒▒▒▒▒ o o ▒▒▒▒▒ ooooooo ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Ground ``` __Figure 2, Adding the wall__: by adding the wall, the ball will initially behave as described in __Figure 1__ but eventually hit the wall. The following table enumerates some configuration options and the simulation outcome. Default values are indicated as "(d)". | Ground | Compliant Wall | Sphere | Contact Model | Note | | --------- | ---------------- | ------------- | ------------- | ---------------------------------- | | rigid (d) | no (d) | compliant (d) | point (d) | Behavior as described in Figure 1 - point pairs visualized | | rigid (d) | no (d) | compliant (d) | hydroelastic | Behavior as described in Figure 1 - contact surfaces visualized | | rigid (d) | no (d) | compliant (d) | hybrid | Same as "hydroelastic" | | rigid (d) | no (d) | rigid | point (d) | Behavior as described in Figure 1 - the sphere's rigid declaration is meaningless for point contact and ignored | | rigid (d) | no (d) | rigid | hydroelastic | Throws _immediate_ exception -- cannot support rigid-rigid contact surface between ground and sphere | | rigid (d) | no (d) | rigid | hybrid | Behavior as described in Figure 1 - rigid-rigid contact (between sphere and ground) uses point-pair contact | | rigid (d) | yes | compliant (d) | point (d) | Behavior as described in Figure 2 - point pairs visualized | | rigid (d) | yes | compliant (d) | hydroelastic | Behavior as described in Figure 2 - Throws exception when sphere hits wall; cannot support compliant-compliant contact | | rigid (d) | yes | compliant (d) | hybrid | Behavior as described in Figure 2 - sphere-ground contact is contact surface, sphere-wall contact is point pair | | rigid (d) | yes | rigid | hybrid | Behavior as described in Figure 2 - sphere-ground contact is point pair, sphere-wall contact is contact surface | | compliant | either | compliant (d) | point/hybrid | Compliant-compliant contact requires "hybrid" or "point" -- crashes with "hydroelastic" | | compliant | either | rigid | any | Behavior as described in Figure 2 - contact visualized depends on model | ## Prerequisites All instructions assume that you are launching from the `drake` workspace directory. ``` cd drake ``` ## Visualizer Before running the example, launch the visualizer: ``` bazel run //tools:meldis -- --open-window & ``` ## Example Various incarnations of the example combining the parameters in ways to illustrate the differences that contact model and hydroelastic representation can make. ##### Default behavior The command below runs the default configuration using a continuous modeling of the dynamics. ``` bazel run //examples/multibody/rolling_sphere:rolling_sphere_run_dynamics ``` ##### Default behavior, discrete solver Run the same configuration as above, but this time using a discrete approximation of the dynamics with an update period of one millisecond. ``` bazel run //examples/multibody/rolling_sphere:rolling_sphere_run_dynamics -- --mbp_dt=1.0e-3 ``` The discrete solver supports all other configurations below, including hybrid contact. ##### Default behavior with hydroelastic contact with default compliance type; rigid ground, compliant ball ``` bazel run //examples/multibody/rolling_sphere:rolling_sphere_run_dynamics -- --contact_model=hydroelastic ``` ##### Default behavior with hydroelastic contact with reversed compliance; compliant ground, rigid ball ``` bazel run //examples/multibody/rolling_sphere:rolling_sphere_run_dynamics -- --contact_model=hydroelastic --rigid_ball=1 --soft_ground=1 ``` ##### Default behavior with hybrid contact ``` bazel run //examples/multibody/rolling_sphere:rolling_sphere_run_dynamics -- --contact_model=hybrid ``` ##### Add the wall with hydroelastic contact -- throw when sphere hits the wall ``` bazel run //examples/multibody/rolling_sphere:rolling_sphere_run_dynamics -- --contact_model=hydroelastic --add_wall=1 ``` ##### Add the wall with hybrid contact ``` bazel run //examples/multibody/rolling_sphere:rolling_sphere_run_dynamics -- --contact_model=hybrid --add_wall=1 ``` ##### Add the wall, make the sphere rigid with hybrid contact ``` bazel run //examples/multibody/rolling_sphere:rolling_sphere_run_dynamics -- --contact_model=hybrid --add_wall=1 --rigid_ball=1 ```
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/inclined_plane_with_body/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", ) package(default_visibility = ["//visibility:private"]) drake_cc_binary( name = "inclined_plane_with_body", srcs = [ "inclined_plane_with_body.cc", ], add_test_rule = 1, test_rule_args = [ "--simulation_time=0.1", "--target_realtime_rate=0.0", ], deps = [ "//common:add_text_logging_gflags", "//lcm", "//multibody/benchmarks/inclined_plane", "//multibody/plant:contact_results_to_lcm", "//systems/analysis:simulator", "//systems/framework:diagram", "//visualization", "@gflags", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/inclined_plane_with_body/README.md
## Simulate motion of a body (e.g., sphere or block) on an inclined plane. ### Description This example simulates the motion of a rigid body B (e.g., a sphere or a block) on an inclined plane A. You can simulate a uniform-density sphere B rolling down an inclined plane A or simulate a block B that contacts an inclined plane A (first possibly dropping/colliding with A and then slipping and/or sticking). The inclined plane can be modeled as either an infinite half-space or as a finite box (if a finite box, the block can fall off the inclined plane). 1. A coefficient of friction is assigned separately to each object (a default value is assigned or you may assign a value via command-line arguments). Thereafter, a "combining equation" calculates the coefficient of friction by combining the coefficients of friction assigned to each object. 2. When time_step > 0 (fixed-time step), the coefficient of kinetic friction is ignored. Only the coefficient of static friction is used. 3. More information on the friction model being used is in [coulomb_friction.h](https://drake.mit.edu/doxygen_cxx/classdrake_1_1multibody_1_1_coulomb_friction.html). ### Building and running this example Open a terminal in the `drake` workspace, and type commands as shown below. Run the example like so: ``` bazel run //tools:meldis -- --open-window & bazel run //examples/multibody/inclined_plane_with_body:inclined_plane_with_body ``` Alternatively, to simulate body B as a block that has 4 contacting spheres welded to its lowest four corners on a 30 degree inclined plane A (modeled as a half-space), pass command line arguments to the executable by typing: ``` bazel run //examples/multibody/inclined_plane_with_body:inclined_plane_with_body -- -inclined_plane_angle_degrees=30 -bodyB_type=block_with_4Spheres ``` To see a list of all possible command-line arguments: ``` bazel run //examples/multibody/inclined_plane_with_body:inclined_plane_with_body -- -help ```
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/inclined_plane_with_body/inclined_plane_with_body.cc
#include <iostream> #include <memory> #include <gflags/gflags.h> #include "drake/geometry/scene_graph.h" #include "drake/lcm/drake_lcm.h" #include "drake/multibody/benchmarks/inclined_plane/inclined_plane_plant.h" #include "drake/multibody/plant/contact_results_to_lcm.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/visualization/visualization_config_functions.h" namespace drake { namespace multibody { namespace examples { namespace inclined_plane_with_body { namespace { // This simulates the motion of a rigid body B (e.g., a sphere or a block) on an // inclined plane A (which may be an infinite half-space or a finite box). // TODO(Mitiguy) Consider an option to configure body B to be in contact with // inclined plane A, or allow for user-defined initial configuration/motion. // // Information on how to build, run, and visualize this example and how to use // command-line arguments is in the accompanying file README.md. DEFINE_double(target_realtime_rate, 1.0, "Desired rate relative to real time (usually between 0 and 1). " "This is documented in Simulator::set_target_realtime_rate()."); DEFINE_double(simulation_time, 2.0, "Simulation duration in seconds"); DEFINE_double(time_step, 1.0E-3, "If time_step > 0, the fixed-time step period (in seconds) of " "discrete updates for the plant (modeled as a discrete system). " "If time_step = 0, the plant is modeled as a continuous system " "and no contact forces are displayed. time_step must be >= 0."); DEFINE_double(integration_accuracy, 1.0E-6, "When time_step = 0 (plant is modeled as a continuous system), " "this is the desired integration accuracy. This value is not " "used if time_step > 0 (fixed-time step)."); DEFINE_double(penetration_allowance, 1.0E-5, "Allowable penetration (meters)."); DEFINE_double(stiction_tolerance, 1.0E-5, "Allowable drift speed during stiction (m/s)."); DEFINE_double(inclined_plane_angle_degrees, 15.0, "Inclined plane angle (degrees), i.e., angle from Wx to Ax."); DEFINE_double(inclined_plane_coef_static_friction, 0.3, "Inclined plane's coefficient of static friction (no units)."); DEFINE_double(inclined_plane_coef_kinetic_friction, 0.3, "Inclined plane's coefficient of kinetic friction (no units). " "When time_step > 0, this value is ignored. Only the " "coefficient of static friction is used in fixed-time step."); DEFINE_double(bodyB_coef_static_friction, 0.3, "Body B's coefficient of static friction (no units)."); DEFINE_double(bodyB_coef_kinetic_friction, 0.3, "Body B's coefficient of kinetic friction (no units). " "When time_step > 0, this value is ignored. Only the " "coefficient of static friction is used in fixed-time step."); DEFINE_bool(is_inclined_plane_half_space, true, "Is inclined plane a half-space (true) or box (false)."); DEFINE_string(bodyB_type, "sphere", "Valid body types are " "'sphere', 'block', or 'block_with_4Spheres'"); DEFINE_string(contact_approximation, "tamsi", "Discrete contact approximation. Options are: 'tamsi', " "'sap', 'similar', 'lagged'"); using drake::multibody::MultibodyPlant; int do_main() { // Build a generic multibody plant. systems::DiagramBuilder<double> builder; MultibodyPlantConfig plant_config; plant_config.time_step = FLAGS_time_step; plant_config.stiction_tolerance = FLAGS_stiction_tolerance; plant_config.discrete_contact_approximation = FLAGS_contact_approximation; auto [plant, scene_graph] = multibody::AddMultibodyPlant(plant_config, &builder); // Set constants that are relevant whether body B is a sphere or block. const double massB = 0.1; // Body B's mass (kg). const double gravity = 9.8; // Earth's gravitational acceleration (m/s^2). const double inclined_plane_angle = FLAGS_inclined_plane_angle_degrees / 180 * M_PI; // Information on how coefficients of friction are used in the file README.md // (which is in the folder associated with this example). const drake::multibody::CoulombFriction<double> coef_friction_bodyB( FLAGS_bodyB_coef_static_friction, FLAGS_bodyB_coef_kinetic_friction); const drake::multibody::CoulombFriction<double> coef_friction_inclined_plane( FLAGS_inclined_plane_coef_static_friction, FLAGS_inclined_plane_coef_kinetic_friction); if (FLAGS_bodyB_type == "sphere") { const double radiusB = 0.04; // B's radius when modeled as a sphere. const double LAx = 20 * radiusB; // Inclined plane length in Ax direction. const double LAy = 10 * radiusB; // Inclined plane length in Ay direction. const double LAz = radiusB; // Inclined plane length in Az direction. const Vector3<double> LAxyz(LAx, LAy, LAz); const std::optional<Vector3<double>> inclined_plane_dimensions = FLAGS_is_inclined_plane_half_space ? std::nullopt : std::optional<Vector3<double>>(LAxyz); benchmarks::inclined_plane::AddInclinedPlaneWithSphereToPlant( gravity, inclined_plane_angle, inclined_plane_dimensions, coef_friction_inclined_plane, coef_friction_bodyB, massB, radiusB, &plant); } else if (FLAGS_bodyB_type == "block" || FLAGS_bodyB_type == "block_with_4Spheres") { // B's contacting surface can be modeled with 4 spheres or a single box. const bool is_bodyB_block_with_4Spheres = (FLAGS_bodyB_type == "block_with_4Spheres"); const double LBx = 0.4; // Block B's length in Bx-direction (meters). const double LBy = 0.2; // Block B's length in By-direction (meters). const double LBz = 0.04; // Block B's length in Bz-direction (meters). const double LAx = 8 * LBx; // Inclined plane A's length in Ax direction. const double LAy = 8 * LBy; // Inclined plane A's length in Ay direction. const double LAz = 0.04; // Inclined plane A's length in Az direction. const Vector3<double> block_dimensions(LBx, LBy, LBz); const Vector3<double> LAxyz(LAx, LAy, LAz); const std::optional<Vector3<double>> inclined_plane_dimensions = FLAGS_is_inclined_plane_half_space ? std::nullopt : std::optional<Vector3<double>>(LAxyz); benchmarks::inclined_plane::AddInclinedPlaneWithBlockToPlant( gravity, inclined_plane_angle, inclined_plane_dimensions, coef_friction_inclined_plane, coef_friction_bodyB, massB, block_dimensions, is_bodyB_block_with_4Spheres, &plant); } else { std::cerr << "Invalid body_type '" << FLAGS_bodyB_type << "' (note that types are case sensitive)." << std::endl; return -1; } plant.Finalize(); plant.set_penetration_allowance(FLAGS_penetration_allowance); // Set the speed tolerance (m/s) for the underlying Stribeck friction model // (the allowable drift speed during stiction). For two points in contact, // this is the maximum sliding speed for the points to be regarded as // stationary relative to each other (so that static friction is used). plant.set_stiction_tolerance(FLAGS_stiction_tolerance); // Do a reality check that body B is a free-flying rigid body. DRAKE_DEMAND(plant.num_velocities() == 6); DRAKE_DEMAND(plant.num_positions() == 7); // Provide visualization. visualization::AddDefaultVisualization(&builder); auto diagram = builder.Build(); // Create a context for this system: std::unique_ptr<systems::Context<double>> diagram_context = diagram->CreateDefaultContext(); diagram->SetDefaultContext(diagram_context.get()); systems::Context<double>& plant_context = diagram->GetMutableSubsystemContext(plant, diagram_context.get()); // In the plant's default context, we assume the state of body B in world W is // such that X_WB is an identity transform and B's spatial velocity is zero. plant.SetDefaultContext(&plant_context); // Overwrite B's default initial position so it is somewhere above the // inclined plane provided `0 < inclined_plane_angle < 40`. const drake::multibody::RigidBody<double>& bodyB = plant.GetBodyByName("BodyB"); const Vector3<double> p_WoBo_W(-1.0, 0, 1.2); const math::RigidTransform<double> X_WB(p_WoBo_W); plant.SetFreeBodyPoseInWorldFrame(&plant_context, bodyB, X_WB); systems::Simulator<double> simulator(*diagram, std::move(diagram_context)); systems::IntegratorBase<double>& integrator = simulator.get_mutable_integrator(); // Set the integration accuracy when the plant is integrated with a variable- // step integrator. This value is not used if time_step > 0 (fixed-time step). integrator.set_target_accuracy(FLAGS_integration_accuracy); simulator.set_publish_every_time_step(false); simulator.set_target_realtime_rate(FLAGS_target_realtime_rate); simulator.Initialize(); simulator.AdvanceTo(FLAGS_simulation_time); return 0; } } // namespace } // namespace inclined_plane_with_body } // namespace examples } // namespace multibody } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "\nSimulation of a body (e.g., sphere or block) on an inclined plane." "\nThe type of body is user-selected and may slip or stick (roll)." "\nInformation on how to build, run, and visualize this example and how" "\nto use command-line arguments is in the file README.md" "\n(which is in the folder associated with this example).\n"); gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::multibody::examples::inclined_plane_with_body::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/pendulum/passive_simulation.cc
#include <memory> #include <gflags/gflags.h> #include "drake/common/drake_assert.h" #include "drake/geometry/drake_visualizer.h" #include "drake/geometry/scene_graph.h" #include "drake/lcm/drake_lcm.h" #include "drake/multibody/benchmarks/pendulum/make_pendulum_plant.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/systems/analysis/implicit_euler_integrator.h" #include "drake/systems/analysis/runge_kutta3_integrator.h" #include "drake/systems/analysis/semi_explicit_euler_integrator.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/constant_vector_source.h" namespace drake { using geometry::SceneGraph; using geometry::SourceId; using lcm::DrakeLcm; using multibody::benchmarks::pendulum::MakePendulumPlant; using multibody::benchmarks::pendulum::PendulumParameters; using multibody::MultibodyPlant; using multibody::RevoluteJoint; using systems::ImplicitEulerIntegrator; using systems::RungeKutta3Integrator; using systems::SemiExplicitEulerIntegrator; namespace examples { namespace multibody { namespace pendulum { namespace { DEFINE_double(target_realtime_rate, 1.0, "Desired rate relative to real time. See documentation for " "Simulator::set_target_realtime_rate() for details."); DEFINE_string(integration_scheme, "runge_kutta3", "Integration scheme to be used. Available options are:" "'runge_kutta3','implicit_euler','semi_explicit_euler'"); int do_main() { systems::DiagramBuilder<double> builder; SceneGraph<double>& scene_graph = *builder.AddSystem<SceneGraph>(); scene_graph.set_name("scene_graph"); // The model's parameters: PendulumParameters parameters; // Define simulation parameters: // Compute a reference time scale to set reasonable values for time step and // simulation time. const double reference_time_scale = 2.0 * M_PI * sqrt(parameters.l() / parameters.g()); // Define a reasonable maximum time step based off the expected dynamics's // time scales. const double max_time_step = reference_time_scale / 100; // Simulate about five periods of oscillation. const double simulation_time = 5.0 * reference_time_scale; // The target accuracy determines the size of the actual time steps taken // whenever a variable time step integrator is used. const double target_accuracy = 0.001; MultibodyPlant<double>& pendulum = *builder.AddSystem(MakePendulumPlant(parameters, &scene_graph)); const RevoluteJoint<double>& pin = pendulum.GetJointByName<RevoluteJoint>(parameters.pin_joint_name()); // A constant source for a zero applied torque at the pin joint. double applied_torque(0.0); auto torque_source = builder.AddSystem<systems::ConstantVectorSource>(applied_torque); torque_source->set_name("Applied Torque"); builder.Connect(torque_source->get_output_port(), pendulum.get_actuation_input_port()); // Sanity check on the availability of the optional source id before using it. DRAKE_DEMAND(pendulum.get_source_id().has_value()); builder.Connect( pendulum.get_geometry_poses_output_port(), scene_graph.get_source_pose_port(pendulum.get_source_id().value())); geometry::DrakeVisualizerd::AddToBuilder(&builder, scene_graph); auto diagram = builder.Build(); auto diagram_context = diagram->CreateDefaultContext(); systems::Context<double>& pendulum_context = diagram->GetMutableSubsystemContext(pendulum, diagram_context.get()); pin.set_angle(&pendulum_context, M_PI / 3.0); systems::Simulator<double> simulator(*diagram, std::move(diagram_context)); systems::IntegratorBase<double>* integrator{nullptr}; if (FLAGS_integration_scheme == "implicit_euler") { integrator = &simulator.reset_integrator<ImplicitEulerIntegrator<double>>(); } else if (FLAGS_integration_scheme == "runge_kutta3") { integrator = &simulator.reset_integrator<RungeKutta3Integrator<double>>(); } else if (FLAGS_integration_scheme == "semi_explicit_euler") { integrator = &simulator.reset_integrator<SemiExplicitEulerIntegrator<double>>( max_time_step); } else { throw std::runtime_error( "Integration scheme '" + FLAGS_integration_scheme + "' not supported for this example."); } integrator->set_maximum_step_size(max_time_step); // Error control is only supported for variable time step integrators. if (!integrator->get_fixed_step_mode()) integrator->set_target_accuracy(target_accuracy); simulator.set_publish_every_time_step(false); simulator.set_target_realtime_rate(FLAGS_target_realtime_rate); simulator.Initialize(); simulator.AdvanceTo(simulation_time); // Some sanity checks: if (FLAGS_integration_scheme == "semi_explicit_euler") { DRAKE_DEMAND(integrator->get_fixed_step_mode() == true); } // Checks for variable time step integrators. if (!integrator->get_fixed_step_mode()) { // From IntegratorBase::set_maximum_step_size(): // "The integrator may stretch the maximum step size by as much as 1% to // reach discrete event." Thus the 1.01 factor in this DRAKE_DEMAND. DRAKE_DEMAND( integrator->get_largest_step_size_taken() <= 1.01 * max_time_step); DRAKE_DEMAND(integrator->get_smallest_adapted_step_size_taken() <= integrator->get_largest_step_size_taken()); DRAKE_DEMAND( integrator->get_num_steps_taken() >= simulation_time / max_time_step); } // Checks for fixed time step integrators. if (integrator->get_fixed_step_mode()) { DRAKE_DEMAND(integrator->get_num_derivative_evaluations() == integrator->get_num_steps_taken()); DRAKE_DEMAND( integrator->get_num_step_shrinkages_from_error_control() == 0); } // We made a good guess for max_time_step and therefore we expect no // failures when taking a time step. DRAKE_DEMAND(integrator->get_num_substep_failures() == 0); DRAKE_DEMAND( integrator->get_num_step_shrinkages_from_substep_failures() == 0); return 0; } } // namespace } // namespace pendulum } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A simple pendulum demo using Drake's MultibodyPlant. " "Launch meldis before running this example."); gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::pendulum::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/pendulum/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", ) package(default_visibility = ["//visibility:private"]) drake_cc_binary( name = "passive_simulation", srcs = ["passive_simulation.cc"], add_test_rule = 1, test_rule_args = ["--target_realtime_rate=0.0"], deps = [ "//geometry:drake_visualizer", "//lcm", "//multibody/benchmarks/pendulum", "//systems/analysis:implicit_euler_integrator", "//systems/analysis:runge_kutta3_integrator", "//systems/analysis:semi_explicit_euler_integrator", "//systems/analysis:simulator", "//systems/framework:diagram", "//systems/primitives:constant_vector_source", "@gflags", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/strandbeest/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load("//tools/skylark:drake_cc.bzl", "drake_cc_binary") load("//tools/skylark:drake_py.bzl", "drake_py_unittest") load("//tools/workspace/ros_xacro_internal:defs.bzl", "xacro_filegroup") package(default_visibility = ["//visibility:private"]) xacro_filegroup( name = "StrandbeestModels", srcs = [ "model/StrandbeestBushings.urdf.xacro", "model/StrandbeestConstraints.urdf.xacro", ], data = [ "model/LegAssembly.xacro", "model/LegPair.xacro", "model/Macros.xacro", "model/Strandbeest.xacro", ], ) drake_cc_binary( name = "run_with_motor", srcs = ["run_with_motor.cc"], data = [":StrandbeestModels"], deps = [ "//common:add_text_logging_gflags", "//multibody/inverse_kinematics", "//multibody/parsing", "//multibody/plant", "//multibody/tree", "//solvers", "//systems/analysis:simulator", "//systems/analysis:simulator_gflags", "//systems/analysis:simulator_print_stats", "//systems/framework:diagram", "//visualization:visualization_config_functions", "@fmt", "@gflags", ], ) drake_py_unittest( name = "run_with_motor_test", args = select({ "//tools/cc_toolchain:debug": ["TestEmpty"], "//conditions:default": ["TestRunWithMotor"], }), data = [ ":run_with_motor", ], ) add_lint_tests()
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/strandbeest/README.md
# Strandbeest This example runs a simulation of Theo Jansen's [Strandbeest](https://www.strandbeest.com/) mechanism. ## Change the model Modify any relevant values in `model/Macros.xacro`. The Strandbeest model is a dependency of the executable, and `xacro` will be run automatically. ## Run the example Run the example with the default available solver: ``` bazel run //tools:meldis -- --open-window & bazel run //examples/multibody/strandbeest:run_with_motor ``` Run the example with the [SNOPT](https://drake.mit.edu/bazel.html#snopt) solver for faster IK solves: ``` bazel run --config snopt //examples/multibody/strandbeest:run_with_motor ```
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/strandbeest/run_with_motor.cc
/* @file A Strandbeest demo demonstrating the use of a linear bushing as a way to model kinematic loops. It shows: - How to model a parameterized Strandbeest in SDF. - Use the `multibody::Parser` to load a model from an SDF file into a MultibodyPlant. - Model revolute joints with a `multibody::LinearBushingRollPitchYaw` to model closed kinematic chains. - Parsing custom drake:linear_bushing_rpy tags. - Computing inverse kinematics for the Strandbeest model. Refer to README.md for more details on how to run and modify this example. */ #include <fmt/format.h> #include <gflags/gflags.h> #include "drake/multibody/inverse_kinematics/inverse_kinematics.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/tree/linear_bushing_roll_pitch_yaw.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/solvers/solve.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/analysis/simulator_gflags.h" #include "drake/systems/analysis/simulator_print_stats.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/leaf_system.h" #include "drake/visualization/visualization_config_functions.h" namespace drake { using Eigen::Vector3d; using Eigen::Vector4d; using Eigen::VectorXd; using multibody::BodyIndex; using multibody::ForceElementIndex; using multibody::InverseKinematics; using multibody::Joint; using multibody::LinearBushingRollPitchYaw; using multibody::MultibodyPlant; using multibody::Parser; using multibody::RevoluteJoint; using multibody::internal::BallConstraintSpec; using solvers::Solve; using systems::BasicVector; using systems::Context; using systems::DiagramBuilder; using systems::LeafSystem; using systems::OutputPort; using systems::OutputPortIndex; using systems::Simulator; namespace examples { namespace multibody { namespace strandbeest { namespace { DEFINE_double(simulation_time, 20.0, "Duration of the simulation in seconds."); DEFINE_double(initial_velocity, 5.0, "Initial velocity of the crossbar_crank joint."); DEFINE_double(mbt_dt, 5e-2, "Discrete time step."); DEFINE_double(penetration_allowance, 5.0e-3, "MBP penetration allowance."); DEFINE_double(stiction_tolerance, 5.0e-2, "MBP stiction tolerance."); DEFINE_bool(with_constraints, true, "Use strandbeest model with constraints, otherwise bushing force " "elements are used."); // A simple proportional controller to keep the angular velocity of the // joint at a desired rate. template <typename T> class DesiredVelocityMotor final : public LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DesiredVelocityMotor) DesiredVelocityMotor(const MultibodyPlant<T>& plant, const Joint<T>& joint, double omega_desired, double proportional) : velocity_index_(plant.num_positions() + joint.velocity_start()), omega_desired_(omega_desired), kProportional_(proportional) { this->DeclareInputPort("Plant state", systems::kVectorValued, plant.num_multibody_states()); output_index_ = this->DeclareVectorOutputPort( "Torque", 1, &DesiredVelocityMotor<T>::CalcTorque) .get_index(); } /// Returns the output port on which the sum is presented. const OutputPort<T>& get_output_port() const { return LeafSystem<T>::get_output_port(output_index_); } private: int velocity_index_; double omega_desired_; OutputPortIndex output_index_; double kProportional_; // Calculates the torque on the motor proportional to the difference in // desired angular velocity and given angular velocity. void CalcTorque(const Context<T>& context, BasicVector<T>* torque) const { const T omega = this->get_input_port(0).Eval(context)[velocity_index_]; const T tau = kProportional_ * (omega_desired_ - omega); (*torque)[0] = tau; } }; int do_main() { DRAKE_DEMAND((FLAGS_with_constraints && FLAGS_mbt_dt > 0) || (!FLAGS_with_constraints && FLAGS_mbt_dt == 0)); // Build a generic MultibodyPlant and SceneGraph. DiagramBuilder<double> builder; auto [strandbeest, scene_graph] = AddMultibodyPlantSceneGraph( &builder, std::make_unique<MultibodyPlant<double>>(FLAGS_mbt_dt)); // Make and add the strandbeest model from a URDF model. const std::string urdf_url = (FLAGS_with_constraints ? "package://drake/examples/multibody/" "strandbeest/model/StrandbeestConstraints.urdf" : "package://drake/examples/multibody/" "strandbeest/model/StrandbeestBushings.urdf"); if (FLAGS_with_constraints) { strandbeest.set_discrete_contact_approximation( drake::multibody::DiscreteContactApproximation::kSap); } Parser parser(&strandbeest); parser.AddModelsFromUrl(urdf_url); // We are done defining the model. Finalize. strandbeest.Finalize(); // Calculate the total mass of the model. Do not include the mass of // BodyIndex(0) a.k.a. the world. double total_mass = 0; for (BodyIndex body_index(1); body_index < strandbeest.num_bodies(); ++body_index) { const auto& body = strandbeest.get_body(body_index); total_mass += body.default_mass(); } // Set the penetration allowance and stiction tolerance to values that make // sense for the scale of our simulation. strandbeest.set_penetration_allowance(FLAGS_penetration_allowance); strandbeest.set_stiction_tolerance(FLAGS_stiction_tolerance); visualization::AddDefaultVisualization(&builder); // Create a DesiredVelocityMotor where the proportional term is directly // proportional to the mass of the model. RevoluteJoint<double>& crank_joint_actuated = strandbeest.GetMutableJointByName<RevoluteJoint>("joint_crossbar_crank"); auto torque_source = builder.AddSystem<DesiredVelocityMotor>( strandbeest, crank_joint_actuated, FLAGS_initial_velocity, total_mass); torque_source->set_name("Applied Torque"); builder.Connect(torque_source->get_output_port(), strandbeest.get_actuation_input_port()); builder.Connect(strandbeest.get_state_output_port(), torque_source->get_input_port(0)); auto diagram = builder.Build(); // Create a context for the diagram and extract the context for the // strandbeest model. std::unique_ptr<Context<double>> diagram_context = diagram->CreateDefaultContext(); Context<double>& strandbeest_context = strandbeest.GetMyMutableContextFromRoot(diagram_context.get()); // Set up an initial condition to fix the floating body (crossbar) // for inverse kinematics. VectorXd lower = strandbeest.GetPositionLowerLimits(); VectorXd upper = strandbeest.GetPositionUpperLimits(); // Fix the orientation of the floating body (crossbar) to the unit // quaternion. lower.head<4>() = Eigen::Vector4d(1, 0, 0, 0); upper.head<4>() = Eigen::Vector4d(1, 0, 0, 0); // Fix the translation of the floating body (crossbar) to (-2, 0, 1.35). // Place the Strandbeest model slightly above the ground plane box so it is // not in collision and also does not have to fall far to land. lower.segment<3>(4) = Eigen::Vector3d(-2, 0, 1.35); upper.segment<3>(4) = Eigen::Vector3d(-2, 0, 1.35); strandbeest.SetFreeBodyPose( &strandbeest_context, strandbeest.GetBodyByName("crossbar"), drake::math::RigidTransformd(Vector3d(-2, 0, 1.35))); // Fix the crank shaft to top dead center. const RevoluteJoint<double>& joint_crossbar_crank = strandbeest.GetJointByName<RevoluteJoint>("joint_crossbar_crank"); const int start_position = joint_crossbar_crank.position_start(); lower[start_position] = 0; upper[start_position] = 0; // Create an InverseKinematics program with our strandbeest context but // without it parsing the default position limits as constraints. InverseKinematics ik(strandbeest, &strandbeest_context, false); // Add our custom position constraints that fix the floating body (crossbar). ik.get_mutable_prog()->AddBoundingBoxConstraint(lower, upper, ik.q()); if (FLAGS_with_constraints) { for (const auto& [id, spec] : strandbeest.get_ball_constraint_specs()) { ik.AddPointToPointDistanceConstraint( strandbeest.get_body(spec.body_A).body_frame(), spec.p_AP, strandbeest.get_body(spec.body_B).body_frame(), spec.p_BQ, 0, 0); } } else { // Add a position constraint for each bushing element. The origins of the // two frames defining the bushing should be coincident, so we add an // equality constraint for those poses. Skip the 0th force element // (UniformGravity). for (ForceElementIndex bushing_index(1); bushing_index < strandbeest.num_force_elements(); ++bushing_index) { const LinearBushingRollPitchYaw<double>& bushing = strandbeest.GetForceElement<LinearBushingRollPitchYaw>(bushing_index); ik.AddPointToPointDistanceConstraint( bushing.frameA(), Eigen::Vector3d(0, 0, 0), bushing.frameC(), Eigen::Vector3d(0, 0, 0), 0, 0); } } // Solve the IK. The solved positions will be stored in the context passed // to the InverseKinematics constructor. Solve(ik.prog()); // Create a simulator and run the simulation. std::unique_ptr<Simulator<double>> simulator = MakeSimulatorFromGflags(*diagram, std::move(diagram_context)); simulator->AdvanceTo(FLAGS_simulation_time); // Print some useful statistics. PrintSimulatorStatistics(*simulator); return 0; } // namespace } // namespace } // namespace strandbeest } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A demo showing the Strandbeest walking forward with a proportionally " "controlled motor set to a desired crank velocity. Launch meldis before " "running this example."); FLAGS_simulator_target_realtime_rate = 1.0; FLAGS_simulator_accuracy = 1e-2; FLAGS_simulator_max_time_step = 1e-1; FLAGS_simulator_integration_scheme = "implicit_euler"; gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::strandbeest::do_main(); }
0
/home/johnshepherd/drake/examples/multibody/strandbeest
/home/johnshepherd/drake/examples/multibody/strandbeest/model/Strandbeest.xacro
<?xml version="1.0"?> <!-- @author: Joseph Masterjohn (github: @joemasterjohn) @author: Robin Deits (github: @rdeits) Strandbeest.xacro is not intended to be invoked directly. Instead, use the 'strandbeest' macro contained here in a separate file after including Strandbeest.xacro. These files are an adaptation of the original Strandbeest example in Drake, written by Robin Deits: https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/examples/Strandbeest/ --> <robot xmlns:drake="http://drake.mit.edu" xmlns:xacro="http://ros.org/wiki/xacro" name="Strandbeest"> <xacro:macro name="strandbeest" params="with_constraints"> <xacro:include filename="Macros.xacro"/> <xacro:include filename="LegPair.xacro"/> <!-- Materials --> <material name="tri_red"> <color rgba="0.8 0 0 1"/> </material> <material name="tri_black"> <color rgba="0 0 0 1"/> </material> <material name="tri_grey"> <color rgba="0.6 0.6 0.6 1"/> </material> <!-- Fixed floor link for collision and walking --> <link name="floor"> <inertial> <origin rpy="0 0 0" xyz="0 0 0"/> <mass value="1"/> <inertia ixx="1" ixy="0" ixz="0" iyy="1" iyz="0" izz="1"/> </inertial> <visual> <origin rpy="0 0 0" xyz="0 0 0"/> <geometry> <box size="10 10 1"/> </geometry> <material name="gray"> <color rgba=".4 .4 .4 1"/> </material> </visual> <collision> <origin rpy="0 0 0" xyz="0 0 0"/> <geometry> <box size="10 10 1"/> </geometry> <drake:proximity_properties> <drake:mu_static value="1"/> <drake:mu_dynamic value="0.6"/> </drake:proximity_properties> </collision> </link> <joint name="floor_weld" type="fixed"> <origin rpy="0 0 0" xyz="0 0 0.0"/> <parent link="world"/> <child link="floor"/> </joint> <!-- Links --> <link name="crossbar"> <xacro:strandbeest_cylinder xyz="0 0 0" rpy="${pi/2} 0 0" length="1.2" radius="0.01" material="tri_black"/> </link> <link name="crank_axle"> <xacro:strandbeest_cylinder xyz="0 0 0" rpy="${pi/2} 0 0" length="1.2" radius="0.02" material="tri_red"/> </link> <!-- Joints --> <joint name="joint_crossbar_crank" type="continuous"> <axis xyz="0 1 0"/> <parent link="crossbar"/> <child link="crank_axle"/> <origin rpy="0 0 0" xyz="0 0 0.078"/> </joint> <transmission name="crossbar_crank_transmission" type="pr2_mechanism_model/SimpleTransmission"> <joint name="joint_crossbar_crank"/> <actuator name="crossbar_crank_motor"/> <mechanicalReduction>1</mechanicalReduction> </transmission> <!-- Macro to define a pair of legs at an offset along the crank shaft --> <xacro:macro name="positioned_leg_pair" params="name offset angle"> <xacro:strandbeest_leg_pair prefix="${name}" with_constraints="${with_constraints}"/> <joint name="${name}_joint_crossbar_l" type="fixed"> <axis xyz="0 1 0"/> <parent link="crossbar"/> <child link="${name}_bar_l"/> <origin rpy="0 0 0" xyz="0 ${offset} 0"/> </joint> <joint name="${name}_joint_crank_axle_m" type="fixed"> <axis xyz="0 1 0"/> <parent link="crank_axle"/> <child link="${name}_bar_m"/> <origin rpy="0 ${angle} 0" xyz="0 ${offset} 0"/> </joint> </xacro:macro> <!-- Define the legs --> <xacro:positioned_leg_pair name="pair01" offset="0.6" angle="0"> </xacro:positioned_leg_pair> <xacro:positioned_leg_pair name="pair02" offset="0.36" angle="${2*pi/3}"> </xacro:positioned_leg_pair> <xacro:positioned_leg_pair name="pair03" offset="0.12" angle="${4*pi/3}"> </xacro:positioned_leg_pair> <xacro:positioned_leg_pair name="pair04" offset="-0.12" angle="${pi/3}"> </xacro:positioned_leg_pair> <xacro:positioned_leg_pair name="pair05" offset="-0.36" angle="${3*pi/3}"> </xacro:positioned_leg_pair> <xacro:positioned_leg_pair name="pair06" offset="-0.6" angle="${5*pi/3}"> </xacro:positioned_leg_pair> </xacro:macro> </robot>
0
/home/johnshepherd/drake/examples/multibody/strandbeest
/home/johnshepherd/drake/examples/multibody/strandbeest/model/StrandbeestConstraints.urdf.xacro
<?xml version="1.0"?> <!-- @author: Joseph Masterjohn (github: @joemasterjohn) @author: Robin Deits (github: @rdeits) These files are an adaptation of the original Strandbeest example in Drake, written by Robin Deits: https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/examples/Strandbeest/ --> <robot xmlns:drake="http://drake.mit.edu" xmlns:xacro="http://ros.org/wiki/xacro" name="Strandbeest"> <xacro:include filename="Strandbeest.xacro"/> <xacro:strandbeest with_constraints="true" /> </robot>
0
/home/johnshepherd/drake/examples/multibody/strandbeest
/home/johnshepherd/drake/examples/multibody/strandbeest/model/Macros.xacro
<?xml version="1.0"?> <!-- @author: Joseph Masterjohn (github: @joemasterjohn) @author: Robin Deits (github: @rdeits) These files are an adaptation of the original Strandbeest example in Drake, written by Robin Deits: https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/examples/Strandbeest/ --> <robot xmlns:drake="http://drake.mit.edu" xmlns:xacro="http://ros.org/wiki/xacro" name="Macros"> <!-- LinearBushingRollPitchYaw parameters --> <xacro:property name="torque_stiffness" value="20000"/> <xacro:property name="torque_damping" value="2000"/> <xacro:property name="force_stiffness" value="20000"/> <xacro:property name="force_damping" value="2000"/> <!--PVC Material Properties --> <!-- http://www.midcoonline.com/web/Pages/Products/Pipe/Info/PVC_CPVC/ --> <!-- PVC linear density: mass per unit length constant. --> <xacro:property name="pvc_kg_per_m" value=".476212462"/> <xacro:property name="pvc_radius_outer" value="0.03683"/> <xacro:property name="pvc_radius_inner" value="0.0266446"/> <!-- Macro to create the inertial properties modelling pvc pipe --> <xacro:macro name="strandbeest_cylinder_inertial" params="xyz rpy length"> <inertial> <origin xyz="${xyz}" rpy="${rpy}"/> <mass value="${pvc_kg_per_m * length}"/> <!-- Inertial tensor for a cylindrical tube (e.g. pvc pipe) --> <inertia ixx="${(1.0/12.0) * (pvc_kg_per_m * length) * (3*(pvc_radius_outer**2 + pvc_radius_inner**2) + length**2)}" iyy="${(1.0/12.0) * (pvc_kg_per_m * length) * (3*(pvc_radius_outer**2 + pvc_radius_inner**2) + length**2)}" izz="${0.5 * (pvc_kg_per_m * length) * (pvc_radius_outer**2 + pvc_radius_inner**2)}" ixy="0" ixz="0" iyz="0"/> </inertial> </xacro:macro> <!-- Macro to create the visual properties for a length of pvc --> <xacro:macro name="strandbeest_cylinder_visual" params="xyz rpy length radius material"> <visual> <origin xyz="${xyz}" rpy="${rpy}"/> <geometry> <cylinder length="${length}" radius="${radius}"/> </geometry> <material name="${material}"/> </visual> </xacro:macro> <!-- Macro to create the inertial and visual tags for a length of pvc --> <xacro:macro name="strandbeest_cylinder" params="xyz rpy length radius material"> <xacro:strandbeest_cylinder_inertial xyz="${xyz}" rpy="${rpy}" length="${length}"/> <xacro:strandbeest_cylinder_visual xyz="${xyz}" rpy="${rpy}" length="${length}" radius="${radius}" material="${material}"/> </xacro:macro> </robot>
0
/home/johnshepherd/drake/examples/multibody/strandbeest
/home/johnshepherd/drake/examples/multibody/strandbeest/model/LegAssembly.xacro
<?xml version="1.0"?> <!-- @author: Joseph Masterjohn (github: @joemasterjohn) @author: Robin Deits (github: @rdeits) These files are an adaptation of the original Strandbeest example in Drake, written by Robin Deits: https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/examples/Strandbeest/ --> <robot xmlns:drake="http://drake.mit.edu" xmlns:xacro="http://ros.org/wiki/xacro" name="LegAssembly"> <xacro:include filename="Macros.xacro"/> <xacro:macro name="strandbeest_leg" params="prefix with_constraints"> <!-- Links --> <link name="${prefix}_bar_j"> <xacro:strandbeest_cylinder xyz="0 0 0.25" rpy="0 0 0" length="0.50" radius="0.01" material="tri_grey"/> </link> <link name="${prefix}_bar_k"> <xacro:strandbeest_cylinder xyz="0 0 0.3095" rpy="0 0 0" length="0.619" radius="0.01" material="tri_grey"/> </link> <link name="${prefix}_bar_c"> <xacro:strandbeest_cylinder xyz="0 0 0.1965" rpy="0 0 0" length="0.393" radius="0.01" material="tri_grey"/> </link> <link name="${prefix}_bar_g"> <xacro:strandbeest_cylinder xyz="0 0 0.245" rpy="0 0 0" length="0.49" radius="0.01" material="tri_black"/> <collision> <origin rpy="0 0 0" xyz="0 0 0.49"/> <geometry> <sphere radius="0.02"/> </geometry> <drake:proximity_properties> <drake:mu_static value="1"/> <drake:mu_dynamic value="0.6"/> </drake:proximity_properties> </collision> <visual> <origin rpy="0 0 0" xyz="0 0 0.49"/> <geometry> <sphere radius="0.02"/> </geometry> <material name="tri_red"/> </visual> </link> <link name="${prefix}_bar_h"> <xacro:strandbeest_cylinder xyz="0.1812 0 -0.0291" rpy="0 1.73 0" length="0.367" radius="0.01" material="tri_black"/> </link> <link name="${prefix}_bar_i"> <xacro:strandbeest_cylinder xyz="0.1811 0 0.2159" rpy="0 2.5576 0" length="0.657" radius="0.01" material="tri_black"/> </link> <link name="${prefix}_bar_b"> <xacro:strandbeest_cylinder xyz="0 0 0.279" rpy="0 0 0" length="0.558" radius="0.01" material="tri_black"/> </link> <link name="${prefix}_bar_d"> <xacro:strandbeest_cylinder xyz="-0.1488 0 0.4236" rpy="0 -2.3056 0" length="0.401" radius="0.01" material="tri_black"/> </link> <link name="${prefix}_bar_e"> <xacro:strandbeest_cylinder xyz="-0.1489 0 0.1446" rpy="0 -0.8 0" length="0.415" radius="0.01" material="tri_black"/> </link> <link name="${prefix}_bar_f"> <xacro:strandbeest_cylinder xyz="0 0 0.197" rpy="0 0 0" length="0.394" radius="0.01" material="tri_grey"/> </link> <!-- Joints --> <joint name="${prefix}_joint_j_k" type="revolute"> <axis xyz="0 1 0"/> <parent link="${prefix}_bar_j"/> <child link="${prefix}_bar_k"/> <origin rpy="0 0 0" xyz="0 0 0"/> <limit lower="-1.8" upper="-1.1" effort="0" velocity="1000"/> </joint> <joint name="${prefix}_joint_k_c" type="revolute"> <axis xyz="0 1 0"/> <parent link="${prefix}_bar_k"/> <child link="${prefix}_bar_c"/> <origin rpy="0 0 0" xyz="0 0 0.619"/> <limit lower="${pi/2}" upper="${pi}" effort="0" velocity="1000"/> </joint> <joint name="${prefix}_joint_g_h" type="fixed"> <origin rpy="0 0 0" xyz="0 0 0"/> <parent link="${prefix}_bar_g"/> <child link="${prefix}_bar_h"/> </joint> <joint name="${prefix}_joint_g_i" type="fixed"> <origin rpy="0 0 0" xyz="0 0 0"/> <parent link="${prefix}_bar_g"/> <child link="${prefix}_bar_i"/> </joint> <joint name="${prefix}_joint_k_g" type="revolute"> <axis xyz="0 1 0"/> <parent link="${prefix}_bar_k"/> <child link="${prefix}_bar_g"/> <origin rpy="0 0 0" xyz="0 0 0.619"/> <limit lower="-2" upper="-0.05" effort="0" velocity="1000"/> </joint> <joint name="${prefix}_joint_b_d" type="fixed"> <origin rpy="0 0 0" xyz="0 0 0"/> <parent link="${prefix}_bar_b"/> <child link="${prefix}_bar_d"/> </joint> <joint name="${prefix}_joint_b_e" type="fixed"> <origin rpy="0 0 0" xyz="0 0 0"/> <parent link="${prefix}_bar_b"/> <child link="${prefix}_bar_e"/> </joint> <joint name="${prefix}_joint_j_b" type="revolute"> <axis xyz="0 1 0"/> <parent link="${prefix}_bar_j"/> <child link="${prefix}_bar_b"/> <origin rpy="0 0 0" xyz="0 0 0.50"/> <limit lower="-1.9" upper="-1.0" effort="0" velocity="1000"/> </joint> <joint name="${prefix}_joint_b_f" type="revolute"> <axis xyz="0 1 0"/> <parent link="${prefix}_bar_b"/> <child link="${prefix}_bar_f"/> <origin rpy="0 0 0" xyz="0 0 0.558"/> <limit lower="-1.7" upper="0.4" effort="0" velocity="1000"/> </joint> <xacro:if value="${with_constraints}"> <!-- Custom Ball Constraint Elements --> <drake:ball_constraint> <drake:ball_constraint_body_A name="${prefix}_bar_f"/> <drake:ball_constraint_p_AP value="0 0 0.394"/> <drake:ball_constraint_body_B name="${prefix}_bar_g"/> <drake:ball_constraint_p_BQ value="0.3624 0 -0.0582"/> </drake:ball_constraint> <drake:ball_constraint> <drake:ball_constraint_body_A name="${prefix}_bar_b"/> <drake:ball_constraint_p_AP value="-0.2978 0 0.2892"/> <drake:ball_constraint_body_B name="${prefix}_bar_c"/> <drake:ball_constraint_p_BQ value="0 0 0.393"/> </drake:ball_constraint> </xacro:if> <xacro:unless value="${with_constraints}"> <!-- Custom Bushing Elements --> <frame name="${prefix}_loop_f_g_bushing_frameA" link="${prefix}_bar_f" rpy="${-pi/2} 0 0" xyz="0 0 0.394"/> <frame name="${prefix}_loop_f_g_bushing_frameC" link="${prefix}_bar_g" rpy="${-pi/2} 0 0" xyz="0.3624 0 -0.0582"/> <drake:linear_bushing_rpy> <drake:bushing_frameA name="${prefix}_loop_f_g_bushing_frameA"/> <drake:bushing_frameC name="${prefix}_loop_f_g_bushing_frameC"/> <drake:bushing_torque_stiffness value="${torque_stiffness} ${torque_stiffness} 0"/> <drake:bushing_torque_damping value="${torque_damping} ${torque_damping} 0"/> <drake:bushing_force_stiffness value="${force_stiffness} ${force_stiffness} ${force_stiffness}"/> <drake:bushing_force_damping value="${force_damping} ${force_damping} ${force_damping}"/> </drake:linear_bushing_rpy> <frame name="${prefix}_loop_b_c_bushing_frameA" link="${prefix}_bar_b" rpy="${-pi/2} 0 0" xyz="-0.2978 0 0.2892"/> <frame name="${prefix}_loop_b_c_bushing_frameC" link="${prefix}_bar_c" rpy="${-pi/2} 0 0" xyz="0 0 0.393"/> <drake:linear_bushing_rpy> <drake:bushing_frameA name="${prefix}_loop_b_c_bushing_frameA"/> <drake:bushing_frameC name="${prefix}_loop_b_c_bushing_frameC"/> <drake:bushing_torque_stiffness value="${torque_stiffness} ${torque_stiffness} 0"/> <drake:bushing_torque_damping value="${torque_damping} ${torque_damping} 0"/> <drake:bushing_force_stiffness value="${force_stiffness} ${force_stiffness} ${force_stiffness}"/> <drake:bushing_force_damping value="${force_damping} ${force_damping} ${force_damping}"/> </drake:linear_bushing_rpy> </xacro:unless> </xacro:macro> </robot>
0
/home/johnshepherd/drake/examples/multibody/strandbeest
/home/johnshepherd/drake/examples/multibody/strandbeest/model/StrandbeestBushings.urdf.xacro
<?xml version="1.0"?> <!-- @author: Joseph Masterjohn (github: @joemasterjohn) @author: Robin Deits (github: @rdeits) These files are an adaptation of the original Strandbeest example in Drake, written by Robin Deits: https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/examples/Strandbeest/ --> <robot xmlns:drake="http://drake.mit.edu" xmlns:xacro="http://ros.org/wiki/xacro" name="Strandbeest"> <xacro:include filename="Strandbeest.xacro"/> <xacro:strandbeest with_constraints="false" /> </robot>
0
/home/johnshepherd/drake/examples/multibody/strandbeest
/home/johnshepherd/drake/examples/multibody/strandbeest/model/LegPair.xacro
<?xml version="1.0"?> <!-- @author: Joseph Masterjohn (github: @joemasterjohn) @author: Robin Deits (github: @rdeits) These files are an adaptation of the original Strandbeest example in Drake, written by Robin Deits: https://github.com/RobotLocomotion/drake/blob/last_sha_with_original_matlab/drake/examples/Strandbeest/ --> <robot xmlns:drake="http://drake.mit.edu" xmlns:xacro="http://ros.org/wiki/xacro" name="LegPair"> <xacro:include filename="Macros.xacro"/> <xacro:include filename="LegAssembly.xacro"/> <xacro:macro name="strandbeest_leg_pair" params="prefix with_constraints"> <!-- Create the two legs --> <xacro:strandbeest_leg prefix="${prefix}_leg1" with_constraints="${with_constraints}"/> <xacro:strandbeest_leg prefix="${prefix}_leg2" with_constraints="${with_constraints}"/> <!-- Links --> <link name="${prefix}_bar_l"> <xacro:strandbeest_cylinder xyz="0 0 0.039" rpy="0 0 0" length="0.078" radius="0.01" material="tri_black"/> </link> <link name="${prefix}_bar_a"> <xacro:strandbeest_cylinder xyz="0 0 0" rpy="0 0 0" length="0.76" radius="0.01" material="tri_black"/> </link> <link name="${prefix}_bar_m"> <xacro:strandbeest_cylinder xyz="0 0 0.075" rpy="0 0 0" length="0.15" radius="0.01" material="tri_red"/> </link> <!-- Joints --> <joint name="${prefix}_joint_l_a" type="fixed"> <axis xyz="0 1 0"/> <parent link="${prefix}_bar_l"/> <child link="${prefix}_bar_a"/> <origin rpy="0 ${-pi/2} 0" xyz="0 0 0"/> </joint> <joint name="${prefix}_leg1_joint_m_j" type="continuous"> <axis xyz="0 1 0"/> <parent link="${prefix}_bar_m"/> <child link="${prefix}_leg1_bar_j"/> <origin rpy="0 0 0" xyz="0 0 0.15"/> </joint> <joint name="${prefix}_leg2_joint_m_j" type="continuous"> <axis xyz="0 1 0"/> <parent link="${prefix}_bar_m"/> <child link="${prefix}_leg2_bar_j"/> <origin rpy="0 0 ${pi}" xyz="0 0 0.15"/> </joint> <xacro:if value="${with_constraints}"> <!-- Custom Ball Constraint Elements --> <drake:ball_constraint> <drake:ball_constraint_body_A name="${prefix}_bar_a"/> <drake:ball_constraint_p_AP value="0 0 0.38"/> <drake:ball_constraint_body_B name="${prefix}_leg1_bar_c"/> <drake:ball_constraint_p_BQ value="0 0 0.393"/> </drake:ball_constraint> <drake:ball_constraint> <drake:ball_constraint_body_A name="${prefix}_bar_a"/> <drake:ball_constraint_p_AP value="0 0 -0.38"/> <drake:ball_constraint_body_B name="${prefix}_leg2_bar_c"/> <drake:ball_constraint_p_BQ value="0 0 0.393"/> </drake:ball_constraint> </xacro:if> <xacro:unless value="${with_constraints}"> <!-- Custom Bushing Elements --> <frame name="${prefix}_leg1_loop_a_c_bushing_frameA" link="${prefix}_bar_a" rpy="${-pi/2} 0 0" xyz="0 0 0.38"/> <frame name="${prefix}_leg1_loop_a_c_bushing_frameC" link="${prefix}_leg1_bar_c" rpy="${-pi/2} 0 0" xyz="0 0 0.393"/> <drake:linear_bushing_rpy> <drake:bushing_frameA name="${prefix}_leg1_loop_a_c_bushing_frameA"/> <drake:bushing_frameC name="${prefix}_leg1_loop_a_c_bushing_frameC"/> <drake:bushing_torque_stiffness value="${torque_stiffness} ${torque_stiffness} 0"/> <drake:bushing_torque_damping value="${torque_damping} ${torque_damping} 0"/> <drake:bushing_force_stiffness value="${force_stiffness} ${force_stiffness} ${force_stiffness}"/> <drake:bushing_force_damping value="${force_damping} ${force_damping} ${force_damping}"/> </drake:linear_bushing_rpy> <frame name="${prefix}_leg2_loop_a_c_bushing_frameA" link="${prefix}_bar_a" rpy="${-pi/2} 0 ${pi}" xyz="0 0 -0.38"/> <frame name="${prefix}_leg2_loop_a_c_bushing_frameC" link="${prefix}_leg2_bar_c" rpy="${-pi/2} 0 0" xyz="0 0 0.393"/> <drake:linear_bushing_rpy> <drake:bushing_frameA name="${prefix}_leg2_loop_a_c_bushing_frameA"/> <drake:bushing_frameC name="${prefix}_leg2_loop_a_c_bushing_frameC"/> <drake:bushing_torque_stiffness value="${torque_stiffness} ${torque_stiffness} 0"/> <drake:bushing_torque_damping value="${torque_damping} ${torque_damping} 0"/> <drake:bushing_force_stiffness value="${force_stiffness} ${force_stiffness} ${force_stiffness}"/> <drake:bushing_force_damping value="${force_damping} ${force_damping} ${force_damping}"/> </drake:linear_bushing_rpy> </xacro:unless> </xacro:macro> </robot>
0
/home/johnshepherd/drake/examples/multibody/strandbeest
/home/johnshepherd/drake/examples/multibody/strandbeest/test/run_with_motor_test.py
import subprocess import unittest class TestRunWithMotor(unittest.TestCase): def test_run_with_motor(self): """Test that run_with_motor doesn't crash.""" subprocess.check_call( ["examples/multibody/strandbeest/run_with_motor", "--simulation_time=0.1"]) class TestEmpty(unittest.TestCase): def test_empty(self): """Empty test case for debug build"""
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cart_pole/BUILD.bazel
load("//tools/install:install_data.bzl", "install_data") load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_binary", "drake_cc_googletest", "drake_cc_library", ) load("//tools/skylark:drake_data.bzl", "models_filegroup") package(default_visibility = ["//visibility:private"]) models_filegroup( name = "models", visibility = ["//visibility:public"], ) install_data( name = "install_data", data = [":models"], visibility = ["//visibility:public"], ) drake_cc_library( name = "cart_pole_params", srcs = ["cart_pole_params.cc"], hdrs = ["cart_pole_params.h"], deps = [ "//common:dummy_value", "//common:essential", "//common:name_value", "//common/symbolic:expression", "//systems/framework:vector", ], ) drake_cc_binary( name = "cart_pole_passive_simulation", srcs = ["cart_pole_passive_simulation.cc"], add_test_rule = 1, data = ["cart_pole.sdf"], test_rule_args = [ "--simulation_time=0.1", "--target_realtime_rate=0.0", ], deps = [ "//common:add_text_logging_gflags", "//multibody/parsing", "//multibody/plant", "//systems/analysis:simulator", "//systems/framework:diagram", "//visualization:visualization_config_functions", "@gflags", ], ) drake_cc_googletest( name = "cart_pole_test", data = [":models"], deps = [ ":cart_pole_params", "//common/test_utilities:eigen_matrix_compare", "//common/test_utilities:limit_malloc", "//multibody/parsing", "//multibody/plant", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cart_pole/cart_pole_params.h
#pragma once // This file was previously auto-generated, but now is just a normal source // file in git. However, it still retains some historical oddities from its // heritage. In general, we do recommend against subclassing BasicVector in // new code. #include <cmath> #include <limits> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <Eigen/Core> #include "drake/common/drake_bool.h" #include "drake/common/dummy_value.h" #include "drake/common/name_value.h" #include "drake/common/never_destroyed.h" #include "drake/common/symbolic/expression.h" #include "drake/systems/framework/basic_vector.h" namespace drake { namespace examples { namespace multibody { namespace cart_pole { /// Describes the row indices of a CartPoleParams. struct CartPoleParamsIndices { /// The total number of rows (coordinates). static const int kNumCoordinates = 4; // The index of each individual coordinate. static const int kMc = 0; static const int kMp = 1; static const int kL = 2; static const int kGravity = 3; /// Returns a vector containing the names of each coordinate within this /// class. The indices within the returned vector matches that of this class. /// In other words, `CartPoleParamsIndices::GetCoordinateNames()[i]` /// is the name for `BasicVector::GetAtIndex(i)`. static const std::vector<std::string>& GetCoordinateNames(); }; /// Specializes BasicVector with specific getters and setters. template <typename T> class CartPoleParams final : public drake::systems::BasicVector<T> { public: /// An abbreviation for our row index constants. typedef CartPoleParamsIndices K; /// Default constructor. Sets all rows to their default value: /// @arg @c mc defaults to 10.0 kg. /// @arg @c mp defaults to 1.0 kg. /// @arg @c l defaults to 0.5 m. /// @arg @c gravity defaults to 9.81 m/s^2. CartPoleParams() : drake::systems::BasicVector<T>(K::kNumCoordinates) { this->set_mc(10.0); this->set_mp(1.0); this->set_l(0.5); this->set_gravity(9.81); } // Note: It's safe to implement copy and move because this class is final. /// @name Implements CopyConstructible, CopyAssignable, MoveConstructible, /// MoveAssignable //@{ CartPoleParams(const CartPoleParams& other) : drake::systems::BasicVector<T>(other.values()) {} CartPoleParams(CartPoleParams&& other) noexcept : drake::systems::BasicVector<T>(std::move(other.values())) {} CartPoleParams& operator=(const CartPoleParams& other) { this->values() = other.values(); return *this; } CartPoleParams& operator=(CartPoleParams&& other) noexcept { this->values() = std::move(other.values()); other.values().resize(0); return *this; } //@} /// Create a symbolic::Variable for each element with the known variable /// name. This is only available for T == symbolic::Expression. template <typename U = T> typename std::enable_if_t<std::is_same_v<U, symbolic::Expression>> SetToNamedVariables() { this->set_mc(symbolic::Variable("mc")); this->set_mp(symbolic::Variable("mp")); this->set_l(symbolic::Variable("l")); this->set_gravity(symbolic::Variable("gravity")); } [[nodiscard]] CartPoleParams<T>* DoClone() const final { return new CartPoleParams; } /// @name Getters and Setters //@{ /// Mass of the cart. /// @note @c mc is expressed in units of kg. /// @note @c mc has a limited domain of [0.0, +Inf]. const T& mc() const { ThrowIfEmpty(); return this->GetAtIndex(K::kMc); } /// Setter that matches mc(). void set_mc(const T& mc) { ThrowIfEmpty(); this->SetAtIndex(K::kMc, mc); } /// Fluent setter that matches mc(). /// Returns a copy of `this` with mc set to a new value. [[nodiscard]] CartPoleParams<T> with_mc(const T& mc) const { CartPoleParams<T> result(*this); result.set_mc(mc); return result; } /// Value of the point mass at the end of the pole. /// @note @c mp is expressed in units of kg. /// @note @c mp has a limited domain of [0.0, +Inf]. const T& mp() const { ThrowIfEmpty(); return this->GetAtIndex(K::kMp); } /// Setter that matches mp(). void set_mp(const T& mp) { ThrowIfEmpty(); this->SetAtIndex(K::kMp, mp); } /// Fluent setter that matches mp(). /// Returns a copy of `this` with mp set to a new value. [[nodiscard]] CartPoleParams<T> with_mp(const T& mp) const { CartPoleParams<T> result(*this); result.set_mp(mp); return result; } /// Length of the pole. /// @note @c l is expressed in units of m. /// @note @c l has a limited domain of [0.0, +Inf]. const T& l() const { ThrowIfEmpty(); return this->GetAtIndex(K::kL); } /// Setter that matches l(). void set_l(const T& l) { ThrowIfEmpty(); this->SetAtIndex(K::kL, l); } /// Fluent setter that matches l(). /// Returns a copy of `this` with l set to a new value. [[nodiscard]] CartPoleParams<T> with_l(const T& l) const { CartPoleParams<T> result(*this); result.set_l(l); return result; } /// Standard acceleration due to gravity near Earth's surface. /// @note @c gravity is expressed in units of m/s^2. /// @note @c gravity has a limited domain of [0.0, +Inf]. const T& gravity() const { ThrowIfEmpty(); return this->GetAtIndex(K::kGravity); } /// Setter that matches gravity(). void set_gravity(const T& gravity) { ThrowIfEmpty(); this->SetAtIndex(K::kGravity, gravity); } /// Fluent setter that matches gravity(). /// Returns a copy of `this` with gravity set to a new value. [[nodiscard]] CartPoleParams<T> with_gravity(const T& gravity) const { CartPoleParams<T> result(*this); result.set_gravity(gravity); return result; } //@} /// Visit each field of this named vector, passing them (in order) to the /// given Archive. The archive can read and/or write to the vector values. /// One common use of Serialize is the //common/yaml tools. template <typename Archive> void Serialize(Archive* a) { T& mc_ref = this->GetAtIndex(K::kMc); a->Visit(drake::MakeNameValue("mc", &mc_ref)); T& mp_ref = this->GetAtIndex(K::kMp); a->Visit(drake::MakeNameValue("mp", &mp_ref)); T& l_ref = this->GetAtIndex(K::kL); a->Visit(drake::MakeNameValue("l", &l_ref)); T& gravity_ref = this->GetAtIndex(K::kGravity); a->Visit(drake::MakeNameValue("gravity", &gravity_ref)); } /// See CartPoleParamsIndices::GetCoordinateNames(). static const std::vector<std::string>& GetCoordinateNames() { return CartPoleParamsIndices::GetCoordinateNames(); } /// Returns whether the current values of this vector are well-formed. drake::boolean<T> IsValid() const { using std::isnan; drake::boolean<T> result{true}; result = result && !isnan(mc()); result = result && (mc() >= T(0.0)); result = result && !isnan(mp()); result = result && (mp() >= T(0.0)); result = result && !isnan(l()); result = result && (l() >= T(0.0)); result = result && !isnan(gravity()); result = result && (gravity() >= T(0.0)); return result; } void GetElementBounds(Eigen::VectorXd* lower, Eigen::VectorXd* upper) const final { const double kInf = std::numeric_limits<double>::infinity(); *lower = Eigen::Matrix<double, 4, 1>::Constant(-kInf); *upper = Eigen::Matrix<double, 4, 1>::Constant(kInf); (*lower)(K::kMc) = 0.0; (*lower)(K::kMp) = 0.0; (*lower)(K::kL) = 0.0; (*lower)(K::kGravity) = 0.0; } private: void ThrowIfEmpty() const { if (this->values().size() == 0) { throw std::out_of_range( "The CartPoleParams vector has been moved-from; " "accessor methods may no longer be used"); } } }; } // namespace cart_pole } // namespace multibody } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cart_pole/cart_pole.sdf
<?xml version="1.0"?> <sdf version="1.7"> <model name="CartPole"> <!-- This sdf file produces a model with the default parameters as documented in cart_pole_params.h. They MUST be kept in sync. --> <link name="Cart"> <inertial> <mass>10.0</mass> <!-- For this model case, with the cart not having any rotational degrees of freedom, the values of the inertia matrix do not participate in the model. Therefore we just set them to zero (or near to zero since sdformat does not allow exact zeroes for inertia values). --> <inertia> <ixx>1.0e-20</ixx> <iyy>1.0e-20</iyy> <izz>1.0e-20</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> <visual name="cart_visual"> <geometry> <box> <size>0.24 0.12 0.12</size> </box> </geometry> </visual> </link> <link name="Pole"> <!-- The pole is modeled as a point mass at the end of a pole. --> <!-- The length of the pole is 0.5 meters. --> <pose>0 0 -0.5 0 0 0</pose> <inertial> <mass>1.0</mass> <!-- A point mass has zero rotational inertia. We must specify small values since otherwise sdformat throws an exception. --> <inertia> <ixx>1.0e-20</ixx> <iyy>1.0e-20</iyy> <izz>1.0e-20</izz> <ixy>0</ixy> <ixz>0</ixz> <iyz>0</iyz> </inertia> </inertial> <visual name="pole_point_mass"> <geometry> <sphere> <radius>0.05</radius> </sphere> </geometry> </visual> <visual name="pole_rod"> <pose>0 0 0.25 0 0 0</pose> <geometry> <cylinder> <radius>0.025</radius> <length>0.5</length> </cylinder> </geometry> </visual> </link> <joint name="CartSlider" type="prismatic"> <parent>world</parent> <child>Cart</child> <axis> <xyz>1.0 0.0 0.0</xyz> </axis> </joint> <joint name="PolePin" type="revolute"> <!-- Pose of the joint frame in the pole's frame (located at the point mass) --> <pose>0 0 0.5 0 0 0</pose> <parent>Cart</parent> <child>Pole</child> <axis> <xyz>0.0 -1.0 0.0</xyz> <limit> <!-- The pole pin joint is not actuated. --> <effort>0</effort> </limit> </axis> </joint> </model> </sdf>
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cart_pole/cart_pole_passive_simulation.cc
#include <memory> #include <gflags/gflags.h> #include "drake/common/drake_assert.h" #include "drake/geometry/scene_graph.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/tree/prismatic_joint.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/visualization/visualization_config_functions.h" namespace drake { namespace examples { namespace multibody { namespace cart_pole { namespace { using geometry::SceneGraph; // "multibody" namespace is ambiguous here without "drake::". using drake::multibody::AddMultibodyPlantSceneGraph; using drake::multibody::MultibodyPlant; using drake::multibody::Parser; using drake::multibody::PrismaticJoint; using drake::multibody::RevoluteJoint; DEFINE_double(target_realtime_rate, 1.0, "Desired rate relative to real time. See documentation for " "Simulator::set_target_realtime_rate() for details."); DEFINE_double(simulation_time, 10.0, "Desired duration of the simulation in seconds."); DEFINE_double(time_step, 0, "If greater than zero, the plant is modeled as a system with " "discrete updates and period equal to this time_step. " "If 0, the plant is modeled as a continuous system."); int do_main() { systems::DiagramBuilder<double> builder; // Make and add the cart_pole model. auto [cart_pole, scene_graph] = AddMultibodyPlantSceneGraph(&builder, FLAGS_time_step); const std::string sdf_url = "package://drake/examples/multibody/cart_pole/cart_pole.sdf"; Parser(&cart_pole, &scene_graph).AddModelsFromUrl(sdf_url); // Now the model is complete. cart_pole.Finalize(); visualization::AddDefaultVisualization(&builder); auto diagram = builder.Build(); // Create a context for this system: std::unique_ptr<systems::Context<double>> diagram_context = diagram->CreateDefaultContext(); diagram->SetDefaultContext(diagram_context.get()); systems::Context<double>& cart_pole_context = diagram->GetMutableSubsystemContext(cart_pole, diagram_context.get()); // There is no input actuation in this example for the passive dynamics. cart_pole.get_actuation_input_port().FixValue(&cart_pole_context, 0.); // Get joints so that we can set initial conditions. const PrismaticJoint<double>& cart_slider = cart_pole.GetJointByName<PrismaticJoint>("CartSlider"); const RevoluteJoint<double>& pole_pin = cart_pole.GetJointByName<RevoluteJoint>("PolePin"); // Set initial state. cart_slider.set_translation(&cart_pole_context, 0.0); pole_pin.set_angle(&cart_pole_context, 2.0); systems::Simulator<double> simulator(*diagram, std::move(diagram_context)); simulator.set_publish_every_time_step(false); simulator.set_target_realtime_rate(FLAGS_target_realtime_rate); simulator.Initialize(); simulator.AdvanceTo(FLAGS_simulation_time); return 0; } } // namespace } // namespace cart_pole } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A simple cart pole demo using Drake's MultibodyPlant," "with SceneGraph visualization. " "Launch meldis before running this example."); gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::cart_pole::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cart_pole/cart_pole_params.cc
#include "drake/examples/multibody/cart_pole/cart_pole_params.h" namespace drake { namespace examples { namespace multibody { namespace cart_pole { const int CartPoleParamsIndices::kNumCoordinates; const int CartPoleParamsIndices::kMc; const int CartPoleParamsIndices::kMp; const int CartPoleParamsIndices::kL; const int CartPoleParamsIndices::kGravity; const std::vector<std::string>& CartPoleParamsIndices::GetCoordinateNames() { static const drake::never_destroyed<std::vector<std::string>> coordinates( std::vector<std::string>{ "mc", "mp", "l", "gravity", }); return coordinates.access(); } } // namespace cart_pole } // namespace multibody } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody/cart_pole
/home/johnshepherd/drake/examples/multibody/cart_pole/test/cart_pole_test.cc
#include <limits> #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/limit_malloc.h" #include "drake/examples/multibody/cart_pole/cart_pole_params.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/multibody/tree/joint_actuator.h" #include "drake/multibody/tree/prismatic_joint.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/multibody/tree/uniform_gravity_field_element.h" #include "drake/systems/framework/context.h" namespace drake { namespace examples { namespace multibody { namespace cart_pole { namespace { using drake::multibody::JointActuator; using drake::multibody::MultibodyPlant; using drake::multibody::Parser; using drake::multibody::PrismaticJoint; using drake::multibody::RevoluteJoint; using drake::multibody::RigidBody; using drake::multibody::UniformGravityFieldElement; using drake::systems::Context; class CartPoleTest : public ::testing::Test { public: void SetUp() override { // Make the cart_pole model. const std::string sdf_url = "package://drake/examples/multibody/cart_pole/cart_pole.sdf"; Parser(&cart_pole_).AddModelsFromUrl(sdf_url); // Add gravity to the model. cart_pole_.mutable_gravity_field().set_gravity_vector( -default_parameters_.gravity() * Vector3<double>::UnitZ()); // Now the model is complete. cart_pole_.Finalize(); ASSERT_EQ(cart_pole_.num_bodies(), 3); // Includes the world body. ASSERT_EQ(cart_pole_.num_joints(), 2); // Get joints so that we can set the state. cart_slider_ = &cart_pole_.GetJointByName<PrismaticJoint>("CartSlider"); pole_pin_ = &cart_pole_.GetJointByName<RevoluteJoint>("PolePin"); // Verify there is a single actuator for the slider joint. ASSERT_EQ(cart_pole_.num_actuators(), 1); const JointActuator<double>& actuator = cart_pole_.GetJointActuatorByName("CartSlider"); ASSERT_EQ(actuator.joint().index(), cart_slider_->index()); // Create a context to store the state for this model: context_ = cart_pole_.CreateDefaultContext(); cart_pole_.get_actuation_input_port().FixValue(context_.get(), 0.); } // Makes the mass matrix for the cart-pole system. // See http://underactuated.csail.mit.edu/underactuated.html?chapter=acrobot. Matrix2<double> CartPoleHandWrittenMassMatrix(double theta) { const double mc = default_parameters_.mc(); // mass of the cart in kg. const double mp = default_parameters_.mp(); // Pole's point mass in kg. const double l = default_parameters_.l(); // length of the pole in m const double c = cos(theta); Matrix2<double> M; M << mc+mp, mp*l*c, mp*l*c, mp*l*l; return M; } Vector4<double> CartPoleHandWrittenDynamics( const Vector2<double>& q, const Vector2<double>& v) { const double mp = default_parameters_.mp(); // Pole's point mass in kg. const double l = default_parameters_.l(); // length of the pole in m const double g = default_parameters_.gravity(); // Gravity in m/s^2. // Mass matrix. const double theta = q(1); const Matrix2<double> M = CartPoleHandWrittenMassMatrix(theta); // Coriolis and gyroscopic terms. const double theta_dot = v(1); const double s = sin(theta); Matrix2<double> C = Matrix2<double>::Zero(); C(0, 1) = -mp * l * theta_dot * s; // Vector of generalized forces due to gravity. Vector2<double> tau_g = Vector2<double>(0.0, -mp * g * l * s); // Compute the dynamics of the system. Vector4<double> state_dot; state_dot << v , M.llt().solve(tau_g - C * v); return state_dot; } protected: MultibodyPlant<double> cart_pole_{0.0}; const PrismaticJoint<double>* cart_slider_{nullptr}; const RevoluteJoint<double>* pole_pin_{nullptr}; std::unique_ptr<Context<double>> context_; const CartPoleParams<double> default_parameters_; }; // Tests that the hand-derived mass matrix matches the mass matrix computed with // a MultibodyPlant built from an SDF file. TEST_F(CartPoleTest, MassMatrix) { // The mass matrix of the system does not depend on the x location of the // cart. Therefore we only need the angle of the pole. const double theta = M_PI / 3; Matrix2<double> M; pole_pin_->set_angle(context_.get(), theta); cart_pole_.CalcMassMatrixViaInverseDynamics(*context_, &M); Matrix2<double> M_expected = CartPoleHandWrittenMassMatrix(theta); // Matrix verified to this tolerance. const double kTolerance = 10 * std::numeric_limits<double>::epsilon(); EXPECT_TRUE(CompareMatrices(M, M_expected, kTolerance, MatrixCompareType::relative)); { // Repeat the computation to confirm the heap behavior. We allow the // method to heap-allocate 4 temporaries. drake::test::LimitMalloc guard({.max_num_allocations = 4}); cart_pole_.CalcMassMatrixViaInverseDynamics(*context_, &M); } } // Tests that the hand-derived dynamics matches that computed with a // MultibodyPlant built from an SDF file. TEST_F(CartPoleTest, SystemDynamics) { // State arbitrarily chosen for this test. const Vector2<double> q(2.5, M_PI / 3); const Vector2<double> v(-1.5, 0.5); Matrix2<double> M; cart_slider_->set_translation(context_.get(), q(0)); cart_slider_->set_translation_rate(context_.get(), v(0)); pole_pin_->set_angle(context_.get(), q(1)); pole_pin_->set_angular_rate(context_.get(), v(1)); std::unique_ptr<systems::ContinuousState<double>> xc_dot = cart_pole_.AllocateTimeDerivatives(); cart_pole_.CalcTimeDerivatives(*context_, xc_dot.get()); const Vector4<double> xc_dot_expected = CartPoleHandWrittenDynamics(q, v); const double kTolerance = 10 * std::numeric_limits<double>::epsilon(); EXPECT_TRUE(CompareMatrices(xc_dot->CopyToVector(), xc_dot_expected, kTolerance, MatrixCompareType::relative)); // Verify that the implicit dynamics match the continuous ones. Eigen::VectorXd residual = cart_pole_.AllocateImplicitTimeDerivativesResidual(); cart_pole_.CalcImplicitTimeDerivativesResidual(*context_, *xc_dot, &residual); EXPECT_TRUE(CompareMatrices(residual, Eigen::VectorXd::Zero(4), 1e-15)); } } // namespace } // namespace cart_pole } // namespace multibody } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cylinder_with_multicontact/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", ) package(default_visibility = ["//visibility:private"]) drake_cc_library( name = "populate_cylinder_plant", srcs = [ "populate_cylinder_plant.cc", ], hdrs = [ "populate_cylinder_plant.h", ], deps = [ "//common:default_scalars", "//geometry:geometry_ids", "//geometry:scene_graph", "//math:geometric_transform", "//multibody/plant", ], ) drake_cc_googletest( name = "populate_cylinder_plant_test", deps = [ ":populate_cylinder_plant", "//common/test_utilities:eigen_matrix_compare", "//multibody/plant", "//systems/framework:diagram_builder", ], ) drake_cc_binary( name = "cylinder_run_dynamics", srcs = ["cylinder_run_dynamics.cc"], # Running this example with the default parameters incurs in a case with # a violent collision between the cylinder and the ground. MultibodyPlant # must use sub-stepping in order to handle this situation. Otherwise the # contact solver aborts with a non-convergence error. # Therefore the success of this test indicates MultibodyPlant correctly # identified this event and used sub-stepping. add_test_rule = 1, test_rule_args = [ # If MultibodyPlant does not use sub-stepping, i.e attempts to handle # the collision with the default time step of 1.0e-3 seconds, the # simulation will abort at t = 0.514 seconds due to non-convergence of # the contact solver. Therefore we run this example as a test past that # time in order to test that MultibodyPlant correctly handled this case # using sub-stepping. "--simulation_time=0.6", "--target_realtime_rate=0.0", ], test_rule_timeout = "long", deps = [ ":populate_cylinder_plant", "//common:add_text_logging_gflags", "//lcm", "//systems/analysis:simulator", "//systems/framework:diagram", "//systems/lcm:lcm_pubsub_system", "//visualization:visualization_config_functions", "@gflags", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cylinder_with_multicontact/cylinder_run_dynamics.cc
#include <memory> #include <gflags/gflags.h> #include "drake/common/drake_assert.h" #include "drake/examples/multibody/cylinder_with_multicontact/populate_cylinder_plant.h" #include "drake/geometry/scene_graph.h" #include "drake/lcm/drake_lcm.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_publisher_system.h" #include "drake/visualization/visualization_config_functions.h" namespace drake { namespace examples { namespace multibody { namespace cylinder_with_multicontact { inline namespace kcov339_avoidance_magic { namespace { DEFINE_double(target_realtime_rate, 0.5, "Desired rate relative to real time. See documentation for " "Simulator::set_target_realtime_rate() for details."); DEFINE_double(simulation_time, 10.0, "Desired duration of the simulation in seconds."); DEFINE_double(z0, 0.5, "The initial height of the cylinder, m."); DEFINE_double(vx0, 1.0, "The initial x-velocity of the cylinder, m/s."); DEFINE_double(wx0, 0.1, "The initial x-angular velocity of the cylinder, rad/s."); DEFINE_double(friction_coefficient, 0.3, "The friction coefficient of both the cylinder and the ground."); DEFINE_double(penetration_allowance, 1.0e-3, "Penetration allowance. [m]. " "See MultibodyPlant::set_penetration_allowance()."); DEFINE_double(stiction_tolerance, 1.0e-4, "The maximum slipping speed allowed during stiction. [m/s]"); DEFINE_double(time_step, 1.0e-3, "If zero, the plant is modeled as a continuous system. " "If positive, the period (in seconds) of the discrete updates " "for the plant modeled as a discrete system." "This parameter must be non-negative."); using Eigen::Vector3d; using geometry::SceneGraph; // "multibody" namespace is ambiguous here without "drake::". using drake::multibody::AddMultibodyPlantSceneGraph; using drake::multibody::CoulombFriction; using drake::multibody::SpatialVelocity; int do_main() { systems::DiagramBuilder<double> builder; auto [plant, scene_graph] = AddMultibodyPlantSceneGraph(&builder, FLAGS_time_step); // Plant's parameters. const double radius = 0.05; // The cylinder's radius, m const double mass = 0.1; // The cylinder's mass, kg const double g = 9.81; // Acceleration of gravity, m/s^2 const double length = 4.0 * radius; // The cylinder's length, m. const CoulombFriction<double> coulomb_friction( FLAGS_friction_coefficient /* static friction */, FLAGS_friction_coefficient /* dynamic friction */); PopulateCylinderPlant(radius, length, mass, coulomb_friction, -g * Vector3d::UnitZ(), &plant); plant.Finalize(); // Set how much penetration (in meters) we are willing to accept. plant.set_penetration_allowance(FLAGS_penetration_allowance); plant.set_stiction_tolerance(FLAGS_stiction_tolerance); DRAKE_DEMAND(plant.num_velocities() == 6); DRAKE_DEMAND(plant.num_positions() == 7); visualization::AddDefaultVisualization(&builder); auto diagram = builder.Build(); // Create a context for this system: std::unique_ptr<systems::Context<double>> diagram_context = diagram->CreateDefaultContext(); systems::Context<double>& plant_context = diagram->GetMutableSubsystemContext(plant, diagram_context.get()); // Set at height z0. math::RigidTransformd X_WB(Vector3d(0.0, 0.0, FLAGS_z0)); const auto& cylinder = plant.GetBodyByName("Cylinder"); plant.SetFreeBodyPose(&plant_context, cylinder, X_WB); plant.SetFreeBodySpatialVelocity( &plant_context, cylinder, SpatialVelocity<double>( Vector3<double>(FLAGS_wx0, 0.0, 0.0), Vector3<double>(FLAGS_vx0, 0.0, 0.0))); systems::Simulator<double> simulator(*diagram, std::move(diagram_context)); simulator.set_publish_every_time_step(true); simulator.set_target_realtime_rate(FLAGS_target_realtime_rate); simulator.Initialize(); simulator.AdvanceTo(FLAGS_simulation_time); return 0; } } // namespace } // inline namespace kcov339_avoidance_magic } // namespace cylinder_with_multicontact } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A demo for a cylinder falling towards the ground using Drake's" "MultibodyPlant, with SceneGraph contact handling and visualization. " "Launch meldis before running this example."); gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::cylinder_with_multicontact::do_main(); }
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cylinder_with_multicontact/populate_cylinder_plant.cc
#include "drake/examples/multibody/cylinder_with_multicontact/populate_cylinder_plant.h" #include "drake/multibody/tree/uniform_gravity_field_element.h" namespace drake { namespace examples { namespace multibody { namespace cylinder_with_multicontact { using drake::multibody::CoulombFriction; using drake::multibody::MultibodyPlant; using drake::multibody::RigidBody; using drake::multibody::SpatialInertia; using drake::multibody::UnitInertia; using Eigen::Vector3d; using geometry::Cylinder; using geometry::HalfSpace; using geometry::Sphere; using math::RigidTransformd; void AddCylinderWithMultiContact( MultibodyPlant<double>* plant, const RigidBody<double>& body, double radius, double length, const CoulombFriction<double>& friction, double contact_spheres_radius, int num_contacts) { const Vector4<double> orange(1.0, 0.55, 0.0, 1.0); const Vector4<double> red(1.0, 0.0, 0.0, 1.0); // Visual for the Cylinder plant->RegisterVisualGeometry( body, /* Pose X_BG of the geometry frame G in the cylinder body frame B. */ RigidTransformd::Identity(), Cylinder(radius, length), "visual", orange); // Add a bunch of little spheres to simulate "multi-contact". for (int i = 0; i < num_contacts; ++i) { const double theta = 2.0 * i / num_contacts * M_PI; const double x = cos(theta) * radius; const double y = sin(theta) * radius; // Top spheres: /* Pose X_BG of the geometry frame G in the cylinder body frame B. */ const RigidTransformd X_BS1(Vector3d(x, y, length / 2)); plant->RegisterCollisionGeometry( body, X_BS1, Sphere(contact_spheres_radius), "collision_top_" + std::to_string(i), friction); plant->RegisterVisualGeometry(body, X_BS1, Sphere(contact_spheres_radius), "visual_top_" + std::to_string(i), red); // Bottom spheres: const RigidTransformd X_BS2(Vector3d(x, y, -length / 2)); plant->RegisterCollisionGeometry( body, X_BS2, Sphere(contact_spheres_radius), "collision_bottom_" + std::to_string(i), friction); plant->RegisterVisualGeometry(body, X_BS2, Sphere(contact_spheres_radius), "visual_bottom_" + std::to_string(i), red); } } void PopulateCylinderPlant(double radius, double length, double mass, const CoulombFriction<double>& surface_friction, const Vector3<double>& gravity_W, MultibodyPlant<double>* plant) { const SpatialInertia<double> M_Bcm = SpatialInertia<double>::SolidCylinderWithMass( mass, radius, length, Vector3<double>::UnitZ()); const RigidBody<double>& cylinder = plant->AddRigidBody("Cylinder", M_Bcm); // The radius of the small spheres used to emulate multicontact. const double contact_radius = radius / 20.0; // The number of small spheres places at each rim of the cylinder to emulate // multicontact. const int num_contact_spheres = 10; // Add geometry to the cylinder for both contact and visualization. AddCylinderWithMultiContact( plant, cylinder, radius, length, surface_friction, contact_radius, num_contact_spheres); // Add a model for the ground. Vector3<double> normal_W(0, 0, 1); Vector3<double> point_W(0, 0, 0); // A half-space for the ground geometry. RigidTransformd X_WG(HalfSpace::MakePose(normal_W, point_W)); plant->RegisterCollisionGeometry(plant->world_body(), X_WG, HalfSpace(), "collision", surface_friction); // Add visual for the ground. plant->RegisterVisualGeometry( plant->world_body(), X_WG, HalfSpace(), "visual"); plant->mutable_gravity_field().set_gravity_vector(gravity_W); } } // namespace cylinder_with_multicontact } // namespace multibody } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody
/home/johnshepherd/drake/examples/multibody/cylinder_with_multicontact/populate_cylinder_plant.h
#pragma once #include <memory> #include "drake/geometry/scene_graph.h" #include "drake/multibody/plant/multibody_plant.h" namespace drake { namespace examples { namespace multibody { namespace cylinder_with_multicontact { /// This function populates the given MultibodyPlant with a model of a cylinder /// free to fall onto the ground. /// The model adds a fixed number of spheres (10) around each rim of the /// cylinder as a way of emulating multicontact so that we can evaluate /// MultibodyPlant's contact solver. /// MultibodyPlant models the contact of the ball with the ground as a perfectly /// inelastic collision (zero coefficient of restitution), i.e. energy is lost /// due to the collision. /// /// @param[in] radius /// The radius of the cylinder. /// @param[in] length /// The length of the cylinder. /// @param[in] mass /// The mass of the cylinder. /// @param[in] surface_friction /// The Coulomb's law coefficients of friction. /// @param[in] gravity_W /// The acceleration of gravity vector, expressed in the world frame W. /// @param plant /// A valid pointer to a MultibodyPlant. This function will register /// geometry for contact modeling. /// @pre `plant` is not null, finalized, and is registered with a SceneGraph. /// @note The given plant is not finalized. You must call Finalize() on the new /// model once you are done populating it. void PopulateCylinderPlant( double radius, double length, double mass, const drake::multibody::CoulombFriction<double>& surface_friction, const Vector3<double>& gravity_W, drake::multibody::MultibodyPlant<double>* plant); } // namespace cylinder_with_multicontact } // namespace multibody } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/multibody/cylinder_with_multicontact
/home/johnshepherd/drake/examples/multibody/cylinder_with_multicontact/test/populate_cylinder_plant_test.cc
#include "drake/examples/multibody/cylinder_with_multicontact/populate_cylinder_plant.h" #include <limits> #include <memory> #include <gtest/gtest.h> #include "drake/common/eigen_types.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace examples { namespace multibody { namespace cylinder_with_multicontact { namespace { using drake::multibody::AddMultibodyPlantSceneGraph; using drake::multibody::CoulombFriction; using drake::multibody::RigidBody; using drake::multibody::SpatialInertia; using drake::systems::DiagramBuilder; using Eigen::Vector3d; GTEST_TEST(PopulateCylinderPlant, VerifyPlant) { // Plant's parameters. const double radius = 0.05; // The cylinder's radius, m const double mass = 0.1; // The cylinder's mass, kg const double g = 9.81; // Acceleration of gravity, m/s^2 const double length = 4.0 * radius; // The cylinder's length, m. const CoulombFriction<double> coulomb_friction( 0.5 /* static friction */, 0.5 /* dynamic friction */); // Time stepping step size. const double time_step = 1.0e-3; // The builder is garbage; we won't be building the diagram, we just need // this to use AddMultibodyPlantSceneGraph. DiagramBuilder<double> builder; auto [plant, scene_graph] = AddMultibodyPlantSceneGraph(&builder, time_step); PopulateCylinderPlant(radius, length, mass, coulomb_friction, -g * Vector3d::UnitZ(), &plant); plant.Finalize(); EXPECT_EQ(plant.num_velocities(), 6); EXPECT_EQ(plant.num_positions(), 7); EXPECT_EQ(plant.time_step(), time_step); EXPECT_TRUE(plant.geometry_source_is_registered()); ASSERT_TRUE(plant.HasBodyNamed("Cylinder")); const RigidBody<double>& cylinder = plant.GetRigidBodyByName("Cylinder"); EXPECT_EQ(cylinder.default_mass(), mass); // Verify the value of the inertial properties for the cylinder. const SpatialInertia<double>& M_Bcm_B = cylinder.default_spatial_inertia(); // Unit inertia about the revolute axis, the z axis, of the cylinder. const double G_axis = radius * radius / 2.0; // Unit inertia about any axis perpendicular to the revolute axis passing // through the COM. const double G_perp = (3.0 * radius * radius + length * length) / 12.0; EXPECT_EQ(M_Bcm_B.get_mass(), mass); EXPECT_EQ(M_Bcm_B.get_com(), Vector3d::Zero()); // An empirical tolerance: two bits = 2^2 times machine epsilon. const double kTolerance = 4 * std::numeric_limits<double>::epsilon(); EXPECT_TRUE(CompareMatrices(M_Bcm_B.get_unit_inertia().get_moments(), Vector3d(G_perp, G_perp, G_axis), kTolerance)); EXPECT_EQ(M_Bcm_B.get_unit_inertia().get_products(), Vector3d::Zero()); // TODO(amcastro-tri): Verify geometry including: // - The number of registered geometries. // - Whether it is for visualization or contact modeling. // - Obtain geometry specifics; type, radius, length, etc. // - Obtain friction coefficients for each geometry. // However, we need proper SceneGraph/MBP APIs to enable this. // TODO(amcastro-tri): verify gravity is correct. // We need an API to retrieve the gravity force element, #9253. } } // namespace } // namespace cylinder_with_multicontact } // namespace multibody } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/BUILD.bazel
load("//tools/install:install_data.bzl", "install_data") load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_binary", "drake_cc_googletest", "drake_cc_library", ) load("//tools/skylark:drake_data.bzl", "models_filegroup") package(default_visibility = ["//visibility:private"]) models_filegroup( name = "glob_models", ) install_data( name = "install_data", data = [":glob_models"], visibility = ["//visibility:public"], ) filegroup( name = "models", srcs = [ ":glob_models", "@drake_models//:skydio_2", ], visibility = ["//visibility:public"], ) drake_cc_library( name = "quadrotor_plant", srcs = ["quadrotor_plant.cc"], hdrs = ["quadrotor_plant.h"], visibility = ["//visibility:public"], deps = [ "//common:default_scalars", "//math:geometric_transform", "//systems/controllers:linear_quadratic_regulator", "//systems/framework:leaf_system", "//systems/primitives:affine_system", ], ) drake_cc_library( name = "quadrotor_geometry", srcs = ["quadrotor_geometry.cc"], hdrs = ["quadrotor_geometry.h"], data = [":models"], visibility = ["//visibility:public"], deps = [ "//geometry:scene_graph", "//math:geometric_transform", "//multibody/parsing", "//multibody/plant", "//systems/framework:diagram_builder", "//systems/framework:leaf_system", ], ) drake_cc_binary( name = "run_quadrotor_dynamics", srcs = ["run_quadrotor_dynamics.cc"], add_test_rule = 1, data = [":models"], test_rule_args = [ "--duration=0.1", "--initial_height=0.051", ], deps = [ ":quadrotor_plant", "//common:add_text_logging_gflags", "//multibody/parsing", "//multibody/plant", "//systems/analysis:simulator", "//systems/analysis:simulator_gflags", "//systems/framework:diagram", "//systems/primitives:constant_vector_source", "//visualization:visualization_config_functions", "@gflags", ], ) drake_cc_binary( name = "run_quadrotor_lqr", srcs = ["run_quadrotor_lqr.cc"], add_test_rule = 1, test_rule_args = [ "-simulation_trials=2", "-simulation_real_time_rate=0.0", ], deps = [ ":quadrotor_geometry", ":quadrotor_plant", "//common:is_approx_equal_abstol", "//geometry:drake_visualizer", "//lcm", "//systems/analysis:simulator", "//systems/framework:diagram", "@gflags", ], ) drake_cc_googletest( name = "quadrotor_plant_test", deps = [ ":quadrotor_plant", "//common/test_utilities:expect_no_throw", "//systems/framework/test_utilities", ], ) drake_cc_googletest( name = "quadrotor_dynamics_test", data = [":models"], deps = [ ":quadrotor_plant", "//common/test_utilities:eigen_matrix_compare", "//multibody/parsing", "//multibody/plant", "//systems/analysis:simulator", "//systems/framework:diagram", "//systems/primitives:constant_vector_source", ], ) drake_cc_googletest( name = "quadrotor_geometry_test", deps = [ ":quadrotor_geometry", ":quadrotor_plant", ], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/run_quadrotor_lqr.cc
/// @file /// /// This demo sets up a controlled Quadrotor that uses a Linear Quadratic /// Regulator to (locally) stabilize a nominal hover. /// /// Use meldis to view the visualization: /// bazel run //tools:meldis -- -w #include <memory> #include <gflags/gflags.h> #include "drake/common/is_approx_equal_abstol.h" #include "drake/examples/quadrotor/quadrotor_geometry.h" #include "drake/examples/quadrotor/quadrotor_plant.h" #include "drake/geometry/drake_visualizer.h" #include "drake/lcm/drake_lcm.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" DEFINE_int32(simulation_trials, 10, "Number of trials to simulate."); DEFINE_double(simulation_real_time_rate, 1.0, "Real time rate"); DEFINE_double(trial_duration, 7.0, "Duration of execution of each trial"); namespace drake { using systems::DiagramBuilder; using systems::Simulator; using systems::Context; using systems::ContinuousState; using systems::VectorBase; namespace examples { namespace quadrotor { namespace { int do_main() { lcm::DrakeLcm lcm; DiagramBuilder<double> builder; // The nominal hover position is at (0, 0, 1.0) in world coordinates. const Eigen::Vector3d kNominalPosition{((Eigen::Vector3d() << 0.0, 0.0, 1.0). finished())}; auto quadrotor = builder.AddSystem<QuadrotorPlant<double>>(); quadrotor->set_name("quadrotor"); auto controller = builder.AddSystem(StabilizingLQRController( quadrotor, kNominalPosition)); controller->set_name("controller"); builder.Connect(quadrotor->get_output_port(0), controller->get_input_port()); builder.Connect(controller->get_output_port(), quadrotor->get_input_port(0)); // Set up visualization auto scene_graph = builder.AddSystem<geometry::SceneGraph>(); QuadrotorGeometry::AddToBuilder( &builder, quadrotor->get_output_port(0), scene_graph); geometry::DrakeVisualizerd::AddToBuilder(&builder, *scene_graph); auto diagram = builder.Build(); Simulator<double> simulator(*diagram); VectorX<double> x0 = VectorX<double>::Zero(12); const VectorX<double> kNominalState{((Eigen::VectorXd(12) << kNominalPosition, Eigen::VectorXd::Zero(9)).finished())}; srand(42); for (int i = 0; i < FLAGS_simulation_trials; i++) { auto diagram_context = diagram->CreateDefaultContext(); x0 = VectorX<double>::Random(12); simulator.get_mutable_context() .get_mutable_continuous_state_vector() .SetFromVector(x0); simulator.Initialize(); simulator.set_target_realtime_rate(FLAGS_simulation_real_time_rate); // The following accuracy is necessary for the example to satisfy its // ending state tolerances. simulator.get_mutable_integrator().set_target_accuracy(5e-5); simulator.AdvanceTo(FLAGS_trial_duration); // Goal state verification. const Context<double>& context = simulator.get_context(); const ContinuousState<double>& state = context.get_continuous_state(); const VectorX<double>& position_vector = state.CopyToVector(); if (!is_approx_equal_abstol( position_vector, kNominalState, 1e-4)) { throw std::runtime_error("Target state is not achieved."); } simulator.reset_context(std::move(diagram_context)); } return 0; } } // namespace } // namespace quadrotor } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::quadrotor::do_main(); }
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/run_quadrotor_dynamics.cc
/// @file /// /// This demo sets up a passive Quadrotor plant in a world described by the /// warehouse model. The robot simply passively falls to the floor within the /// walls of the warehouse, falling from the initial_height command line /// argument. #include <gflags/gflags.h> #include "drake/common/text_logging.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" #include "drake/systems/analysis/runge_kutta2_integrator.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/analysis/simulator_gflags.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/constant_vector_source.h" #include "drake/visualization/visualization_config_functions.h" namespace drake { namespace examples { namespace quadrotor { namespace { DEFINE_double(duration, 0.5, "Total duration of simulation."); DEFINE_double(initial_height, 0.051, "Initial height of the Quadrotor."); template <typename T> class Quadrotor : public systems::Diagram<T> { public: Quadrotor() { this->set_name("Quadrotor"); systems::DiagramBuilder<T> builder; auto [plant, scene_graph] = multibody::AddMultibodyPlantSceneGraph(&builder, 0.0); multibody::Parser parser(&plant); parser.AddModelsFromUrl( "package://drake_models/skydio_2/quadrotor.urdf"); parser.AddModelsFromUrl( "package://drake/examples/quadrotor/warehouse.sdf"); plant.Finalize(); DRAKE_DEMAND(plant.num_actuators() == 0); DRAKE_DEMAND(plant.num_positions() == 7); visualization::AddDefaultVisualization(&builder); builder.BuildInto(this); plant_ = &plant; } void SetDefaultState(const systems::Context<T>& context, systems::State<T>* state) const override { DRAKE_DEMAND(state != nullptr); systems::Diagram<T>::SetDefaultState(context, state); const systems::Context<T>& plant_context = this->GetSubsystemContext(*plant_, context); systems::State<T>& plant_state = this->GetMutableSubsystemState(*plant_, state); const math::RigidTransform<T> X_WB( Vector3<T>{0.0, 0.0, FLAGS_initial_height}); plant_->SetFreeBodyPose( plant_context, &plant_state, plant_->GetBodyByName("base_link"), X_WB); } private: multibody::MultibodyPlant<T>* plant_{}; }; int do_main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); const Quadrotor<double> model; auto simulator = MakeSimulatorFromGflags(model); simulator->AdvanceTo(FLAGS_duration); return 0; } } // namespace } // namespace quadrotor } // namespace examples } // namespace drake int main(int argc, char* argv[]) { return drake::examples::quadrotor::do_main(argc, argv); }
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/README.md
The Quadrotor - an underactuated aerial vehicle =============================================== This directory contains models and a plant for a Quadrotor. You can try out sample programs; each has its own overview atop the file: - `run_quadrotor_dynamics` - `run_quadrotor_lqr`
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/office.urdf
<?xml version="1.0"?> <robot name="office"> <material name="Brown"> <color rgba="0.33 0.21 0.04 1"/> </material> <material name="White"> <color rgba="1 1 1 1"/> </material> <material name="Grey"> <color rgba=".3 .3 .3 1"/> </material> <material name="Red"> <color rgba="1 0 0 1"/> </material> <link name="wall1"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="0 0 1" rpy="0 0 0"/> <geometry> <box size="10 .1 2."/> </geometry> <material name="Brown"/> </visual> <collision> <origin xyz="0 0 1" rpy="0 0 0"/> <geometry> <box size="10 .1 2."/> </geometry> </collision> </link> <link name="wall2"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="0 0 0" rpy="0 0 0"/> <geometry> <box size=".1 8. 2."/> </geometry> <material name="Brown"/> </visual> <collision> <origin xyz="0 0 0" rpy="0 0 0"/> <geometry> <box size=".1 8. 2."/> </geometry> </collision> </link> <link name="wall3"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="0 0. .5" rpy="0 0 0"/> <geometry> <box size="10 .1 1."/> </geometry> <material name="Brown"/> </visual> <collision> <origin xyz="0 0. .5" rpy="0 0 0"/> <geometry> <box size="10 .1 1."/> </geometry> </collision> </link> <link name="wall4"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="0 0 0" rpy="0 0 0"/> <geometry> <box size=".1 8. 2."/> </geometry> <material name="Brown"/> </visual> <collision> <origin xyz="0 0 0" rpy="0 0 0"/> <geometry> <box size=".1 8. 2."/> </geometry> </collision> </link> <link name="internalWall"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="0 0 0" rpy="0 0 0"/> <geometry> <box size="7.5 .1 2."/> </geometry> <material name="Brown"/> </visual> <collision> <origin xyz="0 0 0" rpy="0 0 0"/> <geometry> <box size="7.5 .1 2."/> </geometry> </collision> </link> <link name="tableLegUL"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="-1 3 .5" rpy="0 0 0"/> <geometry> <box size=".1 .1 1."/> </geometry> <material name="White"/> </visual> <collision> <origin xyz="-1 3 .5" rpy="0 0 0"/> <geometry> <box size=".1 .1 1."/> </geometry> </collision> </link> <link name="wall23"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <!-- <origin xyz="1.75 8. 1" rpy="0 0 0" /> --> <origin xyz="1.75 0. 1" rpy="0 0 0"/> <geometry> <box size="6.5 .1 2."/> </geometry> <material name="Brown"/> </visual> <collision> <origin xyz="1.75 0. 1" rpy="0 0 0"/> <geometry> <box size="6.5 .1 2."/> </geometry> </collision> </link> <link name="wall34"> <inertial> <mass value=".5"/> <origin xyz="0 0. 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <!-- <origin xyz="-4.125 8. 1" rpy="0 0 0" /> --> <origin xyz="-4.125 0. 1" rpy="0 0 0"/> <geometry> <box size="1.75 .1 2."/> </geometry> <material name="Brown"/> </visual> <collision> <origin xyz="-4.125 0. 1" rpy="0 0 0"/> <geometry> <box size="1.75 .1 2."/> </geometry> </collision> </link> <link name="tableLegUR"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="1 3 .5" rpy="0 0 0"/> <geometry> <box size=".1 .1 1."/> </geometry> <material name="White"/> </visual> <collision> <origin xyz="1 3 .5" rpy="0 0 0"/> <geometry> <box size=".1 .1 1."/> </geometry> </collision> </link> <link name="tableLegLR"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="1 1 .5" rpy="0 0 0"/> <geometry> <box size=".1 .1 1."/> </geometry> <material name="White"/> </visual> <collision> <origin xyz="1 1 .5" rpy="0 0 0"/> <geometry> <box size=".1 .1 1."/> </geometry> </collision> </link> <link name="tableLegLL"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="-1 1 .5" rpy="0 0 0"/> <geometry> <box size=".1 .1 1."/> </geometry> <material name="White"/> </visual> <collision> <origin xyz="-1 1 .5" rpy="0 0 0"/> <geometry> <box size=".1 .1 1."/> </geometry> </collision> </link> <link name="TableTop"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="0 2 .98" rpy="0 0 0"/> <geometry> <box size="2.1 2.1 .1"/> </geometry> <material name="Grey"/> </visual> <collision> <origin xyz="0 2 .98" rpy="0 0 0"/> <geometry> <box size="2.1 2.1 .1"/> </geometry> </collision> </link> <link name="cabinet"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="-3.3 5.5 .9" rpy="0 0 0"/> <geometry> <box size="2.2 1. 1.8"/> </geometry> <material name="Grey"/> </visual> <collision> <origin xyz="-3.3 5.5 .9" rpy="0 0 0"/> <geometry> <box size="2.2 1. 1.8"/> </geometry> </collision> </link> <link name="drawer1"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="-3.3 5.3 .9" rpy="0 0 0"/> <geometry> <box size="2. 1. .33"/> </geometry> <material name="White"/> </visual> <collision> <origin xyz="-3.3 5.3 .9" rpy="0 0 0"/> <geometry> <box size="2. 1. .33"/> </geometry> </collision> </link> <link name="drawer2"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="-3.3 5.3 1.4" rpy="0 0 0"/> <geometry> <box size="2. 1. .33"/> </geometry> <material name="White"/> </visual> <collision> <origin xyz="-3.3 5.3 1.4" rpy="0 0 0"/> <geometry> <box size="2. 1. .33"/> </geometry> </collision> </link> <link name="drawer3"> <inertial> <mass value=".5"/> <origin xyz="0 0 0" rpy="0 0 0"/> <inertia ixx="10" ixy="0" ixz="0" iyy="10" iyz="0" izz="10"/> </inertial> <visual> <origin xyz="-3.3 5.3 .4" rpy="0 0 0"/> <geometry> <box size="2. 1. .33"/> </geometry> <material name="White"/> </visual> <collision> <origin xyz="-3.3 5.3 .4" rpy="0 0 0"/> <geometry> <box size="2. 1. .33"/> </geometry> </collision> </link> <joint name="joint1" type="fixed"> <parent link="wall1"/> <child link="wall2"/> <origin xyz="5 4 1" rpy="0 0 0"/> </joint> <joint name="joint2" type="fixed"> <parent link="wall2"/> <child link="wall3"/> <origin xyz="-5 4 -1" rpy="0 0 0"/> </joint> <joint name="joint3" type="fixed"> <parent link="wall3"/> <child link="wall4"/> <origin xyz="-5 -4 1" rpy="0 0 0"/> </joint> <joint name="lowerToUpperWall3From2" type="fixed"> <parent link="wall3"/> <child link="wall23"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="lowerToUpperWall3From4" type="fixed"> <parent link="wall3"/> <child link="wall34"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="internalJoint" type="fixed"> <parent link="wall4"/> <child link="internalWall"/> <origin xyz="3.75 2 0" rpy="0 0 0"/> </joint> <joint name="WallToTableTop" type="fixed"> <parent link="wall1"/> <child link="TableTop"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="TableTopToLegUL" type="fixed"> <parent link="TableTop"/> <child link="tableLegUL"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="TableTopToLegUR" type="fixed"> <parent link="TableTop"/> <child link="tableLegUR"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="TableTopToLegLR" type="fixed"> <parent link="TableTop"/> <child link="tableLegLR"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="TableTopToLegLL" type="fixed"> <parent link="TableTop"/> <child link="tableLegLL"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="WallToCabinet" type="fixed"> <parent link="wall1"/> <child link="cabinet"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="CabinetToDrawer1" type="fixed"> <parent link="cabinet"/> <child link="drawer1"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="CabinetToDrawer2" type="fixed"> <parent link="cabinet"/> <child link="drawer2"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> <joint name="CabinetToDrawer3" type="fixed"> <parent link="cabinet"/> <child link="drawer3"/> <origin xyz="0 0 0" rpy="0 0 0"/> </joint> </robot>
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/quadrotor_plant.h
#pragma once #include <memory> #include <Eigen/Core> #include "drake/systems/framework/basic_vector.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/primitives/affine_system.h" namespace drake { namespace examples { namespace quadrotor { /// The Quadrotor - an underactuated aerial vehicle. This version of the /// Quadrotor is implemented to match the dynamics of the plant specified in /// the `package://drake_models/skydio_2/quadrotor.urdf` model file. /// /// @system /// name: QuadrotorPlant /// input_ports: /// - propeller_force (optional) /// output_ports: /// - state /// @endsystem /// /// Note: If the propeller_force input port is not connected, then the force is /// taken to be zero. /// /// @tparam_default_scalar template <typename T> class QuadrotorPlant final : public systems::LeafSystem<T> { public: QuadrotorPlant(); QuadrotorPlant(double m_arg, double L_arg, const Eigen::Matrix3d& I_arg, double kF_arg, double kM_arg); /// Scalar-converting copy constructor. See @ref system_scalar_conversion. template <typename U> explicit QuadrotorPlant(const QuadrotorPlant<U>&); ~QuadrotorPlant() override; [[nodiscard]] double m() const { return m_; } [[nodiscard]] double g() const { return g_; } [[nodiscard]] double length() const { return L_; } [[nodiscard]] double force_constant() const { return kF_; } [[nodiscard]] double moment_constant() const { return kM_; } [[nodiscard]] const Eigen::Matrix3d& inertia() const { return I_; } private: void DoCalcTimeDerivatives( const systems::Context<T>& context, systems::ContinuousState<T>* derivatives) const override; // Allow different specializations to access each other's private data. template <typename> friend class QuadrotorPlant; // TODO(naveenoid): Declare these as parameters in the context. const double g_; // Gravitational acceleration (m/s^2). const double m_; // Mass of the robot (kg). const double L_; // Length of the arms (m). const double kF_; // Force input constant. const double kM_; // Moment input constant. const Eigen::Matrix3d I_; // Moment of Inertia about the Center of Mass }; /// Generates an LQR controller to move to @p nominal_position. Internally /// computes the nominal input corresponding to a hover at position @p x0. /// @see systems::LinearQuadraticRegulator. std::unique_ptr<systems::AffineSystem<double>> StabilizingLQRController( const QuadrotorPlant<double>* quadrotor_plant, Eigen::Vector3d nominal_position); } // namespace quadrotor } // namespace examples } // namespace drake DRAKE_DECLARE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::examples::quadrotor::QuadrotorPlant)
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/warehouse.sdf
<?xml version="1.0"?> <sdf version="1.7"> <model name="room_w_lidar"> <static>1</static> <link name="bottom_wall"> <pose>3.5 -0.25 -1.6 0 0 0</pose> <visual name="wall"> <geometry> <box> <size>10 4.5 0.2</size> </box> </geometry> </visual> <collision name="wall"> <geometry> <box> <size>10 4.5 0.2</size> </box> </geometry> </collision> </link> <link name="left_wall"> <pose>3.5 1.75 0 0 0 0</pose> <visual name="wall"> <geometry> <box> <size>9 0.5 3</size> </box> </geometry> </visual> <collision name="wall"> <geometry> <box> <size>9 0.5 3</size> </box> </geometry> </collision> </link> <link name="right_wall"> <pose>3.5 -2.25 0 0 0 0</pose> <visual name="wall"> <geometry> <box> <size>9 0.5 3</size> </box> </geometry> </visual> <collision name="wall"> <geometry> <box> <size>9 0.5 3</size> </box> </geometry> </collision> </link> <link name="back_wall"> <pose>-1.25 -0.25 0 0 0 0</pose> <visual name="wall"> <geometry> <box> <size>0.5 4.5 3</size> </box> </geometry> </visual> <collision name="wall"> <geometry> <box> <size>0.5 4.5 3</size> </box> </geometry> </collision> </link> <link name="front_wall"> <pose>8.25 -0.25 0 0 0 0</pose> <visual name="wall"> <geometry> <box> <size>0.5 4.5 3</size> </box> </geometry> </visual> <collision name="wall"> <geometry> <box> <size>0.5 4.5 3</size> </box> </geometry> </collision> </link> <link name="slalom_1"> <pose>1.75 0.5 0 0 0 0</pose> <visual name="wall"> <geometry> <box> <size>0.5 2 3</size> </box> </geometry> </visual> <collision name="wall"> <geometry> <box> <size>0.5 2 3</size> </box> </geometry> </collision> </link> <link name="slalom_2"> <pose>3.75 -1 0 0 0 0</pose> <visual name="wall"> <geometry> <box> <size>0.5 2 3</size> </box> </geometry> </visual> <collision name="wall"> <geometry> <box> <size>0.5 2 3</size> </box> </geometry> </collision> </link> <link name="slalom_3"> <pose>5.75 0.5 0 0 0 0</pose> <visual name="wall"> <geometry> <box> <size>0.5 2 3</size> </box> </geometry> </visual> <collision name="wall"> <geometry> <box> <size>0.5 2 3</size> </box> </geometry> </collision> </link> </model> </sdf>
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/quadrotor_geometry.h
#pragma once #include "drake/geometry/scene_graph.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace examples { namespace quadrotor { /// Expresses a QuadrotorPlant's geometry to a SceneGraph. /// /// @system /// name: QuadrotorGeometry /// input_ports: /// - state /// output_ports: /// - geometry_pose /// @endsystem /// /// This class has no public constructor; instead use the AddToBuilder() static /// method to create and add it to a DiagramBuilder directly. class QuadrotorGeometry final : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QuadrotorGeometry); ~QuadrotorGeometry() final; /// Returns the frame of the geometry registered with a SceneGraph. This can /// be useful, e.g., if one would like to add a camera to the quadrotor. geometry::FrameId get_frame_id() const { return frame_id_; } /// Creates, adds, and connects a QuadrotorGeometry system into the given /// `builder`. Both the `quadrotor_state.get_system()` and `scene_graph` /// systems must have been added to the given `builder` already. /// /// The `scene_graph` pointer is not retained by the %QuadrotorGeometry /// system. The return value pointer is an alias of the new /// %QuadrotorGeometry system that is owned by the `builder`. static const QuadrotorGeometry* AddToBuilder( systems::DiagramBuilder<double>* builder, const systems::OutputPort<double>& quadrotor_state_port, geometry::SceneGraph<double>* scene_graph); private: explicit QuadrotorGeometry(geometry::SceneGraph<double>*); void OutputGeometryPose(const systems::Context<double>&, geometry::FramePoseVector<double>*) const; // Geometry source identifier for this system to interact with SceneGraph. geometry::SourceId source_id_{}; // The id for the quadrotor body. geometry::FrameId frame_id_{}; }; } // namespace quadrotor } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/quadrotor_plant.cc
#include "drake/examples/quadrotor/quadrotor_plant.h" #include "drake/common/default_scalars.h" #include "drake/math/rotation_matrix.h" #include "drake/systems/controllers/linear_quadratic_regulator.h" using Eigen::Matrix3d; namespace drake { namespace examples { namespace quadrotor { namespace { Matrix3d default_moment_of_inertia() { return (Eigen::Matrix3d() << // BR 0.0015, 0, 0, // BR 0, 0.0025, 0, // BR 0, 0, 0.0035).finished(); } } // namespace template <typename T> QuadrotorPlant<T>::QuadrotorPlant() : QuadrotorPlant(0.775, // m (kg) 0.15, // L (m) default_moment_of_inertia(), 1.0, // kF 0.0245 // kM ) {} template <typename T> QuadrotorPlant<T>::QuadrotorPlant(double m_arg, double L_arg, const Matrix3d& I_arg, double kF_arg, double kM_arg) : systems::LeafSystem<T>(systems::SystemTypeTag<QuadrotorPlant>{}), g_{9.81}, m_(m_arg), L_(L_arg), kF_(kF_arg), kM_(kM_arg), I_(I_arg) { // Four inputs -- one for each propeller. this->DeclareInputPort("propeller_force", systems::kVectorValued, 4); // State is x ,y , z, roll, pitch, yaw + velocities. auto state_index = this->DeclareContinuousState(12); this->DeclareStateOutputPort("state", state_index); // TODO(russt): Declare input limits. R2 has @ 2:1 thrust to weight ratio. } template <typename T> template <typename U> QuadrotorPlant<T>:: QuadrotorPlant(const QuadrotorPlant<U>& other) : QuadrotorPlant<T>(other.m_, other.L_, other.I_, other.kF_, other.kM_) {} template <typename T> QuadrotorPlant<T>::~QuadrotorPlant() {} // TODO(russt): Generalize this to support the rotor locations on the Skydio R2. template <typename T> void QuadrotorPlant<T>::DoCalcTimeDerivatives( const systems::Context<T> &context, systems::ContinuousState<T> *derivatives) const { // Get the input value characterizing each of the 4 rotor's aerodynamics. const systems::BasicVector<T>* u_vec = this->EvalVectorInput(context, 0); const Vector4<T> u = u_vec ? u_vec->value() : Vector4<T>::Zero(); // For each rotor, calculate the Bz measure of its aerodynamic force on B. // Note: B is the quadrotor body and Bz is parallel to each rotor's spin axis. const Vector4<T> uF_Bz = kF_ * u; // Compute the net aerodynamic force on B (from the 4 rotors), expressed in B. const Vector3<T> Faero_B(0, 0, uF_Bz.sum()); // Compute the Bx and By measures of the moment on B about Bcm (B's center of // mass) from the 4 rotor forces. These moments arise from the cross product // of a position vector with an aerodynamic force at the center of each rotor. // For example, the moment of the aerodynamic forces on rotor 0 about Bcm // results from Cross( L_* Bx, uF_Bz(0) * Bz ) = -L_ * uF_Bz(0) * By. const T Mx = L_ * (uF_Bz(1) - uF_Bz(3)); const T My = L_ * (uF_Bz(2) - uF_Bz(0)); // For rotors 0 and 2, get the Bz measure of its aerodynamic torque on B. // For rotors 1 and 3, get the -Bz measure of its aerodynamic torque on B. // Sum the net Bz measure of the aerodynamic torque on B. // Note: Rotors 0 and 2 rotate one way and rotors 1 and 3 rotate the other. const Vector4<T> uTau_Bz = kM_ * u; const T Mz = uTau_Bz(0) - uTau_Bz(1) + uTau_Bz(2) - uTau_Bz(3); // Form the net moment on B about Bcm, expressed in B. The net moment accounts // for all contact and distance forces (aerodynamic and gravity forces) on B. // Note: Since the net moment on B is about Bcm, gravity does not contribute. const Vector3<T> Tau_B(Mx, My, Mz); // Calculate local celestial body's (Earth's) gravity force on B, expressed in // the Newtonian frame N (a.k.a the inertial or World frame). const Vector3<T> Fgravity_N(0, 0, -m_ * g_); // Extract roll-pitch-yaw angles (rpy) and their time-derivatives (rpyDt). VectorX<T> state = context.get_continuous_state_vector().CopyToVector(); const drake::math::RollPitchYaw<T> rpy(state.template segment<3>(3)); const Vector3<T> rpyDt = state.template segment<3>(9); // Convert roll-pitch-yaw (rpy) orientation to the R_NB rotation matrix. const drake::math::RotationMatrix<T> R_NB(rpy); // Calculate the net force on B, expressed in N. Use Newton's law to // calculate a_NBcm_N (acceleration of B's center of mass, expressed in N). const Vector3<T> Fnet_N = Fgravity_N + R_NB * Faero_B; const Vector3<T> xyzDDt = Fnet_N / m_; // Equal to a_NBcm_N. // Use rpy and rpyDt to calculate B's angular velocity in N, expressed in B. const Vector3<T> w_NB_B = rpy.CalcAngularVelocityInChildFromRpyDt(rpyDt); // To compute α (B's angular acceleration in N) due to the net moment 𝛕 on B, // rearrange Euler rigid body equation 𝛕 = I α + ω × (I ω) and solve for α. const Vector3<T> wIw = w_NB_B.cross(I_ * w_NB_B); // Expressed in B const Vector3<T> alpha_NB_B = I_.ldlt().solve(Tau_B - wIw); // Expressed in B const Vector3<T> alpha_NB_N = R_NB * alpha_NB_B; // Expressed in N // Calculate the 2nd time-derivative of rpy. const Vector3<T> rpyDDt = rpy.CalcRpyDDtFromRpyDtAndAngularAccelInParent(rpyDt, alpha_NB_N); // Recomposing the derivatives vector. VectorX<T> xDt(12); xDt << state.template tail<6>(), xyzDDt, rpyDDt; derivatives->SetFromVector(xDt); } std::unique_ptr<systems::AffineSystem<double>> StabilizingLQRController( const QuadrotorPlant<double>* quadrotor_plant, Eigen::Vector3d nominal_position) { auto quad_context_goal = quadrotor_plant->CreateDefaultContext(); Eigen::VectorXd x0 = Eigen::VectorXd::Zero(12); x0.topRows(3) = nominal_position; // Nominal input corresponds to a hover. Eigen::VectorXd u0 = Eigen::VectorXd::Constant( 4, quadrotor_plant->m() * quadrotor_plant->g() / 4); quadrotor_plant->get_input_port(0).FixValue(quad_context_goal.get(), u0); quad_context_goal->SetContinuousState(x0); // Setup LQR cost matrices (penalize position error 10x more than velocity // error). Eigen::MatrixXd Q = Eigen::MatrixXd::Identity(12, 12); Q.topLeftCorner<6, 6>() = 10 * Eigen::MatrixXd::Identity(6, 6); Eigen::Matrix4d R = Eigen::Matrix4d::Identity(); return systems::controllers::LinearQuadraticRegulator( *quadrotor_plant, *quad_context_goal, Q, R); } } // namespace quadrotor } // namespace examples } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::examples::quadrotor::QuadrotorPlant)
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/quadrotor/quadrotor_geometry.cc
#include "drake/examples/quadrotor/quadrotor_geometry.h" #include <memory> #include "drake/math/rigid_transform.h" #include "drake/math/roll_pitch_yaw.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" using Eigen::Matrix3d; namespace drake { namespace examples { namespace quadrotor { const QuadrotorGeometry* QuadrotorGeometry::AddToBuilder( systems::DiagramBuilder<double>* builder, const systems::OutputPort<double>& quadrotor_state_port, geometry::SceneGraph<double>* scene_graph) { DRAKE_THROW_UNLESS(builder != nullptr); DRAKE_THROW_UNLESS(scene_graph != nullptr); auto quadrotor_geometry = builder->AddSystem( std::unique_ptr<QuadrotorGeometry>( new QuadrotorGeometry(scene_graph))); builder->Connect( quadrotor_state_port, quadrotor_geometry->get_input_port(0)); builder->Connect( quadrotor_geometry->get_output_port(0), scene_graph->get_source_pose_port(quadrotor_geometry->source_id_)); return quadrotor_geometry; } QuadrotorGeometry::QuadrotorGeometry( geometry::SceneGraph<double>* scene_graph) { DRAKE_THROW_UNLESS(scene_graph != nullptr); // Use (temporary) MultibodyPlant to parse the urdf and setup the // scene_graph. // TODO(SeanCurtis-TRI): Update this on resolution of #10775. multibody::MultibodyPlant<double> mbp(0.0); multibody::Parser parser(&mbp, scene_graph); const auto model_instance_indices = parser.AddModelsFromUrl( "package://drake_models/skydio_2/quadrotor.urdf"); mbp.Finalize(); // Identify the single quadrotor body and its frame. DRAKE_THROW_UNLESS(model_instance_indices.size() == 1); const auto body_indices = mbp.GetBodyIndices(model_instance_indices[0]); DRAKE_THROW_UNLESS(body_indices.size() == 1); const multibody::BodyIndex body_index = body_indices[0]; source_id_ = *mbp.get_source_id(); frame_id_ = mbp.GetBodyFrameIdOrThrow(body_index); this->DeclareVectorInputPort("state", 12); this->DeclareAbstractOutputPort( "geometry_pose", &QuadrotorGeometry::OutputGeometryPose); } QuadrotorGeometry::~QuadrotorGeometry() = default; void QuadrotorGeometry::OutputGeometryPose( const systems::Context<double>& context, geometry::FramePoseVector<double>* poses) const { DRAKE_DEMAND(frame_id_.is_valid()); const auto& state = get_input_port(0).Eval(context); math::RigidTransformd pose( math::RollPitchYawd(state.segment<3>(3)), state.head<3>()); *poses = {{frame_id_, pose}}; } } // namespace quadrotor } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/quadrotor
/home/johnshepherd/drake/examples/quadrotor/test/quadrotor_dynamics_test.cc
#include <stdexcept> #include <Eigen/Geometry> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/examples/quadrotor/quadrotor_plant.h" #include "drake/math/rigid_transform.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.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/constant_vector_source.h" namespace drake { namespace examples { namespace quadrotor { namespace { using Eigen::Quaterniond; using Eigen::VectorXd; using Eigen::Vector3d; using math::RigidTransformd; using math::RollPitchYawd; using multibody::MultibodyPlant; using multibody::Parser; using multibody::RigidBody; using multibody::SpatialVelocity; using systems::ConstantVectorSource; using systems::Context; using systems::ContinuousState; using systems::Diagram; using systems::DiagramBuilder; using systems::Simulator; constexpr double kEpsilon = std::numeric_limits<double>::epsilon(); // This test program compares the behaviour of two plants: // // (#1) a GenericQuadrotor created from a QuadrotorPlant, and // // (#2) a MultibodyQuadrotor created from parsing a corresponding model URDF // file into a MultibodyPlant. // // Both types of plant provide a method SetState whose argument is organized as // [x, y, z, r, p, y, ẋ, ẏ, ż, ṙ, ṗ, ẏ], but the underlying state representation // in the Context is NOT necessarily organized that way. // // Both types also provide GetPose. // The models are integrated and compared for the duration specified by the // following constant. const double kSimulationDuration = 0.1; // Case (#1): The Diagram that wraps a QuadrotorPlant. class GenericQuadrotor: public Diagram<double> { public: GenericQuadrotor() { DiagramBuilder<double> builder; plant_ = builder.template AddSystem<QuadrotorPlant<double>>(); auto* source = builder.template AddSystem<ConstantVectorSource<double>>( VectorXd::Zero(plant_->num_total_inputs())); builder.Cascade(*source, *plant_); builder.BuildInto(this); } // @param[in,out] context a mutable Context to be set from the state vector x. // @param[in] x 12-element state vector [x, y, z, r, p, y, ẋ, ẏ, ż, ṙ, ṗ, ẏ]. void SetState(Context<double>* context, const VectorXd& x) const { DRAKE_DEMAND(x.size() == 12); Context<double>& plant_context = this->GetMutableSubsystemContext(*plant_, context); plant_context.SetContinuousState(x); } // Returns X_WB, the pose relating world W to the base-link body B. // @param[in] context contains the state of the multibody system. RigidTransformd GetPose(const Context<double>& context) const { // Reminder: The state vector is [x, y, z, r, p, y, ẋ, ẏ, ż, ṙ, ṗ, ẏ]. const VectorXd state = context.get_continuous_state().get_vector().CopyToVector(); const Vector3d xyz = state.segment(0, 3); const Vector3d rpy = state.segment(3, 3); return RigidTransformd(RollPitchYawd(rpy), xyz); } // Returns V_WB_W, base-link B's spatial velocity measured and expressed in // the world frame W. // @param[in] context contains the state of the multibody system. SpatialVelocity<double> GetVelocity(const Context<double>& context) const { // Reminder: The state vector is [x, y, z, r, p, y, ẋ, ẏ, ż, ṙ, ṗ, ẏ]. const VectorXd state = context.get_continuous_state().get_vector().CopyToVector(); const Vector3d xyz_dot = state.segment(6, 3); // v_WBo_W = [ẋ, ẏ, ż]. const Vector3d rpy_dot = state.segment(9, 3); const math::RollPitchYaw<double> rpy(state.segment(3, 3)); const Vector3d w_WB_W = rpy.CalcAngularVelocityInParentFromRpyDt(rpy_dot); return SpatialVelocity<double>(w_WB_W, xyz_dot); } private: QuadrotorPlant<double>* plant_{}; }; // Case (#2): The Diagram that wraps a MultibodyPlant. class MultibodyQuadrotor: public Diagram<double> { public: MultibodyQuadrotor() { auto owned_plant = std::make_unique<MultibodyPlant<double>>(0.0); plant_ = owned_plant.get(); Parser(plant_).AddModelsFromUrl( "package://drake_models/skydio_2/quadrotor.urdf"); plant_->Finalize(); body_ = &plant_->GetBodyByName("base_link"); DiagramBuilder<double> builder; builder.AddSystem(std::move(owned_plant)); builder.BuildInto(this); } // @param[in,out] context a mutable Context to be set from the state vector x. // @param[in] x 12-element state vector [x, y, z, r, p, y, ẋ, ẏ, ż, ṙ, ṗ, ẏ]. void SetState(Context<double>* context, const VectorXd& x) const { const Vector3d xyz = x.segment(0, 3); const Vector3d rpy = x.segment(3, 3); const Vector3d xyz_dot = x.segment(6, 3); const Vector3d rpy_dot = x.segment(9, 3); // Convert the state values into our conventional multibody types. const Vector3d p_WB(xyz); const RollPitchYawd R_WB(rpy); const Vector3d v_WB(xyz_dot); const Vector3d w_WB = R_WB.CalcAngularVelocityInParentFromRpyDt(rpy_dot); const RigidTransformd X_WB(R_WB, p_WB); const SpatialVelocity<double> V_WB(w_WB, v_WB); // Set the state of the base_link. Context<double>& plant_context = this->GetMutableSubsystemContext(*plant_, context); plant_->SetFreeBodyPoseInWorldFrame(&plant_context, *body_, X_WB); plant_->SetFreeBodySpatialVelocity(&plant_context, *body_, V_WB); } // Returns X_WB, the pose relating world W to the base-link body B. // @param[in] context contains the state of the multibody system. RigidTransformd GetPose(const Context<double>& context) const { const Context<double>& plant_context = this->GetSubsystemContext(*plant_, context); return plant_->EvalBodyPoseInWorld(plant_context, *body_); } // Returns V_WB_W, base-link B's spatial velocity measured and expressed in // the world frame W. // @param[in] context contains the state of the multibody system. SpatialVelocity<double> GetVelocity(const Context<double>& context) const { const Context<double>& plant_context = this->GetSubsystemContext(*plant_, context); const SpatialVelocity<double>& V_WB_W = plant_->EvalBodySpatialVelocityInWorld(plant_context, *body_); return V_WB_W; } private: MultibodyPlant<double>* plant_{}; const RigidBody<double>* body_{}; }; void TestPassiveBehavior(const VectorXd& x0) { const GenericQuadrotor ge_model; const MultibodyQuadrotor mb_model; Simulator<double> ge_simulator(ge_model); Simulator<double> mb_simulator(mb_model); auto& ge_context = ge_simulator.get_mutable_context(); auto& mb_context = mb_simulator.get_mutable_context(); ge_model.SetState(&ge_context, x0); mb_model.SetState(&mb_context, x0); // Verify initial configuration (rotation matrix and position). const RigidTransformd ge_initial_pose = ge_model.GetPose(ge_context); const RigidTransformd mb_initial_pose = mb_model.GetPose(mb_context); EXPECT_TRUE(CompareMatrices( ge_initial_pose.translation(), mb_initial_pose.translation(), 4 * kEpsilon, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices( ge_initial_pose.rotation().matrix(), mb_initial_pose.rotation().matrix(), 4 * kEpsilon, MatrixCompareType::absolute)); // Verify initial motion (translational and rotational velocities). const SpatialVelocity<double> ge_initial_velocity = ge_model.GetVelocity(ge_context); const SpatialVelocity<double> mb_initial_velocity = mb_model.GetVelocity(mb_context); EXPECT_TRUE(CompareMatrices( ge_initial_velocity.translational(), mb_initial_velocity.translational(), 4 * kEpsilon, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices( ge_initial_velocity.rotational(), mb_initial_velocity.rotational(), 4 * kEpsilon, MatrixCompareType::absolute)); // Simulate and advance time. ge_simulator.AdvanceTo(kSimulationDuration); mb_simulator.AdvanceTo(kSimulationDuration); // Verify configuration after advancing time. Herein, the allowable error in // rotation is much higher than the allowable error in translation. const RigidTransformd ge_pose = ge_model.GetPose(ge_context); const RigidTransformd mb_pose = mb_model.GetPose(mb_context); EXPECT_TRUE(CompareMatrices( ge_pose.translation(), mb_pose.translation(), 1e-10, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices( ge_pose.rotation().matrix(), mb_pose.rotation().matrix(), 1e-5, MatrixCompareType::absolute)); // Verify motion after advancing time. Herein, the allowable error in // rotation is much higher than the allowable error in translation. const SpatialVelocity<double> ge_velocity = ge_model.GetVelocity(ge_context); const SpatialVelocity<double> mb_velocity = mb_model.GetVelocity(mb_context); EXPECT_TRUE(CompareMatrices( ge_velocity.translational(), mb_velocity.translational(), 1E-14, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices( ge_velocity.rotational(), mb_velocity.rotational(), 1E-4, MatrixCompareType::absolute)); } // Test comparing the state for of each kind of plant under passive behaviour. // Each plant is dropped from rest at the origin. GTEST_TEST(QuadrotorDynamicsTest, DropFromRest) { VectorXd x0 = VectorXd::Zero(12); TestPassiveBehavior(x0); } // Test comparing the state for of each kind of plant under passive behaviour. // Each plant is dropped from the origin with an initial translational velocity. GTEST_TEST(QuadrotorDynamicsTest, DropFromInitialVelocity) { VectorXd x0 = VectorXd::Zero(12); x0.segment(6, 3) << 1, 1, 1; // Some translational velocity. TestPassiveBehavior(x0); } // Test comparing the state for of each kind of plant under passive behaviour. // Each plant is dropped from the origin with an initial rotational velocity. GTEST_TEST(QuadrotorDynamicsTest, DropFromInitialRotation) { VectorXd x0 = VectorXd::Zero(12); x0.segment(9, 3) << 1, 1, 1; // Some rotary velocity. TestPassiveBehavior(x0); } // Test comparing the state for of each kind of plant under passive behaviour. // Each plant is dropped from and arbitrary initial state. GTEST_TEST(QuadrotorDynamicsTest, DropFromArbitraryState) { VectorXd x0 = VectorXd::Zero(12); x0 << 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6; // Some initial state. TestPassiveBehavior(x0); } } // namespace } // namespace quadrotor } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/quadrotor
/home/johnshepherd/drake/examples/quadrotor/test/quadrotor_plant_test.cc
#include "drake/examples/quadrotor/quadrotor_plant.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/systems/framework/test_utilities/scalar_conversion.h" namespace drake { namespace examples { namespace quadrotor { namespace { using symbolic::Expression; using symbolic::Variable; GTEST_TEST(QuadrotorPlantTest, DirectFeedthrough) { const QuadrotorPlant<double> plant; EXPECT_FALSE(plant.HasAnyDirectFeedthrough()); } GTEST_TEST(QuadrotorPlantTest, ToAutoDiff) { const QuadrotorPlant<double> plant; EXPECT_TRUE(is_autodiffxd_convertible(plant)); } GTEST_TEST(QuadrotorPlantTest, ToSymbolic) { const QuadrotorPlant<double> plant; EXPECT_TRUE(is_symbolic_convertible(plant)); auto plant_sym = plant.ToSymbolic(); auto context_sym = plant_sym->CreateDefaultContext(); VectorX<Variable> x = symbolic::MakeVectorVariable(12, "x"); context_sym->get_mutable_continuous_state_vector().SetFromVector( x.cast<Expression>()); VectorX<Expression> derivatives = plant_sym->EvalTimeDerivatives(*context_sym).CopyToVector(); for (int i = 0; i < 6; ++i) { EXPECT_EQ(derivatives[i], x[i+6]); } } // Ensure that DoCalcTimeDerivatives succeeds even if the input port is // disconnected. GTEST_TEST(QuadrotorPlantTest, NoInput) { const QuadrotorPlant<double> plant; auto context = plant.CreateDefaultContext(); DRAKE_EXPECT_NO_THROW(plant.EvalTimeDerivatives(*context)); } } // namespace } // namespace quadrotor } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples/quadrotor
/home/johnshepherd/drake/examples/quadrotor/test/quadrotor_geometry_test.cc
#include "drake/examples/quadrotor/quadrotor_geometry.h" #include <gtest/gtest.h> #include "drake/examples/quadrotor/quadrotor_plant.h" #include "drake/geometry/scene_graph.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { namespace examples { namespace quadrotor { namespace { GTEST_TEST(QuadrotorGeometryTest, AcceptanceTest) { // Just make sure nothing faults out. systems::DiagramBuilder<double> builder; auto plant = builder.AddSystem<QuadrotorPlant>(); auto scene_graph = builder.AddSystem<geometry::SceneGraph>(); auto geom = QuadrotorGeometry::AddToBuilder( &builder, plant->get_output_port(0), scene_graph); auto diagram = builder.Build(); ASSERT_NE(geom, nullptr); EXPECT_TRUE(geom->get_frame_id().is_valid()); } } // namespace } // namespace quadrotor } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/van_der_pol/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", ) load( "//tools/skylark:drake_py.bzl", "drake_py_binary", ) package(default_visibility = ["//visibility:private"]) drake_cc_library( name = "van_der_pol", srcs = ["van_der_pol.cc"], hdrs = ["van_der_pol.h"], visibility = ["//visibility:public"], deps = [ "//systems/analysis:simulator", "//systems/framework:diagram_builder", "//systems/framework:leaf_system", "//systems/framework:system_constraint", "//systems/framework:vector", "//systems/primitives:vector_log_sink", ], ) drake_py_binary( name = "plot_limit_cycle", srcs = ["plot_limit_cycle.py"], add_test_rule = 1, deps = [ "//bindings/pydrake", ], ) drake_cc_googletest( name = "van_der_pol_test", deps = [ ":van_der_pol", "//systems/framework/test_utilities:scalar_conversion", ], ) add_lint_tests()
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/van_der_pol/van_der_pol.h
#pragma once #include "drake/systems/framework/leaf_system.h" namespace drake { namespace examples { namespace van_der_pol { /// van der Pol oscillator /// /// The van der Pol oscillator, governed by the following equations: /// q̈ + μ(q² - 1)q̇ + q = 0, μ > 0 /// y₀ = q /// y₁ = [q,q̇]' /// is a canonical example of a nonlinear system that exhibits a /// limit cycle stability. As such it serves as an important for /// examining nonlinear stability and stochastic stability. /// /// (Examples involving region of attraction analysis and analyzing /// the stationary distribution of the oscillator under process /// noise are coming soon). /// /// @system /// name: VanDerPolOscillator /// output_ports: /// - y0 /// - y1 /// @endsystem /// /// @tparam_default_scalar template <typename T> class VanDerPolOscillator final : public systems::LeafSystem<T> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(VanDerPolOscillator) /// Constructs a default oscillator. VanDerPolOscillator(); /// Scalar-converting copy constructor. template <typename U> explicit VanDerPolOscillator(const VanDerPolOscillator<U>&) : VanDerPolOscillator() {} /// Returns the output port containing the output configuration (only). const systems::OutputPort<T>& get_position_output_port() const { return this->get_output_port(0); } /// Returns the output port containing the full state. This is /// provided primarily as a tool for debugging/visualization. const systems::OutputPort<T>& get_full_state_output_port() const { return this->get_output_port(1); } // TODO(russt): generalize this to any mu using trajectory optimization // (this could also improve the numerical accuracy). /// Returns a 2-row matrix containing the result of simulating the oscillator /// with the default mu=1 from (approximately) one point on the limit cycle /// for (approximately) one period. The first row is q, and the second row /// is q̇. static Eigen::Matrix2Xd CalcLimitCycle(); private: void DoCalcTimeDerivatives( const systems::Context<T>& context, systems::ContinuousState<T>* derivatives) const override; void CopyPositionToOutput(const systems::Context<T>& context, systems::BasicVector<T>* output) const; }; } // namespace van_der_pol } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/van_der_pol/van_der_pol.cc
#include "drake/examples/van_der_pol/van_der_pol.h" #include "drake/common/default_scalars.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/basic_vector.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/system_constraint.h" #include "drake/systems/primitives/vector_log_sink.h" namespace drake { namespace examples { namespace van_der_pol { template <typename T> VanDerPolOscillator<T>::VanDerPolOscillator() : systems::LeafSystem<T>(systems::SystemTypeTag<VanDerPolOscillator>{}) { // State is (q,q̇). auto state_index = this->DeclareContinuousState(1, 1, 0); // First output, y₀ = q, for interesting estimation problems. this->DeclareVectorOutputPort(systems::kUseDefaultName, 1, &VanDerPolOscillator::CopyPositionToOutput); // Second output, y₁ = [q,q̇]', for e.g. visualizing the full state. this->DeclareStateOutputPort(systems::kUseDefaultName, state_index); // Single parameter, μ, with default μ=1. this->DeclareNumericParameter(systems::BasicVector<T>(Vector1<T>(1.0))); // Declare μ≥0 constraint. systems::ContextConstraintCalc<T> mu = [](const systems::Context<T>& context, VectorX<T>* value) { // Extract μ from the parameters. *value = Vector1<T>(context.get_numeric_parameter(0).GetAtIndex(0)); }; this->DeclareInequalityConstraint(mu, {Vector1d(0), std::nullopt}, "mu ≥ 0"); } template <typename T> Eigen::Matrix2Xd VanDerPolOscillator<T>::CalcLimitCycle() { systems::DiagramBuilder<double> builder; auto vdp = builder.AddSystem<VanDerPolOscillator<double>>(); auto logger = LogVectorOutput(vdp->get_full_state_output_port(), &builder); auto diagram = builder.Build(); systems::Simulator<double> simulator(*diagram); // The following initial state was pre-computed (by running the simulation // with μ=1 long enough for it to effectively reach the steady-state limit // cycle). simulator.get_mutable_context().SetContinuousState( Eigen::Vector2d{-0.1144, 2.0578}); // Simulate for the approximate period (acquired by inspection of numerical // simulation results) of the cycle for μ=1. simulator.AdvanceTo(6.667); return logger->FindLog(simulator.get_context()).data(); } // q̈ + μ(q² - 1)q̇ + q = 0 template <typename T> void VanDerPolOscillator<T>::DoCalcTimeDerivatives( const systems::Context<T>& context, systems::ContinuousState<T>* derivatives) const { const T q = context.get_continuous_state().get_generalized_position().GetAtIndex(0); const T qdot = context.get_continuous_state().get_generalized_velocity().GetAtIndex(0); const T mu = context.get_numeric_parameter(0).GetAtIndex(0); using std::pow; const T qddot = -mu * (q * q - 1) * qdot - q; derivatives->get_mutable_generalized_position().SetAtIndex(0, qdot); derivatives->get_mutable_generalized_velocity().SetAtIndex(0, qddot); } template <typename T> void VanDerPolOscillator<T>::CopyPositionToOutput( const systems::Context<T>& context, systems::BasicVector<T>* output) const { output->SetAtIndex( 0, context.get_continuous_state().get_generalized_position().GetAtIndex(0)); } } // namespace van_der_pol } // namespace examples } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS( class ::drake::examples::van_der_pol::VanDerPolOscillator)
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/van_der_pol/plot_limit_cycle.py
# To be a meaningful unit test, we must render the figure somehow. # The Agg backend (creating a PNG image) is suitably cross-platform. # Users should feel free to use a different back-end in their own code. import os os.environ['MPLBACKEND'] = 'Agg' # noqa # Now that the environment is set up, it's safe to import matplotlib, etc. import matplotlib.pyplot as plt import webbrowser from pydrake.examples import VanDerPolOscillator x = VanDerPolOscillator.CalcLimitCycle() fig, ax = plt.subplots() ax.plot(x[0, :], x[1, :], color='k', linewidth=2) ax.set_xlim([-2.5, 2.5]) ax.set_ylim([-3, 3]) ax.set_xlabel('q') ax.set_ylabel('qdot') plt.savefig('plot_limit_cycle.png') assert os.path.exists('plot_limit_cycle.png') # Show the figure (but not when testing). if 'TEST_TMPDIR' not in os.environ: webbrowser.open_new_tab(url='plot_limit_cycle.png')
0
/home/johnshepherd/drake/examples/van_der_pol
/home/johnshepherd/drake/examples/van_der_pol/test/van_der_pol_test.cc
#include "drake/examples/van_der_pol/van_der_pol.h" #include <gtest/gtest.h> #include "drake/systems/framework/test_utilities/scalar_conversion.h" namespace drake { namespace examples { namespace van_der_pol { namespace { GTEST_TEST(VanDerPolTest, ScalarConversionTest) { VanDerPolOscillator<double> vdp; EXPECT_TRUE(is_autodiffxd_convertible(vdp)); EXPECT_TRUE(is_symbolic_convertible(vdp)); } GTEST_TEST(VanDerPolTest, LimitCycle) { const auto cycle = VanDerPolOscillator<double>::CalcLimitCycle(); const int N = cycle.cols(); EXPECT_NEAR(cycle(0, 0), cycle(0, N - 1), 1e-2); EXPECT_NEAR(cycle(1, 0), cycle(1, N - 1), 5e-3); } } // namespace } // namespace van_der_pol } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kuka_iiwa_arm/iiwa_controller.cc
/// @file /// /// Implements a controller for a KUKA iiwa arm. #include <cstdlib> #include <iostream> #include <memory> #include <gflags/gflags.h> #include "drake/common/text_logging.h" #include "drake/examples/kuka_iiwa_arm/lcm_plan_interpolator.h" #include "drake/lcm/drake_lcm.h" #include "drake/lcmt_iiwa_command.hpp" #include "drake/lcmt_iiwa_status.hpp" #include "drake/lcmt_robot_plan.hpp" #include "drake/multibody/parsing/package_map.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/context.h" #include "drake/systems/framework/diagram.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/lcm/lcm_publisher_system.h" #include "drake/systems/lcm/lcm_subscriber_system.h" DEFINE_string(urdf, "", "Name of urdf to load"); DEFINE_string(interp_type, "cubic", "Robot plan interpolation type. Can be {zoh, foh, cubic, pchip}"); DEFINE_string(lcm_status_channel, "IIWA_STATUS", "Channel on which to listen for lcmt_iiwa_status messages."); DEFINE_string(lcm_command_channel, "IIWA_COMMAND", "Channel on which to publish lcmt_iiwa_command messages."); DEFINE_string(lcm_plan_channel, "COMMITTED_ROBOT_PLAN", "Channel on which to listen for lcmt_robot_plan messages."); namespace drake { namespace examples { namespace kuka_iiwa_arm { namespace { using manipulation::util::InterpolatorType; using manipulation::util::RobotPlanInterpolator; using multibody::PackageMap; const char kIiwaUrdfUrl[] = "package://drake_models/iiwa_description/urdf/" "iiwa14_polytope_collision.urdf"; // Create a system which has an integrator on the interpolated // reference position for received plans. int DoMain() { const std::string kLcmStatusChannel = FLAGS_lcm_status_channel; const std::string kLcmCommandChannel = FLAGS_lcm_command_channel; const std::string kLcmPlanChannel = FLAGS_lcm_plan_channel; lcm::DrakeLcm lcm; systems::DiagramBuilder<double> builder; drake::log()->debug("Status channel: {}", kLcmStatusChannel); drake::log()->debug("Command channel: {}", kLcmCommandChannel); drake::log()->debug("Plan channel: {}", kLcmPlanChannel); const std::string urdf = (!FLAGS_urdf.empty() ? FLAGS_urdf : PackageMap{}.ResolveUrl(kIiwaUrdfUrl)); // Sets the robot plan interpolation type. std::string interp_str(FLAGS_interp_type); std::transform(interp_str.begin(), interp_str.end(), interp_str.begin(), ::tolower); InterpolatorType interpolator_type{}; if (interp_str == "zoh") { interpolator_type = InterpolatorType::ZeroOrderHold; } else if (interp_str == "foh") { interpolator_type = InterpolatorType::FirstOrderHold; } else if (interp_str == "cubic") { interpolator_type = InterpolatorType::Cubic; } else if (interp_str == "pchip") { interpolator_type = InterpolatorType::Pchip; } else { std::cerr << "Robot plan interpolation type not recognized. " "Use the gflag --helpshort to display " "flag options for interpolator type.\n"; return EXIT_FAILURE; } auto plan_interpolator = builder.AddSystem<LcmPlanInterpolator>(urdf, interpolator_type); const int kNumJoints = plan_interpolator->num_joints(); auto plan_sub = builder.AddSystem( systems::lcm::LcmSubscriberSystem::Make<lcmt_robot_plan>( kLcmPlanChannel, &lcm)); plan_sub->set_name("plan_sub"); auto command_pub = builder.AddSystem( systems::lcm::LcmPublisherSystem::Make<lcmt_iiwa_command>( kLcmCommandChannel, &lcm)); command_pub->set_name("command_pub"); // Connect subscribers to input ports. builder.Connect(plan_sub->get_output_port(), plan_interpolator->get_input_port_iiwa_plan()); // Connect publisher to output port. builder.Connect(plan_interpolator->get_output_port_iiwa_command(), command_pub->get_input_port()); // Create the diagram, simulator, and context. auto owned_diagram = builder.Build(); const auto& diagram = *owned_diagram; systems::Simulator<double> simulator(std::move(owned_diagram)); auto& diagram_context = simulator.get_mutable_context(); auto& plan_interpolator_context = diagram.GetMutableSubsystemContext(*plan_interpolator, &diagram_context); // Wait for the first message. drake::log()->info("Waiting for first lcmt_iiwa_status"); lcm::Subscriber<lcmt_iiwa_status> status_sub(&lcm, kLcmStatusChannel); LcmHandleSubscriptionsUntil(&lcm, [&]() { return status_sub.count() > 0; }); DRAKE_DEMAND(status_sub.message().num_joints == kNumJoints); // Initialize the context based on the first message. const double t0 = status_sub.message().utime * 1e-6; VectorX<double> q0(kNumJoints); for (int i = 0; i < kNumJoints; ++i) { q0[i] = status_sub.message().joint_position_measured[i]; } diagram_context.SetTime(t0); plan_interpolator->Initialize(t0, q0, &plan_interpolator_context); auto& status_value = plan_interpolator->get_input_port_iiwa_status().FixValue( &plan_interpolator_context, status_sub.message()); // Run forever, using the lcmt_iiwa_status message to dictate when simulation // time advances. The lcmt_robot_plan message is handled whenever the next // lcmt_iiwa_status occurs. drake::log()->info("Controller started"); while (true) { // Wait for an lcmt_iiwa_status message. status_sub.clear(); LcmHandleSubscriptionsUntil(&lcm, [&]() { return status_sub.count() > 0; }); // Write the lcmt_iiwa_status message into the context and advance. status_value.GetMutableData()->set_value(status_sub.message()); const double time = status_sub.message().utime * 1e-6; simulator.AdvanceTo(time); // Force-publish the lcmt_iiwa_command (via the command_pub system within // the diagram). diagram.ForcedPublish(diagram_context); } // We should never reach here. return EXIT_FAILURE; } } // namespace } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::kuka_iiwa_arm::DoMain(); }
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kuka_iiwa_arm/iiwa_lcm.h
#pragma once #include "drake/manipulation/kuka_iiwa/iiwa_command_receiver.h" #include "drake/manipulation/kuka_iiwa/iiwa_command_sender.h" #include "drake/manipulation/kuka_iiwa/iiwa_constants.h" #include "drake/manipulation/kuka_iiwa/iiwa_status_receiver.h" #include "drake/manipulation/kuka_iiwa/iiwa_status_sender.h" namespace drake { namespace examples { namespace kuka_iiwa_arm { // These details have moved to files under drake/manipulation/kuka_iiwa. // These forwarding aliases are placed here for compatibility purposes. using manipulation::kuka_iiwa::IiwaCommandReceiver; using manipulation::kuka_iiwa::IiwaCommandSender; using manipulation::kuka_iiwa::IiwaStatusReceiver; using manipulation::kuka_iiwa::IiwaStatusSender; using manipulation::kuka_iiwa::kIiwaLcmStatusPeriod; } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kuka_iiwa_arm/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", ) load( "//tools/skylark:drake_py.bzl", "drake_py_unittest", ) package(default_visibility = ["//visibility:private"]) drake_cc_library( name = "iiwa_common", srcs = ["iiwa_common.cc"], hdrs = ["iiwa_common.h"], deps = [ "//manipulation/kuka_iiwa:iiwa_constants", ], ) drake_cc_library( name = "iiwa_lcm", srcs = ["iiwa_lcm.cc"], hdrs = ["iiwa_lcm.h"], deps = [ "//manipulation/kuka_iiwa", ], ) drake_cc_library( name = "lcm_plan_interpolator", srcs = ["lcm_plan_interpolator.cc"], hdrs = ["lcm_plan_interpolator.h"], deps = [ ":iiwa_common", ":iiwa_lcm", "//manipulation/util:robot_plan_interpolator", "//systems/framework:diagram_builder", "//systems/primitives:demultiplexer", ], ) drake_cc_library( name = "kuka_torque_controller", srcs = ["kuka_torque_controller.cc"], hdrs = ["kuka_torque_controller.h"], deps = [ "//multibody/plant", "//systems/controllers:inverse_dynamics", "//systems/controllers:pid_controller", "//systems/controllers:state_feedback_controller_interface", "//systems/framework:diagram_builder", "//systems/framework:leaf_system", "//systems/primitives:adder", "//systems/primitives:pass_through", ], ) drake_cc_binary( name = "iiwa_controller", srcs = ["iiwa_controller.cc"], data = [ ":models", "@drake_models//:iiwa_description", ], deps = [ ":iiwa_common", ":lcm_plan_interpolator", "//common:add_text_logging_gflags", "//lcm:drake_lcm", "//systems/analysis:simulator", ], ) drake_cc_binary( name = "kuka_simulation", srcs = ["kuka_simulation.cc"], add_test_rule = 1, data = [ ":models", "@drake_models//:iiwa_description", ], test_rule_args = ["--simulation_sec=0.1 --target_realtime_rate=0.0"], # TODO([email protected]): Re-enable this test when it no longer # causes timeouts in kcov. test_rule_tags = ["no_kcov"], deps = [ ":iiwa_common", ":iiwa_lcm", ":kuka_torque_controller", "//common:add_text_logging_gflags", "//lcm", "//multibody/parsing", "//multibody/plant", "//systems/analysis:simulator", "//systems/controllers:inverse_dynamics_controller", "//systems/controllers:state_feedback_controller_interface", "//systems/primitives:constant_vector_source", "//systems/primitives:demultiplexer", "//systems/primitives:discrete_derivative", "//visualization", ], ) drake_cc_binary( name = "kuka_plan_runner", srcs = ["kuka_plan_runner.cc"], data = [ ":models", "@drake_models//:iiwa_description", ], deps = [ "//common/trajectories:piecewise_polynomial", "//lcmtypes:iiwa", "//lcmtypes:robot_plan", "//multibody/parsing", "//multibody/plant", "@lcm", ], ) drake_cc_binary( name = "move_iiwa_ee", srcs = ["move_iiwa_ee.cc"], data = [ ":models", "@drake_models//:iiwa_description", ], deps = [ ":iiwa_common", "//common:add_text_logging_gflags", "//lcmtypes:iiwa", "//manipulation/util:move_ik_demo_base", "//math:geometric_transform", "@lcm", ], ) alias( name = "models", actual = "//examples/kuka_iiwa_arm/models:models", visibility = ["//visibility:public"], ) # === test/ === drake_cc_googletest( name = "kuka_torque_controller_test", data = [ "@drake_models//:iiwa_description", ], deps = [ ":iiwa_common", ":kuka_torque_controller", "//common/test_utilities:eigen_matrix_compare", "//multibody/parsing", ], ) alias( name = "dual_iiwa14_polytope_collision.urdf", actual = "@drake_models//:iiwa_description/urdf/dual_iiwa14_polytope_collision.urdf", # noqa ) # Test that kuka_simulation can load the dual arm urdf sh_test( name = "dual_kuka_simulation_test", size = "small", srcs = ["kuka_simulation"], args = [ "$(location :kuka_simulation)", "--urdf", "$(location :dual_iiwa14_polytope_collision.urdf)", "--simulation_sec=0.01", ], data = [ ":dual_iiwa14_polytope_collision.urdf", ], # TODO([email protected]): Re-enable this test when it no longer # causes timeouts in kcov. tags = ["no_kcov"], ) add_lint_tests(enable_clang_format_lint = False)
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kuka_iiwa_arm/lcm_plan_interpolator.cc
#include "drake/examples/kuka_iiwa_arm/lcm_plan_interpolator.h" #include "drake/examples/kuka_iiwa_arm/iiwa_lcm.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/primitives/demultiplexer.h" namespace drake { namespace examples { namespace kuka_iiwa_arm { using manipulation::util::InterpolatorType; using manipulation::util::RobotPlanInterpolator; using systems::DiagramBuilder; LcmPlanInterpolator::LcmPlanInterpolator(const std::string& model_path, InterpolatorType interpolator_type) { DiagramBuilder<double> builder; // Add plan interpolation block. robot_plan_interpolator_ = builder.AddNamedSystem<RobotPlanInterpolator>( "plan_interpolator", model_path, interpolator_type); num_joints_ = robot_plan_interpolator_->plant().num_positions(); // Add block to export a received iiwa status. auto status_receiver = builder.AddNamedSystem<IiwaStatusReceiver>( "status_receiver", num_joints_); input_port_iiwa_status_ = builder.ExportInput(status_receiver->get_input_port()); // Add a demux block to pull out the positions from the position + velocity // vector auto target_demux = builder.AddNamedSystem<systems::Demultiplexer>( "target_demux", num_joints_ * 2, num_joints_); // Add a block to convert the desired position vector to iiwa command. auto command_sender = builder.AddSystem<IiwaCommandSender>(num_joints_); command_sender->set_name("command_sender"); // Export the inputs. input_port_iiwa_plan_ = builder.ExportInput(robot_plan_interpolator_->get_plan_input_port()); // Export the output. output_port_iiwa_command_ = builder.ExportOutput(command_sender->get_output_port()); // Connect the subsystems. builder.Connect(robot_plan_interpolator_->get_output_port(0), target_demux->get_input_port(0)); builder.Connect(target_demux->get_output_port(0), command_sender->get_position_input_port()); // Build the system. builder.BuildInto(this); } void LcmPlanInterpolator::Initialize(double plan_start_time, const VectorX<double>& q0, systems::Context<double>* context) const { robot_plan_interpolator_->Initialize( plan_start_time, q0, &this->GetMutableSubsystemContext(*robot_plan_interpolator_, context) .get_mutable_state()); } } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kuka_iiwa_arm/kuka_plan_runner.cc
/// @file /// /// kuka_plan_runner is designed to wait for LCM messages constraining /// a lcmt_robot_plan message, and then execute the plan on an iiwa arm /// (also communicating via LCM using the /// lcmt_iiwa_command/lcmt_iiwa_status messages). /// /// When a plan is received, it will immediately begin executing that /// plan on the arm (replacing any plan in progress). /// /// If a stop message is received, it will immediately discard the /// current plan and wait until a new plan is received. #include <iostream> #include <memory> #include "lcm/lcm-cpp.hpp" #include "drake/common/drake_assert.h" #include "drake/common/fmt_eigen.h" #include "drake/common/trajectories/piecewise_polynomial.h" #include "drake/lcmt_iiwa_command.hpp" #include "drake/lcmt_iiwa_status.hpp" #include "drake/lcmt_robot_plan.hpp" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/plant/multibody_plant.h" using Eigen::MatrixXd; using Eigen::VectorXd; using Eigen::VectorXi; using drake::Vector1d; using Eigen::Vector2d; using Eigen::Vector3d; namespace drake { namespace examples { namespace kuka_iiwa_arm { namespace { const char* const kLcmStatusChannel = "IIWA_STATUS"; const char* const kLcmCommandChannel = "IIWA_COMMAND"; const char* const kLcmPlanChannel = "COMMITTED_ROBOT_PLAN"; const char* const kLcmStopChannel = "STOP"; const int kNumJoints = 7; using trajectories::PiecewisePolynomial; typedef PiecewisePolynomial<double> PPType; typedef Polynomial<double> PPPoly; typedef PPType::PolynomialMatrix PPMatrix; class RobotPlanRunner { public: /// plant is aliased explicit RobotPlanRunner(const multibody::MultibodyPlant<double>& plant) : plant_(plant), plan_number_(0) { lcm_.subscribe(kLcmStatusChannel, &RobotPlanRunner::HandleStatus, this); lcm_.subscribe(kLcmPlanChannel, &RobotPlanRunner::HandlePlan, this); lcm_.subscribe(kLcmStopChannel, &RobotPlanRunner::HandleStop, this); } void Run() { int cur_plan_number = plan_number_; int64_t cur_time_us = -1; int64_t start_time_us = -1; // Initialize the timestamp to an invalid number so we can detect // the first message. iiwa_status_.utime = cur_time_us; lcmt_iiwa_command iiwa_command; iiwa_command.num_joints = kNumJoints; iiwa_command.joint_position.resize(kNumJoints, 0.); iiwa_command.num_torques = 0; iiwa_command.joint_torque.resize(kNumJoints, 0.); while (true) { // Call lcm handle until at least one status message is // processed. while (0 == lcm_.handleTimeout(10) || iiwa_status_.utime == -1) { } cur_time_us = iiwa_status_.utime; if (plan_) { if (plan_number_ != cur_plan_number) { std::cout << "Starting new plan." << std::endl; start_time_us = cur_time_us; cur_plan_number = plan_number_; } const double cur_traj_time_s = static_cast<double>(cur_time_us - start_time_us) / 1e6; const auto desired_next = plan_->value(cur_traj_time_s); iiwa_command.utime = iiwa_status_.utime; for (int joint = 0; joint < kNumJoints; joint++) { iiwa_command.joint_position[joint] = desired_next(joint); } lcm_.publish(kLcmCommandChannel, &iiwa_command); } } } private: void HandleStatus(const ::lcm::ReceiveBuffer*, const std::string&, const lcmt_iiwa_status* status) { iiwa_status_ = *status; } void HandlePlan(const ::lcm::ReceiveBuffer*, const std::string&, const lcmt_robot_plan* plan) { std::cout << "New plan received." << std::endl; if (iiwa_status_.utime == -1) { std::cout << "Discarding plan, no status message received yet" << std::endl; return; } else if (plan->num_states < 2) { std::cout << "Discarding plan, Not enough knot points." << std::endl; return; } std::vector<Eigen::MatrixXd> knots(plan->num_states, Eigen::MatrixXd::Zero(kNumJoints, 1)); for (int i = 0; i < plan->num_states; ++i) { const auto& state = plan->plan[i]; for (int j = 0; j < state.num_joints; ++j) { if (!plant_.HasJointNamed(state.joint_name[j])) { continue; } const multibody::Joint<double>& joint = plant_.GetJointByName(state.joint_name[j]); DRAKE_DEMAND(joint.num_positions() == 1); const int idx = joint.position_start(); DRAKE_DEMAND(idx < kNumJoints); // Treat the matrix at knots[i] as a column vector. if (i == 0) { // Always start moving from the position which we're // currently commanding. DRAKE_DEMAND(iiwa_status_.utime != -1); knots[0](idx, 0) = iiwa_status_.joint_position_commanded[j]; } else { knots[i](idx, 0) = state.joint_position[j]; } } } for (int i = 0; i < plan->num_states; ++i) { fmt::print("{}\n", fmt_eigen(knots[i])); } std::vector<double> input_time; for (int k = 0; k < static_cast<int>(plan->plan.size()); ++k) { input_time.push_back(plan->plan[k].utime / 1e6); } const Eigen::MatrixXd knot_dot = Eigen::MatrixXd::Zero(kNumJoints, 1); plan_.reset(new PiecewisePolynomial<double>( PiecewisePolynomial<double>::CubicWithContinuousSecondDerivatives( input_time, knots, knot_dot, knot_dot))); ++plan_number_; } void HandleStop(const ::lcm::ReceiveBuffer*, const std::string&, const lcmt_robot_plan*) { std::cout << "Received stop command. Discarding plan." << std::endl; plan_.reset(); } ::lcm::LCM lcm_; const multibody::MultibodyPlant<double>& plant_; int plan_number_{}; std::unique_ptr<PiecewisePolynomial<double>> plan_; lcmt_iiwa_status iiwa_status_; }; int do_main() { multibody::MultibodyPlant<double> plant(0.0); multibody::Parser(&plant).AddModelsFromUrl( "package://drake_models/iiwa_description/urdf/" "iiwa14_no_collision.urdf"); plant.WeldFrames(plant.world_frame(), plant.GetBodyByName("base").body_frame()); plant.Finalize(); RobotPlanRunner runner(plant); runner.Run(); return 0; } } // namespace } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake int main() { return drake::examples::kuka_iiwa_arm::do_main(); }
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kuka_iiwa_arm/lcm_plan_interpolator.h
#pragma once #include <string> #include "drake/manipulation/util/robot_plan_interpolator.h" #include "drake/systems/framework/diagram.h" namespace drake { namespace examples { namespace kuka_iiwa_arm { /** * A Diagram that adapts a RobotPlanInterpolator for use with an Iiwa arm. * * @system * name: LcmPlanInterpolator * input_ports: * - status_receiver_lcmt_iiwa_status * - plan_interpolator_plan * output_ports: * - command_sender_lcmt_iiwa_command * @endsystem * * @see `lcmt_iiwa_status.lcm`, `lcmt_iiwa_command.lcm`, `lcmt_robot_plan.lcm`, * and `lcmt_robot_state.lcm` for additional documentation. */ class LcmPlanInterpolator : public systems::Diagram<double> { public: LcmPlanInterpolator( const std::string& model_path, manipulation::util::InterpolatorType interpolator_type); const systems::InputPort<double>& get_input_port_iiwa_status() const { return get_input_port(input_port_iiwa_status_); } const systems::InputPort<double>& get_input_port_iiwa_plan() const { return get_input_port(input_port_iiwa_plan_); } const systems::OutputPort<double>& get_output_port_iiwa_command() const { return get_output_port(output_port_iiwa_command_); } /** * Makes a plan to hold at the measured joint configuration @p q0 starting at * @p plan_start_time. This function needs to be explicitly called before any * simulation. Otherwise this aborts in CalcOutput(). */ void Initialize(double plan_start_time, const VectorX<double>& q0, systems::Context<double>* context) const; int num_joints() const { return num_joints_; } private: // Input ports. int input_port_iiwa_status_{-1}; int input_port_iiwa_plan_{-1}; // Output ports. int output_port_iiwa_command_{-1}; manipulation::util::RobotPlanInterpolator* robot_plan_interpolator_{}; int num_joints_{}; }; } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kuka_iiwa_arm/README.md
IIWA Manipulation Examples ========================== There are a number of examples contained in these directories. The following instructions assume Drake was [built using bazel](https://drake.mit.edu/bazel.html?highlight=bazel). Prerequisites ------------- All instructions assume that you are launching from the `drake` workspace directory. ``` cd drake ``` Open a visualizer window ``` bazel run //tools:meldis -- --open-window & ``` Basic IIWA Simulation --------------------- Launch the kuka simulation ``` bazel-bin/examples/kuka_iiwa_arm/kuka_simulation ``` Launch the "plan runner" (which produces position commands over time upon receiving a single plan message) ``` bazel-bin/examples/kuka_iiwa_arm/kuka_plan_runner ``` Command the robot to move the end effector ``` bazel-bin/examples/kuka_iiwa_arm/move_iiwa_ee -x 0.8 -y 0.3 -z 0.25 -yaw 1.57 ```
0
/home/johnshepherd/drake/examples
/home/johnshepherd/drake/examples/kuka_iiwa_arm/iiwa_lcm.cc
#include "drake/examples/kuka_iiwa_arm/iiwa_lcm.h"
0